Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

9 Answers

Another way is to use time.mktime:

future = datetime.datetime.now() + datetime.timedelta(minutes=5)
return time.mktime(future.timetuple())

It's also more portable than %s flag to strftime — latter is not supported on win32.

share|improve this answer
9  
You beat me by a few moments. Why not datetime.timedelta(minutes=5) instead? – D.Shawley May 5 '10 at 19:02
3  
Bah, I'm never sure what arguments timedelta actually takes. Edited. – Cat Plus Plus May 5 '10 at 19:04
14  
It's worth noting that this doesn't take microseconds into account, which is included in Python's normal UNIX time representation (ie, time.time()). You'd need to add the datetime.microsecond / 1000000. to the result of time.mktime(). – Joe Shaw Nov 23 '11 at 21:40
18  
Note that time.mktime assumes the timetuple is local, not UTC. If is UTC, use calendar.timegm – tumbleweed Dec 17 '11 at 23:58
5  
.timetuple() sets DST flag to -1 so there is 50% chance your code introduces an one hour error during a daylight-savings-time transition. See Problems with Localtime. – J.F. Sebastian Aug 14 '12 at 14:49
show 3 more comments
up vote 69 down vote accepted

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)
share|improve this answer
8  
This doesn't answer the question. – Jesse Dhillon Apr 6 '12 at 3:30
10  
@JesseDhillon it answers the question (make a UNIX timestamp 5 mins in future), just not the title. – dbr Jul 7 '12 at 13:56
2  
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 Aug 14 '12 at 15:00

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"))
share|improve this answer
20  
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). – Antony Hatchkins Dec 25 '10 at 21:23

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
share|improve this answer
1  
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) – J.F. Sebastian Aug 14 '12 at 9:37

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.

share|improve this answer
def in_unix(input):
  start = datetime.datetime(year=1970,month=1,day=1)
  diff = input - start
  return diff.total_seconds()
share|improve this answer

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()
unix_timestamp = current_time.timestamp()
share|improve this answer
def expiration_time():
    import datetime,calendar
    timestamp = calendar.timegm(datetime.datetime.now().timetuple())
    returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
    return returnValue
share|improve this answer

This is what you need:

import time
import datetime
n = datetime.datetime.now()
unix_time = time.mktime(n.timetuple())
share|improve this answer
How is this different or adds to the one 'Cat Plus Plus' provided? – David Apr 30 at 19:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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