1.1 --- a/imiptools/dates.py Fri Mar 06 00:07:47 2015 +0100
1.2 +++ b/imiptools/dates.py Fri Mar 06 21:41:56 2015 +0100
1.3 @@ -33,8 +33,28 @@
1.4 ur'(?P<utc>Z)?' \
1.5 ur')?'
1.6
1.7 +duration_time_icalendar_regexp_str = \
1.8 + ur'T' \
1.9 + ur'(?:' \
1.10 + ur'([0-9]+H)(?:([0-9]+M)([0-9]+S)?)?' \
1.11 + ur'|' \
1.12 + ur'([0-9]+M)([0-9]+S)?' \
1.13 + ur'|' \
1.14 + ur'([0-9]+S)' \
1.15 + ur')'
1.16 +
1.17 +duration_icalendar_regexp_str = ur'P' \
1.18 + ur'(?:' \
1.19 + ur'([0-9]+W)' \
1.20 + ur'|' \
1.21 + ur'(?:%s)' \
1.22 + ur'|' \
1.23 + ur'([0-9]+D)(?:%s)?' \
1.24 + ur')' % (duration_time_icalendar_regexp_str, duration_time_icalendar_regexp_str)
1.25 +
1.26 match_date_icalendar = re.compile(date_icalendar_regexp_str, re.UNICODE).match
1.27 match_datetime_icalendar = re.compile(datetime_icalendar_regexp_str, re.UNICODE).match
1.28 +match_duration_icalendar = re.compile(duration_icalendar_regexp_str, re.UNICODE).match
1.29
1.30 def to_utc_datetime(dt):
1.31
1.32 @@ -169,6 +189,52 @@
1.33
1.34 return None
1.35
1.36 +def get_period(value, attr=None):
1.37 +
1.38 + """
1.39 + Return a tuple of the form (start, end) for the given 'value' in iCalendar
1.40 + format, using the 'attr' mapping (if specified) to control the conversion.
1.41 + """
1.42 +
1.43 + if not value or attr and attr.get("VALUE") != "PERIOD":
1.44 + return None
1.45 +
1.46 + t = value.split("/")
1.47 + if len(t) != 2:
1.48 + return None
1.49 +
1.50 + start = get_datetime(t[0])
1.51 + if t[1].startswith("P"):
1.52 + end = start + get_duration(t[1])
1.53 + else:
1.54 + end = get_datetime(t[1])
1.55 +
1.56 + return start, end
1.57 +
1.58 +def get_duration(value):
1.59 +
1.60 + "Return a duration for the given 'value'."
1.61 +
1.62 + if not value:
1.63 + return None
1.64 +
1.65 + m = match_duration_icalendar(value)
1.66 + if m:
1.67 + weeks, days, hours, minutes, seconds = 0, 0, 0, 0, 0
1.68 + for s in m.groups():
1.69 + if not s: continue
1.70 + if s[-1] == "W": weeks += int(s[:-1])
1.71 + elif s[-1] == "D": days += int(s[:-1])
1.72 + elif s[-1] == "H": hours += int(s[:-1])
1.73 + elif s[-1] == "M": minutes += int(s[:-1])
1.74 + elif s[-1] == "S": seconds += int(s[:-1])
1.75 + return timedelta(
1.76 + int(weeks) * 7 + int(days),
1.77 + (int(hours) * 60 + int(minutes)) * 60 + int(seconds)
1.78 + )
1.79 + else:
1.80 + return None
1.81 +
1.82 def get_date(dt):
1.83
1.84 "Return the date of 'dt'."