I use this function datetime_to_local_timezone()
, which seems overly convoluted but I found no simpler version of a function that converts a datetime
instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:
import time, datetime
def datetime_to_local_timezone(dt):
epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
st_time = time.localtime(epoch) # Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.
return dt.astimezone(tz) # Move the datetime instance to the new time zone.
utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect
print(dt1)
print(datetime_to_local_timezone(dt1))
print(dt2)
print(datetime_to_local_timezone(dt2))
This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:
2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00
2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00
astimezone()
, e.g.datetime.datetime(2010, 4, 27, 12, 0, 0, 0).astimezone().isoformat()
->'2010-04-27T12:00:00+02:00'