306

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. Commented 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. Commented 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" Commented 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/… Commented Feb 26, 2014 at 16:19
  • @TimTisdall yes since the title is changed it makes no sense Commented 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).

Sign up to request clarification or add additional context in comments.

11 Comments

Thanks D.Shawley. help(datetime.timedelta) didn't mention that shortcut. It only had days, seconds, and microseconds.
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.
Can't upvote @tumbleweed's comment enough. If you're trying to get a UNIX timestamp (and therefore one in UTC), use calendar.timegm.
@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
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).
|
166

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 Comments

+1 for this. It should be displayed much higher, because it's the clean way how to do that in Python 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.
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.
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.
@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.
|
145

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 Comments

This doesn't answer the question.
@JesseDhillon it answers the question (make a UNIX timestamp 5 mins in future), just not the title.
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.
@j-f-sebastian time.monotonic() does not return a UNIX timestamp, it returns a timestamp with an undefined reference point.
@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.
|
57

This is what you need:

import time
import datetime
n = datetime.datetime.now()
unix_time = time.mktime(n.timetuple())

5 Comments

How is this different or adds to the one 'Cat Plus Plus' provided?
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: 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.
@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?
@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.
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 Comments

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).
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
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.

Comments

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

Comments

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 Comment

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)
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 Comment

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

Comments

1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.