Get (output) current time - files are named according to the experimental time

Scheduling during repeated tests, each experiment will produce a result, but if the same name generated result, all results will be lost in the process, if the distinction between manual, will be very complicated and prone to error. Here's a current can be generated named as a result of Beijing, this will not be the phenomenon of the same name, it can also generate time for each order of the results and generate results at a glance.

Get the current time

now = datetime.datetime.now(dateutil.tz.tzlocal())

The current phrase can accurately time and the current time zone output together. As shown below:
Here Insert Picture Description

The acquisition time or output in the form of a string

timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')

Sentence can be above the current standard time (when _ _ _ day of _ minutes _ dated seconds) in the form of output. As shown below:
Here Insert Picture Description

Complete Usage

import datetime
import dateutil.tz

if __name__ == '__main__':
    now = datetime.datetime.now(dateutil.tz.tzlocal())
    timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
    print(now)
    print(timestamp)

To get the current time as a string, set it to the name of the file is easy.

Named using the current time

import datetime
import dateutil.tz

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

if __name__ == '__main__':
    now = datetime.datetime.now(dateutil.tz.tzlocal())
    timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
    
    output_dir = './output/%s' % (timestamp)
    mkdir_p(output_dir)
Published 35 original articles · won praise 6 · views 3053

Guess you like

Origin blog.csdn.net/qq_37974048/article/details/104371644