2 # http://www.cl.cam.ac.uk/~mgk25/iso-time.html
4 import calendar, datetime, re, time
6 def iso_utc_date(now=None, t=time.time):
9 return datetime.datetime.utcfromtimestamp(now).isoformat()[:10]
11 def iso_utc(now=None, sep='_', t=time.time):
14 return datetime.datetime.utcfromtimestamp(now).isoformat(sep)
16 def iso_local(now=None, sep='_', t=time.time):
19 return datetime.datetime.fromtimestamp(now).isoformat(sep)
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+)?")):
23 The inverse of iso_utc().
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".
28 m = _conversion_re.match(isotime)
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')
35 subsecfloat = float(subsecstr)
39 return calendar.timegm( (year, month, day, hour, minute, second, 0, 1, 0) ) + subsecfloat
41 def parse_duration(s):
52 elif s.endswith("month"):
55 elif s.endswith("mo"):
58 elif s.endswith("year"):
62 raise ValueError("no unit (like day, month, or year) in '%s'" % orig)
67 # return seconds-since-epoch for the UTC midnight that starts the given
69 return int(iso_utc_time_to_seconds(s + "T00:00:00"))
71 def format_delta(time_1, time_2):
72 TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
74 absolute_str, relative_str = "N/A", "N/A"
76 delta = int( time_2 - time_1 )
79 minutes = (delta / 60) % 60
81 hours = delta / (60*60) % 24
83 days = delta / (24*60*60)
87 relative_str = "%ss" % (seconds)
89 relative_str = "%sm%ss" % (minutes, seconds)
91 relative_str = "%sh%sm%ss" % (hours, minutes, seconds)
93 relative_str = "%sd%sh%sm%ss" % (days, hours, minutes, seconds)
94 absolute_str = time.strftime(TIME_FORMAT, time.localtime(time_1))
95 return absolute_str, relative_str