Skip to content

Instantly share code, notes, and snippets.

@rca
Created Sep 11, 2012
Embed
What would you like to do?
Convert an ISO 8601 timestamp to unix timestamp
import calendar
from iso8601 import parse_date
def iso2unix(timestamp):
"""
Convert a UTC timestamp formatted in ISO 8601 into a UNIX timestamp
"""
# use iso8601.parse_date to convert the timestamp into a datetime object.
parsed = parse_date(timestamp)
# now grab a time tuple that we can feed mktime
timetuple = parsed.timetuple()
# return a unix timestamp
return calendar.timegm(timetuple)
if __name__ == '__main__':
import sys
import time
import pytz
from datetime import datetime, timedelta
utc = pytz.timezone('UTC')
if len(sys.argv) > 1:
timestamp = sys.argv[1]
else:
utcnow = datetime.utcnow().replace(tzinfo=utc)
timestamp = utcnow.isoformat('T')
print 'timestamp: %s' % timestamp
unix_time = iso2unix(timestamp)
print 'unix_time: %s' % unix_time
print '\nsanity check ...\n'
epoch = datetime(1970, 1, 1, 0, 0, 0)
print 'epoch: %s' % (epoch,)
delta = timedelta(seconds=unix_time)
print 'delta: %s' % delta
x = epoch + delta
print 'epoch + delta: %s' % x
print '\nlocal timestamps\n'
localtime = time.localtime(unix_time)
print 'localtime: %s' % (localtime,)
gmtime = time.gmtime(unix_time)
print 'gmtime: %s' % (gmtime,)
@rca
Copy link
Author

rca commented Sep 12, 2012

@blairg23
Copy link

blairg23 commented Feb 28, 2017

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