# HG changeset patch # User Paul Boddie # Date 1423341200 -3600 # Node ID 5291a33d8fc7e7afb561a44c928f5877e2072ce1 # Parent bca36db624cea5b4b918dd81c413a46feb8cc005 Prevent bad datetimes from being interpreted as dates. Added time formatting and datetime-to-date functions. diff -r bca36db624ce -r 5291a33d8fc7 imiptools/dates.py --- a/imiptools/dates.py Sat Feb 07 18:33:40 2015 +0100 +++ b/imiptools/dates.py Sat Feb 07 21:33:20 2015 +0100 @@ -85,6 +85,20 @@ else: return dt.strftime("%Y%m%d") +def format_time(dt): + + "Format the time portion of 'dt' as an iCalendar-compatible string." + + if not dt: + return None + elif isinstance(dt, datetime): + if dt.tzname() == "UTC": + return dt.strftime("%H%M%SZ") + else: + return dt.strftime("%H%M%S") + else: + return None + def get_datetime_item(dt, tzid): "Return an iCalendar-compatible string and attributes for 'dt' and 'tzid'." @@ -102,7 +116,7 @@ the 'attr' mapping (if specified) to control the conversion. """ - if not attr or attr.get("VALUE") in (None, "DATE-TIME"): + if len(value) > 9 and (not attr or attr.get("VALUE") in (None, "DATE-TIME")): m = match_datetime_icalendar(value) if m: year, month, day, hour, minute, second = map(m.group, [ @@ -119,6 +133,8 @@ return to_timezone(dt, m.group("utc") and "UTC" or attr and attr.get("TZID") or None) + return None + # Permit dates even if the VALUE is not set to DATE. if not attr or attr.get("VALUE") in (None, "DATE"): @@ -129,6 +145,12 @@ return None +def get_date(dt): + + "Return the date of 'dt'." + + return date(dt.year, dt.month, dt.day) + def get_start_of_day(dt, tzid): """