You are on page 1of 4

Take the 2-minute tour

Doug Harris
666 6 18
Off Rhoden
3,305 4 12 23
11 Answers
community wiki
7 revs, 4 users 67%
Cat Plus Plus
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?
python datetime unix-timestamp
edited Feb 18 at 19:42 asked May 5 '10 at 18:38
7 I recommend changing the subject of this question. The question is good, but it is not about converting
datetime to Unix timestamp. It is about how to get a Unix timestamp 5 minutes in the future. D. A. May 21
'13 at 18:10
I disagree, @D.A. The question essentially says "I need to do X and Y. Here's what I have now. What's a
better way to do Y?" Maybe there are better ways to do X, but the title and the body clearly ask about Y.
Rob Kennedy Jun 22 '13 at 12:40
6 I agree with you completely on the question, and I think it a good one with a good answer. The problem is
"Python datetime to Unix timestamp" doesn't reflect either the question or answer. I found this post
searching for a way to do the conversion, and I lost time because of the misleading subject line. I suggest:
"Python, 5 minutes in the future as UNIX Timestamp" D. A. Jul 31 '13 at 21:57
2 @JimmyKane - A pretty comprehensive answer on how to get a timestamp from a date time can be found
here: stackoverflow.com/questions/8777753/ Tim Tisdall Feb 26 at 16:19
@TimTisdall yes since the title is changed it makes no sense Jimmy Kane Feb 27 at 20:12
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).
edited Apr 29 at 15:25
11 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
Thanks D.Shawley. help(datetime.timedelta) didn't mention that shortcut. It only had days, seconds, and
microseconds. Off Rhoden May 5 '10 at 19:05
12 Note that, combining the previous two comments, the right solution is:
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no
registration required.
Python Create unix timestamp five minutes in the future
sign up

log in

tour

help

careers 2.0

add comment
Off Rhoden
3,305 4 12 23
Tim Tisdall
2,965 1 8 24
Ali
4,217 6 30 61
calendar.timegm(future.utctimetuple()) . This ensures that a UTC time is passed into
calendar.timegm . shadowmatter Jan 31 '13 at 4:28
1 Can't upvote @tumbleweed's comment enough. If you're trying to get a UNIX timestamp (and therefore one
in UTC), use calendar.timegm. Bialecki Feb 20 '13 at 20:58
show 6 more comments
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)
answered May 5 '10 at 20:06
12 This doesn't answer the question. Jesse Dhillon Apr 6 '12 at 3:30
18 @JesseDhillon it answers the question (make a UNIX timestamp 5 mins in future), just not the title. dbr
Jul 7 '12 at 13:56
3 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
@j-f-sebastian time.monotonic() does not return a UNIX timestamp, it returns a timestamp with an undefined
reference point. rspeer Jun 3 '13 at 22:34
@rspeer: yes, as the docs say, only the difference between consecutive calls is valid. Whether
monotonic can be used depends on your use-case e.g., subprocess module does use it to implement
timeout option. J.F. Sebastian Jun 15 '13 at 7:31
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
edited Feb 26 at 15:04 answered Apr 9 '13 at 18:57
1 +1 for this. It should be displayed much higher, because it's the clean way how to do that in Python 3
Viktor Stskala May 21 '13 at 20:28
3 I would say if the question doesn't specify a version, Python 2 should be assumed. After reading this, I
couldn't figure out why it didn't work for me until I finally noticed the comment about >= 3.3. 10flow Sep 17
'13 at 21:45
1 @scott654 I thought having it right at the beginning of the comment made it clear enough, but I added some
bold to it too. Tim Tisdall Oct 1 '13 at 13:16
1 I'd make the note as a comment in the code block because we all just scan the code in the answers first and
only read the rest if the code looks good. Good answer though. Matthew Purdon Oct 4 '13 at 17:21
1 local time may be ambigous. The example ( datetime.now() ) is bad because it encourages the usage of
naive datetime objects that represent local time and it might fail during DST transitions (due to the inherent
ambiguity). You could use ts = datetime.now(timezone.utc).timestamp() instead. J.F. Sebastian
Nov 17 '13 at 18:19
show 4 more comments
This is what you need:
import time
import datetime
n = datetime.datetime.now()
unix_time = time.mktime(n.timetuple())
answered Apr 30 '13 at 19:18
add comment
mipadi
131k 28 276 325
J.F. Sebastian
102k 17 160 267
fawce
557 3 9
How is this different or adds to the one 'Cat Plus Plus' provided? David Apr 30 '13 at 19:19
3 E.G. this is the answer to the question "Python datetime to Unix timestamp" while Cat Plus Plus answered
the question "Python datetime that will be in 5 minutes to Unix timestamp". So this one is clean and
obvious. running.t Jun 25 '13 at 17:45
@running.t: it reminds me: "every problem has simple, obvious and wrong solution". See possible issues with
mktime(dt.timetuple()) . datetime.now(timezone.utc).timestamp() provided by @Tim Tisdall is
the solution in Python 3.3+. Otherwise (dt - epoch).total_seconds() could be used. J.F. Sebastian
Dec 11 '13 at 3:28
@J.F.Sebastian what if I really do want all computation to take place in local time? Is it the case when eg. to
parse a naive string that one knows is localtime and decide whether there was DST in effect in that particular
time? naxa May 8 at 13:35
1 @naxa: yes, some local times are ambiguous or non-existent. Also timezone offset may be different for
reasons other than DST (you need a tz database such as pytz, to find out the correct offset). Local time
means whatever local politician thinks is a good idea to measure time I.e., it may be highly irregular.
J.F. Sebastian May 8 at 13:45
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"))
answered May 5 '10 at 18:51
29 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
This method doesn't work with timezones. Changing timezone will give the same result
datetime(2013,12,7,tzinfo=timezone("America/Chicago")).strftime("%s") 1386385200
datetime(2013,12,7,tzinfo=timezone("Europe/Riga")).strftime("%s") 1386385200 Martins Balodis Dec 9
'13 at 13:58
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.
answered Nov 16 '12 at 20:26
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
answered Apr 6 '12 at 20:22
2 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:
add comment
add comment
add comment
rgrinberg
2,334 1 7 19
Sravan
133 10
andrew cooke
20.5k 3 32 70
hd1
11.1k 2 14 29
mighq
66 4
datetime.fromtimestamp(ts) J.F. Sebastian Aug 14 '12 at 9:37
def in_unix(input):
start = datetime.datetime(year=1970,month=1,day=1)
diff = input - start
return diff.total_seconds()
edited Jan 17 '13 at 2:12 answered Aug 17 '12 at 17:51
The following is based on the answers above (plus a correction for the milliseconds) and emulates
datetime.timestamp() for Python 3 before 3.3 when timezones are used.
def datetime_timestamp(datetime):
'''
Equivalent to datetime.timestamp() for pre-3.3
'''
try:
return datetime.timestamp()
except AttributeError:
utc_datetime = datetime.astimezone(utc)
return timegm(utc_datetime.timetuple()) + utc_datetime.microsecond / 1e6
To strictly answer the question as asked, you'd want:
datetime_timestamp(my_datetime) + 5 * 60
datetime_timestamp is part of simple-date. But if you were using that package you'd probably type:
SimpleDate(my_datetime).timestamp + 5 * 60
which handles many more formats / types for my_datetime.
edited Aug 7 '13 at 15:41 answered Jun 19 '13 at 3:08
shouldn't you add (5 * 60) to add 5 minutes? I think just adding 5 adds only 5 seconds to the timestamp.
Tim Tisdall Aug 7 '13 at 15:32
you're right - will correct, thanks. andrew cooke Aug 7 '13 at 15:41
def expiration_time():
import datetime,calendar
timestamp = calendar.timegm(datetime.datetime.now().timetuple())
returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
return returnValue
answered Nov 16 '12 at 20:39
Note that solutions with timedelta.total_seconds() work on python-2.7+. Use
calendar.timegm(future.utctimetuple()) for lower versions of Python.
answered Sep 26 '13 at 17:12
Not the answer you're looking for? Browse other questions tagged python datetime
unix-timestamp or ask your own question.
add comment
add comment
add comment
add comment
add comment

You might also like