first version of upstream package from subversion
[python-iso8601.debian] / iso8601 / iso8601.py
1 """ISO 8601 date time string parsing
2
3 Basic usage:
4 >>> import iso8601
5 >>> iso8601.parse_date("2007-01-25T12:00:00Z")
6 datetime.datetime(2007, 1, 25, 12, 0, tzinfo=<iso8601.iso8601.Utc ...>)
7 >>>
8
9 """
10
11 from datetime import datetime, timedelta, tzinfo
12 import re
13
14 __all__ = ["parse_date", "ParseError"]
15
16 # Adapted from http://delete.me.uk/2005/03/iso8601.html
17 ISO8601_REGEX = re.compile(r"(?P<year>[0-9]{4})(-(?P<month>[0-9]{1,2})(-(?P<day>[0-9]{1,2})"
18     r"((?P<separator>.)(?P<hour>[0-9]{2}):(?P<minute>[0-9]{2})(:(?P<second>[0-9]{2})(\.(?P<fraction>[0-9]+))?)?"
19     r"(?P<timezone>Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?"
20 )
21 TIMEZONE_REGEX = re.compile("(?P<prefix>[+-])(?P<hours>[0-9]{2}).(?P<minutes>[0-9]{2})")
22
23 class ParseError(Exception):
24     """Raised when there is a problem parsing a date string"""
25
26 # Yoinked from python docs
27 ZERO = timedelta(0)
28 class Utc(tzinfo):
29     """UTC
30     
31     """
32     def utcoffset(self, dt):
33         return ZERO
34
35     def tzname(self, dt):
36         return "UTC"
37
38     def dst(self, dt):
39         return ZERO
40 UTC = Utc()
41
42 class FixedOffset(tzinfo):
43     """Fixed offset in hours and minutes from UTC
44     
45     """
46     def __init__(self, offset_hours, offset_minutes, name):
47         self.__offset = timedelta(hours=offset_hours, minutes=offset_minutes)
48         self.__name = name
49
50     def utcoffset(self, dt):
51         return self.__offset
52
53     def tzname(self, dt):
54         return self.__name
55
56     def dst(self, dt):
57         return ZERO
58     
59     def __repr__(self):
60         return "<FixedOffset %r>" % self.__name
61
62 def parse_timezone(tzstring, default_timezone=UTC):
63     """Parses ISO 8601 time zone specs into tzinfo offsets
64     
65     """
66     if tzstring == "Z":
67         return default_timezone
68     # This isn't strictly correct, but it's common to encounter dates without
69     # timezones so I'll assume the default (which defaults to UTC).
70     # Addresses issue 4.
71     if tzstring is None:
72         return default_timezone
73     m = TIMEZONE_REGEX.match(tzstring)
74     prefix, hours, minutes = m.groups()
75     hours, minutes = int(hours), int(minutes)
76     if prefix == "-":
77         hours = -hours
78         minutes = -minutes
79     return FixedOffset(hours, minutes, tzstring)
80
81 def parse_date(datestring, default_timezone=UTC):
82     """Parses ISO 8601 dates into datetime objects
83     
84     The timezone is parsed from the date string. However it is quite common to
85     have dates without a timezone (not strictly correct). In this case the
86     default timezone specified in default_timezone is used. This is UTC by
87     default.
88     """
89     if not isinstance(datestring, basestring):
90         raise ParseError("Expecting a string %r" % datestring)
91     m = ISO8601_REGEX.match(datestring)
92     if not m:
93         raise ParseError("Unable to parse date string %r" % datestring)
94     groups = m.groupdict()
95     tz = parse_timezone(groups["timezone"], default_timezone=default_timezone)
96     if groups["fraction"] is None:
97         groups["fraction"] = 0
98     else:
99         groups["fraction"] = int(float("0.%s" % groups["fraction"]) * 1e6)
100     return datetime(int(groups["year"]), int(groups["month"]), int(groups["day"]),
101         int(groups["hour"]), int(groups["minute"]), int(groups["second"]),
102         int(groups["fraction"]), tz)

Benjamin Mako Hill || Want to submit a patch?