Io uso questa funzione datetime_to_local_timezone()
, che sembra eccessivamente contorto ma non ho trovato nessuna versione più semplice di una funzione che converte un'istanza datetime
per il fuso orario locale, come configurato nel sistema operativo , con l'UTC compensato che era in vigore in quel momento :
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))
Questo esempio stampa quattro date. Per due momenti nel tempo, uno a gennaio e uno a luglio 2009, ciascuno stampa il timestamp una volta in UTC e una volta nel fuso orario locale.Qui, dove CET (GMT + 01: 00) è utilizzato nel CEST inverno e (GMT + 02: 00) è utilizzato nel periodo estivo, si stampa il seguente:
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
locale per cosa? –
correlati: [Come convertire un python utc datetime in un datetime locale utilizzando solo la libreria standard python?] (Http://stackoverflow.com/a/13287083/4279) – jfs