Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Last active February 13, 2024 19:22
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 kgriffs/0321be9e627bf42a6dae31028a2523e3 to your computer and use it in GitHub Desktop.
Save kgriffs/0321be9e627bf42a6dae31028a2523e3 to your computer and use it in GitHub Desktop.
Python TZ Aware datetime and DST Conversion Example
import datetime
import pytz
tz_ny = pytz.timezone('America/New_York')
dt_aware_dst_active = tz_ny.localize(datetime.datetime(2023, 5, 1, 12, 0))
dt_aware_dst_inactive = tz_ny.localize(datetime.datetime(2023, 12, 1, 12, 0))
print("Original DST Active Offset (America/New_York):", dt_aware_dst_active.dst())
print("Original DST Active (America/New_York):", dt_aware_dst_active)
print("To UTC, DST Active (America/New_York):", dt_aware_dst_active.astimezone(pytz.utc))
print("Roundtrip, DST Active (America/New_York):", dt_aware_dst_active.astimezone(pytz.utc).astimezone(tz_ny))
print()
print("Original DST Inactive Offset (America/New_York):", dt_aware_dst_inactive.dst())
print("Original DST Inactive (America/New_York):", dt_aware_dst_inactive)
print("To UTC, DST Inactive (America/New_York):", dt_aware_dst_inactive.astimezone(pytz.utc))
print("Roundtrip, DST Inactive (America/New_York):", dt_aware_dst_inactive.astimezone(pytz.utc).astimezone(tz_ny))
@kgriffs
Copy link
Author

kgriffs commented Feb 13, 2024

Output:

Original DST Active Offset (America/New_York): 1:00:00
Original DST Active (America/New_York): 2023-05-01 12:00:00-04:00
To UTC, DST Active (America/New_York): 2023-05-01 16:00:00+00:00
Roundtrip, DST Active (America/New_York): 2023-05-01 12:00:00-04:00

Original DST Inactive Offset (America/New_York): 0:00:00
Original DST Inactive (America/New_York): 2023-12-01 12:00:00-05:00
To UTC, DST Inactive (America/New_York): 2023-12-01 17:00:00+00:00
Roundtrip, DST Inactive (America/New_York): 2023-12-01 12:00:00-05:00

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment