Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Create unix timestamp five minutes in the future

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?

like image 821
Daniel Rhoden Avatar asked May 05 '10 18:05

Daniel Rhoden


People also ask

How do you create a Unix timestamp in Python?

The timetuple() function of the datetime class returns the datetime's properties as a named tuple. To obtain the Unix timestamp, use print(UTC). Code: Python3.

How long will Unix timestamp last?

At 03:14:08 UTC on Tuesday, 19 January 2038, 32-bit versions of the Unix timestamp will cease to work, as it will overflow the largest value that can be held in a signed 32-bit number (7FFFFFFF16 or 2147483647).

What is Unix timestamp in Python?

A Unix timestamp is the number of seconds that have passed (elapsed) since the epoch (January 1, 1970 at 00:00:00 UTC). It provides a way to express any date and time as a single number without having to worry about multiple unit components (like hours and minutes) and time zones (since it uses UTC).


2 Answers

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

like image 111
7 revs, 4 users 67% Avatar answered Oct 15 '22 10:10

7 revs, 4 users 67%


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 
like image 23
Tim Tisdall Avatar answered Oct 15 '22 10:10

Tim Tisdall