Se d = date(2011, 1, 1)è in UTC:
>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)
Se dè nel fuso orario locale:
>>> import time
>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011, 1, 1, 0, 0)
timestamp1e timestamp2può differire se la mezzanotte nel fuso orario locale non è la stessa istanza della mezzanotte in UTC.
mktime()può restituire un risultato errato se dcorrisponde a un orario locale ambiguo (ad esempio, durante la transizione dell'ora legale) o se dè una data passata (futura) in cui l'offset utc potrebbe essere stato diverso e la C mktime()non ha accesso al database tz sulla piattaforma data . È possibile utilizzare il pytzmodulo (ad es. Via tzlocal.get_localzone()) per ottenere l'accesso al database tz su tutte le piattaforme . Inoltre, utcfromtimestamp()potrebbe non riuscire e mktime()potrebbe restituire un timestamp non POSIX se "right"si utilizza il fuso orario .
Per convertire un datetime.dateoggetto che rappresenta la data in UTC senza calendar.timegm():
DAY = 24*60*60 # POSIX day in seconds (exact value)
timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY
timestamp = (utc_date - date(1970, 1, 1)).days * DAY
Come posso ottenere una data convertita in secondi dall'epoca secondo UTC?
Per convertire datetime.datetime(non datetime.date) un oggetto che rappresenta già l'ora in UTC nel corrispondente timestamp POSIX (a float).
Python 3.3+
datetime.timestamp():
from datetime import timezone
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
Nota: è necessario fornire timezone.utcesplicitamente altrimenti .timestamp()presupporre che l'oggetto datetime ingenuo sia nel fuso orario locale.
Python 3 (<3.3)
Dai documenti per datetime.utcfromtimestamp():
Non esiste un metodo per ottenere il timestamp da un'istanza datetime, ma il timestamp POSIX corrispondente a un'istanza datetime dt può essere facilmente calcolato come segue. Per un ingenuo dt:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
E per un dt consapevole:
timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)
Lettura interessante: tempo di epoca vs. ora del giorno sulla differenza tra che ora è? e quanti secondi sono trascorsi?
Vedi anche: datetime ha bisogno di un metodo "epoca"
Python 2
Per adattare il codice sopra per Python 2:
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
dove timedelta.total_seconds()equivale a (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6calcolato con vera divisione abilitata.
from __future__ import division
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
# return td.total_seconds()
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6
now = datetime.utcnow()
print now
print totimestamp(now)
Attenzione ai problemi in virgola mobile .
Produzione
2012-01-08 15:34:10.022403
1326036850.02
Come convertire un datetimeoggetto consapevole nel timestamp POSIX
assert dt.tzinfo is not None and dt.utcoffset() is not None
timestamp = dt.timestamp() # Python 3.3+
Su Python 3:
from datetime import datetime, timedelta, timezone
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
timestamp = (dt - epoch) / timedelta(seconds=1)
integer_timestamp = (dt - epoch) // timedelta(seconds=1)
Su Python 2:
# utc time = local time - utc offset
utc_naive = dt.replace(tzinfo=None) - dt.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()