datetime - Python Create unix timestamp five minutes in the future

ID : 10205

viewed : 23

Tags : pythondatetimeunix-timestamppython

Top 5 Answer for datetime - Python Create unix timestamp five minutes in the future

vote vote

90

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

vote vote

84

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 
vote vote

79

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

66

This is what you need:

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

59

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.

Top 3 video Explaining datetime - Python Create unix timestamp five minutes in the future

Related QUESTION?