305

I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack.

def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    epoch = datetime.datetime(1970, 1, 1)
    seconds_in_a_day = 60 * 60 * 24
    five_minutes = datetime.timedelta(seconds=5*60)
    five_minutes_from_now = datetime.datetime.now() + five_minutes
    since_epoch = five_minutes_from_now - epoch
    return since_epoch.days * seconds_in_a_day + since_epoch.seconds

Is there a module or function that does the timestamp conversion for me?

5
  • 7
    I recommend changing the subject of this question. The question is good, but it is not about converting datetime to Unix timestamp. It is about how to get a Unix timestamp 5 minutes in the future.
    – D. A.
    May 21, 2013 at 18:10
  • I disagree, @D.A. The question essentially says "I need to do X and Y. Here's what I have now. What's a better way to do Y?" Maybe there are better ways to do X, but the title and the body clearly ask about Y. Jun 22, 2013 at 12:40
  • 6
    I agree with you completely on the question, and I think it a good one with a good answer. The problem is "Python datetime to Unix timestamp" doesn't reflect either the question or answer. I found this post searching for a way to do the conversion, and I lost time because of the misleading subject line. I suggest: "Python, 5 minutes in the future as UNIX Timestamp"
    – D. A.
    Jul 31, 2013 at 21:57
  • 3
    @JimmyKane - A pretty comprehensive answer on how to get a timestamp from a date time can be found here: stackoverflow.com/questions/8777753/… Feb 26, 2014 at 16:19
  • @TimTisdall yes since the title is changed it makes no sense
    – Jimmy Kane
    Feb 27, 2014 at 20:12

12 Answers 12

355

Another way is to use calendar.timegm:

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return calendar.timegm(future.timetuple())

It's also more portable than %s flag to strftime (which doesn't work on Windows).

11
  • Thanks D.Shawley. help(datetime.timedelta) didn't mention that shortcut. It only had days, seconds, and microseconds. May 5, 2010 at 19:05
  • 12
    Note that, combining the previous two comments, the right solution is: calendar.timegm(future.utctimetuple()). This ensures that a UTC time is passed into calendar.timegm. Jan 31, 2013 at 4:28
  • 1
    Can't upvote @tumbleweed's comment enough. If you're trying to get a UNIX timestamp (and therefore one in UTC), use calendar.timegm.
    – Bialecki
    Feb 20, 2013 at 20:58
  • @tumbleweed, right. If you use mktime plus gmtime(0) will result in nonzero roundtrip delta for any time zone besides UTC: e.g. ` time.mktime(datetime.fromtimestamp(time.mktime(time.gmtime(0))).timetuple())` gives 21600.0 seconds (6 hours) instead of 0.0 for my unix machine's TZ
    – hobs
    Nov 5, 2013 at 23:55
  • If you want to get UTC timestamp you should use this: calendar.timegm(datetime.datetime.utcnow().timetuple()). Method using datetime.datetime.now().utctimetuple() doesn't work for me (Python 3.2).
    – Wookie88
    Dec 28, 2013 at 15:21
165

Now in Python >= 3.3 you can just call the timestamp() method to get the timestamp as a float.

import datetime
current_time = datetime.datetime.now(datetime.timezone.utc)
unix_timestamp = current_time.timestamp() # works if Python >= 3.3

unix_timestamp_plus_5_min = unix_timestamp + (5 * 60)  # 5 min * 60 seconds
10
  • 5
    +1 for this. It should be displayed much higher, because it's the clean way how to do that in Python 3 May 21, 2013 at 20:28
  • 3
    @scott654 I thought having it right at the beginning of the comment made it clear enough, but I added some bold to it too. Oct 1, 2013 at 13:16
  • 1
    I'd make the note as a comment in the code block because we all just scan the code in the answers first and only read the rest if the code looks good. Good answer though. Oct 4, 2013 at 17:21
  • 2
    local time may be ambigous. The example (datetime.now()) is bad because it encourages the usage of naive datetime objects that represent local time and it might fail during DST transitions (due to the inherent ambiguity). You could use ts = datetime.now(timezone.utc).timestamp() instead.
    – jfs
    Nov 17, 2013 at 18:19
  • @J.F.Sebastian - good point. I didn't want to add to the imports, though, so I changed it to utcnow(). I'm used to working on machines where the timezone is set to UTC, but that shouldn't be assumed in this code snippet. Nov 18, 2013 at 14:01
146

Just found this, and its even shorter.

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)
6
  • 12
    This doesn't answer the question. Apr 6, 2012 at 3:30
  • 24
    @JesseDhillon it answers the question (make a UNIX timestamp 5 mins in future), just not the title.
    – dbr
    Jul 7, 2012 at 13:56
  • 3
    time.time() can be set back. To create an "Expires" value 5 minutes in the future you might need time.monotonic() analog depending on your use-case.
    – jfs
    Aug 14, 2012 at 15:00
  • @j-f-sebastian time.monotonic() does not return a UNIX timestamp, it returns a timestamp with an undefined reference point.
    – rspeer
    Jun 3, 2013 at 22:34
  • @rspeer: yes, as the docs say, only the difference between consecutive calls is valid. Whether monotonic can be used depends on your use-case e.g., subprocess module does use it to implement timeout option.
    – jfs
    Jun 15, 2013 at 7:31
57

This is what you need:

import time
import datetime
n = datetime.datetime.now()
unix_time = time.mktime(n.timetuple())
5
  • How is this different or adds to the one 'Cat Plus Plus' provided?
    – David
    Apr 30, 2013 at 19:19
  • 3
    E.G. this is the answer to the question "Python datetime to Unix timestamp" while Cat Plus Plus answered the question "Python datetime that will be in 5 minutes to Unix timestamp". So this one is clean and obvious.
    – running.t
    Jun 25, 2013 at 17:45
  • @running.t: it reminds me: "every problem has simple, obvious and wrong solution". See possible issues with mktime(dt.timetuple()). datetime.now(timezone.utc).timestamp() provided by @Tim Tisdall is the solution in Python 3.3+. Otherwise (dt - epoch).total_seconds() could be used.
    – jfs
    Dec 11, 2013 at 3:28
  • @J.F.Sebastian what if I really do want all computation to take place in local time? Is it the case when eg. to parse a naive string that one knows is localtime and decide whether there was DST in effect in that particular time?
    – n611x007
    May 8, 2014 at 13:35
  • 1
    @naxa: yes, some local times are ambiguous or non-existent. Also timezone offset may be different for reasons other than DST (you need a tz database such as pytz, to find out the correct offset). Local time means whatever local politician thinks is a good idea to measure time I.e., it may be highly irregular.
    – jfs
    May 8, 2014 at 13:45
49

You can use datetime.strftime to get the time in Epoch form, using the %s format string:

def expires():
    future = datetime.datetime.now() + datetime.timedelta(seconds=5*60)
    return int(future.strftime("%s"))

Note: This only works under linux, and this method doesn't work with timezones.

2
  • 32
    This is a somewhat undocumented behaviour ( python.org/doc/current/library/datetime.html ). Seems to be working under linux and not working under win32 (generating ValueError: Invalid format string). Dec 25, 2010 at 21:23
  • 3
    This method doesn't work with timezones. Changing timezone will give the same result datetime(2013,12,7,tzinfo=timezone("America/Chicago")).strftime("%s") 1386385200 datetime(2013,12,7,tzinfo=timezone("Europe/Riga")).strftime("%s") 1386385200 Dec 9, 2013 at 13:58
11

Here's a less broken datetime-based solution to convert from datetime object to posix timestamp:

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return (future - datetime.datetime(1970, 1, 1)).total_seconds()

See more details at Converting datetime.date to UTC timestamp in Python.

6
def in_unix(input):
  start = datetime.datetime(year=1970,month=1,day=1)
  diff = input - start
  return diff.total_seconds()
0
4

The key is to ensure all the dates you are using are in the utc timezone before you start converting. See http://pytz.sourceforge.net/ to learn how to do that properly. By normalizing to utc, you eliminate the ambiguity of daylight savings transitions. Then you can safely use timedelta to calculate distance from the unix epoch, and then convert to seconds or milliseconds.

Note that the resulting unix timestamp is itself in the UTC timezone. If you wish to see the timestamp in a localized timezone, you will need to make another conversion.

Also note that this will only work for dates after 1970.

   import datetime
   import pytz

   UNIX_EPOCH = datetime.datetime(1970, 1, 1, 0, 0, tzinfo = pytz.utc)
   def EPOCH(utc_datetime):
      delta = utc_datetime - UNIX_EPOCH
      seconds = delta.total_seconds()
      ms = seconds * 1000
      return ms
1
  • 3
    note: I don't understand "the [unix] timestamp in a localized timezone". The timestamp is the same (elapsed seconds since 1970-01-01 00:00:00+00:00). To get a naive datetime object in local timezone: datetime.fromtimestamp(ts)
    – jfs
    Aug 14, 2012 at 9:37
4

The following is based on the answers above (plus a correction for the milliseconds) and emulates datetime.timestamp() for Python 3 before 3.3 when timezones are used.

def datetime_timestamp(datetime):
    '''
    Equivalent to datetime.timestamp() for pre-3.3
    '''
    try:
        return datetime.timestamp()
    except AttributeError:
        utc_datetime = datetime.astimezone(utc)
        return timegm(utc_datetime.timetuple()) + utc_datetime.microsecond / 1e6

To strictly answer the question as asked, you'd want:

datetime_timestamp(my_datetime) + 5 * 60

datetime_timestamp is part of simple-date. But if you were using that package you'd probably type:

SimpleDate(my_datetime).timestamp + 5 * 60

which handles many more formats / types for my_datetime.

1
  • shouldn't you add (5 * 60) to add 5 minutes? I think just adding 5 adds only 5 seconds to the timestamp. Aug 7, 2013 at 15:32
1
def expiration_time():
    import datetime,calendar
    timestamp = calendar.timegm(datetime.datetime.now().timetuple())
    returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
    return returnValue
1

Note that solutions with timedelta.total_seconds() work on python-2.7+. Use calendar.timegm(future.utctimetuple()) for lower versions of Python.

0

How about this method using built-in timestamp function? The snippet is working for different time (not just current time).

import datetime

a = "2017-01-01 14:30:00"
b = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
c = int(b.timestamp()/60.0)
alarm_time = c + 5

Runtime environment   OS: Ubuntu 16.04   Python 3.6

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.