How to generate filename with date & time in Python
When storing real-time data from a Python script, it is often helpful to have a timestamp consisting of both date & time in your filename, such as
generate_datetime_filename_example.txt
mydata-2022-09-02_00-31-50-613015.csvWith this specific syntax we avoid special characters which are an issue on Windows operating systems, and we provide a lexically sortable filename
In Python you can do that using UliEngineering.Utils.generate_datetime_filename() from the UliEngineering library.
First, install UliEngineering.
Now you can generate your filename using
example_use_generate_datetime_filename.py
from UliEngineering.Utils.Date import *
filename = generate_datetime_filename()
# example: filename == 'data-2022-09-02_03-02-00-045587.csv'or you can just open the file using with open():
open_generate_datetime_filename_write.py
with open(generate_datetime_filename(), "w") as outfile:
# Example of what you can do with outfile
outfile.write("test")Without using UliEngineering
You can use this simplified version which does not support fractional seconds and will generate filenames like
generate_datetime_filename_simple_example.txt
data-2022-09-02_00-31-50.csvSource code (simple version - the UliEngineering version is more robust and supports more features):
generate_datetime_filename_simple.py
from datetime import datetime
def generate_datetime_filename(label="data", extension="csv", dt=None):
if dt is None:
dt = datetime.now()
return f"{label}-{dt.year}-{dt.month:02d}-{dt.day:02d}_{dt.hour:02d}-{dt.minute:02d}-{dt.second:02d}.{extension}"Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow