paul@152 | 1 | #!/usr/bin/env python |
paul@152 | 2 | |
paul@152 | 3 | """ |
paul@152 | 4 | Date processing functions. |
paul@152 | 5 | |
paul@152 | 6 | Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk> |
paul@152 | 7 | |
paul@152 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@152 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@152 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@152 | 11 | version. |
paul@152 | 12 | |
paul@152 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@152 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@152 | 15 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@152 | 16 | details. |
paul@152 | 17 | |
paul@152 | 18 | You should have received a copy of the GNU General Public License along with |
paul@152 | 19 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@152 | 20 | """ |
paul@152 | 21 | |
paul@195 | 22 | from datetime import date, datetime, timedelta |
paul@291 | 23 | from os.path import exists |
paul@152 | 24 | from pytz import timezone, UnknownTimeZoneError |
paul@152 | 25 | import re |
paul@152 | 26 | |
paul@152 | 27 | # iCalendar date and datetime parsing (from DateSupport in MoinSupport). |
paul@152 | 28 | |
paul@152 | 29 | date_icalendar_regexp_str = ur'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})' |
paul@152 | 30 | datetime_icalendar_regexp_str = date_icalendar_regexp_str + \ |
paul@152 | 31 | ur'(?:' \ |
paul@152 | 32 | ur'T(?P<hour>[0-2][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-6][0-9])' \ |
paul@152 | 33 | ur'(?P<utc>Z)?' \ |
paul@152 | 34 | ur')?' |
paul@152 | 35 | |
paul@387 | 36 | duration_time_icalendar_regexp_str = \ |
paul@387 | 37 | ur'T' \ |
paul@387 | 38 | ur'(?:' \ |
paul@387 | 39 | ur'([0-9]+H)(?:([0-9]+M)([0-9]+S)?)?' \ |
paul@387 | 40 | ur'|' \ |
paul@387 | 41 | ur'([0-9]+M)([0-9]+S)?' \ |
paul@387 | 42 | ur'|' \ |
paul@387 | 43 | ur'([0-9]+S)' \ |
paul@387 | 44 | ur')' |
paul@387 | 45 | |
paul@387 | 46 | duration_icalendar_regexp_str = ur'P' \ |
paul@387 | 47 | ur'(?:' \ |
paul@387 | 48 | ur'([0-9]+W)' \ |
paul@387 | 49 | ur'|' \ |
paul@387 | 50 | ur'(?:%s)' \ |
paul@387 | 51 | ur'|' \ |
paul@387 | 52 | ur'([0-9]+D)(?:%s)?' \ |
paul@387 | 53 | ur')' % (duration_time_icalendar_regexp_str, duration_time_icalendar_regexp_str) |
paul@387 | 54 | |
paul@152 | 55 | match_date_icalendar = re.compile(date_icalendar_regexp_str, re.UNICODE).match |
paul@152 | 56 | match_datetime_icalendar = re.compile(datetime_icalendar_regexp_str, re.UNICODE).match |
paul@387 | 57 | match_duration_icalendar = re.compile(duration_icalendar_regexp_str, re.UNICODE).match |
paul@152 | 58 | |
paul@152 | 59 | def to_utc_datetime(dt): |
paul@247 | 60 | |
paul@247 | 61 | "Return a datetime corresponding to 'dt' in the UTC time zone." |
paul@247 | 62 | |
paul@152 | 63 | if not dt: |
paul@152 | 64 | return None |
paul@152 | 65 | elif isinstance(dt, datetime): |
paul@157 | 66 | return to_timezone(dt, "UTC") |
paul@152 | 67 | else: |
paul@152 | 68 | return dt |
paul@152 | 69 | |
paul@291 | 70 | def get_default_timezone(): |
paul@291 | 71 | |
paul@291 | 72 | "Return the system time regime." |
paul@291 | 73 | |
paul@291 | 74 | filename = "/etc/timezone" |
paul@291 | 75 | |
paul@291 | 76 | if exists(filename): |
paul@291 | 77 | f = open(filename) |
paul@291 | 78 | try: |
paul@291 | 79 | return f.read().strip() |
paul@291 | 80 | finally: |
paul@291 | 81 | f.close() |
paul@291 | 82 | else: |
paul@291 | 83 | return None |
paul@291 | 84 | |
paul@152 | 85 | def to_timezone(dt, name): |
paul@247 | 86 | |
paul@247 | 87 | """ |
paul@247 | 88 | Return a datetime corresponding to 'dt' in the time regime having the given |
paul@247 | 89 | 'name'. |
paul@247 | 90 | """ |
paul@247 | 91 | |
paul@152 | 92 | try: |
paul@152 | 93 | tz = name and timezone(name) or None |
paul@152 | 94 | except UnknownTimeZoneError: |
paul@152 | 95 | tz = None |
paul@157 | 96 | return to_tz(dt, tz) |
paul@157 | 97 | |
paul@157 | 98 | def to_tz(dt, tz): |
paul@247 | 99 | |
paul@247 | 100 | "Return a datetime corresponding to 'dt' employing the pytz.timezone 'tz'." |
paul@247 | 101 | |
paul@232 | 102 | if tz is not None and isinstance(dt, datetime): |
paul@152 | 103 | if not dt.tzinfo: |
paul@152 | 104 | return tz.localize(dt) |
paul@152 | 105 | else: |
paul@152 | 106 | return dt.astimezone(tz) |
paul@152 | 107 | else: |
paul@152 | 108 | return dt |
paul@152 | 109 | |
paul@152 | 110 | def format_datetime(dt): |
paul@247 | 111 | |
paul@247 | 112 | "Format 'dt' as an iCalendar-compatible string." |
paul@247 | 113 | |
paul@152 | 114 | if not dt: |
paul@152 | 115 | return None |
paul@152 | 116 | elif isinstance(dt, datetime): |
paul@152 | 117 | if dt.tzname() == "UTC": |
paul@152 | 118 | return dt.strftime("%Y%m%dT%H%M%SZ") |
paul@152 | 119 | else: |
paul@152 | 120 | return dt.strftime("%Y%m%dT%H%M%S") |
paul@152 | 121 | else: |
paul@152 | 122 | return dt.strftime("%Y%m%d") |
paul@152 | 123 | |
paul@285 | 124 | def format_time(dt): |
paul@285 | 125 | |
paul@285 | 126 | "Format the time portion of 'dt' as an iCalendar-compatible string." |
paul@285 | 127 | |
paul@285 | 128 | if not dt: |
paul@285 | 129 | return None |
paul@285 | 130 | elif isinstance(dt, datetime): |
paul@285 | 131 | if dt.tzname() == "UTC": |
paul@285 | 132 | return dt.strftime("%H%M%SZ") |
paul@285 | 133 | else: |
paul@285 | 134 | return dt.strftime("%H%M%S") |
paul@285 | 135 | else: |
paul@285 | 136 | return None |
paul@285 | 137 | |
paul@300 | 138 | def get_datetime_item(dt, tzid=None): |
paul@247 | 139 | |
paul@252 | 140 | "Return an iCalendar-compatible string and attributes for 'dt' and 'tzid'." |
paul@247 | 141 | |
paul@239 | 142 | if not dt: |
paul@239 | 143 | return None, None |
paul@239 | 144 | value = format_datetime(dt) |
paul@300 | 145 | if isinstance(dt, datetime): |
paul@300 | 146 | attr = {"VALUE" : "DATE-TIME"} |
paul@300 | 147 | if tzid: |
paul@300 | 148 | attr["TZID"] = tzid |
paul@300 | 149 | else: |
paul@300 | 150 | attr = {"VALUE" : "DATE"} |
paul@239 | 151 | return value, attr |
paul@239 | 152 | |
paul@152 | 153 | def get_datetime(value, attr=None): |
paul@152 | 154 | |
paul@152 | 155 | """ |
paul@152 | 156 | Return a datetime object from the given 'value' in iCalendar format, using |
paul@152 | 157 | the 'attr' mapping (if specified) to control the conversion. |
paul@152 | 158 | """ |
paul@152 | 159 | |
paul@295 | 160 | if not value: |
paul@295 | 161 | return None |
paul@295 | 162 | |
paul@285 | 163 | if len(value) > 9 and (not attr or attr.get("VALUE") in (None, "DATE-TIME")): |
paul@152 | 164 | m = match_datetime_icalendar(value) |
paul@152 | 165 | if m: |
paul@232 | 166 | year, month, day, hour, minute, second = map(m.group, [ |
paul@232 | 167 | "year", "month", "day", "hour", "minute", "second" |
paul@232 | 168 | ]) |
paul@152 | 169 | |
paul@232 | 170 | if hour and minute and second: |
paul@232 | 171 | dt = datetime( |
paul@232 | 172 | int(year), int(month), int(day), int(hour), int(minute), int(second) |
paul@232 | 173 | ) |
paul@152 | 174 | |
paul@232 | 175 | # Impose the indicated timezone. |
paul@232 | 176 | # NOTE: This needs an ambiguity policy for DST changes. |
paul@232 | 177 | |
paul@232 | 178 | return to_timezone(dt, m.group("utc") and "UTC" or attr and attr.get("TZID") or None) |
paul@152 | 179 | |
paul@285 | 180 | return None |
paul@285 | 181 | |
paul@239 | 182 | # Permit dates even if the VALUE is not set to DATE. |
paul@239 | 183 | |
paul@239 | 184 | if not attr or attr.get("VALUE") in (None, "DATE"): |
paul@152 | 185 | m = match_date_icalendar(value) |
paul@152 | 186 | if m: |
paul@232 | 187 | year, month, day = map(m.group, ["year", "month", "day"]) |
paul@232 | 188 | return date(int(year), int(month), int(day)) |
paul@232 | 189 | |
paul@152 | 190 | return None |
paul@152 | 191 | |
paul@387 | 192 | def get_period(value, attr=None): |
paul@387 | 193 | |
paul@387 | 194 | """ |
paul@387 | 195 | Return a tuple of the form (start, end) for the given 'value' in iCalendar |
paul@387 | 196 | format, using the 'attr' mapping (if specified) to control the conversion. |
paul@387 | 197 | """ |
paul@387 | 198 | |
paul@387 | 199 | if not value or attr and attr.get("VALUE") != "PERIOD": |
paul@387 | 200 | return None |
paul@387 | 201 | |
paul@387 | 202 | t = value.split("/") |
paul@387 | 203 | if len(t) != 2: |
paul@387 | 204 | return None |
paul@387 | 205 | |
paul@387 | 206 | start = get_datetime(t[0]) |
paul@387 | 207 | if t[1].startswith("P"): |
paul@387 | 208 | end = start + get_duration(t[1]) |
paul@387 | 209 | else: |
paul@387 | 210 | end = get_datetime(t[1]) |
paul@387 | 211 | |
paul@387 | 212 | return start, end |
paul@387 | 213 | |
paul@387 | 214 | def get_duration(value): |
paul@387 | 215 | |
paul@387 | 216 | "Return a duration for the given 'value'." |
paul@387 | 217 | |
paul@387 | 218 | if not value: |
paul@387 | 219 | return None |
paul@387 | 220 | |
paul@387 | 221 | m = match_duration_icalendar(value) |
paul@387 | 222 | if m: |
paul@387 | 223 | weeks, days, hours, minutes, seconds = 0, 0, 0, 0, 0 |
paul@387 | 224 | for s in m.groups(): |
paul@387 | 225 | if not s: continue |
paul@387 | 226 | if s[-1] == "W": weeks += int(s[:-1]) |
paul@387 | 227 | elif s[-1] == "D": days += int(s[:-1]) |
paul@387 | 228 | elif s[-1] == "H": hours += int(s[:-1]) |
paul@387 | 229 | elif s[-1] == "M": minutes += int(s[:-1]) |
paul@387 | 230 | elif s[-1] == "S": seconds += int(s[:-1]) |
paul@387 | 231 | return timedelta( |
paul@387 | 232 | int(weeks) * 7 + int(days), |
paul@387 | 233 | (int(hours) * 60 + int(minutes)) * 60 + int(seconds) |
paul@387 | 234 | ) |
paul@387 | 235 | else: |
paul@387 | 236 | return None |
paul@387 | 237 | |
paul@285 | 238 | def get_date(dt): |
paul@285 | 239 | |
paul@285 | 240 | "Return the date of 'dt'." |
paul@285 | 241 | |
paul@285 | 242 | return date(dt.year, dt.month, dt.day) |
paul@285 | 243 | |
paul@244 | 244 | def get_start_of_day(dt, tzid): |
paul@245 | 245 | |
paul@245 | 246 | """ |
paul@245 | 247 | Get the start of the day in which 'dt' is positioned, using the given 'tzid' |
paul@245 | 248 | to obtain a datetime in the appropriate time zone. Where time zone |
paul@245 | 249 | transitions occur within a day, the zone of 'dt' may not be the eventual |
paul@245 | 250 | zone of the returned object. |
paul@245 | 251 | """ |
paul@245 | 252 | |
paul@244 | 253 | start = datetime(dt.year, dt.month, dt.day, 0, 0) |
paul@244 | 254 | return to_timezone(start, tzid) |
paul@152 | 255 | |
paul@244 | 256 | def get_end_of_day(dt, tzid): |
paul@245 | 257 | |
paul@245 | 258 | """ |
paul@245 | 259 | Get the end of the day in which 'dt' is positioned, using the given 'tzid' |
paul@245 | 260 | to obtain a datetime in the appropriate time zone. Where time zone |
paul@245 | 261 | transitions occur within a day, the zone of 'dt' may not be the eventual |
paul@245 | 262 | zone of the returned object. |
paul@245 | 263 | """ |
paul@245 | 264 | |
paul@232 | 265 | return get_start_of_day(dt + timedelta(1), tzid) |
paul@195 | 266 | |
paul@244 | 267 | def get_start_of_next_day(dt, tzid): |
paul@245 | 268 | |
paul@245 | 269 | """ |
paul@245 | 270 | Get the start of the day after the day in which 'dt' is positioned. This |
paul@245 | 271 | function is intended to extend either dates or datetimes to the end of a |
paul@245 | 272 | day for the purpose of generating a missing end date or datetime for an |
paul@245 | 273 | event. |
paul@245 | 274 | |
paul@245 | 275 | If 'dt' is a date and not a datetime, a plain date object for the next day |
paul@245 | 276 | will be returned. |
paul@245 | 277 | |
paul@245 | 278 | If 'dt' is a datetime, the given 'tzid' is used to obtain a datetime in the |
paul@245 | 279 | appropriate time zone. Where time zone transitions occur within a day, the |
paul@245 | 280 | zone of 'dt' may not be the eventual zone of the returned object. |
paul@245 | 281 | """ |
paul@245 | 282 | |
paul@239 | 283 | if isinstance(dt, datetime): |
paul@239 | 284 | return get_end_of_day(dt, tzid) |
paul@239 | 285 | else: |
paul@239 | 286 | return dt + timedelta(1) |
paul@239 | 287 | |
paul@244 | 288 | def ends_on_same_day(dt, end, tzid): |
paul@245 | 289 | |
paul@245 | 290 | """ |
paul@245 | 291 | Return whether 'dt' ends on the same day as 'end', testing the date |
paul@245 | 292 | components of 'dt' and 'end' against each other, but also testing whether |
paul@245 | 293 | 'end' is the actual end of the day in which 'dt' is positioned. |
paul@245 | 294 | |
paul@245 | 295 | Since time zone transitions may occur within a day, 'tzid' is required to |
paul@245 | 296 | determine the end of the day in which 'dt' is positioned, using the zone |
paul@245 | 297 | appropriate at that point in time, not necessarily the zone applying to |
paul@245 | 298 | 'dt'. |
paul@245 | 299 | """ |
paul@245 | 300 | |
paul@195 | 301 | return ( |
paul@195 | 302 | dt.date() == end.date() or |
paul@244 | 303 | end == get_end_of_day(dt, tzid) |
paul@195 | 304 | ) |
paul@195 | 305 | |
paul@222 | 306 | def get_timestamp(): |
paul@247 | 307 | |
paul@247 | 308 | "Return the current time as an iCalendar-compatible string." |
paul@247 | 309 | |
paul@222 | 310 | return format_datetime(to_timezone(datetime.utcnow(), "UTC")) |
paul@222 | 311 | |
paul@291 | 312 | def get_freebusy_period(start, end, tzid): |
paul@291 | 313 | |
paul@291 | 314 | """ |
paul@291 | 315 | For the given 'start' datetime, together with the given 'end' datetime, and |
paul@291 | 316 | given a 'tzid' either from the datetimes or provided for the user, return a |
paul@291 | 317 | (start, end) tuple containing datetimes in the UTC time zone, where dates |
paul@291 | 318 | are converted to points in time so that each day has a specific start and |
paul@291 | 319 | end point defined in UTC. |
paul@291 | 320 | """ |
paul@291 | 321 | |
paul@291 | 322 | start = to_utc_datetime_only(start, tzid) |
paul@291 | 323 | end = to_utc_datetime_only(end, tzid) |
paul@291 | 324 | return start, end |
paul@291 | 325 | |
paul@291 | 326 | def to_utc_datetime_only(dt, tzid): |
paul@291 | 327 | |
paul@291 | 328 | """ |
paul@291 | 329 | Return the datetime 'dt' as a point in time in the UTC time zone, given the |
paul@291 | 330 | 'tzid' defined for the datetime. Where 'dt' is a date, the start of the |
paul@291 | 331 | indicated day is returned, defined in UTC. |
paul@291 | 332 | """ |
paul@291 | 333 | |
paul@291 | 334 | if not isinstance(dt, datetime): |
paul@291 | 335 | return to_timezone(get_start_of_day(dt, tzid), "UTC") |
paul@291 | 336 | else: |
paul@291 | 337 | return to_timezone(dt, "UTC") |
paul@291 | 338 | |
paul@152 | 339 | # vim: tabstop=4 expandtab shiftwidth=4 |