datetime in local time zone

ruff and flake8 consider that it is a mistake to ever use "naive" datetime objects.

However, this leaves no "obvious" way to do something like convert between local and UTC time using the datetime module!

I was not able to find a way in standard Python, but I was able to find it in dateutil (based on some stackoverflow where the top answer was a wrong answer, purposely not linked)

So: Use dateutil.tz.gettz() to get a timezone object that reflects the system's local time zone. This will pass ruff's checks.

>>> localtime = dateutil.tz.gettz()
>>> localnow
datetime.datetime(2024, 7, 8, 21, 33, 51, 897086, tzinfo=tzfile('/etc/localtime'))
>>> localnow.astimezone(datetime.timezone.utc)
datetime.datetime(2024, 7, 9, 2, 33, 51, 897086, tzinfo=datetime.timezone.utc)

You can also use a piece of code from the documentation called LocalTimeZone that makes a best effort to implement the local system time zone based on the items available in the "time" module. This has caveats, such as not working properly when a zone historically had different offsets than it does today, and you can't pip install it, you have to copy & paste it.

Entry first conceived on 9 July 2024, 2:33 UTC, last modified on 9 July 2024, 2:44 UTC
Website Copyright © 2004-2024 Jeff Epler