How to create filename containing date/time in Python

In datalogging quiten often you have to create a new log file once you start to log data.

Often it’s convenient to include the current date and time in the log file.  In Python, this is pretty easy to do:

from datetime import datetime

filename = f"Temperature log-{ %H-%m-%d}.csv"

This will create filenames like

Temperature log 2020-06-17 22-37-41.csv
Temperature log 2019-12-31 00-15-55.csv

Note that if you use another Date/time format, you need to avoid special characters that must not occur in filenames. The rules for which filename is correct are much easier on Linux than on Windows, but since you should be compatible with both operating systems, you should always check the Windows rules.

These characters are forbidden for Windows filenames:


The date-time format we used above, %Y-%m-%d %H-%m-%d is specially crafted in order to avoid colons in ISO-8601-like date/time formats such as 2020-04-02 11:45:33 since colons would be illegal in Windows filenames (they would work in Linux filenames, though). %Y-%m-%d %H-%m-%d only contains spaces and dash (-) characters in order to avoid any issues with filename rules.