Created
August 29, 2012 18:19
-
-
Save pythonjunkie/3516531 to your computer and use it in GitHub Desktop.
Convert given time in ISO8601 and converts it to epoch time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import datetime, time | |
| def convert_enddate_to_seconds(self, ts): | |
| """Takes ISO 8601 format(string) and converts into epoch time.""" | |
| dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\ | |
| datetime.timedelta(hours=int(ts[-5:-3]), | |
| minutes=int(ts[-2:]))*int(ts[-6:-5]+'1') | |
| seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0 | |
| return seconds |
Author
So much simpler:
If you want to get the seconds since epoch, you can use python-dateutil to convert it to a datetime object and then convert it so seconds using the strftime method. Like so:
>>> import dateutil.parser as dp
>>> t = '1984-06-02T19:05:00.000Z'
>>> parsed_t = dp.parse(t)
>>> t_in_seconds = parsed_t.strftime('%s')
>>> t_in_seconds
'455047500'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One can use various external libraries to accomplish this.
A couple of libraries are dateutil and pyXML
import xml.utils.iso8601
From ISO8601 string, to seconds since epoch UTC
print xml.utils.iso8601.parse("2004-04-09T21:39:00-08:00") # -8:00 for PDT/PST
str = '2007-03-04T21:08:12'
import dateutil.parser
print dateutil.parser.parse(str)