2014-12-21 18 views
7

Come assicurarsi che lo datetime.date.today() sia convertito in ora UTC?Come convertire datetime.date.today() in ora UTC?

Questo è il mio codice finora:

#today : 2014-12-21 
today = datetime.date.today() 

#1900-01-01 16:00:00+00:00 
timeformat = datetime.datetime.strptime('16:00', '%H:%M').replace(tzinfo=pytz.utc) 

#combine today and timeformat 2014-12-21 16:00:00 
now = datetime.datetime.combine(u, timeformat.time()) 
str_now = now.strftime("%Y-%m-%d %H:%M:%S") 

risposta

16

Uso utcnow:

today = datetime.datetime.utcnow().date() 
+0

non è corretto a meno di mezzanotte in ora locale ('date.today()') è la stessa istanza temporale della mezzanotte in UTC ('.utcnow(). Date()'). Vedi [Come ottengo l'ora UTC di "mezzanotte" per un determinato fuso orario?] (Http://stackoverflow.com/questions/373370/how-do-i-get-the-utc-time-of-midnight- per-a-date-timezone) – jfs

+0

Che cosa ha a che fare con la mezzanotte? Ottiene solo la data in cui UTC è in questo momento. – webjunkie

+0

@webjunkie: guarda il titolo della domanda, avviso: 'date.today()' lì. Restituisce la data nel fuso orario * local *. Quel valore cambia a mezzanotte nel fuso orario * locale *. A '23: 59: 59' è un giorno,' 00: 00: 00' è un altro. Stai seguendo? Quel momento: '00: 00' nel fuso orario locale corrisponde a * diverso * tempo UTC in base al fuso orario locale, ad esempio,' 2016-02-27 00: 00' a New York corrisponde a '2016-02-27 05:00 'UTC. Se il titolo della domanda fosse "qual è la data corrente in UTC adesso"; Sarei d'accordo con te. – jfs

-4

per data di stampa con il tempo si può usare ...

tomorrow = twtomorrow.strftime("%Y-%m-%d %H:%M:%S") 

invece di

tomorrow = twtomorrow.strftime("%Y-%m-%d") 
Problemi correlati