The most efficient way to create a filename containing the current date or time is to use f-strings (Python 3.6+) with datetime.now() and .strftime() methods.
For embedding a formatted date and time into a string, you can always use f-strings for a concise and readable format.
In the above figure, the left-side file has a name without a date and time, while the filename on the right side includes a date and time.
Some tasks are performed daily, hourly, or weekly, and their reports are being generated. If that is the case, we must ensure that the user can easily access the files, date, or time-wise. And what is the efficient way? Well, by appending the date or time to the filenames while creating.
Let’s say, we will generate the files in this “output” folder, which is empty currently:
We will write code that generates new files with names containing the date and time in this directory.
from datetime import datetime
from pathlib import Path
# Getting the current datetime once
now = datetime.now()
# Format with strftime()
timestamp = now.strftime("%Y%m%d-%H%M%S")
filename = f"file_{timestamp}.txt"
# Ensure output directory exists
Path("output").mkdir(exist_ok=True)
# Write to file
with open(Path("output") / filename, "w") as f:
f.write("Checkout this file's name")
If you run the above code, it will generate a file like this:
In this code, we first store the datetime object that represents the current date and time, down to microsecond precision, in a now variable for reuse.
In the next step, we convert the datetime object into a compact, filesystem‑safe timestamp using the .strftime() method.
Then, for creating a file, we used pathlib’s mkdir(exist_ok=True) to avoid checking for existence manually.
Finally, write a file using the open() method with a context manager.
As shown in the above screenshot, we generated a .txt file with appended names.
Efficient One-liner
Just use the f-strings with inline datetime formatting:
filename = f"file_{datetime.now():%Y%m%d-%H%M%S}.txt"
Filename with Current Time
If you want to append a time while creating a file, you can use the f-string with datetime.now():%H-%M-%S expression.
from datetime import datetime
from pathlib import Path
# Appending current time
filename = f"data_{datetime.now():%H-%M-%S}.csv"
# Ensure output directory exists
Path("output").mkdir(exist_ok=True)
# Write to file
with open(Path("output") / filename, "w") as f:
f.write("Checkout this file's name")
High Precision (Milliseconds/Microseconds)
If your file generations are in millions, where milliseconds or microseconds matter, you can append microseconds for uniqueness, trimming to milliseconds if needed.
from datetime import datetime
from pathlib import Path
# Trim to milliseconds
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")[:-3]
# Appending current date and time with precision upto milliseconds
filename = f"log_{timestamp}.log"
# Ensure output directory exists
Path("output").mkdir(exist_ok=True)
# Write to file
with open(Path("output") / filename, "w") as f:
f.write("Checkout this file's name and log")
Hourly or Periodic Rotation
This type of naming convention is efficient when you need multiple files per day, such as hourly logs or sensor dumps every hour.
from datetime import datetime
from pathlib import Path
now = datetime.now()
hour_str = now.strftime("%Y%m%d_%H")
filename = f"sensor_data_{hour_str}.json"
# Ensure output directory exists
Path("output").mkdir(exist_ok=True)
# Write to file
with open(Path("output") / filename, "w") as f:
f.write("Checkout this file's name and log")
Unique filenames
If you want your file name to be highly unique, then you can combine timestamps with unique identifiers (UUIDs).
from uuid import uuid4
from datetime import datetime
from pathlib import Path
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
unique_id = uuid4().hex[:6] # Shorten UUID
filename = f"session_{timestamp}_{unique_id}.log"
# Ensure output directory exists
Path("output").mkdir(exist_ok=True)
# Write to file
with open(Path("output") / filename, "w") as f:
f.write("Checkout this file's name and log")
Timezone-Aware Filenames
Use zoneinfo (Python 3.9+) or pytz for timezone handling.
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo
tz = ZoneInfo("America/New_York")
now = datetime.now(tz)
filename = f"data_{now:%Y-%m-%d_%H-%M-%S_%Z}.py"
Path("output").mkdir(exist_ok=True)
# Write to file
with open(Path("output") / filename, "w") as f:
f.write("Checkout this file's name and log")
That’s all!








