327

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 current date/time (I'm not an expert in Python)

filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
sys.stdout = open(filename1 + '.xml', 'w')

I want to write out a file name with the exact date and time, it is a xml file, that the program has already create, I just need to name the file. The above code is not working.

The error returned:

  File "./fix.py", line 226, in <module>
    filenames = datetime.now().strftime("%Y%m%d-%H%M%S")
AttributeError: 'module' object has no attribute 'now'
0

8 Answers 8

611

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.

6
  • 3
    Gotcha! time was not defined in my script and I was trying to use timedate (not work, I do not why), but with time it is clear now, the filename is created with success. Thank You so much! Commented May 15, 2012 at 19:56
  • 3
    I don't know why you accepted this answer when there are two answers that explain perfectly well what was wrong with the code in the question. Nothing against the way Levon did this, it works fine, but when you say "not work, I don't know why", it seems odd because you have answers that explain why. Commented May 15, 2012 at 19:58
  • When I tried the code above, I received a, "E AttributeError: 'int' object has no attribute 'strftime'" error.
    – rwbyrd
    Commented Aug 25, 2015 at 15:30
  • 5
    @rwbyrd You probably have an int variable called "time" somewhere in scope that is shadowing the time module.
    – Thomas
    Commented Sep 20, 2015 at 5:04
  • 1
    For the ones looking for the strftime parameters: docs.python.org/3/library/time.html#time.strftime
    – Torsten
    Commented Feb 7, 2023 at 10:16
83

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

3
  • 1
    @B4NZ41 That's not true. The error message makes it clear that your code has import datetime somewhere. Commented May 15, 2012 at 20:00
  • ;) Sorry! NOW I'm using import time, before I was using import datetime Commented May 15, 2012 at 20:04
  • 3
    @B4NZ41 It doesn't matter what you are doing now. It matters what is in the question. Commented May 15, 2012 at 20:07
77

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'
5
  • 3
    Yes but sorting by name will not sort chronologically
    – Peter
    Commented Jan 31, 2020 at 23:49
  • 4
    I guess that just requires YYMMDD instead of DDMMYY? Commented Feb 1, 2020 at 11:20
  • 1
    Now its fine for chronological sorting (it has been edited). Commented Dec 27, 2022 at 17:26
  • that is NOT chronologically sorted... 4 PM shows before 5 AM... I rather use: datetime.now().strftime("%Y_%m_%d-%p%I_%M_%S") Commented May 29, 2023 at 12:50
  • 1
    Another option for sorting the hours chronologically is using 24-hour based timestamps instead of 12-hour based timestamps using %H instead of %I, with no need to include the AM/PM indicator %p.
    – Cory Gross
    Commented Nov 8, 2023 at 20:04
40

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
8

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 datetime
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)
2
  • 1
    A safer way to create your path, might be: folder_to_save_files = shutil.os.path.join(drive_letter, folder_name +folder_time) (also an import shutil statement can replace the import os statement ) Commented Jul 6, 2020 at 17:30
  • Thanks to yosemite_k for adding the import datetime. Yes, oneindelijk that is a safer way. Commented Oct 20, 2021 at 3:35
7

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
6

This prints in an easy to read format -

import datetime

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

print(time_now)

Output: 02_03_2021_22_44_50

3
import datetime

def print_time():
    parser = datetime.datetime.now() 
    return parser.strftime("%d-%m-%Y %H:%M:%S")

print(print_time())

# Output>
# 03-02-2021 22:39:28
2
  • 1
    Please add ``` around your code. Like this: ``` code ``` -> code. Also add some explaination. Commented Dec 10, 2020 at 11:59
  • 3
    You cannot create a filename containing : on Windows.
    – sekrett
    Commented Nov 18, 2021 at 8:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.