Я использую эту функцию datetime_to_local_timezone()
, которая кажется чрезмерно запутанной, но я не нашел более простой версии функции, которая преобразует экземпляр datetime
в местный часовой пояс, как настроено в операционной системе , со смещением UTC, действовавшим в то время :
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))
В этом примере печатаются четыре даты. Для двух моментов времени, по одному в январе и по одному в июле 2009 года, каждый печатает метку времени один раз в UTC и один раз в местном часовом поясе. Здесь, когда CET (UTC + 01: 00) используется зимой, а CEST (UTC + 02: 00) используется летом, он печатает следующее:
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