How to create a file name with the current date & time in Python?

后端 未结 6 1335
北海茫月
北海茫月 2020-12-07 07:40

Here is a functional code (create file with success)

sys.stdout = open(\'filename1.xml\', \'w\')

Now I\'m trying to name the file with the cu

相关标签:
6条回答
  • 2020-12-07 08:21

    Change this line

    filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
    

    To

    filename1 = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    

    Note the extra datetime. Alternatively, change your import datetime to from datetime import datetime

    0 讨论(0)
  • 2020-12-07 08:22

    now is a class method in the class datetime in the module datetime. So you need

    datetime.datetime.now()
    

    Or you can use a different import

    from datetime import datetime
    

    Done this way allows you to use datetime.now as per the code in the question.

    0 讨论(0)
  • 2020-12-07 08:27

    I'm surprised there is not some single formatter that returns a default (and safe) 'for appending in filename' - format of the time, We could simply write FD.write('mybackup'+time.strftime('%(formatter here)') + 'ext'

    "%x" instead of "%Y%m%d-%H%M%S"
    
    0 讨论(0)
  • 2020-12-07 08:32

    While not using datetime, this solves your problem (answers your question) of getting a string with the current time and date format you specify:

    import time
    timestr = time.strftime("%Y%m%d-%H%M%S")
    print timestr
    

    yields:

    20120515-155045
    

    so your filename could append or use this string.

    0 讨论(0)
  • 2020-12-07 08:36

    This one is much more human readable.

    from datetime import datetime
    
    datetime.now().strftime("%Y_%m_%d-%I_%M_%S_%p")
    
    '2020_08_12-03_29_22_AM'
    
    0 讨论(0)
  • 2020-12-07 08:36

    Here's some that I needed to include the date-time stamp in the folder name for dumping files from a web scraper.

    # import time and OS modules to use to build file folder name
    import time
    import os 
    
    # Build string for directory to hold files
    # Output Configuration
    #   drive_letter = Output device location (hard drive) 
    #   folder_name = directory (folder) to receive and store PDF files
    
    drive_letter = r'D:\\' 
    folder_name = r'downloaded-files'
    folder_time = datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
    folder_to_save_files = drive_letter + folder_name + folder_time 
    
    # IF no such folder exists, create one automatically
    if not os.path.exists(folder_to_save_files):
        os.mkdir(folder_to_save_files)
    
    0 讨论(0)
提交回复
热议问题