Explain Codes LogoExplain Codes Logo

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

python
time-module
datetime-module
file-system
Alex KataevbyAlex Kataev·Aug 29, 2024
TLDR

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:

from datetime import datetime filename = datetime.now().strftime("file_%Y-%m-%d_%H-%M-%S.txt") print(filename) # e.g., "file_2023-03-25_14-30-45.txt"

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:

folder = r"C:\Users\YourName\Documents\Snapshots" # not creating an orchestra, just a raw string! # OR folder = "C:\\Users\\YourName\\Documents\\Snapshots" # double trouble for escape characters

Combine your directory and filename using the reliable os.path.join method:

import os from datetime import datetime folder = r"C:\Users\YourName\Documents\Snapshots" filename = datetime.now().strftime("snapshot_%Y-%m-%d_%H-%M-%S.png") file_path = os.path.join(folder, filename) # here's the magic spell for combining paths

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:

import time filename = time.strftime("entry_%Y-%m-%d_%H-%M-%S.log")

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:

import os from datetime import datetime dir_path = r"~/snapshots" if not os.path.exists(dir_path): os.makedirs(dir_path) # if home does not exist, build it! file_path = os.path.join(dir_path, datetime.now().strftime("snapshot_%Y-%m-%d_%H-%M-%S.png"))

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:

filename = datetime.now().strftime("report_%Y_%m_%d-%I_%M_%S_%p.txt")

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.