paul@0 | 1 | # -*- coding: iso-8859-1 -*- |
paul@0 | 2 | """ |
paul@0 | 3 | MoinMoin - DateSupport library (derived from EventAggregatorSupport) |
paul@0 | 4 | |
paul@0 | 5 | @copyright: 2008, 2009, 2010, 2011, 2012 by Paul Boddie <paul@boddie.org.uk> |
paul@0 | 6 | @license: GNU GPL (v2 or later), see COPYING.txt for details. |
paul@0 | 7 | """ |
paul@0 | 8 | |
paul@0 | 9 | import calendar |
paul@0 | 10 | import datetime |
paul@0 | 11 | import re |
paul@0 | 12 | import bisect |
paul@0 | 13 | |
paul@0 | 14 | try: |
paul@0 | 15 | import pytz |
paul@0 | 16 | except ImportError: |
paul@0 | 17 | pytz = None |
paul@0 | 18 | |
paul@0 | 19 | __version__ = "0.1" |
paul@0 | 20 | |
paul@0 | 21 | # Date labels. |
paul@0 | 22 | |
paul@0 | 23 | month_labels = ["January", "February", "March", "April", "May", "June", |
paul@0 | 24 | "July", "August", "September", "October", "November", "December"] |
paul@0 | 25 | weekday_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] |
paul@0 | 26 | |
paul@0 | 27 | # Month, date, time and datetime parsing. |
paul@0 | 28 | |
paul@0 | 29 | month_regexp_str = ur'(?P<year>[0-9]{4})-(?P<month>[0-9]{2})' |
paul@0 | 30 | date_regexp_str = ur'(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})' |
paul@0 | 31 | time_regexp_str = ur'(?P<hour>[0-2][0-9]):(?P<minute>[0-5][0-9])(?::(?P<second>[0-6][0-9]))?' |
paul@0 | 32 | timezone_offset_str = ur'(?P<offset>(UTC)?(?:(?P<sign>[-+])(?P<hours>[0-9]{2})(?::?(?P<minutes>[0-9]{2}))?))' |
paul@0 | 33 | timezone_olson_str = ur'(?P<olson>[a-zA-Z]+(?:/[-_a-zA-Z]+){1,2})' |
paul@0 | 34 | timezone_utc_str = ur'UTC' |
paul@0 | 35 | timezone_regexp_str = ur'(?P<zone>' + timezone_offset_str + '|' + timezone_olson_str + '|' + timezone_utc_str + ')' |
paul@0 | 36 | datetime_regexp_str = date_regexp_str + ur'(?:\s+' + time_regexp_str + ur'(?:\s+' + timezone_regexp_str + ur')?)?' |
paul@0 | 37 | |
paul@0 | 38 | month_regexp = re.compile(month_regexp_str, re.UNICODE) |
paul@0 | 39 | date_regexp = re.compile(date_regexp_str, re.UNICODE) |
paul@0 | 40 | time_regexp = re.compile(time_regexp_str, re.UNICODE) |
paul@0 | 41 | timezone_olson_regexp = re.compile(timezone_olson_str, re.UNICODE) |
paul@0 | 42 | timezone_offset_regexp = re.compile(timezone_offset_str, re.UNICODE) |
paul@0 | 43 | datetime_regexp = re.compile(datetime_regexp_str, re.UNICODE) |
paul@0 | 44 | |
paul@0 | 45 | # iCalendar date and datetime parsing. |
paul@0 | 46 | |
paul@0 | 47 | date_icalendar_regexp_str = ur'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})' |
paul@0 | 48 | datetime_icalendar_regexp_str = date_icalendar_regexp_str + \ |
paul@0 | 49 | ur'(?:' \ |
paul@0 | 50 | ur'T(?P<hour>[0-2][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-6][0-9])' \ |
paul@0 | 51 | ur'(?P<utc>Z)?' \ |
paul@0 | 52 | ur')?' |
paul@0 | 53 | |
paul@0 | 54 | date_icalendar_regexp = re.compile(date_icalendar_regexp_str, re.UNICODE) |
paul@0 | 55 | datetime_icalendar_regexp = re.compile(datetime_icalendar_regexp_str, re.UNICODE) |
paul@0 | 56 | |
paul@0 | 57 | # Utility functions. |
paul@0 | 58 | |
paul@0 | 59 | def int_or_none(x): |
paul@0 | 60 | if x is None: |
paul@0 | 61 | return x |
paul@0 | 62 | else: |
paul@0 | 63 | return int(x) |
paul@0 | 64 | |
paul@0 | 65 | def getMonthLabel(month): |
paul@0 | 66 | |
paul@0 | 67 | "Return an unlocalised label for the given 'month'." |
paul@0 | 68 | |
paul@0 | 69 | return month_labels[month - 1] # zero-based labels |
paul@0 | 70 | |
paul@0 | 71 | def getDayLabel(weekday): |
paul@0 | 72 | |
paul@0 | 73 | "Return an unlocalised label for the given 'weekday'." |
paul@0 | 74 | |
paul@0 | 75 | return weekday_labels[weekday] |
paul@0 | 76 | |
paul@0 | 77 | # Interfaces. |
paul@0 | 78 | |
paul@0 | 79 | class ActsAsTimespan: |
paul@0 | 80 | pass |
paul@0 | 81 | |
paul@0 | 82 | # Date-related functions. |
paul@0 | 83 | |
paul@0 | 84 | def cmp_dates_as_day_start(a, b): |
paul@0 | 85 | |
paul@0 | 86 | """ |
paul@0 | 87 | Compare dates/datetimes 'a' and 'b' treating dates without time information |
paul@0 | 88 | as the earliest time in a particular day. |
paul@0 | 89 | """ |
paul@0 | 90 | |
paul@0 | 91 | are_equal = a == b |
paul@0 | 92 | |
paul@0 | 93 | if are_equal: |
paul@0 | 94 | a2 = a.as_datetime_or_date() |
paul@0 | 95 | b2 = b.as_datetime_or_date() |
paul@0 | 96 | |
paul@0 | 97 | if isinstance(a2, Date) and isinstance(b2, DateTime): |
paul@0 | 98 | return -1 |
paul@0 | 99 | elif isinstance(a2, DateTime) and isinstance(b2, Date): |
paul@0 | 100 | return 1 |
paul@0 | 101 | |
paul@0 | 102 | return cmp(a, b) |
paul@0 | 103 | |
paul@0 | 104 | class Convertible: |
paul@0 | 105 | |
paul@0 | 106 | "Support for converting temporal objects." |
paul@0 | 107 | |
paul@0 | 108 | def _get_converter(self, resolution): |
paul@0 | 109 | if resolution == "month": |
paul@0 | 110 | return lambda x: x and x.as_month() |
paul@0 | 111 | elif resolution == "date": |
paul@0 | 112 | return lambda x: x and x.as_date() |
paul@0 | 113 | elif resolution == "datetime": |
paul@0 | 114 | return lambda x: x and x.as_datetime_or_date() |
paul@0 | 115 | else: |
paul@0 | 116 | return lambda x: x |
paul@0 | 117 | |
paul@0 | 118 | class Temporal(Convertible): |
paul@0 | 119 | |
paul@0 | 120 | "A simple temporal representation, common to dates and times." |
paul@0 | 121 | |
paul@0 | 122 | def __init__(self, data): |
paul@0 | 123 | self.data = list(data) |
paul@0 | 124 | |
paul@0 | 125 | def __repr__(self): |
paul@0 | 126 | return "%s(%r)" % (self.__class__.__name__, self.data) |
paul@0 | 127 | |
paul@0 | 128 | def __hash__(self): |
paul@0 | 129 | return hash(self.as_tuple()) |
paul@0 | 130 | |
paul@0 | 131 | def as_tuple(self): |
paul@0 | 132 | return tuple(self.data) |
paul@0 | 133 | |
paul@0 | 134 | def convert(self, resolution): |
paul@0 | 135 | return self._get_converter(resolution)(self) |
paul@0 | 136 | |
paul@0 | 137 | def __cmp__(self, other): |
paul@0 | 138 | |
paul@0 | 139 | """ |
paul@0 | 140 | The result of comparing this instance with 'other' is derived from a |
paul@0 | 141 | comparison of the instances' date(time) data at the highest common |
paul@0 | 142 | resolution, meaning that if a date is compared to a datetime, the |
paul@0 | 143 | datetime will be considered as a date. Thus, a date and a datetime |
paul@0 | 144 | referring to the same date will be considered equal. |
paul@0 | 145 | """ |
paul@0 | 146 | |
paul@0 | 147 | if not isinstance(other, Temporal): |
paul@0 | 148 | return NotImplemented |
paul@0 | 149 | else: |
paul@0 | 150 | data = self.as_tuple() |
paul@0 | 151 | other_data = other.as_tuple() |
paul@0 | 152 | length = min(len(data), len(other_data)) |
paul@0 | 153 | return cmp(data[:length], other_data[:length]) |
paul@0 | 154 | |
paul@0 | 155 | def __sub__(self, other): |
paul@0 | 156 | |
paul@0 | 157 | """ |
paul@0 | 158 | Return the difference between this object and the 'other' object at the |
paul@0 | 159 | highest common accuracy of both objects. |
paul@0 | 160 | """ |
paul@0 | 161 | |
paul@0 | 162 | if not isinstance(other, Temporal): |
paul@0 | 163 | return NotImplemented |
paul@0 | 164 | else: |
paul@0 | 165 | data = self.as_tuple() |
paul@0 | 166 | other_data = other.as_tuple() |
paul@0 | 167 | if len(data) < len(other_data): |
paul@0 | 168 | return len(self.until(other)) |
paul@0 | 169 | else: |
paul@0 | 170 | return len(other.until(self)) |
paul@0 | 171 | |
paul@0 | 172 | def _until(self, start, end, nextfn, prevfn): |
paul@0 | 173 | |
paul@0 | 174 | """ |
paul@0 | 175 | Return a collection of units of time by starting from the given 'start' |
paul@0 | 176 | and stepping across intervening units until 'end' is reached, using the |
paul@0 | 177 | given 'nextfn' and 'prevfn' to step from one unit to the next. |
paul@0 | 178 | """ |
paul@0 | 179 | |
paul@0 | 180 | current = start |
paul@0 | 181 | units = [current] |
paul@0 | 182 | if current < end: |
paul@0 | 183 | while current < end: |
paul@0 | 184 | current = nextfn(current) |
paul@0 | 185 | units.append(current) |
paul@0 | 186 | elif current > end: |
paul@0 | 187 | while current > end: |
paul@0 | 188 | current = prevfn(current) |
paul@0 | 189 | units.append(current) |
paul@0 | 190 | return units |
paul@0 | 191 | |
paul@0 | 192 | def ambiguous(self): |
paul@0 | 193 | |
paul@0 | 194 | "Only times can be ambiguous." |
paul@0 | 195 | |
paul@0 | 196 | return 0 |
paul@0 | 197 | |
paul@0 | 198 | class Month(Temporal): |
paul@0 | 199 | |
paul@0 | 200 | "A simple year-month representation." |
paul@0 | 201 | |
paul@0 | 202 | def __str__(self): |
paul@0 | 203 | return "%04d-%02d" % self.as_tuple()[:2] |
paul@0 | 204 | |
paul@0 | 205 | def as_datetime(self, day, hour, minute, second, zone): |
paul@0 | 206 | return DateTime(self.as_tuple() + (day, hour, minute, second, zone)) |
paul@0 | 207 | |
paul@0 | 208 | def as_date(self, day): |
paul@0 | 209 | if day < 0: |
paul@0 | 210 | weekday, ndays = self.month_properties() |
paul@0 | 211 | day = ndays + 1 + day |
paul@0 | 212 | return Date(self.as_tuple() + (day,)) |
paul@0 | 213 | |
paul@0 | 214 | def as_month(self): |
paul@0 | 215 | return self |
paul@0 | 216 | |
paul@0 | 217 | def year(self): |
paul@0 | 218 | return self.data[0] |
paul@0 | 219 | |
paul@0 | 220 | def month(self): |
paul@0 | 221 | return self.data[1] |
paul@0 | 222 | |
paul@0 | 223 | def month_properties(self): |
paul@0 | 224 | |
paul@0 | 225 | """ |
paul@0 | 226 | Return the weekday of the 1st of the month, along with the number of |
paul@0 | 227 | days, as a tuple. |
paul@0 | 228 | """ |
paul@0 | 229 | |
paul@0 | 230 | year, month = self.as_tuple()[:2] |
paul@0 | 231 | return calendar.monthrange(year, month) |
paul@0 | 232 | |
paul@0 | 233 | def month_update(self, n=1): |
paul@0 | 234 | |
paul@0 | 235 | "Return the month updated by 'n' months." |
paul@0 | 236 | |
paul@0 | 237 | year, month = self.as_tuple()[:2] |
paul@0 | 238 | return Month((year + (month - 1 + n) / 12, (month - 1 + n) % 12 + 1)) |
paul@0 | 239 | |
paul@0 | 240 | update = month_update |
paul@0 | 241 | |
paul@0 | 242 | def next_month(self): |
paul@0 | 243 | |
paul@0 | 244 | "Return the month following this one." |
paul@0 | 245 | |
paul@0 | 246 | return self.month_update(1) |
paul@0 | 247 | |
paul@0 | 248 | next = next_month |
paul@0 | 249 | |
paul@0 | 250 | def previous_month(self): |
paul@0 | 251 | |
paul@0 | 252 | "Return the month preceding this one." |
paul@0 | 253 | |
paul@0 | 254 | return self.month_update(-1) |
paul@0 | 255 | |
paul@0 | 256 | previous = previous_month |
paul@0 | 257 | |
paul@0 | 258 | def months_until(self, end): |
paul@0 | 259 | |
paul@0 | 260 | "Return the collection of months from this month until 'end'." |
paul@0 | 261 | |
paul@0 | 262 | return self._until(self.as_month(), end.as_month(), Month.next_month, Month.previous_month) |
paul@0 | 263 | |
paul@0 | 264 | until = months_until |
paul@0 | 265 | |
paul@0 | 266 | class Date(Month): |
paul@0 | 267 | |
paul@0 | 268 | "A simple year-month-day representation." |
paul@0 | 269 | |
paul@0 | 270 | def constrain(self): |
paul@0 | 271 | year, month, day = self.as_tuple()[:3] |
paul@0 | 272 | |
paul@0 | 273 | month = max(min(month, 12), 1) |
paul@0 | 274 | wd, last_day = calendar.monthrange(year, month) |
paul@0 | 275 | day = max(min(day, last_day), 1) |
paul@0 | 276 | |
paul@0 | 277 | self.data[1:3] = month, day |
paul@0 | 278 | |
paul@0 | 279 | def __str__(self): |
paul@0 | 280 | return "%04d-%02d-%02d" % self.as_tuple()[:3] |
paul@0 | 281 | |
paul@0 | 282 | def as_datetime(self, hour, minute, second, zone): |
paul@0 | 283 | return DateTime(self.as_tuple() + (hour, minute, second, zone)) |
paul@0 | 284 | |
paul@0 | 285 | def as_start_of_day(self): |
paul@0 | 286 | return self.as_datetime(None, None, None, None) |
paul@0 | 287 | |
paul@0 | 288 | def as_date(self): |
paul@0 | 289 | return self |
paul@0 | 290 | |
paul@0 | 291 | def as_datetime_or_date(self): |
paul@0 | 292 | return self |
paul@0 | 293 | |
paul@0 | 294 | def as_month(self): |
paul@0 | 295 | return Month(self.data[:2]) |
paul@0 | 296 | |
paul@0 | 297 | def day(self): |
paul@0 | 298 | return self.data[2] |
paul@0 | 299 | |
paul@0 | 300 | def day_update(self, n=1): |
paul@0 | 301 | |
paul@0 | 302 | "Return the month updated by 'n' days." |
paul@0 | 303 | |
paul@0 | 304 | delta = datetime.timedelta(n) |
paul@0 | 305 | dt = datetime.date(*self.as_tuple()[:3]) |
paul@0 | 306 | dt_new = dt + delta |
paul@0 | 307 | return Date((dt_new.year, dt_new.month, dt_new.day)) |
paul@0 | 308 | |
paul@0 | 309 | update = day_update |
paul@0 | 310 | |
paul@0 | 311 | def next_day(self): |
paul@0 | 312 | |
paul@0 | 313 | "Return the date following this one." |
paul@0 | 314 | |
paul@0 | 315 | year, month, day = self.as_tuple()[:3] |
paul@0 | 316 | _wd, end_day = calendar.monthrange(year, month) |
paul@0 | 317 | if day == end_day: |
paul@0 | 318 | if month == 12: |
paul@0 | 319 | return Date((year + 1, 1, 1)) |
paul@0 | 320 | else: |
paul@0 | 321 | return Date((year, month + 1, 1)) |
paul@0 | 322 | else: |
paul@0 | 323 | return Date((year, month, day + 1)) |
paul@0 | 324 | |
paul@0 | 325 | next = next_day |
paul@0 | 326 | |
paul@0 | 327 | def previous_day(self): |
paul@0 | 328 | |
paul@0 | 329 | "Return the date preceding this one." |
paul@0 | 330 | |
paul@0 | 331 | year, month, day = self.as_tuple()[:3] |
paul@0 | 332 | if day == 1: |
paul@0 | 333 | if month == 1: |
paul@0 | 334 | return Date((year - 1, 12, 31)) |
paul@0 | 335 | else: |
paul@0 | 336 | _wd, end_day = calendar.monthrange(year, month - 1) |
paul@0 | 337 | return Date((year, month - 1, end_day)) |
paul@0 | 338 | else: |
paul@0 | 339 | return Date((year, month, day - 1)) |
paul@0 | 340 | |
paul@0 | 341 | previous = previous_day |
paul@0 | 342 | |
paul@0 | 343 | def days_until(self, end): |
paul@0 | 344 | |
paul@0 | 345 | "Return the collection of days from this date until 'end'." |
paul@0 | 346 | |
paul@0 | 347 | return self._until(self.as_date(), end.as_date(), Date.next_day, Date.previous_day) |
paul@0 | 348 | |
paul@0 | 349 | until = days_until |
paul@0 | 350 | |
paul@0 | 351 | class DateTime(Date): |
paul@0 | 352 | |
paul@0 | 353 | "A simple date plus time representation." |
paul@0 | 354 | |
paul@0 | 355 | def constrain(self): |
paul@0 | 356 | Date.constrain(self) |
paul@0 | 357 | |
paul@0 | 358 | hour, minute, second = self.as_tuple()[3:6] |
paul@0 | 359 | |
paul@0 | 360 | if self.has_time(): |
paul@0 | 361 | hour = max(min(hour, 23), 0) |
paul@0 | 362 | minute = max(min(minute, 59), 0) |
paul@0 | 363 | |
paul@0 | 364 | if second is not None: |
paul@0 | 365 | second = max(min(second, 60), 0) # support leap seconds |
paul@0 | 366 | |
paul@0 | 367 | self.data[3:6] = hour, minute, second |
paul@0 | 368 | |
paul@0 | 369 | def __str__(self): |
paul@0 | 370 | return Date.__str__(self) + self.time_string() |
paul@0 | 371 | |
paul@6 | 372 | def time_string(self, zone_as_offset=0): |
paul@0 | 373 | if self.has_time(): |
paul@0 | 374 | data = self.as_tuple() |
paul@0 | 375 | time_str = " %02d:%02d" % data[3:5] |
paul@0 | 376 | if data[5] is not None: |
paul@0 | 377 | time_str += ":%02d" % data[5] |
paul@0 | 378 | if data[6] is not None: |
paul@6 | 379 | if zone_as_offset: |
paul@6 | 380 | utc_offset = self.utc_offset() |
paul@6 | 381 | if utc_offset: |
paul@6 | 382 | time_str += "%02d:02d" % utc_offset |
paul@6 | 383 | else: |
paul@6 | 384 | time_str += " %s" % data[6] |
paul@0 | 385 | return time_str |
paul@0 | 386 | else: |
paul@0 | 387 | return "" |
paul@0 | 388 | |
paul@0 | 389 | def as_HTTP_datetime_string(self): |
paul@0 | 390 | weekday = calendar.weekday(*self.data[:3]) |
paul@0 | 391 | return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (( |
paul@0 | 392 | getDayLabel(weekday), |
paul@0 | 393 | self.data[2], |
paul@0 | 394 | getMonthLabel(self.data[1]), |
paul@0 | 395 | self.data[0] |
paul@0 | 396 | ) + tuple(self.data[3:6])) |
paul@0 | 397 | |
paul@6 | 398 | def as_ISO8601_datetime_string(self): |
paul@6 | 399 | return Date.__str__(self) + self.time_string(1) |
paul@6 | 400 | |
paul@0 | 401 | def as_datetime(self): |
paul@0 | 402 | return self |
paul@0 | 403 | |
paul@0 | 404 | def as_date(self): |
paul@0 | 405 | return Date(self.data[:3]) |
paul@0 | 406 | |
paul@0 | 407 | def as_datetime_or_date(self): |
paul@0 | 408 | |
paul@0 | 409 | """ |
paul@0 | 410 | Return a date for this datetime if fields are missing. Otherwise, return |
paul@0 | 411 | this datetime itself. |
paul@0 | 412 | """ |
paul@0 | 413 | |
paul@0 | 414 | if not self.has_time(): |
paul@0 | 415 | return self.as_date() |
paul@0 | 416 | else: |
paul@0 | 417 | return self |
paul@0 | 418 | |
paul@0 | 419 | def __cmp__(self, other): |
paul@0 | 420 | |
paul@0 | 421 | """ |
paul@0 | 422 | The result of comparing this instance with 'other' is, if both instances |
paul@0 | 423 | are datetime instances, derived from a comparison of the datetimes |
paul@0 | 424 | converted to UTC. If one or both datetimes cannot be converted to UTC, |
paul@0 | 425 | the datetimes are compared using the basic temporal comparison which |
paul@0 | 426 | compares their raw time data. |
paul@0 | 427 | """ |
paul@0 | 428 | |
paul@0 | 429 | this = self |
paul@0 | 430 | |
paul@0 | 431 | if this.has_time(): |
paul@0 | 432 | if isinstance(other, DateTime): |
paul@0 | 433 | if other.has_time(): |
paul@0 | 434 | this_utc = this.to_utc() |
paul@0 | 435 | other_utc = other.to_utc() |
paul@0 | 436 | if this_utc is not None and other_utc is not None: |
paul@0 | 437 | return cmp(this_utc.as_tuple(), other_utc.as_tuple()) |
paul@0 | 438 | else: |
paul@0 | 439 | other = other.padded() |
paul@0 | 440 | else: |
paul@0 | 441 | this = this.padded() |
paul@0 | 442 | |
paul@0 | 443 | return Date.__cmp__(this, other) |
paul@0 | 444 | |
paul@0 | 445 | def has_time(self): |
paul@0 | 446 | |
paul@0 | 447 | """ |
paul@0 | 448 | Return whether this object has any time information. Objects without |
paul@0 | 449 | time information can refer to the very start of a day. |
paul@0 | 450 | """ |
paul@0 | 451 | |
paul@0 | 452 | return self.data[3] is not None and self.data[4] is not None |
paul@0 | 453 | |
paul@0 | 454 | def time(self): |
paul@0 | 455 | return self.data[3:] |
paul@0 | 456 | |
paul@0 | 457 | def seconds(self): |
paul@0 | 458 | return self.data[5] |
paul@0 | 459 | |
paul@0 | 460 | def time_zone(self): |
paul@0 | 461 | return self.data[6] |
paul@0 | 462 | |
paul@0 | 463 | def set_time_zone(self, value): |
paul@0 | 464 | self.data[6] = value |
paul@0 | 465 | |
paul@0 | 466 | def padded(self, empty_value=0): |
paul@0 | 467 | |
paul@0 | 468 | """ |
paul@0 | 469 | Return a datetime with missing fields defined as being the given |
paul@0 | 470 | 'empty_value' or 0 if not specified. |
paul@0 | 471 | """ |
paul@0 | 472 | |
paul@0 | 473 | data = [] |
paul@0 | 474 | for x in self.data[:6]: |
paul@0 | 475 | if x is None: |
paul@0 | 476 | data.append(empty_value) |
paul@0 | 477 | else: |
paul@0 | 478 | data.append(x) |
paul@0 | 479 | |
paul@0 | 480 | data += self.data[6:] |
paul@0 | 481 | return DateTime(data) |
paul@0 | 482 | |
paul@0 | 483 | def to_utc(self): |
paul@0 | 484 | |
paul@0 | 485 | """ |
paul@0 | 486 | Return this object converted to UTC, or None if such a conversion is not |
paul@0 | 487 | defined. |
paul@0 | 488 | """ |
paul@0 | 489 | |
paul@0 | 490 | if not self.has_time(): |
paul@0 | 491 | return None |
paul@0 | 492 | |
paul@0 | 493 | offset = self.utc_offset() |
paul@0 | 494 | if offset: |
paul@0 | 495 | hours, minutes = offset |
paul@0 | 496 | |
paul@0 | 497 | # Invert the offset to get the correction. |
paul@0 | 498 | |
paul@0 | 499 | hours, minutes = -hours, -minutes |
paul@0 | 500 | |
paul@0 | 501 | # Get the components. |
paul@0 | 502 | |
paul@0 | 503 | hour, minute, second, zone = self.time() |
paul@0 | 504 | date = self.as_date() |
paul@0 | 505 | |
paul@0 | 506 | # Add the minutes and hours. |
paul@0 | 507 | |
paul@0 | 508 | minute += minutes |
paul@0 | 509 | if minute < 0 or minute > 59: |
paul@0 | 510 | hour += minute / 60 |
paul@0 | 511 | minute = minute % 60 |
paul@0 | 512 | |
paul@0 | 513 | # NOTE: This makes various assumptions and probably would not work |
paul@0 | 514 | # NOTE: for general arithmetic. |
paul@0 | 515 | |
paul@0 | 516 | hour += hours |
paul@0 | 517 | if hour < 0: |
paul@0 | 518 | date = date.previous_day() |
paul@0 | 519 | hour += 24 |
paul@0 | 520 | elif hour > 23: |
paul@0 | 521 | date = date.next_day() |
paul@0 | 522 | hour -= 24 |
paul@0 | 523 | |
paul@0 | 524 | return date.as_datetime(hour, minute, second, "UTC") |
paul@0 | 525 | |
paul@0 | 526 | # Cannot convert. |
paul@0 | 527 | |
paul@0 | 528 | else: |
paul@0 | 529 | return None |
paul@0 | 530 | |
paul@0 | 531 | def utc_offset(self): |
paul@0 | 532 | |
paul@0 | 533 | "Return the UTC offset in hours and minutes." |
paul@0 | 534 | |
paul@0 | 535 | zone = self.time_zone() |
paul@0 | 536 | if not zone: |
paul@0 | 537 | return None |
paul@0 | 538 | |
paul@0 | 539 | # Support explicit UTC zones. |
paul@0 | 540 | |
paul@0 | 541 | if zone == "UTC": |
paul@0 | 542 | return 0, 0 |
paul@0 | 543 | |
paul@0 | 544 | # Attempt to return a UTC offset where an explicit offset has been set. |
paul@0 | 545 | |
paul@0 | 546 | match = timezone_offset_regexp.match(zone) |
paul@0 | 547 | if match: |
paul@0 | 548 | if match.group("sign") == "-": |
paul@0 | 549 | sign = -1 |
paul@0 | 550 | else: |
paul@0 | 551 | sign = 1 |
paul@0 | 552 | |
paul@0 | 553 | hours = int(match.group("hours")) * sign |
paul@0 | 554 | minutes = int(match.group("minutes") or 0) * sign |
paul@0 | 555 | return hours, minutes |
paul@0 | 556 | |
paul@0 | 557 | # Attempt to handle Olson time zone identifiers. |
paul@0 | 558 | |
paul@0 | 559 | dt = self.as_olson_datetime() |
paul@0 | 560 | if dt: |
paul@0 | 561 | seconds = dt.utcoffset().seconds |
paul@0 | 562 | hours = seconds / 3600 |
paul@0 | 563 | minutes = (seconds % 3600) / 60 |
paul@0 | 564 | return hours, minutes |
paul@0 | 565 | |
paul@0 | 566 | # Otherwise return None. |
paul@0 | 567 | |
paul@0 | 568 | return None |
paul@0 | 569 | |
paul@0 | 570 | def olson_identifier(self): |
paul@0 | 571 | |
paul@0 | 572 | "Return the Olson identifier from any zone information." |
paul@0 | 573 | |
paul@0 | 574 | zone = self.time_zone() |
paul@0 | 575 | if not zone: |
paul@0 | 576 | return None |
paul@0 | 577 | |
paul@0 | 578 | # Attempt to match an identifier. |
paul@0 | 579 | |
paul@0 | 580 | match = timezone_olson_regexp.match(zone) |
paul@0 | 581 | if match: |
paul@0 | 582 | return match.group("olson") |
paul@0 | 583 | else: |
paul@0 | 584 | return None |
paul@0 | 585 | |
paul@0 | 586 | def _as_olson_datetime(self, hours=None): |
paul@0 | 587 | |
paul@0 | 588 | """ |
paul@0 | 589 | Return a Python datetime object for this datetime interpreted using any |
paul@0 | 590 | Olson time zone identifier and the given 'hours' offset, raising one of |
paul@0 | 591 | the pytz exceptions in case of ambiguity. |
paul@0 | 592 | """ |
paul@0 | 593 | |
paul@0 | 594 | olson = self.olson_identifier() |
paul@0 | 595 | if olson and pytz: |
paul@0 | 596 | tz = pytz.timezone(olson) |
paul@0 | 597 | data = self.padded().as_tuple()[:6] |
paul@0 | 598 | dt = datetime.datetime(*data) |
paul@0 | 599 | |
paul@0 | 600 | # With an hours offset, find a time probably in a previously |
paul@0 | 601 | # applicable time zone. |
paul@0 | 602 | |
paul@0 | 603 | if hours is not None: |
paul@0 | 604 | td = datetime.timedelta(0, hours * 3600) |
paul@0 | 605 | dt += td |
paul@0 | 606 | |
paul@0 | 607 | ldt = tz.localize(dt, None) |
paul@0 | 608 | |
paul@0 | 609 | # With an hours offset, adjust the time to define it within the |
paul@0 | 610 | # previously applicable time zone but at the presumably intended |
paul@0 | 611 | # position. |
paul@0 | 612 | |
paul@0 | 613 | if hours is not None: |
paul@0 | 614 | ldt -= td |
paul@0 | 615 | |
paul@0 | 616 | return ldt |
paul@0 | 617 | else: |
paul@0 | 618 | return None |
paul@0 | 619 | |
paul@0 | 620 | def as_olson_datetime(self): |
paul@0 | 621 | |
paul@0 | 622 | """ |
paul@0 | 623 | Return a Python datetime object for this datetime interpreted using any |
paul@0 | 624 | Olson time zone identifier, choosing the time from the zone before the |
paul@0 | 625 | period of ambiguity. |
paul@0 | 626 | """ |
paul@0 | 627 | |
paul@0 | 628 | try: |
paul@0 | 629 | return self._as_olson_datetime() |
paul@0 | 630 | except (pytz.UnknownTimeZoneError, pytz.AmbiguousTimeError): |
paul@0 | 631 | |
paul@0 | 632 | # Try again, using an earlier local time and then stepping forward |
paul@0 | 633 | # in the chosen zone. |
paul@0 | 634 | # NOTE: Four hours earlier seems reasonable. |
paul@0 | 635 | |
paul@0 | 636 | return self._as_olson_datetime(-4) |
paul@0 | 637 | |
paul@0 | 638 | def ambiguous(self): |
paul@0 | 639 | |
paul@0 | 640 | "Return whether the time is local and ambiguous." |
paul@0 | 641 | |
paul@0 | 642 | try: |
paul@0 | 643 | self._as_olson_datetime() |
paul@0 | 644 | except (pytz.UnknownTimeZoneError, pytz.AmbiguousTimeError): |
paul@0 | 645 | return 1 |
paul@0 | 646 | |
paul@0 | 647 | return 0 |
paul@0 | 648 | |
paul@0 | 649 | class Timespan(ActsAsTimespan, Convertible): |
paul@0 | 650 | |
paul@0 | 651 | """ |
paul@0 | 652 | A period of time which can be compared against others to check for overlaps. |
paul@0 | 653 | """ |
paul@0 | 654 | |
paul@0 | 655 | def __init__(self, start, end): |
paul@0 | 656 | self.start = start |
paul@0 | 657 | self.end = end |
paul@0 | 658 | |
paul@0 | 659 | # NOTE: Should perhaps catch ambiguous time problems elsewhere. |
paul@0 | 660 | |
paul@0 | 661 | if self.ambiguous() and self.start is not None and self.end is not None and start > end: |
paul@0 | 662 | self.start, self.end = end, start |
paul@0 | 663 | |
paul@0 | 664 | def __repr__(self): |
paul@0 | 665 | return "%s(%r, %r)" % (self.__class__.__name__, self.start, self.end) |
paul@0 | 666 | |
paul@0 | 667 | def __hash__(self): |
paul@0 | 668 | return hash((self.start, self.end)) |
paul@0 | 669 | |
paul@0 | 670 | def as_timespan(self): |
paul@0 | 671 | return self |
paul@0 | 672 | |
paul@0 | 673 | def as_limits(self): |
paul@0 | 674 | return self.start, self.end |
paul@0 | 675 | |
paul@0 | 676 | def ambiguous(self): |
paul@0 | 677 | return self.start is not None and self.start.ambiguous() or self.end is not None and self.end.ambiguous() |
paul@0 | 678 | |
paul@0 | 679 | def convert(self, resolution): |
paul@0 | 680 | return Timespan(*map(self._get_converter(resolution), self.as_limits())) |
paul@0 | 681 | |
paul@0 | 682 | def is_before(self, a, b): |
paul@0 | 683 | |
paul@0 | 684 | """ |
paul@0 | 685 | Return whether 'a' is before 'b'. Since the end datetime of one period |
paul@0 | 686 | may be the same as the start datetime of another period, and yet the |
paul@0 | 687 | first period is intended to be concluded by the end datetime and not |
paul@0 | 688 | overlap with the other period, a different test is employed for datetime |
paul@0 | 689 | comparisons. |
paul@0 | 690 | """ |
paul@0 | 691 | |
paul@0 | 692 | # Datetimes without times can be equal to dates and be considered as |
paul@0 | 693 | # occurring before those dates. Generally, datetimes should not be |
paul@0 | 694 | # produced without time information as getDateTime converts such |
paul@0 | 695 | # datetimes to dates. |
paul@0 | 696 | |
paul@0 | 697 | if isinstance(a, DateTime) and (isinstance(b, DateTime) or not a.has_time()): |
paul@0 | 698 | return a <= b |
paul@0 | 699 | else: |
paul@0 | 700 | return a < b |
paul@0 | 701 | |
paul@0 | 702 | def __contains__(self, other): |
paul@0 | 703 | |
paul@0 | 704 | """ |
paul@0 | 705 | This instance is considered to contain 'other' if one is not before or |
paul@0 | 706 | after the other. If this instance overlaps or coincides with 'other', |
paul@0 | 707 | then 'other' is regarded as belonging to this instance's time period. |
paul@0 | 708 | """ |
paul@0 | 709 | |
paul@0 | 710 | return self == other |
paul@0 | 711 | |
paul@0 | 712 | def __cmp__(self, other): |
paul@0 | 713 | |
paul@0 | 714 | """ |
paul@0 | 715 | Return whether this timespan occupies the same period of time as the |
paul@0 | 716 | 'other'. Timespans are considered less than others if their end points |
paul@0 | 717 | precede the other's start point, and are considered greater than others |
paul@0 | 718 | if their start points follow the other's end point. |
paul@0 | 719 | """ |
paul@0 | 720 | |
paul@0 | 721 | if isinstance(other, ActsAsTimespan): |
paul@0 | 722 | other = other.as_timespan() |
paul@0 | 723 | |
paul@0 | 724 | if self.end is not None and other.start is not None and self.is_before(self.end, other.start): |
paul@0 | 725 | return -1 |
paul@0 | 726 | elif self.start is not None and other.end is not None and self.is_before(other.end, self.start): |
paul@0 | 727 | return 1 |
paul@0 | 728 | else: |
paul@0 | 729 | return 0 |
paul@0 | 730 | |
paul@0 | 731 | else: |
paul@0 | 732 | if self.end is not None and self.is_before(self.end, other): |
paul@0 | 733 | return -1 |
paul@0 | 734 | elif self.start is not None and self.is_before(other, self.start): |
paul@0 | 735 | return 1 |
paul@0 | 736 | else: |
paul@0 | 737 | return 0 |
paul@0 | 738 | |
paul@0 | 739 | class TimespanCollection: |
paul@0 | 740 | |
paul@0 | 741 | """ |
paul@0 | 742 | A class providing a list-like interface supporting membership tests at a |
paul@0 | 743 | particular resolution in order to maintain a collection of non-overlapping |
paul@0 | 744 | timespans. |
paul@0 | 745 | """ |
paul@0 | 746 | |
paul@0 | 747 | def __init__(self, resolution, values=None): |
paul@0 | 748 | self.resolution = resolution |
paul@0 | 749 | self.values = values or [] |
paul@0 | 750 | |
paul@0 | 751 | def as_timespan(self): |
paul@0 | 752 | return Timespan(*self.as_limits()) |
paul@0 | 753 | |
paul@0 | 754 | def as_limits(self): |
paul@0 | 755 | |
paul@0 | 756 | "Return the earliest and latest points in time for this collection." |
paul@0 | 757 | |
paul@0 | 758 | if not self.values: |
paul@0 | 759 | return None, None |
paul@0 | 760 | else: |
paul@0 | 761 | first, last = self.values[0], self.values[-1] |
paul@0 | 762 | if isinstance(first, ActsAsTimespan): |
paul@0 | 763 | first = first.as_timespan().start |
paul@0 | 764 | if isinstance(last, ActsAsTimespan): |
paul@0 | 765 | last = last.as_timespan().end |
paul@0 | 766 | return first, last |
paul@0 | 767 | |
paul@0 | 768 | def convert(self, value): |
paul@0 | 769 | if isinstance(value, ActsAsTimespan): |
paul@0 | 770 | ts = value.as_timespan() |
paul@0 | 771 | return ts and ts.convert(self.resolution) |
paul@0 | 772 | else: |
paul@0 | 773 | return value.convert(self.resolution) |
paul@0 | 774 | |
paul@0 | 775 | def __iter__(self): |
paul@0 | 776 | return iter(self.values) |
paul@0 | 777 | |
paul@0 | 778 | def __len__(self): |
paul@0 | 779 | return len(self.values) |
paul@0 | 780 | |
paul@0 | 781 | def __getitem__(self, i): |
paul@0 | 782 | return self.values[i] |
paul@0 | 783 | |
paul@0 | 784 | def __setitem__(self, i, value): |
paul@0 | 785 | self.values[i] = value |
paul@0 | 786 | |
paul@0 | 787 | def __contains__(self, value): |
paul@0 | 788 | test_value = self.convert(value) |
paul@0 | 789 | return test_value in self.values |
paul@0 | 790 | |
paul@0 | 791 | def append(self, value): |
paul@0 | 792 | self.values.append(value) |
paul@0 | 793 | |
paul@0 | 794 | def insert(self, i, value): |
paul@0 | 795 | self.values.insert(i, value) |
paul@0 | 796 | |
paul@0 | 797 | def pop(self): |
paul@0 | 798 | return self.values.pop() |
paul@0 | 799 | |
paul@0 | 800 | def insert_in_order(self, value): |
paul@0 | 801 | bisect.insort_left(self, value) |
paul@0 | 802 | |
paul@0 | 803 | def getDate(s): |
paul@0 | 804 | |
paul@0 | 805 | "Parse the string 's', extracting and returning a date object." |
paul@0 | 806 | |
paul@0 | 807 | dt = getDateTime(s) |
paul@0 | 808 | if dt is not None: |
paul@0 | 809 | return dt.as_date() |
paul@0 | 810 | else: |
paul@0 | 811 | return None |
paul@0 | 812 | |
paul@0 | 813 | def getDateTime(s): |
paul@0 | 814 | |
paul@0 | 815 | """ |
paul@0 | 816 | Parse the string 's', extracting and returning a datetime object where time |
paul@0 | 817 | information has been given or a date object where time information is |
paul@0 | 818 | absent. |
paul@0 | 819 | """ |
paul@0 | 820 | |
paul@0 | 821 | m = datetime_regexp.search(s) |
paul@0 | 822 | if m: |
paul@0 | 823 | groups = list(m.groups()) |
paul@0 | 824 | |
paul@0 | 825 | # Convert date and time data to integer or None. |
paul@0 | 826 | |
paul@0 | 827 | return DateTime(map(int_or_none, groups[:6]) + [m.group("zone")]).as_datetime_or_date() |
paul@0 | 828 | else: |
paul@0 | 829 | return None |
paul@0 | 830 | |
paul@0 | 831 | def getDateFromCalendar(s): |
paul@0 | 832 | |
paul@0 | 833 | """ |
paul@0 | 834 | Parse the iCalendar format string 's', extracting and returning a date |
paul@0 | 835 | object. |
paul@0 | 836 | """ |
paul@0 | 837 | |
paul@0 | 838 | dt = getDateTimeFromCalendar(s) |
paul@0 | 839 | if dt is not None: |
paul@0 | 840 | return dt.as_date() |
paul@0 | 841 | else: |
paul@0 | 842 | return None |
paul@0 | 843 | |
paul@0 | 844 | def getDateTimeFromCalendar(s): |
paul@0 | 845 | |
paul@0 | 846 | """ |
paul@0 | 847 | Parse the iCalendar format datetime string 's', extracting and returning a |
paul@0 | 848 | datetime object where time information has been given or a date object where |
paul@0 | 849 | time information is absent. |
paul@0 | 850 | """ |
paul@0 | 851 | |
paul@0 | 852 | m = datetime_icalendar_regexp.search(s) |
paul@0 | 853 | if m: |
paul@0 | 854 | groups = list(m.groups()) |
paul@0 | 855 | |
paul@0 | 856 | # Convert date and time data to integer or None. |
paul@0 | 857 | |
paul@0 | 858 | return DateTime(map(int_or_none, groups[:6]) + [m.group("utc") and "UTC" or None]).as_datetime_or_date() |
paul@0 | 859 | else: |
paul@0 | 860 | return None |
paul@0 | 861 | |
paul@0 | 862 | def getDateStrings(s): |
paul@0 | 863 | |
paul@0 | 864 | "Parse the string 's', extracting and returning all date strings." |
paul@0 | 865 | |
paul@0 | 866 | start = 0 |
paul@0 | 867 | m = date_regexp.search(s, start) |
paul@0 | 868 | l = [] |
paul@0 | 869 | while m: |
paul@0 | 870 | l.append("-".join(m.groups())) |
paul@0 | 871 | m = date_regexp.search(s, m.end()) |
paul@0 | 872 | return l |
paul@0 | 873 | |
paul@0 | 874 | def getMonth(s): |
paul@0 | 875 | |
paul@0 | 876 | "Parse the string 's', extracting and returning a month object." |
paul@0 | 877 | |
paul@0 | 878 | m = month_regexp.search(s) |
paul@0 | 879 | if m: |
paul@0 | 880 | return Month(map(int, m.groups())) |
paul@0 | 881 | else: |
paul@0 | 882 | return None |
paul@0 | 883 | |
paul@0 | 884 | def getCurrentDate(): |
paul@0 | 885 | |
paul@0 | 886 | "Return the current date as a (year, month, day) tuple." |
paul@0 | 887 | |
paul@0 | 888 | today = datetime.date.today() |
paul@0 | 889 | return Date((today.year, today.month, today.day)) |
paul@0 | 890 | |
paul@0 | 891 | def getCurrentMonth(): |
paul@0 | 892 | |
paul@0 | 893 | "Return the current month as a (year, month) tuple." |
paul@0 | 894 | |
paul@0 | 895 | today = datetime.date.today() |
paul@0 | 896 | return Month((today.year, today.month)) |
paul@0 | 897 | |
paul@0 | 898 | def getCurrentYear(): |
paul@0 | 899 | |
paul@0 | 900 | "Return the current year." |
paul@0 | 901 | |
paul@0 | 902 | today = datetime.date.today() |
paul@0 | 903 | return today.year |
paul@0 | 904 | |
paul@0 | 905 | # vim: tabstop=4 expandtab shiftwidth=4 |