Skip to content

Instantly share code, notes, and snippets.

@prehensile
Last active March 22, 2018 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prehensile/4ea07c5dd814d93b74767797b11f37a8 to your computer and use it in GitHub Desktop.
Save prehensile/4ea07c5dd814d93b74767797b11f37a8 to your computer and use it in GitHub Desktop.
Parses timezone strings in ISO 8601 format to datetime.tzinfo objects
import datetime
import re
import logging
class TimeZone( datetime.tzinfo ):
def __init__( self, offset ):
# expects offset in ISO 8601 format e.g '+00:00', '+0000', 'Z'
# see https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
# default offset
offs = datetime.timedelta(0)
# parse the string in a try / except block in case regex parsing fails
try:
if offs != 'Z':
m = re.match( r'([+-]*)(\d\d)(:*)(\d\d)', offset )
sign = m.group(1)
offs = datetime.timedelta(
hours=int(m.group(2)),
minutes=int(m.group(4))
)
if sign == "-":
offs = datetime.timedelta(0) - offs
except Exception as e:
logging.exception( e )
self._offset = offs
self._name = offset
def utcoffset(self, dt):
return self._offset
def tzname(self, dt):
return self._name
def dst(self, dt):
return datetime.timedelta(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment