Python Date and Time

If there is something that can go wrong in programming, it is date and time. If you are using time, think, and do it right first time. It is amazing how many projects end up in an uncomfortable situation because time-zones or daylight saving or ambiguous time causes hard to reverse issues because copious amounts of data has the wrong time.

At Direkt EmbeddedTM we recommend a few simple rules with date and time.

Always save time in UTC

Always send time in UTC, or an ISO format including the Time Zone

Always print time in UTC, or an ISO format including the Time Zone

If you must use local time only do so on a UI, and always include a timezone somewhere, just to be clear!



Here are some recommended Python® snippets for date and time using the base installation (no libraries).

Date Time in ISO UTC

from datetime import datetime, timezone

now = datetime.now(timezone.utc)

# Always use timezone.utc to ensure isoformat returns +00:00.
print(now.isoformat())

2021-08-13T04:53:23.588839+00:00

Getting your timezone

zone = datetime.now(timezone.utc).astimezone().tzinfo
print(zone)
AEST

Date Formatted File Names

For logging, you want a reverse date, similar to ISO format, but without colons. The following format is pretty common. Add the Z at the end to indicate UTC time. Z if for zulu, aka UTC. It is not very common, but common enough and short and clear.

utc_str = now.strftime("%Y%m%dT%H%M%SZ")
app = "my-app"
file_name = f"{utc_str}-{app}.log"
print(file_name)

20210813T051726Z-my-app.log

Note: f formatted strings are dependent on python 3.6


Python ® is a registered trademark of the Python Software Foundation.