Skip to content

Instantly share code, notes, and snippets.

@squioc
Last active December 12, 2015 02:28
Show Gist options
  • Save squioc/4698752 to your computer and use it in GitHub Desktop.
Save squioc/4698752 to your computer and use it in GitHub Desktop.
conversion between iso8601 date format and unix epoch datetime (with timezone awareness)
from datetime import datetime, tzinfo, timedelta
import calendar
import re
def epoch_to_iso8601(timestamp, tz=None):
"""
epoch_to_iso8601 - convert the unix epoch time into a iso8601 formatted date
>>> epoch_to_iso8601(1341866722)
'2012-07-09T22:45:22'
>>> from pytz import timezone
>>> tz = timezone("US/Eastern")
>>> epoch_to_iso8601(1341866722, tz)
'2012-07-09T22:45:22-05:00'
"""
return datetime.fromtimestamp(timestamp, tz).isoformat()
def iso8601_to_epoch(datestring, tz=None):
"""
iso8601_to_epoch - convert the iso8601 date into the unix epoch time
>>> iso8601_to_epoch("2012-07-09T22:27:50.272517")
1341872870
>>> iso8601_to_epoch("2012-07-09T22:27:50.272517-05:00")
1341854870
>>> from pytz import timezone
>>> tz = timezone("Australia/Sydney")
>>> iso8601_to_epoch("2012-07-09T22:27:50.272517-05:00", tz)
1341818870
"""
(date, timezone) = parse_datestring(datestring)
if timezone:
date = timezone.localize(date)
if tz:
date.astimezone(tz)
return calendar.timegm(date.timetuple())
class TimeZone(tzinfo):
def __init__(self, offset):
self.offset = offset
def utcoffset(self, dt):
return timedelta(minutes=self.offset)
def tzname(self, dt):
return str(self)
def dst(self, dt):
return timedelta(0)
def __str__(self):
return "%s%02d:%02d" % (["-","+"][self.offset>=0], self.offset/3600, self.offset%3600)
def parse_datestring(datestring):
"""
parse_datestring - parse the iso8601 date string into datetime and timezone objects
>>> parse_datestring("2012-07-09T22:27:50.272517")
(datetime.datetime(2012, 7, 9, 22, 27, 50, 272517), None)
>>> parse_datestring("2012-07-09T22:27:50.272517-05:00")
(datetime.datetime(2012, 7, 9, 22, 27, 50, 272517), "-05:00")
"""
timezone = None
match = re.match('([0-9\-T:\.]+)(([+-])(\d{2}):(\d{2}))', datestring)
if match:
datestring = match.group(1)
timezone = TimeZone({'-':-1,'+':1}[match.group(3)]*int(match.group(4))*3600+int(match.group(5)))
return (datetime.strptime(datestring, "%Y-%m-%dT%H:%M:%S.%f"), timezone)
if __name__ == "__main__":
import doctest
doctest.testmod()
Copyright © Sébastien Quioc
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment