| 1 |
# Copyright (c) 2007 Michael Twomey |
| 2 |
# |
| 3 |
# Permission is hereby granted, free of charge, to any person obtaining a |
| 4 |
# copy of this software and associated documentation files (the |
| 5 |
# "Software"), to deal in the Software without restriction, including |
| 6 |
# without limitation the rights to use, copy, modify, merge, publish, |
| 7 |
# distribute, sublicense, and/or sell copies of the Software, and to |
| 8 |
# permit persons to whom the Software is furnished to do so, subject to |
| 9 |
# the following conditions: |
| 10 |
# |
| 11 |
# The above copyright notice and this permission notice shall be included |
| 12 |
# in all copies or substantial portions of the Software. |
| 13 |
# |
| 14 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS |
| 15 |
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 16 |
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 17 |
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY |
| 18 |
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, |
| 19 |
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |
| 20 |
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 21 |
|
| 22 |
import re |
| 23 |
import time |
| 24 |
from datetime import datetime, timedelta, tzinfo |
| 25 |
|
| 26 |
__all__ = ["parse_date", "ParseError"] |
| 27 |
|
| 28 |
# Adapted from http://delete.me.uk/2005/03/iso8601.html |
| 29 |
ISO8601_REGEX_RAW = "(?P<year>[0-9]{4})-(?P<month>[0-9]{1,2})-(?P<day>[0-9]{1,2})" \ |
| 30 |
"T(?P<hour>[0-9]{2}):(?P<minute>[0-9]{2})(:(?P<second>[0-9]{2})(.(?P<fraction>[0-9]+))?)?" \ |
| 31 |
"(?P<timezone>Z|[-+][0-9]{2}(:?[0-9]{2})?)?" |
| 32 |
ISO8601_REGEX = re.compile(ISO8601_REGEX_RAW) |
| 33 |
TIMEZONE_REGEX = re.compile("(?P<prefix>[+-])(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})?") |
| 34 |
|
| 35 |
|
| 36 |
class ParseError(Exception): |
| 37 |
"""Raised when there is a problem parsing a date string""" |
| 38 |
|
| 39 |
|
| 40 |
# Yoinked from python docs |
| 41 |
ZERO = timedelta(0) |
| 42 |
|
| 43 |
|
| 44 |
class Utc(tzinfo): |
| 45 |
"""UTC |
| 46 |
|
| 47 |
""" |
| 48 |
|
| 49 |
def utcoffset(self, dt): |
| 50 |
return ZERO |
| 51 |
|
| 52 |
def tzname(self, dt): |
| 53 |
return "UTC" |
| 54 |
|
| 55 |
def dst(self, dt): |
| 56 |
return ZERO |
| 57 |
|
| 58 |
|
| 59 |
UTC = Utc() |
| 60 |
|
| 61 |
|
| 62 |
class FixedOffset(tzinfo): |
| 63 |
"""Fixed offset in hours and minutes from UTC |
| 64 |
|
| 65 |
""" |
| 66 |
|
| 67 |
def __init__(self, name, offset_hours, offset_minutes, offset_seconds=0): |
| 68 |
self.__offset = timedelta(hours=offset_hours, minutes=offset_minutes, seconds=offset_seconds) |
| 69 |
self.__name = name |
| 70 |
|
| 71 |
def utcoffset(self, dt): |
| 72 |
return self.__offset |
| 73 |
|
| 74 |
def tzname(self, dt): |
| 75 |
return self.__name |
| 76 |
|
| 77 |
def dst(self, dt): |
| 78 |
return ZERO |
| 79 |
|
| 80 |
def __repr__(self): |
| 81 |
return "<FixedOffset %r>" % self.__name |
| 82 |
|
| 83 |
|
| 84 |
def parse_timezone(tzstring): |
| 85 |
"""Parses ISO 8601 time zone specs into tzinfo offsets |
| 86 |
|
| 87 |
""" |
| 88 |
if tzstring == "Z": |
| 89 |
return UTC |
| 90 |
|
| 91 |
if tzstring is None: |
| 92 |
zone_sec = -time.timezone |
| 93 |
return FixedOffset(name=time.tzname[0], offset_hours=(zone_sec / 3600), offset_minutes=(zone_sec % 3600) / 60, |
| 94 |
offset_seconds=zone_sec % 60) |
| 95 |
|
| 96 |
m = TIMEZONE_REGEX.match(tzstring) |
| 97 |
prefix, hours, minutes = m.groups() |
| 98 |
if minutes is None: |
| 99 |
minutes = 0 |
| 100 |
else: |
| 101 |
minutes = int(minutes) |
| 102 |
hours = int(hours) |
| 103 |
if prefix == "-": |
| 104 |
hours = -hours |
| 105 |
minutes = -minutes |
| 106 |
return FixedOffset(tzstring, hours, minutes) |
| 107 |
|
| 108 |
|
| 109 |
def parse_date(datestring): |
| 110 |
"""Parses ISO 8601 dates into datetime objects |
| 111 |
|
| 112 |
The timezone is parsed from the date string. However it is quite common to |
| 113 |
have dates without a timezone (not strictly correct). In this case the |
| 114 |
default timezone specified in default_timezone is used. This is UTC by |
| 115 |
default. |
| 116 |
""" |
| 117 |
if not isinstance(datestring, str): |
| 118 |
raise ValueError("Expecting a string %r" % datestring) |
| 119 |
m = ISO8601_REGEX.match(datestring) |
| 120 |
if not m: |
| 121 |
raise ParseError("Unable to parse date string %r" % datestring) |
| 122 |
groups = m.groupdict() |
| 123 |
tz = parse_timezone(groups["timezone"]) |
| 124 |
if groups["fraction"] is None: |
| 125 |
groups["fraction"] = 0 |
| 126 |
else: |
| 127 |
groups["fraction"] = int(float("0.{}".format(groups["fraction"])) * 1e6) |
| 128 |
|
| 129 |
try: |
| 130 |
return datetime(int(groups["year"]), int(groups["month"]), int(groups["day"]), |
| 131 |
int(groups["hour"]), int(groups["minute"]), int(groups["second"]), |
| 132 |
int(groups["fraction"]), tz) |
| 133 |
except Exception as e: |
| 134 |
raise ParseError("Failed to create a valid datetime record due to: {}".format(e)) |