-
-
Save squioc/3078803 to your computer and use it in GitHub Desktop.
from datetime import datetime | |
import calendar | |
def epoch_to_iso8601(timestamp): | |
""" | |
epoch_to_iso8601 - convert the unix epoch time into a iso8601 formatted date | |
>>> epoch_to_iso8601(1341866722) | |
'2012-07-09T22:45:22' | |
""" | |
return datetime.fromtimestamp(timestamp).isoformat() | |
def iso8601_to_epoch(datestring): | |
""" | |
iso8601_to_epoch - convert the iso8601 date into the unix epoch time | |
>>> iso8601_to_epoch("2012-07-09T22:27:50.272517") | |
1341872870 | |
""" | |
return calendar.timegm(datetime.strptime(datestring, "%Y-%m-%dT%H:%M:%S.%f").timetuple()) | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
@diggzhang He's importing the datetime class from the datetime module in the first line of this gist
from datetime import datetime
If you're just importing the datetime module, you'll need to do datetime.datetime.fromtimestamp()
well, you have bug. iso8601_to_epoch
() will not always work with standard.
Example: 2016-06-19T08:43:07.374Z
. Z is UTC (https://en.wikipedia.org/wiki/ISO_8601#UTC)
>>> calendar.timegm(datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f").timetuple())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: Z```
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'
That's not right. strftime will use local time zone, so you're epoch answer does not match 1984-06-02T19:05:00.000Z
Using actual UTC functions:
calendar.timegm(dateutil.parser.parse('2017-03-08T14:55:24Z').timetuple())
You can use that:
>>> from dateutil.parser import parse
>>> parse('2017-03-08T14:55:24Z').timestamp()
1488984924.0
You can use that:
>>> from dateutil.parser import parse >>> parse('2017-03-08T14:55:24Z').timestamp() 1488984924.0
Works well for me. Thanks.
why...