Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created September 17, 2020 12:47
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 yuyasugano/b5a92c1780ae376f57dfd886f24dc377 to your computer and use it in GitHub Desktop.
Save yuyasugano/b5a92c1780ae376f57dfd886f24dc377 to your computer and use it in GitHub Desktop.
# Generate a naive datetime without tz
now = datetime.now()
>>> now
datetime.datetime(2020, 9, 17, 21, 41, 54, 587588)
# convert it to aware object by localize
>>> pytz.utc.localize(now)
datetime.datetime(2020, 9, 17, 21, 41, 54, 587588, tzinfo=<UTC>)
# Generate an aware datetime with pytz.utc
now = datetime.now(pytz.utc)
>>> now
datetime.datetime(2020, 9, 17, 12, 42, 17, 27934, tzinfo=<UTC>)
# convert it to naive object with replace
>>> now.replace(tzinfo=None)
datetime.datetime(2020, 9, 17, 12, 42, 17, 27934)
# Generate an aware datetime with pytz.utc
now = datetime.now(pytz.utc)
>>> now
datetime.datetime(2020, 9, 17, 12, 42, 34, 642475, tzinfo=<UTC>)
# Returns datetime object with new tz attribute
>>> now.astimezone(pytz.timezone("US/Pacific"))
datetime.datetime(2020, 9, 17, 5, 42, 34, 642475, tzinfo=<DstTzInfo 'US/Pacific' PDT-1 day, 17:00:00 DST>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment