source file: /home/buildslave/tahoe/edgy/build/src/allmydata/util/time_format.py
file stats: 49 lines, 47 executed: 95.9% covered
coverage versus previous test: 0 lines added, 0 lines removed
1. # ISO-8601:
2. # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
3.
4. import calendar, datetime, re, time
5.
6. def iso_utc_date(now=None, t=time.time):
7. if now is None:
8. now = t()
9. return datetime.datetime.utcfromtimestamp(now).isoformat()[:10]
10.
11. def iso_utc(now=None, sep='_', t=time.time):
12. if now is None:
13. now = t()
14. return datetime.datetime.utcfromtimestamp(now).isoformat(sep)
15.
16. def iso_local(now=None, sep='_', t=time.time):
17. if now is None:
18. now = t()
19. return datetime.datetime.fromtimestamp(now).isoformat(sep)
20.
21. 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+)?")):
22. """
23. The inverse of iso_utc().
24.
25. Real ISO-8601 is "2003-01-08T06:30:59". We also accept the widely
26. used variants "2003-01-08_06:30:59" and "2003-01-08 06:30:59".
27. """
28. m = _conversion_re.match(isotime)
29. if not m:
30. raise ValueError, (isotime, "not a complete ISO8601 timestamp")
31. year, month, day = int(m.group('year')), int(m.group('month')), int(m.group('day'))
32. hour, minute, second = int(m.group('hour')), int(m.group('minute')), int(m.group('second'))
33. subsecstr = m.group('subsecond')
34. if subsecstr:
35. subsecfloat = float(subsecstr)
36. else:
37. subsecfloat = 0
38.
39. return calendar.timegm( (year, month, day, hour, minute, second, 0, 1, 0) ) + subsecfloat
40.
41. def parse_duration(s):
42. orig = s
43. unit = None
44. DAY = 24*60*60
45. MONTH = 31*DAY
46. YEAR = 365*DAY
47. if s.endswith("s"):
48. s = s[:-1]
49. if s.endswith("day"):
50. unit = DAY
51. s = s[:-len("day")]
52. elif s.endswith("month"):
53. unit = MONTH
54. s = s[:-len("month")]
55. elif s.endswith("mo"):
56. unit = MONTH
57. s = s[:-len("mo")]
58. elif s.endswith("year"):
59. unit = YEAR
60. s = s[:-len("YEAR")]
61. else:
62. raise ValueError("no unit (like day, month, or year) in '%s'" % orig)
63. s = s.strip()
64. return int(s) * unit
65.
66. def parse_date(s):
67. # return seconds-since-epoch for the UTC midnight that starts the given
68. # day
69. return int(iso_utc_time_to_seconds(s + "T00:00:00"))
70.