Skip to content

Instantly share code, notes, and snippets.

@sethrh
Created November 23, 2022 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethrh/e91ba9eb49d58efb8f46bbb1567fc76d to your computer and use it in GitHub Desktop.
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.
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