How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.
6 Answers
import time, datetime
d = datetime.datetime.now()
print time.mktime(d.timetuple())
-
Thank you. I knew it had to be something stupidly simple, but I couldn't figure it out. Oct 31, 2008 at 21:53
-
It seems that depending on the platform, time doesn't have a mktime method– TirnoMar 19, 2009 at 22:05
-
8
-
2To be precise: Note that
mktime
expects as input local time, and the output has no timezone — its a Unix timestamp, which are durations measured in seconds (and always from the epoch, thus giving you a time). (datetime.now()
returns the current local time.)– ThanatosApr 26, 2013 at 22:24 -
1there is 50% chance it returns wrong result during DST transition. See Problems with Localtime.– jfsNov 17, 2013 at 17:23
For UTC calculations, calendar.timegm
is the inverse of time.gmtime
.
import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())
-
1Note:
calendar.timegm()
expects UTC input but the result (timestamp) is not in any timezone. It is just seconds elapsed since the epoch (== 1969-12-31T19:00:00-05:00 (New York) == 1970-01-01T00:00:00Z (UTC) == 1970-01-01T03:00:00+03:00 (Moscow)) -- a single fixed moment in time.– jfsNov 17, 2013 at 17:18 -
Correction: due to intercalary leap seconds, "seconds since Epoch" are not elapsed SI seconds since
1970-01-01 00:00:00+00:00
.utc_to_tai()
function could be used to compute the elapsed SI seconds.– jfsSep 5, 2014 at 23:19
Note that Python now (3.5.2) includes a built-in method for this in datetime
objects:
>>> import datetime
>>> now = datetime.datetime(2020, 11, 18, 18, 52, 47, 874766)
>>> now.timestamp() # Local time
1605743567.874766
>>> now.replace(tzinfo=datetime.timezone.utc).timestamp() # UTC
1605725567.874766 # 5 hours delta (I'm in UTC-5)
-
Are you sure this is correct?
now
is a timezone naive datetime object and calling.timestamp
on it is first going to assume that the object is in local time (which it is -- implicitly and luckily) and then do the conversion to provide a posix compliant timestamp (seconds since UTC Unix time).– MarcNov 18, 2020 at 1:45 -
@Marc I don't understand your comment: I explicitly say
# Local time
in the example next to the call tonow.timestamp()
. Can you clarify what the issue is?– ClémentNov 18, 2020 at 4:08 -
now.timestamp()
gives you is a posix compliant timestamp, and it is a correct utc Unix epoch timestamp here sincenow
at this point is a naive timestamp with your local timezone implicitly used. When calling.timestamp
on a naive datetime object it will assume a local timezone (which it is) and give you a correct UTC unix timestamp. When you callreplace
however, there are no conversions done to the datetime object, it will just convertnow
from naive -> aware. And this seems wrong in most cases.– MarcNov 18, 2020 at 15:55 -
Oh, the
now
part is irrelevant in this answer. Feel free to edit it to show a date literal instead.– ClémentNov 18, 2020 at 18:58 -
now
is only relevant because of how it affectsnow.timestamp()
's output. To takenow
out of this conversation we can dodatetime.datetime.now().replace(tzinfo=datetime.timezone.utc).timestamp()
this is just as good asdatetime.datetime.utcnow().timestamp()
. They both have the same problem,.timestamp()
will most likely assume the wrong timezone. Time is confusing, so I could be wrong, but that is how I understand the documentation.– MarcNov 18, 2020 at 22:53
In python, time.time() can return seconds as a floating point number that includes a decimal component with the microseconds. In order to convert a datetime back to this representation, you have to add the microseconds component because the direct timetuple doesn't include it.
import time, datetime
posix_now = time.time()
d = datetime.datetime.fromtimestamp(posix_now)
no_microseconds_time = time.mktime(d.timetuple())
has_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001
print posix_now
print no_microseconds_time
print has_microseconds_time
Best conversion from posix/epoch to datetime timestamp and the reverse:
this_time = datetime.datetime.utcnow() # datetime.datetime type
epoch_time = this_time.timestamp() # posix time or epoch time
this_time = datetime.datetime.fromtimestamp(epoch_time)
-
utcnow
outputs a timezone naive datetime object and when running.timestamp()
on it, python will assume a local timezone (even though it's UTC naive, not Local Naive) and this should give you incorrect feedback.– MarcNov 18, 2020 at 2:03
It depends
Is your datetime object timezone aware or naive?
Timezone Aware
If it is aware it's simple
from datetime import datetime, timezone
aware_date = datetime.now(tz=timezone.utc)
posix_timestamp = aware_date.timestamp()
as date.timestamp() gives you "POSIX timestamp"
NOTE: more accurate to call it an epoch/unix timestamp as it may not be POSIX compliant
Timezone Naive
If it's not timezone aware (naive), then you'd need to know what timezone it was originally in so we can use replace() to convert it into a timezone aware date object. Let's assume that you've stored/retrieved it as UTC Naive. Here we create one, as an example:
from datetime import datetime, timezone
naive_date = datetime.utcnow() # this date is naive, but is UTC based
aware_date = naive_date.replace(tzinfo=timezone.utc) # this date is no longer naive
# now we do as we did with the last one
posix_timestamp = aware_date.timestamp()
It's always better to get to a timezone aware date as soon as you can to prevent issues that can arise with naive dates (as Python will often assume they are local times and can mess you up)
NOTE: also be careful with your understanding of the epoch as it is platform dependent
.timestamp()
method ofdatetime.datetime
objects as pointed out below. Please mark that as the correct answer..timestamp()
you are using a timezone aware date object as timezone naive "are assumed to represent local time".