The Python Oracle

Python Create unix timestamp five minutes in the future

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind

--

Chapters
00:00 Python Create Unix Timestamp Five Minutes In The Future
00:31 Answer 1 Score 355
00:49 Answer 2 Score 165
01:07 Accepted Answer Score 146
01:22 Answer 4 Score 57
01:34 Answer 5 Score 49
01:55 Thank you

--

Full question
https://stackoverflow.com/questions/2775...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #datetime #unixtimestamp

#avk47



ANSWER 1

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




ANSWER 2

Score 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



ACCEPTED ANSWER

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



ANSWER 4

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