1
# -.- coding: utf-8 -.-
3
# This file is part of wadllib.
5
# Copyright © 2009 Canonical Ltd.
7
# wadllib is free software: you can redistribute it and/or modify it under the
8
# terms of the GNU Lesser General Public License as published by the Free
9
# Software Foundation, version 3 of the License.
11
# wadllib is distributed in the hope that it will be useful, but WITHOUT ANY
12
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16
# You should have received a copy of the GNU Lesser General Public License
17
# along with wadllib. If not, see <http://www.gnu.org/licenses/>.
20
Parser for ISO 8601 time strings
21
================================
23
>>> d = iso_strptime("2008-01-07T05:30:30.345323+03:00")
25
datetime.datetime(2008, 1, 7, 5, 30, 30, 345323, tzinfo=TimeZone(10800))
27
(2008, 1, 7, 5, 30, 30, 0, 7, 0)
29
(2008, 1, 7, 2, 30, 30, 0, 7, 0)
30
>>> iso_strptime("2008-01-07T05:30:30.345323-03:00")
31
datetime.datetime(2008, 1, 7, 5, 30, 30, 345323, tzinfo=TimeZone(-10800))
32
>>> iso_strptime("2008-01-07T05:30:30.345323")
33
datetime.datetime(2008, 1, 7, 5, 30, 30, 345323)
34
>>> iso_strptime("2008-01-07T05:30:30")
35
datetime.datetime(2008, 1, 7, 5, 30, 30)
36
>>> iso_strptime("2008-01-07T05:30:30+02:00")
37
datetime.datetime(2008, 1, 7, 5, 30, 30, tzinfo=TimeZone(7200))
43
RE_TIME = re.compile(r"""^
44
# pattern matching date
45
(?P<year>\d{4})\-(?P<month>\d{2})\-(?P<day>\d{2})
48
# pattern matching time
49
(?P<hour>\d{2})\:(?P<minutes>\d{2})\:(?P<seconds>\d{2})
50
# pattern matching optional microseconds
51
(\.(?P<microseconds>\d{6})\d*)?
52
# pattern matching optional timezone offset
53
(?P<tz_offset>[\-\+]\d{2}\:\d{2})?
56
class TimeZone(datetime.tzinfo):
58
def __init__(self, tz_string):
59
hours, minutes = tz_string.lstrip("-+").split(":")
60
self.stdoffset = datetime.timedelta(hours=int(hours),
62
if tz_string.startswith("-"):
66
return "TimeZone(%s)" % (
67
self.stdoffset.days*24*60*60 + self.stdoffset.seconds)
69
def utcoffset(self, dt):
73
return datetime.timedelta(0)
75
def iso_strptime(time_str):
76
x = RE_TIME.match(time_str)
78
raise ValueError("unable to parse time '%s'" %time_str)
79
d = datetime.datetime(int(x.group("year")), int(x.group("month")),
80
int(x.group("day")), int(x.group("hour")), int(x.group("minutes")),
81
int(x.group("seconds")))
82
if x.group("microseconds"):
83
d = d.replace(microsecond=int(x.group("microseconds")))
84
if x.group("tz_offset"):
85
d = d.replace(tzinfo=TimeZone(x.group("tz_offset")))