I am dealing with dates in Python and I need to convert them to UTC timestamps to be used inside Javascript. The following code does not work:
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)
Converting the date object first to datetime also does not help. I tried the example at this link from, but:
from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)
and now either:
mktime(utc.localize(input_date).utctimetuple())
or
mktime(timezone('US/Eastern').localize(input_date).utctimetuple())
does work.
So general question: how can I get a date converted to seconds since epoch according to UTC?
If d = date(2011, 1, 1)
is in UTC:
>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)
If d
is in local timezone:
>>> import time
>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011, 1, 1, 0, 0)
timestamp1
and timestamp2
may differ if midnight in the local timezone is not the same time instance as midnight in UTC.
mktime()
may return a wrong result if d
corresponds to an ambiguous local time (e.g., during DST transition) or if d
is a past(future) date when the utc offset might have been different and the C mktime()
has no access to the tz database on the given platform. You could use pytz
module (e.g., via tzlocal.get_localzone()
) to get access to the tz database on all platforms. Also, utcfromtimestamp()
may fail and mktime()
may return non-POSIX timestamp if "right"
timezone is used.
To convert datetime.date
object that represents date in UTC without 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
To convert datetime.datetime
(not datetime.date
) object that already represents time in UTC to the corresponding POSIX timestamp (a float
).
from datetime import timezone
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
Note: It is necessary to supply timezone.utc
explicitly otherwise .timestamp()
assume that your naive datetime object is in local timezone.
From the docs for datetime.utcfromtimestamp()
:
There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
And for an aware dt:
timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)
Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed?
See also: datetime needs an "epoch" method
To adapt the above code for Python 2:
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
where timedelta.total_seconds()
is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
computed with true division enabled.
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)
Beware of floating-point issues.
2012-01-08 15:34:10.022403
1326036850.02
datetime
object to POSIX timestampassert dt.tzinfo is not None and dt.utcoffset() is not None
timestamp = dt.timestamp() # Python 3.3+
On 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)
On 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()