views:

1243

answers:

3

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?

+4  A: 

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"))
mipadi
+8  A: 

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.

PiotrLegnica
You beat me by a few moments. Why not `datetime.timedelta(minutes=5)` instead?
D.Shawley
Bah, I'm never sure what arguments `timedelta` actually takes. Edited.
PiotrLegnica
Thanks D.Shawley. help(datetime.timedelta) didn't mention that shortcut. It only had days, seconds, and microseconds.
Off Rhoden
+3  A: 

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)
Off Rhoden