Skip to content

Instantly share code, notes, and snippets.

@pythonjunkie
Created August 29, 2012 18:19
Show Gist options
  • Select an option

  • Save pythonjunkie/3516531 to your computer and use it in GitHub Desktop.

Select an option

Save pythonjunkie/3516531 to your computer and use it in GitHub Desktop.
Convert given time in ISO8601 and converts it to epoch time
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
@pythonjunkie

Copy link
Copy Markdown
Author

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

from xml.utils.iso8601 import parse
parse("2010-01-04T12:15:30+01:00")
1262603730.0

str = '2007-03-04T21:08:12'
import dateutil.parser
print dateutil.parser.parse(str)

@blairg23

Copy link
Copy Markdown

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'

from: http://stackoverflow.com/a/27246418/1224827

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment