]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/util/time_format.py
util/time_format: new routine to parse dates like 2009-03-18, switch expirer to use...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / util / time_format.py
1 #  Copyright (c) 2001 Autonomous Zone Industries
2 #  Copyright (c) 2002-2007 Bryce "Zooko" Wilcox-O'Hearn
3 #  This file is licensed under the
4 #    GNU Lesser General Public License v2.1.
5 #    See the file COPYING or visit http://www.gnu.org/ for details.
6
7 # ISO-8601:
8 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
9
10 import datetime, re, time
11
12 def iso_utc(now=None, sep='_', t=time.time):
13     if now is None:
14         now = t()
15     return datetime.datetime.utcfromtimestamp(now).isoformat(sep)
16
17 def iso_utc_time_to_localseconds(isotime, _conversion_re=re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})[T_ ](?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})(?P<subsecond>\.\d+)?")):
18     """
19     The inverse of iso_utc().
20
21     Real ISO-8601 is "2003-01-08T06:30:59".  We also accept the widely
22     used variants "2003-01-08_06:30:59" and "2003-01-08 06:30:59".
23     """
24     m = _conversion_re.match(isotime)
25     if not m:
26         raise ValueError, (isotime, "not a complete ISO8601 timestamp")
27     year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
28     hour, minute, second = int(m.group('hour')), int(m.group('minute')), int(m.group('second'))
29     utcseconds = time.mktime( (year, month, day, hour, minute, second, 0, 1, 0) )
30     localseconds = utcseconds - time.timezone
31     subsecstr = m.group('subsecond')
32     if subsecstr:
33         subsecfloat = float(subsecstr)
34         localseconds += subsecfloat
35     return localseconds
36
37 def parse_duration(s):
38     orig = s
39     unit = None
40     DAY = 24*60*60
41     MONTH = 31*DAY
42     YEAR = 365*DAY
43     if s.endswith("s"):
44         s = s[:-1]
45     if s.endswith("day"):
46         unit = DAY
47         s = s[:-len("day")]
48     elif s.endswith("month"):
49         unit = MONTH
50         s = s[:-len("month")]
51     elif s.endswith("mo"):
52         unit = MONTH
53         s = s[:-len("mo")]
54     elif s.endswith("year"):
55         unit = YEAR
56         s = s[:-len("YEAR")]
57     else:
58         raise ValueError("no unit (like day, month, or year) in '%s'" % orig)
59     s = s.strip()
60     return int(s) * unit
61
62 def parse_date(s):
63     # return seconds-since-epoch for the UTC midnight that starts the given
64     # day
65     return iso_utc_time_to_localseconds(s + "T00:00:00")
66