Skip to content

Instantly share code, notes, and snippets.

@nenetto
Created September 26, 2023 10:24
Show Gist options
  • Save nenetto/67759dafe222e4339d84f3f57a78cea7 to your computer and use it in GitHub Desktop.
Save nenetto/67759dafe222e4339d84f3f57a78cea7 to your computer and use it in GitHub Desktop.
Datetime and zone conversions
from datetime import datetime, timezone
# Conversion to computer local time
now = datetime(2014, 8, 10, 18, 18, 30)
now_utc = now.replace(tzinfo=timezone.utc)
now_local = now_utc.astimezone()
print(now_local)
# Conversion local to Unix timestamp in UTC
time_str = '2014-08-10 11:18:30'
now = datetime.strptime(time_str, time_format)
time_tuple = now.timetuple()
utc_now = mktime(time_tuple)
print(utc_now)
# Conversion a NYC time to UTC datetime
arrival_nyc = ‘2014-05-01 23:33:24’
nyc_dt_naive = datetime.strptime(arrival_nyc, time_format)
eastern = pytz.timezone(‘US/Eastern’)
nyc_dt = eastern.localize(nyc_dt_naive)
utc_dt = pytz.utc.normalize(nyc_dt.astimezone(pytz.utc))
print(utc_dt)
# Conversion UTC to San Francisco loca time
pacific = pytz.timezone(‘US/Pacific’)
sf_dt = pacific.normalize(utc_dt.astimezone(pacific))
print(sf_dt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment