]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/util/time_format.py
util: hooray! A clean implementation of this simple utility! Black Dew pointed...
[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 calendar, datetime, re, time
11
12 def iso_utc_date(now=None, t=time.time):
13     if now is None:
14         now = t()
15     return datetime.datetime.utcfromtimestamp(now).isoformat()[:10]
16
17 def iso_utc(now=None, sep='_', t=time.time):
18     if now is None:
19         now = t()
20     return datetime.datetime.utcfromtimestamp(now).isoformat(sep)
21
22 def iso_local(now=None, sep='_', t=time.time):
23     if now is None:
24         now = t()
25     return datetime.datetime.fromtimestamp(now).isoformat(sep)
26
27 def iso_utc_time_to_seconds(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+)?")):
28     """
29     The inverse of iso_utc().
30
31     Real ISO-8601 is "2003-01-08T06:30:59".  We also accept the widely
32     used variants "2003-01-08_06:30:59" and "2003-01-08 06:30:59".
33     """
34     m = _conversion_re.match(isotime)
35     if not m:
36         raise ValueError, (isotime, "not a complete ISO8601 timestamp")
37     year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
38     hour, minute, second = int(m.group('hour')), int(m.group('minute')), int(m.group('second'))
39     subsecstr = m.group('subsecond')
40     if subsecstr:
41         subsecfloat = float(subsecstr)
42     else:
43         subsecfloat = 0
44
45     return calendar.timegm( (year, month, day, hour, minute, second, 0, 1, 0) ) + subsecfloat
46
47 def parse_duration(s):
48     orig = s
49     unit = None
50     DAY = 24*60*60
51     MONTH = 31*DAY
52     YEAR = 365*DAY
53     if s.endswith("s"):
54         s = s[:-1]
55     if s.endswith("day"):
56         unit = DAY
57         s = s[:-len("day")]
58     elif s.endswith("month"):
59         unit = MONTH
60         s = s[:-len("month")]
61     elif s.endswith("mo"):
62         unit = MONTH
63         s = s[:-len("mo")]
64     elif s.endswith("year"):
65         unit = YEAR
66         s = s[:-len("YEAR")]
67     else:
68         raise ValueError("no unit (like day, month, or year) in '%s'" % orig)
69     s = s.strip()
70     return int(s) * unit
71
72 def parse_date(s):
73     # return seconds-since-epoch for the UTC midnight that starts the given
74     # day
75     return int(iso_utc_time_to_seconds(s + "T00:00:00"))
76