Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

Creating a Filename Containing Date or Time in Python

  • 21 Apr, 2025
  • Com 0
How to Create a File name Containing Date or Time

The most efficient way to create a filename containing date or time, use f-strings (Python 3.6+) with datetime.now() and .strftime() methods. Here, we are talking about the current date or time.

For embedding a formatted date and time into a string, you can always use f-strings for a concise and readable format.

Filename without and with date and time in Python

In the above figure, the left-side file has a name without a date and time, and on the right side, the filename includes a date and time.

There are tasks that 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:

Empty output directory

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:

Filename with current date and time

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. 

You can see in the above screenshot that 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 just 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")

Filename with current time in Python

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")

Appending datetime with precision in filename

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")

Hourly or Periodic Rotation

Unique filenames

If you want your file name to be extremely 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")

Generating unique filenames with timestamp and UUID in Python

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")

Timezone-Aware Filenames while creating a file in Python

That’s all!

Post Views: 24
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to a Read Binary File in Different Ways in Python
How to Read Text File into List in Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend