Created
November 23, 2022 20:23
-
-
Save sethrh/e91ba9eb49d58efb8f46bbb1567fc76d to your computer and use it in GitHub Desktop.
Get the current time with timezone-aware datetime objects. These are two utility functions to get the current time in a timezone-aware datetime in UTC or the local timezone. Python 3.9+ has finally started to get smarter about timezones. BUT, it's still a fairly arcane process to get the current time with a timezone.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
def utcnow(): | |
"""Return a timezone-aware now, in UTC. | |
""" | |
return datetime.datetime.now(datetime.timezone.utc) | |
def tznow(): | |
"""Return a timezone-aware now, in the local timezone. | |
""" | |
return datetime.datetime.now(datetime.datetime.now().astimezone().tzinfo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment