How to create a file name with the current date & time in Python?
To generate a filename with the current timestamp in Python, you can tap into the powers of the datetime
module coupled with strftime
. Here's a quick glance:
This will output a filename that's formatted as file_YYYY-MM-DD_HH-MM-SS.txt
.
Using strftime to format date and time
The strftime
function is your personal time stylist, enabling you to define how the time should be formatted:
%Y
: Full Year — Not to be mistaken for a why question!%m
: Month — No, it's not short for mom.%d
: Day — No affiliation with the D in DJ.%H
: Hour — Doesn't stand for High five.%M
: Minute — Nope, no connection with M&M's.%S
: Second — You guessed it, no relation to S Club 7.
Tackling filesystem paths
When you're in the business of dealing with file paths, best to use raw strings or double backslashes. This safely sidesteps those annoying escape character issues:
Combine your directory and filename using the reliable os.path.join
method:
Rolling with the time module
As much as datetime
is the star of the show, the understudy time
module can also take a bow. This can be quite handy when you're racing against time on time-related operations:
Time-stamping logs or entries by date and time? This is your time-saving trick.
Confirming directory structure exists
Before saving your masterpiece, it's a good practice to ensure the house is in order, or in this case, the intended directory:
This prevents the drama of trying to write to a non-existent directory.
Embrace human-readable formats
For better relationship with your humans, consider a more human-readable format with underscores and an AM/PM display:
The result is a more intuitive filename like "report_2023_04_01-10_30_45_AM.txt"
that will score you bonus points with your human friends.
Was this article helpful?