Skip to content

Instantly share code, notes, and snippets.

@gwsu2008
Created September 19, 2019 22:33
Show Gist options
  • Save gwsu2008/940be99cf7af0c1c48b2ec2c6d085e99 to your computer and use it in GitHub Desktop.
Save gwsu2008/940be99cf7af0c1c48b2ec2c6d085e99 to your computer and use it in GitHub Desktop.
python_convert_utc_to_local
from datetime import datetime
from dateutil import tz
# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')
# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment