56

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.

2
  • 2
    The answers to this question are no longer up to date. You should use the .timestamp() method of datetime.datetime objects as pointed out below. Please mark that as the correct answer. Dec 16, 2018 at 21:29
  • Also make sure that when you call .timestamp() you are using a timezone aware date object as timezone naive "are assumed to represent local time".
    – Marc
    Nov 18, 2020 at 2:25

6 Answers 6

64
import time, datetime

d = datetime.datetime.now()
print time.mktime(d.timetuple())
7
  • 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
    – Tirno
    Mar 19, 2009 at 22:05
  • 8
    Note this gives local time, not UTC. For UTC see fixermark's answer. Nov 23, 2011 at 23:44
  • 2
    To 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.)
    – Thanatos
    Apr 26, 2013 at 22:24
  • 1
    there is 50% chance it returns wrong result during DST transition. See Problems with Localtime.
    – jfs
    Nov 17, 2013 at 17:23
23

For UTC calculations, calendar.timegm is the inverse of time.gmtime.

import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())
2
  • 1
    Note: 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.
    – jfs
    Nov 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.
    – jfs
    Sep 5, 2014 at 23:19
12

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)
8
  • 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).
    – Marc
    Nov 18, 2020 at 1:45
  • @Marc I don't understand your comment: I explicitly say # Local time in the example next to the call to now.timestamp(). Can you clarify what the issue is?
    – Clément
    Nov 18, 2020 at 4:08
  • now.timestamp() gives you is a posix compliant timestamp, and it is a correct utc Unix epoch timestamp here since now 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 call replace however, there are no conversions done to the datetime object, it will just convert now from naive -> aware. And this seems wrong in most cases.
    – Marc
    Nov 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ément
    Nov 18, 2020 at 18:58
  • now is only relevant because of how it affects now.timestamp()'s output. To take now out of this conversation we can do datetime.datetime.now().replace(tzinfo=datetime.timezone.utc).timestamp() this is just as good as datetime.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.
    – Marc
    Nov 18, 2020 at 22:53
4

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
1
  • don't use local time for a round-trip (ts -> local -> ts). It might break during DST transitions. You could easily extend timegm() to include microseconds and use it for ts -> utc -> ts transformations.
    – jfs
    Nov 18, 2013 at 0:21
0

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)
1
  • 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.
    – Marc
    Nov 18, 2020 at 2:03
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.