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