Datetime - Python Create Unix Timestamp Five Minutes in the Future
Short Description
Is there a module or function that does the timestamp conversion for me? python datetime unix-timestamp edited Feb 18 at...
Description
sign up
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration registration required.
Python Create unix timestamp five minutes in the future
I have to creat e an "Expires" value 5 minutes in the futur e, but I have to supply it in UNIX NIX Timestamp Timestamp format. I have this so far, but it seems like a hack. def expires ex pires(): (): '''return '' 'return a a UNIX style timestamp representing 5 minutes from now''' epoch = datetime. datetime .datetime( datetime(1970 1970, , 1, 1 ) seconds_in_a_day = 60 * 60 * 24 five_minutes = datetime. datetime .timedelta( timedelta(seconds= seconds=5*60 60) ) five_minutes_from_now = datetime. datetime .datetime. datetime.now() now () + five_minutes since_epoch = five_minutes_from_now five_minutes_from_now - epoch return since_epoch. since_epoch .days * seconds_in_a_day seconds_in_a_day + since_epoch. 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 Doug Harris 666 6 18
7
asked May 5 '10 at 18:38 Off Rhoden 3,305 3, 305 4 12 23
I recomm recomm end changing the subject of this question. The question is good, but it is not not about converting converting datetime to Unix U nix timestamp. It is about how to get a Unix timestamp 5 minutes in the future. – D. A. May 21 '13 at 18:10 I disa disagree gree,, @D.A. The question question essentially says "I need to do X do X and and Y. Here's H ere's what what I have now. What's a better way way to do Y?" Maybe there are better ways to do X, but the title and the body clearly ask abou aboutt Y . – Rob Kennedy Kennedy Jun 22 '13 at 12:40
6
I agre agree e with you completely on the question, and I think it a good one with a good answer. The problem is "Python "Pyth on datetime to Unix timestamp" doesn't reflect either the question or answer. I found this post searc hing for a way to do the conversion, and I lost time because of the misleading subject line. I suggest: "Python, "Pyth on, 5 minutes in the future as UNIX Timestamp" – D. A. Jul 31 '13 at 21:57
2
@Jimmy Kane - A pretty pretty c omprehensive answer on how to get get a timest amp from a date time can be found found here: stackover stackoverflow.com/que flow.com/questions/8777753 stions/8777753/… /… – Tim Tisdall Feb 26 at 16:19 @TimTisdall @TimT isdall yes since the title is change changed d it makes no sense – Jimmy Kane Feb 27 at 20:12
11 Answers Another way is to use calendar.timegm : future = datetime. datetime .datetime. datetime.utcnow() utcnow() + datetime. datetime .timedelta( timedelta(minutes= minutes=5) return calendar. calendar .timegm( timegm(future. future.timetuple()) timetuple()) It's also more portable than %s flag to strftime (which doesn't work on Windows). edited Apr 29 at 15:25
community wiki 7 revs, 4 users 67% Cat Plus Plus
beat me by a few moments. Why not datetime.timedelta(minutes=5) datetime.timedelta(minutes=5) instead? instead? – D.Shawley May 11 You beat 5 '10 at 19:02
3
Bah, I'm nev never er sure what arguments timedelta actually takes. Edited. – Cat Plus Plus May 5 '10 at 19:04 Thanks D.Shawley. Thanks D.Shawley. help(d help(datetime.timedelta) atetime.timedelta) didn't mention mention that shortcut. ItIt only only had days, seconds, seconds, and and microseconds. – Off Rhoden May 5 '10 at 19:05
12 Note that, combining the previous two comments, the right solution is:
log in
tour help
careers 2.0
Take the 2-minute tour
×
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 times tamp (and therefore one in UTC), use c alendar.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 Off Rhoden 3,305 4 12 23
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 tim estam p, it returns a times tamp 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 t o 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) edited Feb 26 at 15:04
# 5 min * 60 seconds
answered Apr 9 '13 at 18:57 Tim Tisdall 2,965 1 8 24
1
+1 for this . It should be display ed much higher, because it's the clean way how to do that in Py thon 3 – Viktor Stískala May 21 '13 at 20:28
3
I would say if the question doesn't specify a version, Py thon 2 should be assum ed. 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
@sc ott654 I thought having it right at the beginning of the comment m ade 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 m ay 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 Ali 4,217
6 30 61
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 simpl e, obvious and wrong solution". See possible issues with mktime(dt.timetuple()). datetime.now(timezone.utc).timestamp() provided by @Tim Tisdall is the solution in Pyt hon 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. Als o 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., i t 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 mipadi 131k 28 276 325
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 Antony Hatchkins Dec 25 '10 at 21:23
ValueError: Invalid format string ). –
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 J.F. Sebastian 102k 17 160 267
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 un ix timestamp is itself in the UTC timezone. If you wish to se e the timestamp in a localized timezone, you will need to make another con version. Also note that this will only work for d ates after 19 70. 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 fawce 557 3 9
2
note: I don't understand "the [unix] tim estamp 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:
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
rgrinberg 2,334 1 7 19
Sravan 133 10
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 andrew cooke 20.5k 3 32 70
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 hd1 11.1k
2 14 29
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 mighq 66 4
Not the answer you're looking for? Browse other questions tagged python datetime unix-timestamp or ask your own question.
View more...
Comments