www.rodneybeede.com "I would love to change the world, but they won't give me the source code" - unknown
 Navigation

Python3 and getting datetime with tz_info timezone info - Last Modified 2018-04-12 15:55 UTC - Created 2018-04-12 15:54 UTC

When using something like datetime.datetime.now().isoformat() you would expect to get the timezone on the end or a trailing Z.

However both the .now() and .utcnow() only return naive objects with tz_info of None

If you don't want to use 3rd party libraries (solution for longest time until Python 3.2+) you can use the following tricks:

LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo

enhanced_now = datetime.datetime.now(LOCAL_TIMEZONE)


enhanced_now_utc = datetime.datetime.now(datetime.timezone.utc)

Credits

Python: Figure out local timezone ; Stackoverflow.com; vbem; August 22, 2016

Misc Refs

https://bugs.python.org/issue23332