Created
September 11, 2012 21:08
-
-
Save rca/3702066 to your computer and use it in GitHub Desktop.
Convert an ISO 8601 timestamp to unix timestamp
This file contains 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 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,) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
from: http://stackoverflow.com/a/27246418/1224827