Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1 | /* C implementation for the date/time type documented at |
| 2 | * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage |
| 3 | */ |
| 4 | |
| 5 | #include "Python.h" |
| 6 | #include "modsupport.h" |
| 7 | #include "structmember.h" |
| 8 | |
| 9 | #include <time.h> |
| 10 | |
| 11 | #include "datetime.h" |
| 12 | |
| 13 | /* We require that C int be at least 32 bits, and use int virtually |
| 14 | * everywhere. In just a few cases we use a temp long, where a Python |
| 15 | * API returns a C long. In such cases, we have to ensure that the |
| 16 | * final result fits in a C int (this can be an issue on 64-bit boxes). |
| 17 | */ |
| 18 | #if SIZEOF_INT < 4 |
| 19 | # error "datetime.c requires that C int have at least 32 bits" |
| 20 | #endif |
| 21 | |
| 22 | #define MINYEAR 1 |
| 23 | #define MAXYEAR 9999 |
| 24 | |
| 25 | /* Nine decimal digits is easy to communicate, and leaves enough room |
| 26 | * so that two delta days can be added w/o fear of overflowing a signed |
| 27 | * 32-bit int, and with plenty of room left over to absorb any possible |
| 28 | * carries from adding seconds. |
| 29 | */ |
| 30 | #define MAX_DELTA_DAYS 999999999 |
| 31 | |
| 32 | /* Rename the long macros in datetime.h to more reasonable short names. */ |
| 33 | #define GET_YEAR PyDateTime_GET_YEAR |
| 34 | #define GET_MONTH PyDateTime_GET_MONTH |
| 35 | #define GET_DAY PyDateTime_GET_DAY |
| 36 | #define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR |
| 37 | #define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE |
| 38 | #define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND |
| 39 | #define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND |
| 40 | |
| 41 | /* Date accessors for date and datetime. */ |
| 42 | #define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ |
| 43 | ((o)->data[1] = ((v) & 0x00ff))) |
| 44 | #define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v)) |
| 45 | #define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) |
| 46 | |
| 47 | /* Date/Time accessors for datetime. */ |
| 48 | #define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v)) |
| 49 | #define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v)) |
| 50 | #define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v)) |
| 51 | #define DATE_SET_MICROSECOND(o, v) \ |
| 52 | (((o)->data[7] = ((v) & 0xff0000) >> 16), \ |
| 53 | ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ |
| 54 | ((o)->data[9] = ((v) & 0x0000ff))) |
| 55 | |
| 56 | /* Time accessors for time. */ |
| 57 | #define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR |
| 58 | #define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE |
| 59 | #define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND |
| 60 | #define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND |
| 61 | #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) |
| 62 | #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) |
| 63 | #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) |
| 64 | #define TIME_SET_MICROSECOND(o, v) \ |
| 65 | (((o)->data[3] = ((v) & 0xff0000) >> 16), \ |
| 66 | ((o)->data[4] = ((v) & 0x00ff00) >> 8), \ |
| 67 | ((o)->data[5] = ((v) & 0x0000ff))) |
| 68 | |
| 69 | /* Delta accessors for timedelta. */ |
| 70 | #define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) |
| 71 | #define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) |
| 72 | #define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds) |
| 73 | |
| 74 | #define SET_TD_DAYS(o, v) ((o)->days = (v)) |
| 75 | #define SET_TD_SECONDS(o, v) ((o)->seconds = (v)) |
| 76 | #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v)) |
| 77 | |
| 78 | /* Forward declarations. */ |
| 79 | static PyTypeObject PyDateTime_DateType; |
| 80 | static PyTypeObject PyDateTime_DateTimeType; |
| 81 | static PyTypeObject PyDateTime_DateTimeTZType; |
| 82 | static PyTypeObject PyDateTime_DeltaType; |
| 83 | static PyTypeObject PyDateTime_TimeType; |
| 84 | static PyTypeObject PyDateTime_TZInfoType; |
| 85 | static PyTypeObject PyDateTime_TimeTZType; |
| 86 | |
| 87 | /* --------------------------------------------------------------------------- |
| 88 | * Math utilities. |
| 89 | */ |
| 90 | |
| 91 | /* k = i+j overflows iff k differs in sign from both inputs, |
| 92 | * iff k^i has sign bit set and k^j has sign bit set, |
| 93 | * iff (k^i)&(k^j) has sign bit set. |
| 94 | */ |
| 95 | #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \ |
| 96 | ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0) |
| 97 | |
| 98 | /* Compute Python divmod(x, y), returning the quotient and storing the |
| 99 | * remainder into *r. The quotient is the floor of x/y, and that's |
| 100 | * the real point of this. C will probably truncate instead (C99 |
| 101 | * requires truncation; C89 left it implementation-defined). |
| 102 | * Simplification: we *require* that y > 0 here. That's appropriate |
| 103 | * for all the uses made of it. This simplifies the code and makes |
| 104 | * the overflow case impossible (divmod(LONG_MIN, -1) is the only |
| 105 | * overflow case). |
| 106 | */ |
| 107 | static int |
| 108 | divmod(int x, int y, int *r) |
| 109 | { |
| 110 | int quo; |
| 111 | |
| 112 | assert(y > 0); |
| 113 | quo = x / y; |
| 114 | *r = x - quo * y; |
| 115 | if (*r < 0) { |
| 116 | --quo; |
| 117 | *r += y; |
| 118 | } |
| 119 | assert(0 <= *r && *r < y); |
| 120 | return quo; |
| 121 | } |
| 122 | |
| 123 | /* --------------------------------------------------------------------------- |
| 124 | * General calendrical helper functions |
| 125 | */ |
| 126 | |
| 127 | /* For each month ordinal in 1..12, the number of days in that month, |
| 128 | * and the number of days before that month in the same year. These |
| 129 | * are correct for non-leap years only. |
| 130 | */ |
| 131 | static int _days_in_month[] = { |
| 132 | 0, /* unused; this vector uses 1-based indexing */ |
| 133 | 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 |
| 134 | }; |
| 135 | |
| 136 | static int _days_before_month[] = { |
| 137 | 0, /* unused; this vector uses 1-based indexing */ |
| 138 | 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 |
| 139 | }; |
| 140 | |
| 141 | /* year -> 1 if leap year, else 0. */ |
| 142 | static int |
| 143 | is_leap(int year) |
| 144 | { |
| 145 | /* Cast year to unsigned. The result is the same either way, but |
| 146 | * C can generate faster code for unsigned mod than for signed |
| 147 | * mod (especially for % 4 -- a good compiler should just grab |
| 148 | * the last 2 bits when the LHS is unsigned). |
| 149 | */ |
| 150 | const unsigned int ayear = (unsigned int)year; |
| 151 | return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0); |
| 152 | } |
| 153 | |
| 154 | /* year, month -> number of days in that month in that year */ |
| 155 | static int |
| 156 | days_in_month(int year, int month) |
| 157 | { |
| 158 | assert(month >= 1); |
| 159 | assert(month <= 12); |
| 160 | if (month == 2 && is_leap(year)) |
| 161 | return 29; |
| 162 | else |
| 163 | return _days_in_month[month]; |
| 164 | } |
| 165 | |
| 166 | /* year, month -> number of days in year preceeding first day of month */ |
| 167 | static int |
| 168 | days_before_month(int year, int month) |
| 169 | { |
| 170 | int days; |
| 171 | |
| 172 | assert(month >= 1); |
| 173 | assert(month <= 12); |
| 174 | days = _days_before_month[month]; |
| 175 | if (month > 2 && is_leap(year)) |
| 176 | ++days; |
| 177 | return days; |
| 178 | } |
| 179 | |
| 180 | /* year -> number of days before January 1st of year. Remember that we |
| 181 | * start with year 1, so days_before_year(1) == 0. |
| 182 | */ |
| 183 | static int |
| 184 | days_before_year(int year) |
| 185 | { |
| 186 | int y = year - 1; |
| 187 | /* This is incorrect if year <= 0; we really want the floor |
| 188 | * here. But so long as MINYEAR is 1, the smallest year this |
| 189 | * can see is 0 (this can happen in some normalization endcases), |
| 190 | * so we'll just special-case that. |
| 191 | */ |
| 192 | assert (year >= 0); |
| 193 | if (y >= 0) |
| 194 | return y*365 + y/4 - y/100 + y/400; |
| 195 | else { |
| 196 | assert(y == -1); |
| 197 | return -366; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /* Number of days in 4, 100, and 400 year cycles. That these have |
| 202 | * the correct values is asserted in the module init function. |
| 203 | */ |
| 204 | #define DI4Y 1461 /* days_before_year(5); days in 4 years */ |
| 205 | #define DI100Y 36524 /* days_before_year(101); days in 100 years */ |
| 206 | #define DI400Y 146097 /* days_before_year(401); days in 400 years */ |
| 207 | |
| 208 | /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */ |
| 209 | static void |
| 210 | ord_to_ymd(int ordinal, int *year, int *month, int *day) |
| 211 | { |
| 212 | int n, n1, n4, n100, n400, leapyear, preceding; |
| 213 | |
| 214 | /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of |
| 215 | * leap years repeats exactly every 400 years. The basic strategy is |
| 216 | * to find the closest 400-year boundary at or before ordinal, then |
| 217 | * work with the offset from that boundary to ordinal. Life is much |
| 218 | * clearer if we subtract 1 from ordinal first -- then the values |
| 219 | * of ordinal at 400-year boundaries are exactly those divisible |
| 220 | * by DI400Y: |
| 221 | * |
| 222 | * D M Y n n-1 |
| 223 | * -- --- ---- ---------- ---------------- |
| 224 | * 31 Dec -400 -DI400Y -DI400Y -1 |
| 225 | * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary |
| 226 | * ... |
| 227 | * 30 Dec 000 -1 -2 |
| 228 | * 31 Dec 000 0 -1 |
| 229 | * 1 Jan 001 1 0 400-year boundary |
| 230 | * 2 Jan 001 2 1 |
| 231 | * 3 Jan 001 3 2 |
| 232 | * ... |
| 233 | * 31 Dec 400 DI400Y DI400Y -1 |
| 234 | * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary |
| 235 | */ |
| 236 | assert(ordinal >= 1); |
| 237 | --ordinal; |
| 238 | n400 = ordinal / DI400Y; |
| 239 | n = ordinal % DI400Y; |
| 240 | *year = n400 * 400 + 1; |
| 241 | |
| 242 | /* Now n is the (non-negative) offset, in days, from January 1 of |
| 243 | * year, to the desired date. Now compute how many 100-year cycles |
| 244 | * precede n. |
| 245 | * Note that it's possible for n100 to equal 4! In that case 4 full |
| 246 | * 100-year cycles precede the desired day, which implies the |
| 247 | * desired day is December 31 at the end of a 400-year cycle. |
| 248 | */ |
| 249 | n100 = n / DI100Y; |
| 250 | n = n % DI100Y; |
| 251 | |
| 252 | /* Now compute how many 4-year cycles precede it. */ |
| 253 | n4 = n / DI4Y; |
| 254 | n = n % DI4Y; |
| 255 | |
| 256 | /* And now how many single years. Again n1 can be 4, and again |
| 257 | * meaning that the desired day is December 31 at the end of the |
| 258 | * 4-year cycle. |
| 259 | */ |
| 260 | n1 = n / 365; |
| 261 | n = n % 365; |
| 262 | |
| 263 | *year += n100 * 100 + n4 * 4 + n1; |
| 264 | if (n1 == 4 || n100 == 4) { |
| 265 | assert(n == 0); |
| 266 | *year -= 1; |
| 267 | *month = 12; |
| 268 | *day = 31; |
| 269 | return; |
| 270 | } |
| 271 | |
| 272 | /* Now the year is correct, and n is the offset from January 1. We |
| 273 | * find the month via an estimate that's either exact or one too |
| 274 | * large. |
| 275 | */ |
| 276 | leapyear = n1 == 3 && (n4 != 24 || n100 == 3); |
| 277 | assert(leapyear == is_leap(*year)); |
| 278 | *month = (n + 50) >> 5; |
| 279 | preceding = (_days_before_month[*month] + (*month > 2 && leapyear)); |
| 280 | if (preceding > n) { |
| 281 | /* estimate is too large */ |
| 282 | *month -= 1; |
| 283 | preceding -= days_in_month(*year, *month); |
| 284 | } |
| 285 | n -= preceding; |
| 286 | assert(0 <= n); |
| 287 | assert(n < days_in_month(*year, *month)); |
| 288 | |
| 289 | *day = n + 1; |
| 290 | } |
| 291 | |
| 292 | /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */ |
| 293 | static int |
| 294 | ymd_to_ord(int year, int month, int day) |
| 295 | { |
| 296 | return days_before_year(year) + days_before_month(year, month) + day; |
| 297 | } |
| 298 | |
| 299 | /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */ |
| 300 | static int |
| 301 | weekday(int year, int month, int day) |
| 302 | { |
| 303 | return (ymd_to_ord(year, month, day) + 6) % 7; |
| 304 | } |
| 305 | |
| 306 | /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the |
| 307 | * first calendar week containing a Thursday. |
| 308 | */ |
| 309 | static int |
| 310 | iso_week1_monday(int year) |
| 311 | { |
| 312 | int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */ |
| 313 | /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */ |
| 314 | int first_weekday = (first_day + 6) % 7; |
| 315 | /* ordinal of closest Monday at or before 1/1 */ |
| 316 | int week1_monday = first_day - first_weekday; |
| 317 | |
| 318 | if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */ |
| 319 | week1_monday += 7; |
| 320 | return week1_monday; |
| 321 | } |
| 322 | |
| 323 | /* --------------------------------------------------------------------------- |
| 324 | * Range checkers. |
| 325 | */ |
| 326 | |
| 327 | /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0. |
| 328 | * If not, raise OverflowError and return -1. |
| 329 | */ |
| 330 | static int |
| 331 | check_delta_day_range(int days) |
| 332 | { |
| 333 | if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS) |
| 334 | return 0; |
| 335 | PyErr_Format(PyExc_OverflowError, |
| 336 | "days=%d; must have magnitude <= %d", |
Guido van Rossum | bd43e91 | 2002-12-16 20:34:55 +0000 | [diff] [blame] | 337 | days, MAX_DELTA_DAYS); |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 338 | return -1; |
| 339 | } |
| 340 | |
| 341 | /* Check that date arguments are in range. Return 0 if they are. If they |
| 342 | * aren't, raise ValueError and return -1. |
| 343 | */ |
| 344 | static int |
| 345 | check_date_args(int year, int month, int day) |
| 346 | { |
| 347 | |
| 348 | if (year < MINYEAR || year > MAXYEAR) { |
| 349 | PyErr_SetString(PyExc_ValueError, |
| 350 | "year is out of range"); |
| 351 | return -1; |
| 352 | } |
| 353 | if (month < 1 || month > 12) { |
| 354 | PyErr_SetString(PyExc_ValueError, |
| 355 | "month must be in 1..12"); |
| 356 | return -1; |
| 357 | } |
| 358 | if (day < 1 || day > days_in_month(year, month)) { |
| 359 | PyErr_SetString(PyExc_ValueError, |
| 360 | "day is out of range for month"); |
| 361 | return -1; |
| 362 | } |
| 363 | return 0; |
| 364 | } |
| 365 | |
| 366 | /* Check that time arguments are in range. Return 0 if they are. If they |
| 367 | * aren't, raise ValueError and return -1. |
| 368 | */ |
| 369 | static int |
| 370 | check_time_args(int h, int m, int s, int us) |
| 371 | { |
| 372 | if (h < 0 || h > 23) { |
| 373 | PyErr_SetString(PyExc_ValueError, |
| 374 | "hour must be in 0..23"); |
| 375 | return -1; |
| 376 | } |
| 377 | if (m < 0 || m > 59) { |
| 378 | PyErr_SetString(PyExc_ValueError, |
| 379 | "minute must be in 0..59"); |
| 380 | return -1; |
| 381 | } |
| 382 | if (s < 0 || s > 59) { |
| 383 | PyErr_SetString(PyExc_ValueError, |
| 384 | "second must be in 0..59"); |
| 385 | return -1; |
| 386 | } |
| 387 | if (us < 0 || us > 999999) { |
| 388 | PyErr_SetString(PyExc_ValueError, |
| 389 | "microsecond must be in 0..999999"); |
| 390 | return -1; |
| 391 | } |
| 392 | return 0; |
| 393 | } |
| 394 | |
| 395 | /* --------------------------------------------------------------------------- |
| 396 | * Normalization utilities. |
| 397 | */ |
| 398 | |
| 399 | /* One step of a mixed-radix conversion. A "hi" unit is equivalent to |
| 400 | * factor "lo" units. factor must be > 0. If *lo is less than 0, or |
| 401 | * at least factor, enough of *lo is converted into "hi" units so that |
| 402 | * 0 <= *lo < factor. The input values must be such that int overflow |
| 403 | * is impossible. |
| 404 | */ |
| 405 | static void |
| 406 | normalize_pair(int *hi, int *lo, int factor) |
| 407 | { |
| 408 | assert(factor > 0); |
| 409 | assert(lo != hi); |
| 410 | if (*lo < 0 || *lo >= factor) { |
| 411 | const int num_hi = divmod(*lo, factor, lo); |
| 412 | const int new_hi = *hi + num_hi; |
| 413 | assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi)); |
| 414 | *hi = new_hi; |
| 415 | } |
| 416 | assert(0 <= *lo && *lo < factor); |
| 417 | } |
| 418 | |
| 419 | /* Fiddle days (d), seconds (s), and microseconds (us) so that |
| 420 | * 0 <= *s < 24*3600 |
| 421 | * 0 <= *us < 1000000 |
| 422 | * The input values must be such that the internals don't overflow. |
| 423 | * The way this routine is used, we don't get close. |
| 424 | */ |
| 425 | static void |
| 426 | normalize_d_s_us(int *d, int *s, int *us) |
| 427 | { |
| 428 | if (*us < 0 || *us >= 1000000) { |
| 429 | normalize_pair(s, us, 1000000); |
| 430 | /* |s| can't be bigger than about |
| 431 | * |original s| + |original us|/1000000 now. |
| 432 | */ |
| 433 | |
| 434 | } |
| 435 | if (*s < 0 || *s >= 24*3600) { |
| 436 | normalize_pair(d, s, 24*3600); |
| 437 | /* |d| can't be bigger than about |
| 438 | * |original d| + |
| 439 | * (|original s| + |original us|/1000000) / (24*3600) now. |
| 440 | */ |
| 441 | } |
| 442 | assert(0 <= *s && *s < 24*3600); |
| 443 | assert(0 <= *us && *us < 1000000); |
| 444 | } |
| 445 | |
| 446 | /* Fiddle years (y), months (m), and days (d) so that |
| 447 | * 1 <= *m <= 12 |
| 448 | * 1 <= *d <= days_in_month(*y, *m) |
| 449 | * The input values must be such that the internals don't overflow. |
| 450 | * The way this routine is used, we don't get close. |
| 451 | */ |
| 452 | static void |
| 453 | normalize_y_m_d(int *y, int *m, int *d) |
| 454 | { |
| 455 | int dim; /* # of days in month */ |
| 456 | |
| 457 | /* This gets muddy: the proper range for day can't be determined |
| 458 | * without knowing the correct month and year, but if day is, e.g., |
| 459 | * plus or minus a million, the current month and year values make |
| 460 | * no sense (and may also be out of bounds themselves). |
| 461 | * Saying 12 months == 1 year should be non-controversial. |
| 462 | */ |
| 463 | if (*m < 1 || *m > 12) { |
| 464 | --*m; |
| 465 | normalize_pair(y, m, 12); |
| 466 | ++*m; |
| 467 | /* |y| can't be bigger than about |
| 468 | * |original y| + |original m|/12 now. |
| 469 | */ |
| 470 | } |
| 471 | assert(1 <= *m && *m <= 12); |
| 472 | |
| 473 | /* Now only day can be out of bounds (year may also be out of bounds |
| 474 | * for a datetime object, but we don't care about that here). |
| 475 | * If day is out of bounds, what to do is arguable, but at least the |
| 476 | * method here is principled and explainable. |
| 477 | */ |
| 478 | dim = days_in_month(*y, *m); |
| 479 | if (*d < 1 || *d > dim) { |
| 480 | /* Move day-1 days from the first of the month. First try to |
| 481 | * get off cheap if we're only one day out of range |
| 482 | * (adjustments for timezone alone can't be worse than that). |
| 483 | */ |
| 484 | if (*d == 0) { |
| 485 | --*m; |
| 486 | if (*m > 0) |
| 487 | *d = days_in_month(*y, *m); |
| 488 | else { |
| 489 | --*y; |
| 490 | *m = 12; |
| 491 | *d = 31; |
| 492 | } |
| 493 | } |
| 494 | else if (*d == dim + 1) { |
| 495 | /* move forward a day */ |
| 496 | ++*m; |
| 497 | *d = 1; |
| 498 | if (*m > 12) { |
| 499 | *m = 1; |
| 500 | ++*y; |
| 501 | } |
| 502 | } |
| 503 | else { |
| 504 | int ordinal = ymd_to_ord(*y, *m, 1) + |
| 505 | *d - 1; |
| 506 | ord_to_ymd(ordinal, y, m, d); |
| 507 | } |
| 508 | } |
| 509 | assert(*m > 0); |
| 510 | assert(*d > 0); |
| 511 | } |
| 512 | |
| 513 | /* Fiddle out-of-bounds months and days so that the result makes some kind |
| 514 | * of sense. The parameters are both inputs and outputs. Returns < 0 on |
| 515 | * failure, where failure means the adjusted year is out of bounds. |
| 516 | */ |
| 517 | static int |
| 518 | normalize_date(int *year, int *month, int *day) |
| 519 | { |
| 520 | int result; |
| 521 | |
| 522 | normalize_y_m_d(year, month, day); |
| 523 | if (MINYEAR <= *year && *year <= MAXYEAR) |
| 524 | result = 0; |
| 525 | else { |
| 526 | PyErr_SetString(PyExc_OverflowError, |
| 527 | "date value out of range"); |
| 528 | result = -1; |
| 529 | } |
| 530 | return result; |
| 531 | } |
| 532 | |
| 533 | /* Force all the datetime fields into range. The parameters are both |
| 534 | * inputs and outputs. Returns < 0 on error. |
| 535 | */ |
| 536 | static int |
| 537 | normalize_datetime(int *year, int *month, int *day, |
| 538 | int *hour, int *minute, int *second, |
| 539 | int *microsecond) |
| 540 | { |
| 541 | normalize_pair(second, microsecond, 1000000); |
| 542 | normalize_pair(minute, second, 60); |
| 543 | normalize_pair(hour, minute, 60); |
| 544 | normalize_pair(day, hour, 24); |
| 545 | return normalize_date(year, month, day); |
| 546 | } |
| 547 | |
| 548 | /* --------------------------------------------------------------------------- |
| 549 | * tzinfo helpers. |
| 550 | */ |
| 551 | |
| 552 | /* If self has a tzinfo member, return a BORROWED reference to it. Else |
| 553 | * return NULL, which is NOT AN ERROR. There are no error returns here, |
| 554 | * and the caller must not decref the result. |
| 555 | */ |
| 556 | static PyObject * |
| 557 | get_tzinfo_member(PyObject *self) |
| 558 | { |
| 559 | PyObject *tzinfo = NULL; |
| 560 | |
| 561 | if (PyDateTimeTZ_Check(self)) |
| 562 | tzinfo = ((PyDateTime_DateTimeTZ *)self)->tzinfo; |
| 563 | else if (PyTimeTZ_Check(self)) |
| 564 | tzinfo = ((PyDateTime_TimeTZ *)self)->tzinfo; |
| 565 | |
| 566 | return tzinfo; |
| 567 | } |
| 568 | |
| 569 | /* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not |
| 570 | * raise TypeError and return -1. |
| 571 | */ |
| 572 | static int |
| 573 | check_tzinfo_subclass(PyObject *p) |
| 574 | { |
| 575 | if (p == Py_None || PyTZInfo_Check(p)) |
| 576 | return 0; |
| 577 | PyErr_Format(PyExc_TypeError, |
| 578 | "tzinfo argument must be None or of a tzinfo subclass, " |
| 579 | "not type '%s'", |
| 580 | p->ob_type->tp_name); |
| 581 | return -1; |
| 582 | } |
| 583 | |
| 584 | /* Internal helper. |
| 585 | * Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the |
| 586 | * result. tzinfo must be an instance of the tzinfo class. If the method |
| 587 | * returns None, this returns 0 and sets *none to 1. If the method doesn't |
| 588 | * return a Python int or long, TypeError is raised and this returns -1. |
| 589 | * If it does return an int or long, but is outside the valid range for |
| 590 | * a UTC minute offset, ValueError is raised and this returns -1. |
| 591 | * Else *none is set to 0 and the integer method result is returned. |
| 592 | */ |
| 593 | static int |
| 594 | call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg, |
| 595 | int *none) |
| 596 | { |
| 597 | PyObject *u; |
| 598 | long result = -1; /* Py{Int,Long}_AsLong return long */ |
| 599 | |
| 600 | assert(tzinfo != NULL); |
| 601 | assert(PyTZInfo_Check(tzinfo)); |
| 602 | assert(tzinfoarg != NULL); |
| 603 | |
| 604 | *none = 0; |
| 605 | u = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg); |
| 606 | if (u == NULL) |
| 607 | return -1; |
| 608 | |
| 609 | if (u == Py_None) { |
| 610 | result = 0; |
| 611 | *none = 1; |
| 612 | goto Done; |
| 613 | } |
| 614 | |
| 615 | if (PyInt_Check(u)) |
| 616 | result = PyInt_AS_LONG(u); |
| 617 | else if (PyLong_Check(u)) |
| 618 | result = PyLong_AsLong(u); |
| 619 | else { |
| 620 | PyErr_Format(PyExc_TypeError, |
| 621 | "tzinfo.%s() must return None or int or long", |
| 622 | name); |
| 623 | goto Done; |
| 624 | } |
| 625 | |
| 626 | Done: |
| 627 | Py_DECREF(u); |
| 628 | if (result < -1439 || result > 1439) { |
| 629 | PyErr_Format(PyExc_ValueError, |
| 630 | "tzinfo.%s() returned %ld; must be in " |
| 631 | "-1439 .. 1439", |
| 632 | name, result); |
| 633 | result = -1; |
| 634 | } |
| 635 | return (int)result; |
| 636 | } |
| 637 | |
| 638 | /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the |
| 639 | * result. tzinfo must be an instance of the tzinfo class. If utcoffset() |
| 640 | * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset() |
| 641 | & doesn't return a Python int or long, TypeError is raised and this |
| 642 | * returns -1. If utcoffset() returns an int outside the legitimate range |
| 643 | * for a UTC offset, ValueError is raised and this returns -1. Else |
| 644 | * *none is set to 0 and the offset is returned. |
| 645 | */ |
| 646 | static int |
| 647 | call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none) |
| 648 | { |
| 649 | return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none); |
| 650 | } |
| 651 | |
| 652 | /* Call tzinfo.dst(tzinfoarg), and extract an integer from the |
| 653 | * result. tzinfo must be an instance of the tzinfo class. If dst() |
| 654 | * returns None, call_dst returns 0 and sets *none to 1. If dst() |
| 655 | & doesn't return a Python int or long, TypeError is raised and this |
| 656 | * returns -1. If dst() returns an int outside the legitimate range |
| 657 | * for a UTC offset, ValueError is raised and this returns -1. Else |
| 658 | * *none is set to 0 and the offset is returned. |
| 659 | */ |
| 660 | static int |
| 661 | call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none) |
| 662 | { |
| 663 | return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none); |
| 664 | } |
| 665 | |
| 666 | /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be |
| 667 | * an instance of the tzinfo class. If tzname() doesn't return None or |
| 668 | * a string, TypeError is raised and this returns NULL. |
| 669 | */ |
| 670 | static PyObject * |
| 671 | call_tzname(PyObject *tzinfo, PyObject *tzinfoarg) |
| 672 | { |
| 673 | PyObject *result; |
| 674 | |
| 675 | assert(tzinfo != NULL); |
| 676 | assert(PyTZInfo_Check(tzinfo)); |
| 677 | assert(tzinfoarg != NULL); |
| 678 | |
| 679 | result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg); |
| 680 | if (result != NULL && result != Py_None && !PyString_Check(result)) { |
| 681 | PyErr_Format(PyExc_TypeError, ".tzinfo.tzname() must " |
| 682 | "return None or a string, not '%s'", |
| 683 | result->ob_type->tp_name); |
| 684 | Py_DECREF(result); |
| 685 | result = NULL; |
| 686 | } |
| 687 | return result; |
| 688 | } |
| 689 | |
| 690 | typedef enum { |
| 691 | /* an exception has been set; the caller should pass it on */ |
| 692 | OFFSET_ERROR, |
| 693 | |
| 694 | /* type isn't date, datetime, datetimetz subclass, time, or |
| 695 | * timetz subclass |
| 696 | */ |
| 697 | OFFSET_UNKNOWN, |
| 698 | |
| 699 | /* date, |
| 700 | * datetime, |
| 701 | * datetimetz with None tzinfo, |
| 702 | * datetimetz where utcoffset() return None |
| 703 | * time, |
| 704 | * timetz with None tzinfo, |
| 705 | * timetz where utcoffset() returns None |
| 706 | */ |
| 707 | OFFSET_NAIVE, |
| 708 | |
| 709 | /* timetz where utcoffset() doesn't return None, |
| 710 | * datetimetz where utcoffset() doesn't return None |
| 711 | */ |
| 712 | OFFSET_AWARE, |
| 713 | } naivety; |
| 714 | |
| 715 | /* Classify a datetime object as to whether it's naive or offset-aware. See |
| 716 | * the "naivety" typedef for details. If the type is aware, *offset is set |
| 717 | * to minutes east of UTC (as returned by the tzinfo.utcoffset() method). |
| 718 | * If the type is offset-naive, *offset is set to 0. |
| 719 | */ |
| 720 | static naivety |
| 721 | classify_object(PyObject *op, int *offset) |
| 722 | { |
| 723 | int none; |
| 724 | PyObject *tzinfo; |
| 725 | |
| 726 | *offset = 0; |
| 727 | if (PyDateTime_CheckExact(op) || |
| 728 | PyTime_CheckExact(op) || |
| 729 | PyDate_CheckExact(op)) |
| 730 | return OFFSET_NAIVE; |
| 731 | |
| 732 | tzinfo = get_tzinfo_member(op); /* NULL means none, not error */ |
| 733 | if (tzinfo == Py_None) |
| 734 | return OFFSET_NAIVE; |
| 735 | if (tzinfo == NULL) |
| 736 | return OFFSET_UNKNOWN; |
| 737 | |
| 738 | *offset = call_utcoffset(tzinfo, op, &none); |
| 739 | if (*offset == -1 && PyErr_Occurred()) |
| 740 | return OFFSET_ERROR; |
| 741 | return none ? OFFSET_NAIVE : OFFSET_AWARE; |
| 742 | } |
| 743 | |
| 744 | /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None, |
| 745 | * stuff |
| 746 | * ", tzinfo=" + repr(tzinfo) |
| 747 | * before the closing ")". |
| 748 | */ |
| 749 | static PyObject * |
| 750 | append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo) |
| 751 | { |
| 752 | PyObject *temp; |
| 753 | |
| 754 | assert(PyString_Check(repr)); |
| 755 | assert(tzinfo); |
| 756 | if (tzinfo == Py_None) |
| 757 | return repr; |
| 758 | /* Get rid of the trailing ')'. */ |
| 759 | assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')'); |
| 760 | temp = PyString_FromStringAndSize(PyString_AsString(repr), |
| 761 | PyString_Size(repr) - 1); |
| 762 | Py_DECREF(repr); |
| 763 | if (temp == NULL) |
| 764 | return NULL; |
| 765 | repr = temp; |
| 766 | |
| 767 | /* Append ", tzinfo=". */ |
| 768 | PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo=")); |
| 769 | |
| 770 | /* Append repr(tzinfo). */ |
| 771 | PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo)); |
| 772 | |
| 773 | /* Add a closing paren. */ |
| 774 | PyString_ConcatAndDel(&repr, PyString_FromString(")")); |
| 775 | return repr; |
| 776 | } |
| 777 | |
| 778 | /* --------------------------------------------------------------------------- |
| 779 | * String format helpers. |
| 780 | */ |
| 781 | |
| 782 | static PyObject * |
| 783 | format_ctime(PyDateTime_Date *date, |
| 784 | int hours, int minutes, int seconds) |
| 785 | { |
| 786 | static char *DayNames[] = { |
| 787 | "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" |
| 788 | }; |
| 789 | static char *MonthNames[] = { |
| 790 | "Jan", "Feb", "Mar", "Apr", "May", "Jun", |
| 791 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" |
| 792 | }; |
| 793 | |
| 794 | char buffer[128]; |
| 795 | int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date)); |
| 796 | |
| 797 | PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d", |
| 798 | DayNames[wday], MonthNames[GET_MONTH(date) - 1], |
| 799 | GET_DAY(date), hours, minutes, seconds, |
| 800 | GET_YEAR(date)); |
| 801 | return PyString_FromString(buffer); |
| 802 | } |
| 803 | |
| 804 | /* Add an hours & minutes UTC offset string to buf. buf has no more than |
| 805 | * buflen bytes remaining. The UTC offset is gotten by calling |
| 806 | * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into |
| 807 | * *buf, and that's all. Else the returned value is checked for sanity (an |
| 808 | * integer in range), and if that's OK it's converted to an hours & minutes |
| 809 | * string of the form |
| 810 | * sign HH sep MM |
| 811 | * Returns 0 if everything is OK. If the return value from utcoffset() is |
| 812 | * bogus, an appropriate exception is set and -1 is returned. |
| 813 | */ |
| 814 | static int |
Tim Peters | 328fff7 | 2002-12-20 01:31:27 +0000 | [diff] [blame^] | 815 | format_utcoffset(char *buf, size_t buflen, const char *sep, |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 816 | PyObject *tzinfo, PyObject *tzinfoarg) |
| 817 | { |
| 818 | int offset; |
| 819 | int hours; |
| 820 | int minutes; |
| 821 | char sign; |
| 822 | int none; |
| 823 | |
| 824 | offset = call_utcoffset(tzinfo, tzinfoarg, &none); |
| 825 | if (offset == -1 && PyErr_Occurred()) |
| 826 | return -1; |
| 827 | if (none) { |
| 828 | *buf = '\0'; |
| 829 | return 0; |
| 830 | } |
| 831 | sign = '+'; |
| 832 | if (offset < 0) { |
| 833 | sign = '-'; |
| 834 | offset = - offset; |
| 835 | } |
| 836 | hours = divmod(offset, 60, &minutes); |
| 837 | PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes); |
| 838 | return 0; |
| 839 | } |
| 840 | |
| 841 | /* I sure don't want to reproduce the strftime code from the time module, |
| 842 | * so this imports the module and calls it. All the hair is due to |
| 843 | * giving special meanings to the %z and %Z format codes via a preprocessing |
| 844 | * step on the format string. |
| 845 | */ |
| 846 | static PyObject * |
| 847 | wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple) |
| 848 | { |
| 849 | PyObject *result = NULL; /* guilty until proved innocent */ |
| 850 | |
| 851 | PyObject *zreplacement = NULL; /* py string, replacement for %z */ |
| 852 | PyObject *Zreplacement = NULL; /* py string, replacement for %Z */ |
| 853 | |
| 854 | char *pin; /* pointer to next char in input format */ |
| 855 | char ch; /* next char in input format */ |
| 856 | |
| 857 | PyObject *newfmt = NULL; /* py string, the output format */ |
| 858 | char *pnew; /* pointer to available byte in output format */ |
| 859 | char totalnew; /* number bytes total in output format buffer, |
| 860 | exclusive of trailing \0 */ |
| 861 | char usednew; /* number bytes used so far in output format buffer */ |
| 862 | |
| 863 | char *ptoappend; /* pointer to string to append to output buffer */ |
| 864 | int ntoappend; /* # of bytes to append to output buffer */ |
| 865 | |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 866 | assert(object && format && timetuple); |
| 867 | assert(PyString_Check(format)); |
| 868 | |
| 869 | /* Scan the input format, looking for %z and %Z escapes, building |
Tim Peters | 328fff7 | 2002-12-20 01:31:27 +0000 | [diff] [blame^] | 870 | * a new format. Since computing the replacements for those codes |
| 871 | * is expensive, don't unless they're actually used. |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 872 | */ |
| 873 | totalnew = PyString_Size(format); /* realistic if no %z/%Z */ |
| 874 | newfmt = PyString_FromStringAndSize(NULL, totalnew); |
| 875 | if (newfmt == NULL) goto Done; |
| 876 | pnew = PyString_AsString(newfmt); |
| 877 | usednew = 0; |
| 878 | |
| 879 | pin = PyString_AsString(format); |
| 880 | while ((ch = *pin++) != '\0') { |
| 881 | if (ch != '%') { |
Tim Peters | 328fff7 | 2002-12-20 01:31:27 +0000 | [diff] [blame^] | 882 | ptoappend = pin - 1; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 883 | ntoappend = 1; |
| 884 | } |
| 885 | else if ((ch = *pin++) == '\0') { |
| 886 | /* There's a lone trailing %; doesn't make sense. */ |
| 887 | PyErr_SetString(PyExc_ValueError, "strftime format " |
| 888 | "ends with raw %"); |
| 889 | goto Done; |
| 890 | } |
| 891 | /* A % has been seen and ch is the character after it. */ |
| 892 | else if (ch == 'z') { |
| 893 | if (zreplacement == NULL) { |
| 894 | /* format utcoffset */ |
Tim Peters | 328fff7 | 2002-12-20 01:31:27 +0000 | [diff] [blame^] | 895 | char buf[100]; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 896 | PyObject *tzinfo = get_tzinfo_member(object); |
| 897 | zreplacement = PyString_FromString(""); |
| 898 | if (zreplacement == NULL) goto Done; |
| 899 | if (tzinfo != Py_None && tzinfo != NULL) { |
| 900 | if (format_utcoffset(buf, |
Tim Peters | 328fff7 | 2002-12-20 01:31:27 +0000 | [diff] [blame^] | 901 | sizeof(buf), |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 902 | "", |
| 903 | tzinfo, |
| 904 | object) < 0) |
| 905 | goto Done; |
| 906 | Py_DECREF(zreplacement); |
| 907 | zreplacement = PyString_FromString(buf); |
| 908 | if (zreplacement == NULL) goto Done; |
| 909 | } |
| 910 | } |
| 911 | assert(zreplacement != NULL); |
| 912 | ptoappend = PyString_AsString(zreplacement); |
| 913 | ntoappend = PyString_Size(zreplacement); |
| 914 | } |
| 915 | else if (ch == 'Z') { |
| 916 | /* format tzname */ |
| 917 | if (Zreplacement == NULL) { |
| 918 | PyObject *tzinfo = get_tzinfo_member(object); |
| 919 | Zreplacement = PyString_FromString(""); |
| 920 | if (Zreplacement == NULL) goto Done; |
| 921 | if (tzinfo != Py_None && tzinfo != NULL) { |
| 922 | PyObject *temp = call_tzname(tzinfo, |
| 923 | object); |
| 924 | if (temp == NULL) goto Done; |
| 925 | if (temp != Py_None) { |
| 926 | assert(PyString_Check(temp)); |
| 927 | /* Since the tzname is getting |
| 928 | * stuffed into the format, we |
| 929 | * have to double any % signs |
| 930 | * so that strftime doesn't |
| 931 | * treat them as format codes. |
| 932 | */ |
| 933 | Py_DECREF(Zreplacement); |
| 934 | Zreplacement = PyObject_CallMethod( |
| 935 | temp, "replace", |
| 936 | "ss", "%", "%%"); |
| 937 | Py_DECREF(temp); |
| 938 | if (Zreplacement == NULL) |
| 939 | goto Done; |
| 940 | } |
| 941 | else |
| 942 | Py_DECREF(temp); |
| 943 | } |
| 944 | } |
| 945 | assert(Zreplacement != NULL); |
| 946 | ptoappend = PyString_AsString(Zreplacement); |
| 947 | ntoappend = PyString_Size(Zreplacement); |
| 948 | } |
| 949 | else { |
Tim Peters | 328fff7 | 2002-12-20 01:31:27 +0000 | [diff] [blame^] | 950 | /* percent followed by neither z nor Z */ |
| 951 | ptoappend = pin - 2; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 952 | ntoappend = 2; |
| 953 | } |
| 954 | |
| 955 | /* Append the ntoappend chars starting at ptoappend to |
| 956 | * the new format. |
| 957 | */ |
| 958 | assert(ntoappend >= 0); |
| 959 | if (ntoappend == 0) |
| 960 | continue; |
| 961 | while (usednew + ntoappend > totalnew) { |
| 962 | int bigger = totalnew << 1; |
| 963 | if ((bigger >> 1) != totalnew) { /* overflow */ |
| 964 | PyErr_NoMemory(); |
| 965 | goto Done; |
| 966 | } |
| 967 | if (_PyString_Resize(&newfmt, bigger) < 0) |
| 968 | goto Done; |
| 969 | totalnew = bigger; |
| 970 | pnew = PyString_AsString(newfmt) + usednew; |
| 971 | } |
| 972 | memcpy(pnew, ptoappend, ntoappend); |
| 973 | pnew += ntoappend; |
| 974 | usednew += ntoappend; |
| 975 | assert(usednew <= totalnew); |
| 976 | } /* end while() */ |
| 977 | |
| 978 | if (_PyString_Resize(&newfmt, usednew) < 0) |
| 979 | goto Done; |
| 980 | { |
| 981 | PyObject *time = PyImport_ImportModule("time"); |
| 982 | if (time == NULL) |
| 983 | goto Done; |
| 984 | result = PyObject_CallMethod(time, "strftime", "OO", |
| 985 | newfmt, timetuple); |
| 986 | Py_DECREF(time); |
| 987 | } |
| 988 | Done: |
| 989 | Py_XDECREF(zreplacement); |
| 990 | Py_XDECREF(Zreplacement); |
| 991 | Py_XDECREF(newfmt); |
| 992 | return result; |
| 993 | } |
| 994 | |
| 995 | static char * |
| 996 | isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen) |
| 997 | { |
| 998 | int x; |
| 999 | x = PyOS_snprintf(buffer, bufflen, |
| 1000 | "%04d-%02d-%02d", |
| 1001 | GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt)); |
| 1002 | return buffer + x; |
| 1003 | } |
| 1004 | |
| 1005 | static void |
| 1006 | isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen) |
| 1007 | { |
| 1008 | int us = DATE_GET_MICROSECOND(dt); |
| 1009 | |
| 1010 | PyOS_snprintf(buffer, bufflen, |
| 1011 | "%02d:%02d:%02d", /* 8 characters */ |
| 1012 | DATE_GET_HOUR(dt), |
| 1013 | DATE_GET_MINUTE(dt), |
| 1014 | DATE_GET_SECOND(dt)); |
| 1015 | if (us) |
| 1016 | PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us); |
| 1017 | } |
| 1018 | |
| 1019 | /* --------------------------------------------------------------------------- |
| 1020 | * Wrap functions from the time module. These aren't directly available |
| 1021 | * from C. Perhaps they should be. |
| 1022 | */ |
| 1023 | |
| 1024 | /* Call time.time() and return its result (a Python float). */ |
| 1025 | static PyObject * |
Guido van Rossum | bd43e91 | 2002-12-16 20:34:55 +0000 | [diff] [blame] | 1026 | time_time(void) |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1027 | { |
| 1028 | PyObject *result = NULL; |
| 1029 | PyObject *time = PyImport_ImportModule("time"); |
| 1030 | |
| 1031 | if (time != NULL) { |
| 1032 | result = PyObject_CallMethod(time, "time", "()"); |
| 1033 | Py_DECREF(time); |
| 1034 | } |
| 1035 | return result; |
| 1036 | } |
| 1037 | |
| 1038 | /* Build a time.struct_time. The weekday and day number are automatically |
| 1039 | * computed from the y,m,d args. |
| 1040 | */ |
| 1041 | static PyObject * |
| 1042 | build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag) |
| 1043 | { |
| 1044 | PyObject *time; |
| 1045 | PyObject *result = NULL; |
| 1046 | |
| 1047 | time = PyImport_ImportModule("time"); |
| 1048 | if (time != NULL) { |
| 1049 | result = PyObject_CallMethod(time, "struct_time", |
| 1050 | "((iiiiiiiii))", |
| 1051 | y, m, d, |
| 1052 | hh, mm, ss, |
| 1053 | weekday(y, m, d), |
| 1054 | days_before_month(y, m) + d, |
| 1055 | dstflag); |
| 1056 | Py_DECREF(time); |
| 1057 | } |
| 1058 | return result; |
| 1059 | } |
| 1060 | |
| 1061 | /* --------------------------------------------------------------------------- |
| 1062 | * Miscellaneous helpers. |
| 1063 | */ |
| 1064 | |
| 1065 | /* For obscure reasons, we need to use tp_richcompare instead of tp_compare. |
| 1066 | * The comparisons here all most naturally compute a cmp()-like result. |
| 1067 | * This little helper turns that into a bool result for rich comparisons. |
| 1068 | */ |
| 1069 | static PyObject * |
| 1070 | diff_to_bool(int diff, int op) |
| 1071 | { |
| 1072 | PyObject *result; |
| 1073 | int istrue; |
| 1074 | |
| 1075 | switch (op) { |
| 1076 | case Py_EQ: istrue = diff == 0; break; |
| 1077 | case Py_NE: istrue = diff != 0; break; |
| 1078 | case Py_LE: istrue = diff <= 0; break; |
| 1079 | case Py_GE: istrue = diff >= 0; break; |
| 1080 | case Py_LT: istrue = diff < 0; break; |
| 1081 | case Py_GT: istrue = diff > 0; break; |
| 1082 | default: |
| 1083 | assert(! "op unknown"); |
| 1084 | istrue = 0; /* To shut up compiler */ |
| 1085 | } |
| 1086 | result = istrue ? Py_True : Py_False; |
| 1087 | Py_INCREF(result); |
| 1088 | return result; |
| 1089 | } |
| 1090 | |
| 1091 | /* --------------------------------------------------------------------------- |
| 1092 | * Helpers for setting object fields. These work on pointers to the |
| 1093 | * appropriate base class. |
| 1094 | */ |
| 1095 | |
| 1096 | /* For date, datetime and datetimetz. */ |
| 1097 | static void |
| 1098 | set_date_fields(PyDateTime_Date *self, int y, int m, int d) |
| 1099 | { |
| 1100 | self->hashcode = -1; |
| 1101 | SET_YEAR(self, y); |
| 1102 | SET_MONTH(self, m); |
| 1103 | SET_DAY(self, d); |
| 1104 | } |
| 1105 | |
| 1106 | /* For datetime and datetimetz. */ |
| 1107 | static void |
| 1108 | set_datetime_time_fields(PyDateTime_Date *self, int h, int m, int s, int us) |
| 1109 | { |
| 1110 | DATE_SET_HOUR(self, h); |
| 1111 | DATE_SET_MINUTE(self, m); |
| 1112 | DATE_SET_SECOND(self, s); |
| 1113 | DATE_SET_MICROSECOND(self, us); |
| 1114 | } |
| 1115 | |
| 1116 | /* For time and timetz. */ |
| 1117 | static void |
| 1118 | set_time_fields(PyDateTime_Time *self, int h, int m, int s, int us) |
| 1119 | { |
| 1120 | self->hashcode = -1; |
| 1121 | TIME_SET_HOUR(self, h); |
| 1122 | TIME_SET_MINUTE(self, m); |
| 1123 | TIME_SET_SECOND(self, s); |
| 1124 | TIME_SET_MICROSECOND(self, us); |
| 1125 | } |
| 1126 | |
| 1127 | /* --------------------------------------------------------------------------- |
| 1128 | * Create various objects, mostly without range checking. |
| 1129 | */ |
| 1130 | |
| 1131 | /* Create a date instance with no range checking. */ |
| 1132 | static PyObject * |
| 1133 | new_date(int year, int month, int day) |
| 1134 | { |
| 1135 | PyDateTime_Date *self; |
| 1136 | |
| 1137 | self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType); |
| 1138 | if (self != NULL) |
| 1139 | set_date_fields(self, year, month, day); |
| 1140 | return (PyObject *) self; |
| 1141 | } |
| 1142 | |
| 1143 | /* Create a datetime instance with no range checking. */ |
| 1144 | static PyObject * |
| 1145 | new_datetime(int year, int month, int day, int hour, int minute, |
| 1146 | int second, int usecond) |
| 1147 | { |
| 1148 | PyDateTime_DateTime *self; |
| 1149 | |
| 1150 | self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); |
| 1151 | if (self != NULL) { |
| 1152 | set_date_fields((PyDateTime_Date *)self, year, month, day); |
| 1153 | set_datetime_time_fields((PyDateTime_Date *)self, |
| 1154 | hour, minute, second, usecond); |
| 1155 | } |
| 1156 | return (PyObject *) self; |
| 1157 | } |
| 1158 | |
| 1159 | /* Create a datetimetz instance with no range checking. */ |
| 1160 | static PyObject * |
| 1161 | new_datetimetz(int year, int month, int day, int hour, int minute, |
| 1162 | int second, int usecond, PyObject *tzinfo) |
| 1163 | { |
| 1164 | PyDateTime_DateTimeTZ *self; |
| 1165 | |
| 1166 | self = PyObject_New(PyDateTime_DateTimeTZ, &PyDateTime_DateTimeTZType); |
| 1167 | if (self != NULL) { |
| 1168 | set_date_fields((PyDateTime_Date *)self, year, month, day); |
| 1169 | set_datetime_time_fields((PyDateTime_Date *)self, |
| 1170 | hour, minute, second, usecond); |
| 1171 | Py_INCREF(tzinfo); |
| 1172 | self->tzinfo = tzinfo; |
| 1173 | } |
| 1174 | return (PyObject *) self; |
| 1175 | } |
| 1176 | |
| 1177 | /* Create a time instance with no range checking. */ |
| 1178 | static PyObject * |
| 1179 | new_time(int hour, int minute, int second, int usecond) |
| 1180 | { |
| 1181 | PyDateTime_Time *self; |
| 1182 | |
| 1183 | self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType); |
| 1184 | if (self != NULL) |
| 1185 | set_time_fields(self, hour, minute, second, usecond); |
| 1186 | return (PyObject *) self; |
| 1187 | } |
| 1188 | |
| 1189 | /* Create a timetz instance with no range checking. */ |
| 1190 | static PyObject * |
| 1191 | new_timetz(int hour, int minute, int second, int usecond, PyObject *tzinfo) |
| 1192 | { |
| 1193 | PyDateTime_TimeTZ *self; |
| 1194 | |
| 1195 | self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType); |
| 1196 | if (self != NULL) { |
| 1197 | set_time_fields((PyDateTime_Time *)self, |
| 1198 | hour, minute, second, usecond); |
| 1199 | Py_INCREF(tzinfo); |
| 1200 | self->tzinfo = tzinfo; |
| 1201 | } |
| 1202 | return (PyObject *) self; |
| 1203 | } |
| 1204 | |
| 1205 | /* Create a timedelta instance. Normalize the members iff normalize is |
| 1206 | * true. Passing false is a speed optimization, if you know for sure |
| 1207 | * that seconds and microseconds are already in their proper ranges. In any |
| 1208 | * case, raises OverflowError and returns NULL if the normalized days is out |
| 1209 | * of range). |
| 1210 | */ |
| 1211 | static PyObject * |
| 1212 | new_delta(int days, int seconds, int microseconds, int normalize) |
| 1213 | { |
| 1214 | PyDateTime_Delta *self; |
| 1215 | |
| 1216 | if (normalize) |
| 1217 | normalize_d_s_us(&days, &seconds, µseconds); |
| 1218 | assert(0 <= seconds && seconds < 24*3600); |
| 1219 | assert(0 <= microseconds && microseconds < 1000000); |
| 1220 | |
| 1221 | if (check_delta_day_range(days) < 0) |
| 1222 | return NULL; |
| 1223 | |
| 1224 | self = PyObject_New(PyDateTime_Delta, &PyDateTime_DeltaType); |
| 1225 | if (self != NULL) { |
| 1226 | self->hashcode = -1; |
| 1227 | SET_TD_DAYS(self, days); |
| 1228 | SET_TD_SECONDS(self, seconds); |
| 1229 | SET_TD_MICROSECONDS(self, microseconds); |
| 1230 | } |
| 1231 | return (PyObject *) self; |
| 1232 | } |
| 1233 | |
| 1234 | |
| 1235 | /* --------------------------------------------------------------------------- |
| 1236 | * Cached Python objects; these are set by the module init function. |
| 1237 | */ |
| 1238 | |
| 1239 | /* Conversion factors. */ |
| 1240 | static PyObject *us_per_us = NULL; /* 1 */ |
| 1241 | static PyObject *us_per_ms = NULL; /* 1000 */ |
| 1242 | static PyObject *us_per_second = NULL; /* 1000000 */ |
| 1243 | static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */ |
| 1244 | static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */ |
| 1245 | static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */ |
| 1246 | static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */ |
| 1247 | static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */ |
| 1248 | |
| 1249 | /* Callables to support unpickling. */ |
| 1250 | static PyObject *date_unpickler_object = NULL; |
| 1251 | static PyObject *datetime_unpickler_object = NULL; |
| 1252 | static PyObject *datetimetz_unpickler_object = NULL; |
| 1253 | static PyObject *tzinfo_unpickler_object = NULL; |
| 1254 | static PyObject *time_unpickler_object = NULL; |
| 1255 | static PyObject *timetz_unpickler_object = NULL; |
| 1256 | |
| 1257 | /* --------------------------------------------------------------------------- |
| 1258 | * Class implementations. |
| 1259 | */ |
| 1260 | |
| 1261 | /* |
| 1262 | * PyDateTime_Delta implementation. |
| 1263 | */ |
| 1264 | |
| 1265 | /* Convert a timedelta to a number of us, |
| 1266 | * (24*3600*self.days + self.seconds)*1000000 + self.microseconds |
| 1267 | * as a Python int or long. |
| 1268 | * Doing mixed-radix arithmetic by hand instead is excruciating in C, |
| 1269 | * due to ubiquitous overflow possibilities. |
| 1270 | */ |
| 1271 | static PyObject * |
| 1272 | delta_to_microseconds(PyDateTime_Delta *self) |
| 1273 | { |
| 1274 | PyObject *x1 = NULL; |
| 1275 | PyObject *x2 = NULL; |
| 1276 | PyObject *x3 = NULL; |
| 1277 | PyObject *result = NULL; |
| 1278 | |
| 1279 | x1 = PyInt_FromLong(GET_TD_DAYS(self)); |
| 1280 | if (x1 == NULL) |
| 1281 | goto Done; |
| 1282 | x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */ |
| 1283 | if (x2 == NULL) |
| 1284 | goto Done; |
| 1285 | Py_DECREF(x1); |
| 1286 | x1 = NULL; |
| 1287 | |
| 1288 | /* x2 has days in seconds */ |
| 1289 | x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */ |
| 1290 | if (x1 == NULL) |
| 1291 | goto Done; |
| 1292 | x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */ |
| 1293 | if (x3 == NULL) |
| 1294 | goto Done; |
| 1295 | Py_DECREF(x1); |
| 1296 | Py_DECREF(x2); |
| 1297 | x1 = x2 = NULL; |
| 1298 | |
| 1299 | /* x3 has days+seconds in seconds */ |
| 1300 | x1 = PyNumber_Multiply(x3, us_per_second); /* us */ |
| 1301 | if (x1 == NULL) |
| 1302 | goto Done; |
| 1303 | Py_DECREF(x3); |
| 1304 | x3 = NULL; |
| 1305 | |
| 1306 | /* x1 has days+seconds in us */ |
| 1307 | x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self)); |
| 1308 | if (x2 == NULL) |
| 1309 | goto Done; |
| 1310 | result = PyNumber_Add(x1, x2); |
| 1311 | |
| 1312 | Done: |
| 1313 | Py_XDECREF(x1); |
| 1314 | Py_XDECREF(x2); |
| 1315 | Py_XDECREF(x3); |
| 1316 | return result; |
| 1317 | } |
| 1318 | |
| 1319 | /* Convert a number of us (as a Python int or long) to a timedelta. |
| 1320 | */ |
| 1321 | static PyObject * |
| 1322 | microseconds_to_delta(PyObject *pyus) |
| 1323 | { |
| 1324 | int us; |
| 1325 | int s; |
| 1326 | int d; |
Tim Peters | 0b0f41c | 2002-12-19 01:44:38 +0000 | [diff] [blame] | 1327 | long temp; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1328 | |
| 1329 | PyObject *tuple = NULL; |
| 1330 | PyObject *num = NULL; |
| 1331 | PyObject *result = NULL; |
| 1332 | |
| 1333 | tuple = PyNumber_Divmod(pyus, us_per_second); |
| 1334 | if (tuple == NULL) |
| 1335 | goto Done; |
| 1336 | |
| 1337 | num = PyTuple_GetItem(tuple, 1); /* us */ |
| 1338 | if (num == NULL) |
| 1339 | goto Done; |
Tim Peters | 0b0f41c | 2002-12-19 01:44:38 +0000 | [diff] [blame] | 1340 | temp = PyLong_AsLong(num); |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1341 | num = NULL; |
Tim Peters | 0b0f41c | 2002-12-19 01:44:38 +0000 | [diff] [blame] | 1342 | if (temp == -1 && PyErr_Occurred()) |
| 1343 | goto Done; |
| 1344 | assert(0 <= temp && temp < 1000000); |
| 1345 | us = (int)temp; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1346 | if (us < 0) { |
| 1347 | /* The divisor was positive, so this must be an error. */ |
| 1348 | assert(PyErr_Occurred()); |
| 1349 | goto Done; |
| 1350 | } |
| 1351 | |
| 1352 | num = PyTuple_GetItem(tuple, 0); /* leftover seconds */ |
| 1353 | if (num == NULL) |
| 1354 | goto Done; |
| 1355 | Py_INCREF(num); |
| 1356 | Py_DECREF(tuple); |
| 1357 | |
| 1358 | tuple = PyNumber_Divmod(num, seconds_per_day); |
| 1359 | if (tuple == NULL) |
| 1360 | goto Done; |
| 1361 | Py_DECREF(num); |
| 1362 | |
| 1363 | num = PyTuple_GetItem(tuple, 1); /* seconds */ |
| 1364 | if (num == NULL) |
| 1365 | goto Done; |
Tim Peters | 0b0f41c | 2002-12-19 01:44:38 +0000 | [diff] [blame] | 1366 | temp = PyLong_AsLong(num); |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1367 | num = NULL; |
Tim Peters | 0b0f41c | 2002-12-19 01:44:38 +0000 | [diff] [blame] | 1368 | if (temp == -1 && PyErr_Occurred()) |
| 1369 | goto Done; |
| 1370 | assert(0 <= temp && temp < 24*3600); |
| 1371 | s = (int)temp; |
| 1372 | |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1373 | if (s < 0) { |
| 1374 | /* The divisor was positive, so this must be an error. */ |
| 1375 | assert(PyErr_Occurred()); |
| 1376 | goto Done; |
| 1377 | } |
| 1378 | |
| 1379 | num = PyTuple_GetItem(tuple, 0); /* leftover days */ |
| 1380 | if (num == NULL) |
| 1381 | goto Done; |
| 1382 | Py_INCREF(num); |
Tim Peters | 0b0f41c | 2002-12-19 01:44:38 +0000 | [diff] [blame] | 1383 | temp = PyLong_AsLong(num); |
| 1384 | if (temp == -1 && PyErr_Occurred()) |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1385 | goto Done; |
Tim Peters | 0b0f41c | 2002-12-19 01:44:38 +0000 | [diff] [blame] | 1386 | d = (int)temp; |
| 1387 | if ((long)d != temp) { |
| 1388 | PyErr_SetString(PyExc_OverflowError, "normalized days too " |
| 1389 | "large to fit in a C int"); |
| 1390 | goto Done; |
| 1391 | } |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1392 | result = new_delta(d, s, us, 0); |
| 1393 | |
| 1394 | Done: |
| 1395 | Py_XDECREF(tuple); |
| 1396 | Py_XDECREF(num); |
| 1397 | return result; |
| 1398 | } |
| 1399 | |
| 1400 | static PyObject * |
| 1401 | multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta) |
| 1402 | { |
| 1403 | PyObject *pyus_in; |
| 1404 | PyObject *pyus_out; |
| 1405 | PyObject *result; |
| 1406 | |
| 1407 | pyus_in = delta_to_microseconds(delta); |
| 1408 | if (pyus_in == NULL) |
| 1409 | return NULL; |
| 1410 | |
| 1411 | pyus_out = PyNumber_Multiply(pyus_in, intobj); |
| 1412 | Py_DECREF(pyus_in); |
| 1413 | if (pyus_out == NULL) |
| 1414 | return NULL; |
| 1415 | |
| 1416 | result = microseconds_to_delta(pyus_out); |
| 1417 | Py_DECREF(pyus_out); |
| 1418 | return result; |
| 1419 | } |
| 1420 | |
| 1421 | static PyObject * |
| 1422 | divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj) |
| 1423 | { |
| 1424 | PyObject *pyus_in; |
| 1425 | PyObject *pyus_out; |
| 1426 | PyObject *result; |
| 1427 | |
| 1428 | pyus_in = delta_to_microseconds(delta); |
| 1429 | if (pyus_in == NULL) |
| 1430 | return NULL; |
| 1431 | |
| 1432 | pyus_out = PyNumber_FloorDivide(pyus_in, intobj); |
| 1433 | Py_DECREF(pyus_in); |
| 1434 | if (pyus_out == NULL) |
| 1435 | return NULL; |
| 1436 | |
| 1437 | result = microseconds_to_delta(pyus_out); |
| 1438 | Py_DECREF(pyus_out); |
| 1439 | return result; |
| 1440 | } |
| 1441 | |
| 1442 | static PyObject * |
| 1443 | delta_add(PyObject *left, PyObject *right) |
| 1444 | { |
| 1445 | PyObject *result = Py_NotImplemented; |
| 1446 | |
| 1447 | if (PyDelta_Check(left) && PyDelta_Check(right)) { |
| 1448 | /* delta + delta */ |
| 1449 | /* The C-level additions can't overflow because of the |
| 1450 | * invariant bounds. |
| 1451 | */ |
| 1452 | int days = GET_TD_DAYS(left) + GET_TD_DAYS(right); |
| 1453 | int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right); |
| 1454 | int microseconds = GET_TD_MICROSECONDS(left) + |
| 1455 | GET_TD_MICROSECONDS(right); |
| 1456 | result = new_delta(days, seconds, microseconds, 1); |
| 1457 | } |
| 1458 | |
| 1459 | if (result == Py_NotImplemented) |
| 1460 | Py_INCREF(result); |
| 1461 | return result; |
| 1462 | } |
| 1463 | |
| 1464 | static PyObject * |
| 1465 | delta_negative(PyDateTime_Delta *self) |
| 1466 | { |
| 1467 | return new_delta(-GET_TD_DAYS(self), |
| 1468 | -GET_TD_SECONDS(self), |
| 1469 | -GET_TD_MICROSECONDS(self), |
| 1470 | 1); |
| 1471 | } |
| 1472 | |
| 1473 | static PyObject * |
| 1474 | delta_positive(PyDateTime_Delta *self) |
| 1475 | { |
| 1476 | /* Could optimize this (by returning self) if this isn't a |
| 1477 | * subclass -- but who uses unary + ? Approximately nobody. |
| 1478 | */ |
| 1479 | return new_delta(GET_TD_DAYS(self), |
| 1480 | GET_TD_SECONDS(self), |
| 1481 | GET_TD_MICROSECONDS(self), |
| 1482 | 0); |
| 1483 | } |
| 1484 | |
| 1485 | static PyObject * |
| 1486 | delta_abs(PyDateTime_Delta *self) |
| 1487 | { |
| 1488 | PyObject *result; |
| 1489 | |
| 1490 | assert(GET_TD_MICROSECONDS(self) >= 0); |
| 1491 | assert(GET_TD_SECONDS(self) >= 0); |
| 1492 | |
| 1493 | if (GET_TD_DAYS(self) < 0) |
| 1494 | result = delta_negative(self); |
| 1495 | else |
| 1496 | result = delta_positive(self); |
| 1497 | |
| 1498 | return result; |
| 1499 | } |
| 1500 | |
| 1501 | static PyObject * |
| 1502 | delta_subtract(PyObject *left, PyObject *right) |
| 1503 | { |
| 1504 | PyObject *result = Py_NotImplemented; |
| 1505 | |
| 1506 | if (PyDelta_Check(left) && PyDelta_Check(right)) { |
| 1507 | /* delta - delta */ |
| 1508 | PyObject *minus_right = PyNumber_Negative(right); |
| 1509 | if (minus_right) { |
| 1510 | result = delta_add(left, minus_right); |
| 1511 | Py_DECREF(minus_right); |
| 1512 | } |
| 1513 | else |
| 1514 | result = NULL; |
| 1515 | } |
| 1516 | |
| 1517 | if (result == Py_NotImplemented) |
| 1518 | Py_INCREF(result); |
| 1519 | return result; |
| 1520 | } |
| 1521 | |
| 1522 | /* This is more natural as a tp_compare, but doesn't work then: for whatever |
| 1523 | * reason, Python's try_3way_compare ignores tp_compare unless |
| 1524 | * PyInstance_Check returns true, but these aren't old-style classes. |
| 1525 | */ |
| 1526 | static PyObject * |
| 1527 | delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op) |
| 1528 | { |
| 1529 | int diff; |
| 1530 | |
| 1531 | if (! PyDelta_CheckExact(other)) { |
| 1532 | PyErr_Format(PyExc_TypeError, |
| 1533 | "can't compare %s to %s instance", |
| 1534 | self->ob_type->tp_name, other->ob_type->tp_name); |
| 1535 | return NULL; |
| 1536 | } |
| 1537 | diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); |
| 1538 | if (diff == 0) { |
| 1539 | diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); |
| 1540 | if (diff == 0) |
| 1541 | diff = GET_TD_MICROSECONDS(self) - |
| 1542 | GET_TD_MICROSECONDS(other); |
| 1543 | } |
| 1544 | return diff_to_bool(diff, op); |
| 1545 | } |
| 1546 | |
| 1547 | static PyObject *delta_getstate(PyDateTime_Delta *self); |
| 1548 | |
| 1549 | static long |
| 1550 | delta_hash(PyDateTime_Delta *self) |
| 1551 | { |
| 1552 | if (self->hashcode == -1) { |
| 1553 | PyObject *temp = delta_getstate(self); |
| 1554 | if (temp != NULL) { |
| 1555 | self->hashcode = PyObject_Hash(temp); |
| 1556 | Py_DECREF(temp); |
| 1557 | } |
| 1558 | } |
| 1559 | return self->hashcode; |
| 1560 | } |
| 1561 | |
| 1562 | static PyObject * |
| 1563 | delta_multiply(PyObject *left, PyObject *right) |
| 1564 | { |
| 1565 | PyObject *result = Py_NotImplemented; |
| 1566 | |
| 1567 | if (PyDelta_Check(left)) { |
| 1568 | /* delta * ??? */ |
| 1569 | if (PyInt_Check(right) || PyLong_Check(right)) |
| 1570 | result = multiply_int_timedelta(right, |
| 1571 | (PyDateTime_Delta *) left); |
| 1572 | } |
| 1573 | else if (PyInt_Check(left) || PyLong_Check(left)) |
| 1574 | result = multiply_int_timedelta(left, |
| 1575 | (PyDateTime_Delta *) right); |
| 1576 | |
| 1577 | if (result == Py_NotImplemented) |
| 1578 | Py_INCREF(result); |
| 1579 | return result; |
| 1580 | } |
| 1581 | |
| 1582 | static PyObject * |
| 1583 | delta_divide(PyObject *left, PyObject *right) |
| 1584 | { |
| 1585 | PyObject *result = Py_NotImplemented; |
| 1586 | |
| 1587 | if (PyDelta_Check(left)) { |
| 1588 | /* delta * ??? */ |
| 1589 | if (PyInt_Check(right) || PyLong_Check(right)) |
| 1590 | result = divide_timedelta_int( |
| 1591 | (PyDateTime_Delta *)left, |
| 1592 | right); |
| 1593 | } |
| 1594 | |
| 1595 | if (result == Py_NotImplemented) |
| 1596 | Py_INCREF(result); |
| 1597 | return result; |
| 1598 | } |
| 1599 | |
| 1600 | /* Fold in the value of the tag ("seconds", "weeks", etc) component of a |
| 1601 | * timedelta constructor. sofar is the # of microseconds accounted for |
| 1602 | * so far, and there are factor microseconds per current unit, the number |
| 1603 | * of which is given by num. num * factor is added to sofar in a |
| 1604 | * numerically careful way, and that's the result. Any fractional |
| 1605 | * microseconds left over (this can happen if num is a float type) are |
| 1606 | * added into *leftover. |
| 1607 | * Note that there are many ways this can give an error (NULL) return. |
| 1608 | */ |
| 1609 | static PyObject * |
| 1610 | accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor, |
| 1611 | double *leftover) |
| 1612 | { |
| 1613 | PyObject *prod; |
| 1614 | PyObject *sum; |
| 1615 | |
| 1616 | assert(num != NULL); |
| 1617 | |
| 1618 | if (PyInt_Check(num) || PyLong_Check(num)) { |
| 1619 | prod = PyNumber_Multiply(num, factor); |
| 1620 | if (prod == NULL) |
| 1621 | return NULL; |
| 1622 | sum = PyNumber_Add(sofar, prod); |
| 1623 | Py_DECREF(prod); |
| 1624 | return sum; |
| 1625 | } |
| 1626 | |
| 1627 | if (PyFloat_Check(num)) { |
| 1628 | double dnum; |
| 1629 | double fracpart; |
| 1630 | double intpart; |
| 1631 | PyObject *x; |
| 1632 | PyObject *y; |
| 1633 | |
| 1634 | /* The Plan: decompose num into an integer part and a |
| 1635 | * fractional part, num = intpart + fracpart. |
| 1636 | * Then num * factor == |
| 1637 | * intpart * factor + fracpart * factor |
| 1638 | * and the LHS can be computed exactly in long arithmetic. |
| 1639 | * The RHS is again broken into an int part and frac part. |
| 1640 | * and the frac part is added into *leftover. |
| 1641 | */ |
| 1642 | dnum = PyFloat_AsDouble(num); |
| 1643 | if (dnum == -1.0 && PyErr_Occurred()) |
| 1644 | return NULL; |
| 1645 | fracpart = modf(dnum, &intpart); |
| 1646 | x = PyLong_FromDouble(intpart); |
| 1647 | if (x == NULL) |
| 1648 | return NULL; |
| 1649 | |
| 1650 | prod = PyNumber_Multiply(x, factor); |
| 1651 | Py_DECREF(x); |
| 1652 | if (prod == NULL) |
| 1653 | return NULL; |
| 1654 | |
| 1655 | sum = PyNumber_Add(sofar, prod); |
| 1656 | Py_DECREF(prod); |
| 1657 | if (sum == NULL) |
| 1658 | return NULL; |
| 1659 | |
| 1660 | if (fracpart == 0.0) |
| 1661 | return sum; |
| 1662 | /* So far we've lost no information. Dealing with the |
| 1663 | * fractional part requires float arithmetic, and may |
| 1664 | * lose a little info. |
| 1665 | */ |
| 1666 | assert(PyInt_Check(factor) || PyLong_Check(factor)); |
| 1667 | if (PyInt_Check(factor)) |
| 1668 | dnum = (double)PyInt_AsLong(factor); |
| 1669 | else |
| 1670 | dnum = PyLong_AsDouble(factor); |
| 1671 | |
| 1672 | dnum *= fracpart; |
| 1673 | fracpart = modf(dnum, &intpart); |
| 1674 | x = PyLong_FromDouble(intpart); |
| 1675 | if (x == NULL) { |
| 1676 | Py_DECREF(sum); |
| 1677 | return NULL; |
| 1678 | } |
| 1679 | |
| 1680 | y = PyNumber_Add(sum, x); |
| 1681 | Py_DECREF(sum); |
| 1682 | Py_DECREF(x); |
| 1683 | *leftover += fracpart; |
| 1684 | return y; |
| 1685 | } |
| 1686 | |
| 1687 | PyErr_Format(PyExc_TypeError, |
| 1688 | "unsupported type for timedelta %s component: %s", |
| 1689 | tag, num->ob_type->tp_name); |
| 1690 | return NULL; |
| 1691 | } |
| 1692 | |
| 1693 | static PyObject * |
| 1694 | delta_new(PyTypeObject *type, PyObject *args, PyObject *kw) |
| 1695 | { |
| 1696 | PyObject *self = NULL; |
| 1697 | |
| 1698 | /* Argument objects. */ |
| 1699 | PyObject *day = NULL; |
| 1700 | PyObject *second = NULL; |
| 1701 | PyObject *us = NULL; |
| 1702 | PyObject *ms = NULL; |
| 1703 | PyObject *minute = NULL; |
| 1704 | PyObject *hour = NULL; |
| 1705 | PyObject *week = NULL; |
| 1706 | |
| 1707 | PyObject *x = NULL; /* running sum of microseconds */ |
| 1708 | PyObject *y = NULL; /* temp sum of microseconds */ |
| 1709 | double leftover_us = 0.0; |
| 1710 | |
| 1711 | static char *keywords[] = { |
| 1712 | "days", "seconds", "microseconds", "milliseconds", |
| 1713 | "minutes", "hours", "weeks", NULL |
| 1714 | }; |
| 1715 | |
| 1716 | if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", |
| 1717 | keywords, |
| 1718 | &day, &second, &us, |
| 1719 | &ms, &minute, &hour, &week) == 0) |
| 1720 | goto Done; |
| 1721 | |
| 1722 | x = PyInt_FromLong(0); |
| 1723 | if (x == NULL) |
| 1724 | goto Done; |
| 1725 | |
| 1726 | #define CLEANUP \ |
| 1727 | Py_DECREF(x); \ |
| 1728 | x = y; \ |
| 1729 | if (x == NULL) \ |
| 1730 | goto Done |
| 1731 | |
| 1732 | if (us) { |
| 1733 | y = accum("microseconds", x, us, us_per_us, &leftover_us); |
| 1734 | CLEANUP; |
| 1735 | } |
| 1736 | if (ms) { |
| 1737 | y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); |
| 1738 | CLEANUP; |
| 1739 | } |
| 1740 | if (second) { |
| 1741 | y = accum("seconds", x, second, us_per_second, &leftover_us); |
| 1742 | CLEANUP; |
| 1743 | } |
| 1744 | if (minute) { |
| 1745 | y = accum("minutes", x, minute, us_per_minute, &leftover_us); |
| 1746 | CLEANUP; |
| 1747 | } |
| 1748 | if (hour) { |
| 1749 | y = accum("hours", x, hour, us_per_hour, &leftover_us); |
| 1750 | CLEANUP; |
| 1751 | } |
| 1752 | if (day) { |
| 1753 | y = accum("days", x, day, us_per_day, &leftover_us); |
| 1754 | CLEANUP; |
| 1755 | } |
| 1756 | if (week) { |
| 1757 | y = accum("weeks", x, week, us_per_week, &leftover_us); |
| 1758 | CLEANUP; |
| 1759 | } |
| 1760 | if (leftover_us) { |
| 1761 | /* Round to nearest whole # of us, and add into x. */ |
| 1762 | PyObject *temp; |
| 1763 | if (leftover_us >= 0.0) |
| 1764 | leftover_us = floor(leftover_us + 0.5); |
| 1765 | else |
| 1766 | leftover_us = ceil(leftover_us - 0.5); |
| 1767 | temp = PyLong_FromDouble(leftover_us); |
| 1768 | if (temp == NULL) { |
| 1769 | Py_DECREF(x); |
| 1770 | goto Done; |
| 1771 | } |
| 1772 | y = PyNumber_Add(x, temp); |
| 1773 | Py_DECREF(temp); |
| 1774 | CLEANUP; |
| 1775 | } |
| 1776 | |
| 1777 | self = microseconds_to_delta(x); |
| 1778 | Py_DECREF(x); |
| 1779 | Done: |
| 1780 | return self; |
| 1781 | |
| 1782 | #undef CLEANUP |
| 1783 | } |
| 1784 | |
| 1785 | static int |
| 1786 | delta_nonzero(PyDateTime_Delta *self) |
| 1787 | { |
| 1788 | return (GET_TD_DAYS(self) != 0 |
| 1789 | || GET_TD_SECONDS(self) != 0 |
| 1790 | || GET_TD_MICROSECONDS(self) != 0); |
| 1791 | } |
| 1792 | |
| 1793 | static PyObject * |
| 1794 | delta_repr(PyDateTime_Delta *self) |
| 1795 | { |
| 1796 | if (GET_TD_MICROSECONDS(self) != 0) |
| 1797 | return PyString_FromFormat("%s(%d, %d, %d)", |
| 1798 | self->ob_type->tp_name, |
| 1799 | GET_TD_DAYS(self), |
| 1800 | GET_TD_SECONDS(self), |
| 1801 | GET_TD_MICROSECONDS(self)); |
| 1802 | if (GET_TD_SECONDS(self) != 0) |
| 1803 | return PyString_FromFormat("%s(%d, %d)", |
| 1804 | self->ob_type->tp_name, |
| 1805 | GET_TD_DAYS(self), |
| 1806 | GET_TD_SECONDS(self)); |
| 1807 | |
| 1808 | return PyString_FromFormat("%s(%d)", |
| 1809 | self->ob_type->tp_name, |
| 1810 | GET_TD_DAYS(self)); |
| 1811 | } |
| 1812 | |
| 1813 | static PyObject * |
| 1814 | delta_str(PyDateTime_Delta *self) |
| 1815 | { |
| 1816 | int days = GET_TD_DAYS(self); |
| 1817 | int seconds = GET_TD_SECONDS(self); |
| 1818 | int us = GET_TD_MICROSECONDS(self); |
| 1819 | int hours; |
| 1820 | int minutes; |
Tim Peters | ba87347 | 2002-12-18 20:19:21 +0000 | [diff] [blame] | 1821 | char buf[100]; |
| 1822 | char *pbuf = buf; |
| 1823 | size_t buflen = sizeof(buf); |
| 1824 | int n; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1825 | |
| 1826 | minutes = divmod(seconds, 60, &seconds); |
| 1827 | hours = divmod(minutes, 60, &minutes); |
| 1828 | |
| 1829 | if (days) { |
Tim Peters | ba87347 | 2002-12-18 20:19:21 +0000 | [diff] [blame] | 1830 | n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days, |
| 1831 | (days == 1 || days == -1) ? "" : "s"); |
| 1832 | if (n < 0 || (size_t)n >= buflen) |
| 1833 | goto Fail; |
| 1834 | pbuf += n; |
| 1835 | buflen -= (size_t)n; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1836 | } |
| 1837 | |
Tim Peters | ba87347 | 2002-12-18 20:19:21 +0000 | [diff] [blame] | 1838 | n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d", |
| 1839 | hours, minutes, seconds); |
| 1840 | if (n < 0 || (size_t)n >= buflen) |
| 1841 | goto Fail; |
| 1842 | pbuf += n; |
| 1843 | buflen -= (size_t)n; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1844 | |
| 1845 | if (us) { |
Tim Peters | ba87347 | 2002-12-18 20:19:21 +0000 | [diff] [blame] | 1846 | n = PyOS_snprintf(pbuf, buflen, ".%06d", us); |
| 1847 | if (n < 0 || (size_t)n >= buflen) |
| 1848 | goto Fail; |
| 1849 | pbuf += n; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1850 | } |
| 1851 | |
Tim Peters | ba87347 | 2002-12-18 20:19:21 +0000 | [diff] [blame] | 1852 | return PyString_FromStringAndSize(buf, pbuf - buf); |
| 1853 | |
| 1854 | Fail: |
| 1855 | PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf"); |
| 1856 | return NULL; |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1857 | } |
| 1858 | |
| 1859 | /* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed |
| 1860 | * in the Python implementation, the C implementation also requires |
| 1861 | * __reduce__, and a __safe_for_unpickling__ attr in the type object. |
| 1862 | */ |
| 1863 | static PyObject * |
| 1864 | delta_getstate(PyDateTime_Delta *self) |
| 1865 | { |
| 1866 | return Py_BuildValue("iii", GET_TD_DAYS(self), |
| 1867 | GET_TD_SECONDS(self), |
| 1868 | GET_TD_MICROSECONDS(self)); |
| 1869 | } |
| 1870 | |
| 1871 | static PyObject * |
| 1872 | delta_setstate(PyDateTime_Delta *self, PyObject *state) |
| 1873 | { |
| 1874 | int day; |
| 1875 | int second; |
| 1876 | int us; |
| 1877 | |
| 1878 | if (!PyArg_ParseTuple(state, "iii:__setstate__", &day, &second, &us)) |
| 1879 | return NULL; |
| 1880 | |
| 1881 | self->hashcode = -1; |
| 1882 | SET_TD_DAYS(self, day); |
| 1883 | SET_TD_SECONDS(self, second); |
| 1884 | SET_TD_MICROSECONDS(self, us); |
| 1885 | |
| 1886 | Py_INCREF(Py_None); |
| 1887 | return Py_None; |
| 1888 | } |
| 1889 | |
| 1890 | static PyObject * |
| 1891 | delta_reduce(PyDateTime_Delta* self) |
| 1892 | { |
| 1893 | PyObject* result = NULL; |
| 1894 | PyObject* state = delta_getstate(self); |
| 1895 | |
| 1896 | if (state != NULL) { |
| 1897 | /* The funky "()" in the format string creates an empty |
| 1898 | * tuple as the 2nd component of the result 3-tuple. |
| 1899 | */ |
| 1900 | result = Py_BuildValue("O()O", self->ob_type, state); |
| 1901 | Py_DECREF(state); |
| 1902 | } |
| 1903 | return result; |
| 1904 | } |
| 1905 | |
| 1906 | #define OFFSET(field) offsetof(PyDateTime_Delta, field) |
| 1907 | |
| 1908 | static PyMemberDef delta_members[] = { |
Neal Norwitz | dfb8086 | 2002-12-19 02:30:56 +0000 | [diff] [blame] | 1909 | {"days", T_INT, OFFSET(days), READONLY, |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1910 | PyDoc_STR("Number of days.")}, |
| 1911 | |
Neal Norwitz | dfb8086 | 2002-12-19 02:30:56 +0000 | [diff] [blame] | 1912 | {"seconds", T_INT, OFFSET(seconds), READONLY, |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1913 | PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, |
| 1914 | |
Neal Norwitz | dfb8086 | 2002-12-19 02:30:56 +0000 | [diff] [blame] | 1915 | {"microseconds", T_INT, OFFSET(microseconds), READONLY, |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 1916 | PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, |
| 1917 | {NULL} |
| 1918 | }; |
| 1919 | |
| 1920 | static PyMethodDef delta_methods[] = { |
| 1921 | {"__setstate__", (PyCFunction)delta_setstate, METH_O, |
| 1922 | PyDoc_STR("__setstate__(state)")}, |
| 1923 | |
| 1924 | {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, |
| 1925 | PyDoc_STR("__setstate__(state)")}, |
| 1926 | |
| 1927 | {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS, |
| 1928 | PyDoc_STR("__getstate__() -> state")}, |
| 1929 | {NULL, NULL}, |
| 1930 | }; |
| 1931 | |
| 1932 | static char delta_doc[] = |
| 1933 | PyDoc_STR("Difference between two datetime values."); |
| 1934 | |
| 1935 | static PyNumberMethods delta_as_number = { |
| 1936 | delta_add, /* nb_add */ |
| 1937 | delta_subtract, /* nb_subtract */ |
| 1938 | delta_multiply, /* nb_multiply */ |
| 1939 | delta_divide, /* nb_divide */ |
| 1940 | 0, /* nb_remainder */ |
| 1941 | 0, /* nb_divmod */ |
| 1942 | 0, /* nb_power */ |
| 1943 | (unaryfunc)delta_negative, /* nb_negative */ |
| 1944 | (unaryfunc)delta_positive, /* nb_positive */ |
| 1945 | (unaryfunc)delta_abs, /* nb_absolute */ |
| 1946 | (inquiry)delta_nonzero, /* nb_nonzero */ |
| 1947 | 0, /*nb_invert*/ |
| 1948 | 0, /*nb_lshift*/ |
| 1949 | 0, /*nb_rshift*/ |
| 1950 | 0, /*nb_and*/ |
| 1951 | 0, /*nb_xor*/ |
| 1952 | 0, /*nb_or*/ |
| 1953 | 0, /*nb_coerce*/ |
| 1954 | 0, /*nb_int*/ |
| 1955 | 0, /*nb_long*/ |
| 1956 | 0, /*nb_float*/ |
| 1957 | 0, /*nb_oct*/ |
| 1958 | 0, /*nb_hex*/ |
| 1959 | 0, /*nb_inplace_add*/ |
| 1960 | 0, /*nb_inplace_subtract*/ |
| 1961 | 0, /*nb_inplace_multiply*/ |
| 1962 | 0, /*nb_inplace_divide*/ |
| 1963 | 0, /*nb_inplace_remainder*/ |
| 1964 | 0, /*nb_inplace_power*/ |
| 1965 | 0, /*nb_inplace_lshift*/ |
| 1966 | 0, /*nb_inplace_rshift*/ |
| 1967 | 0, /*nb_inplace_and*/ |
| 1968 | 0, /*nb_inplace_xor*/ |
| 1969 | 0, /*nb_inplace_or*/ |
| 1970 | delta_divide, /* nb_floor_divide */ |
| 1971 | 0, /* nb_true_divide */ |
| 1972 | 0, /* nb_inplace_floor_divide */ |
| 1973 | 0, /* nb_inplace_true_divide */ |
| 1974 | }; |
| 1975 | |
| 1976 | static PyTypeObject PyDateTime_DeltaType = { |
| 1977 | PyObject_HEAD_INIT(NULL) |
| 1978 | 0, /* ob_size */ |
| 1979 | "datetime.timedelta", /* tp_name */ |
| 1980 | sizeof(PyDateTime_Delta), /* tp_basicsize */ |
| 1981 | 0, /* tp_itemsize */ |
| 1982 | 0, /* tp_dealloc */ |
| 1983 | 0, /* tp_print */ |
| 1984 | 0, /* tp_getattr */ |
| 1985 | 0, /* tp_setattr */ |
| 1986 | 0, /* tp_compare */ |
| 1987 | (reprfunc)delta_repr, /* tp_repr */ |
| 1988 | &delta_as_number, /* tp_as_number */ |
| 1989 | 0, /* tp_as_sequence */ |
| 1990 | 0, /* tp_as_mapping */ |
| 1991 | (hashfunc)delta_hash, /* tp_hash */ |
| 1992 | 0, /* tp_call */ |
| 1993 | (reprfunc)delta_str, /* tp_str */ |
| 1994 | PyObject_GenericGetAttr, /* tp_getattro */ |
| 1995 | 0, /* tp_setattro */ |
| 1996 | 0, /* tp_as_buffer */ |
| 1997 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */ |
| 1998 | delta_doc, /* tp_doc */ |
| 1999 | 0, /* tp_traverse */ |
| 2000 | 0, /* tp_clear */ |
| 2001 | (richcmpfunc)delta_richcompare, /* tp_richcompare */ |
| 2002 | 0, /* tp_weaklistoffset */ |
| 2003 | 0, /* tp_iter */ |
| 2004 | 0, /* tp_iternext */ |
| 2005 | delta_methods, /* tp_methods */ |
| 2006 | delta_members, /* tp_members */ |
| 2007 | 0, /* tp_getset */ |
| 2008 | 0, /* tp_base */ |
| 2009 | 0, /* tp_dict */ |
| 2010 | 0, /* tp_descr_get */ |
| 2011 | 0, /* tp_descr_set */ |
| 2012 | 0, /* tp_dictoffset */ |
| 2013 | 0, /* tp_init */ |
| 2014 | 0, /* tp_alloc */ |
| 2015 | delta_new, /* tp_new */ |
| 2016 | _PyObject_Del, /* tp_free */ |
| 2017 | }; |
| 2018 | |
| 2019 | /* |
| 2020 | * PyDateTime_Date implementation. |
| 2021 | */ |
| 2022 | |
| 2023 | /* Accessor properties. */ |
| 2024 | |
| 2025 | static PyObject * |
| 2026 | date_year(PyDateTime_Date *self, void *unused) |
| 2027 | { |
| 2028 | return PyInt_FromLong(GET_YEAR(self)); |
| 2029 | } |
| 2030 | |
| 2031 | static PyObject * |
| 2032 | date_month(PyDateTime_Date *self, void *unused) |
| 2033 | { |
| 2034 | return PyInt_FromLong(GET_MONTH(self)); |
| 2035 | } |
| 2036 | |
| 2037 | static PyObject * |
| 2038 | date_day(PyDateTime_Date *self, void *unused) |
| 2039 | { |
| 2040 | return PyInt_FromLong(GET_DAY(self)); |
| 2041 | } |
| 2042 | |
| 2043 | static PyGetSetDef date_getset[] = { |
| 2044 | {"year", (getter)date_year}, |
| 2045 | {"month", (getter)date_month}, |
| 2046 | {"day", (getter)date_day}, |
| 2047 | {NULL} |
| 2048 | }; |
| 2049 | |
| 2050 | /* Constructors. */ |
| 2051 | |
| 2052 | static PyObject * |
| 2053 | date_new(PyTypeObject *type, PyObject *args, PyObject *kw) |
| 2054 | { |
| 2055 | PyObject *self = NULL; |
| 2056 | int year; |
| 2057 | int month; |
| 2058 | int day; |
| 2059 | |
| 2060 | static char *keywords[] = { |
| 2061 | "year", "month", "day", NULL |
| 2062 | }; |
| 2063 | |
| 2064 | if (PyArg_ParseTupleAndKeywords(args, kw, "iii", keywords, |
| 2065 | &year, &month, &day)) { |
| 2066 | if (check_date_args(year, month, day) < 0) |
| 2067 | return NULL; |
| 2068 | self = new_date(year, month, day); |
| 2069 | } |
| 2070 | return self; |
| 2071 | } |
| 2072 | |
| 2073 | /* Return new date from localtime(t). */ |
| 2074 | static PyObject * |
| 2075 | date_local_from_time_t(PyObject *cls, time_t t) |
| 2076 | { |
| 2077 | struct tm *tm; |
| 2078 | PyObject *result = NULL; |
| 2079 | |
| 2080 | tm = localtime(&t); |
| 2081 | if (tm) |
| 2082 | result = PyObject_CallFunction(cls, "iii", |
| 2083 | tm->tm_year + 1900, |
| 2084 | tm->tm_mon + 1, |
| 2085 | tm->tm_mday); |
| 2086 | else |
| 2087 | PyErr_SetString(PyExc_ValueError, |
| 2088 | "timestamp out of range for " |
| 2089 | "platform localtime() function"); |
| 2090 | return result; |
| 2091 | } |
| 2092 | |
| 2093 | /* Return new date from current time. |
| 2094 | * We say this is equivalent to fromtimestamp(time.time()), and the |
| 2095 | * only way to be sure of that is to *call* time.time(). That's not |
| 2096 | * generally the same as calling C's time. |
| 2097 | */ |
| 2098 | static PyObject * |
| 2099 | date_today(PyObject *cls, PyObject *dummy) |
| 2100 | { |
| 2101 | PyObject *time; |
| 2102 | PyObject *result; |
| 2103 | |
| 2104 | time = time_time(); |
| 2105 | if (time == NULL) |
| 2106 | return NULL; |
| 2107 | |
| 2108 | /* Note well: today() is a class method, so this may not call |
| 2109 | * date.fromtimestamp. For example, it may call |
| 2110 | * datetime.fromtimestamp. That's why we need all the accuracy |
| 2111 | * time.time() delivers; if someone were gonzo about optimization, |
| 2112 | * date.today() could get away with plain C time(). |
| 2113 | */ |
| 2114 | result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); |
| 2115 | Py_DECREF(time); |
| 2116 | return result; |
| 2117 | } |
| 2118 | |
| 2119 | /* Return new date from given timestamp (Python timestamp -- a double). */ |
| 2120 | static PyObject * |
| 2121 | date_fromtimestamp(PyObject *cls, PyObject *args) |
| 2122 | { |
| 2123 | double timestamp; |
| 2124 | PyObject *result = NULL; |
| 2125 | |
| 2126 | if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) |
| 2127 | result = date_local_from_time_t(cls, (time_t)timestamp); |
| 2128 | return result; |
| 2129 | } |
| 2130 | |
| 2131 | /* Return new date from proleptic Gregorian ordinal. Raises ValueError if |
| 2132 | * the ordinal is out of range. |
| 2133 | */ |
| 2134 | static PyObject * |
| 2135 | date_fromordinal(PyObject *cls, PyObject *args) |
| 2136 | { |
| 2137 | PyObject *result = NULL; |
| 2138 | int ordinal; |
| 2139 | |
| 2140 | if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) { |
| 2141 | int year; |
| 2142 | int month; |
| 2143 | int day; |
| 2144 | |
| 2145 | if (ordinal < 1) |
| 2146 | PyErr_SetString(PyExc_ValueError, "ordinal must be " |
| 2147 | ">= 1"); |
| 2148 | else { |
| 2149 | ord_to_ymd(ordinal, &year, &month, &day); |
| 2150 | result = PyObject_CallFunction(cls, "iii", |
| 2151 | year, month, day); |
| 2152 | } |
| 2153 | } |
| 2154 | return result; |
| 2155 | } |
| 2156 | |
| 2157 | /* |
| 2158 | * Date arithmetic. |
| 2159 | */ |
| 2160 | |
| 2161 | /* date + timedelta -> date. If arg negate is true, subtract the timedelta |
| 2162 | * instead. |
| 2163 | */ |
| 2164 | static PyObject * |
| 2165 | add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate) |
| 2166 | { |
| 2167 | PyObject *result = NULL; |
| 2168 | int year = GET_YEAR(date); |
| 2169 | int month = GET_MONTH(date); |
| 2170 | int deltadays = GET_TD_DAYS(delta); |
| 2171 | /* C-level overflow is impossible because |deltadays| < 1e9. */ |
| 2172 | int day = GET_DAY(date) + (negate ? -deltadays : deltadays); |
| 2173 | |
| 2174 | if (normalize_date(&year, &month, &day) >= 0) |
| 2175 | result = new_date(year, month, day); |
| 2176 | return result; |
| 2177 | } |
| 2178 | |
| 2179 | static PyObject * |
| 2180 | date_add(PyObject *left, PyObject *right) |
| 2181 | { |
| 2182 | if (PyDateTime_Check(left) || PyDateTime_Check(right)) { |
| 2183 | Py_INCREF(Py_NotImplemented); |
| 2184 | return Py_NotImplemented; |
| 2185 | } |
| 2186 | if (PyDate_CheckExact(left)) { |
| 2187 | /* date + ??? */ |
| 2188 | if (PyDelta_Check(right)) |
| 2189 | /* date + delta */ |
| 2190 | return add_date_timedelta((PyDateTime_Date *) left, |
| 2191 | (PyDateTime_Delta *) right, |
| 2192 | 0); |
| 2193 | } |
| 2194 | else { |
| 2195 | /* ??? + date |
| 2196 | * 'right' must be one of us, or we wouldn't have been called |
| 2197 | */ |
| 2198 | if (PyDelta_Check(left)) |
| 2199 | /* delta + date */ |
| 2200 | return add_date_timedelta((PyDateTime_Date *) right, |
| 2201 | (PyDateTime_Delta *) left, |
| 2202 | 0); |
| 2203 | } |
| 2204 | Py_INCREF(Py_NotImplemented); |
| 2205 | return Py_NotImplemented; |
| 2206 | } |
| 2207 | |
| 2208 | static PyObject * |
| 2209 | date_subtract(PyObject *left, PyObject *right) |
| 2210 | { |
| 2211 | if (PyDateTime_Check(left) || PyDateTime_Check(right)) { |
| 2212 | Py_INCREF(Py_NotImplemented); |
| 2213 | return Py_NotImplemented; |
| 2214 | } |
| 2215 | if (PyDate_CheckExact(left)) { |
| 2216 | if (PyDate_CheckExact(right)) { |
| 2217 | /* date - date */ |
| 2218 | int left_ord = ymd_to_ord(GET_YEAR(left), |
| 2219 | GET_MONTH(left), |
| 2220 | GET_DAY(left)); |
| 2221 | int right_ord = ymd_to_ord(GET_YEAR(right), |
| 2222 | GET_MONTH(right), |
| 2223 | GET_DAY(right)); |
| 2224 | return new_delta(left_ord - right_ord, 0, 0, 0); |
| 2225 | } |
| 2226 | if (PyDelta_Check(right)) { |
| 2227 | /* date - delta */ |
| 2228 | return add_date_timedelta((PyDateTime_Date *) left, |
| 2229 | (PyDateTime_Delta *) right, |
| 2230 | 1); |
| 2231 | } |
| 2232 | } |
| 2233 | Py_INCREF(Py_NotImplemented); |
| 2234 | return Py_NotImplemented; |
| 2235 | } |
| 2236 | |
| 2237 | |
| 2238 | /* Various ways to turn a date into a string. */ |
| 2239 | |
| 2240 | static PyObject * |
| 2241 | date_repr(PyDateTime_Date *self) |
| 2242 | { |
| 2243 | char buffer[1028]; |
| 2244 | char *typename; |
| 2245 | |
| 2246 | typename = self->ob_type->tp_name; |
| 2247 | PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)", |
| 2248 | typename, |
| 2249 | GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); |
| 2250 | |
| 2251 | return PyString_FromString(buffer); |
| 2252 | } |
| 2253 | |
| 2254 | static PyObject * |
| 2255 | date_isoformat(PyDateTime_Date *self) |
| 2256 | { |
| 2257 | char buffer[128]; |
| 2258 | |
| 2259 | isoformat_date(self, buffer, sizeof(buffer)); |
| 2260 | return PyString_FromString(buffer); |
| 2261 | } |
| 2262 | |
| 2263 | /* str() calls the appropriate isofomat() method. */ |
| 2264 | static PyObject * |
| 2265 | date_str(PyDateTime_Date *self) |
| 2266 | { |
| 2267 | return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); |
| 2268 | } |
| 2269 | |
| 2270 | |
| 2271 | static PyObject * |
| 2272 | date_ctime(PyDateTime_Date *self) |
| 2273 | { |
| 2274 | return format_ctime(self, 0, 0, 0); |
| 2275 | } |
| 2276 | |
| 2277 | static PyObject * |
| 2278 | date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw) |
| 2279 | { |
| 2280 | /* This method can be inherited, and needs to call the |
| 2281 | * timetuple() method appropriate to self's class. |
| 2282 | */ |
| 2283 | PyObject *result; |
| 2284 | PyObject *format; |
| 2285 | PyObject *tuple; |
| 2286 | static char *keywords[] = {"format", NULL}; |
| 2287 | |
| 2288 | if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords, |
| 2289 | &PyString_Type, &format)) |
| 2290 | return NULL; |
| 2291 | |
| 2292 | tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); |
| 2293 | if (tuple == NULL) |
| 2294 | return NULL; |
| 2295 | result = wrap_strftime((PyObject *)self, format, tuple); |
| 2296 | Py_DECREF(tuple); |
| 2297 | return result; |
| 2298 | } |
| 2299 | |
| 2300 | /* ISO methods. */ |
| 2301 | |
| 2302 | static PyObject * |
| 2303 | date_isoweekday(PyDateTime_Date *self) |
| 2304 | { |
| 2305 | int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); |
| 2306 | |
| 2307 | return PyInt_FromLong(dow + 1); |
| 2308 | } |
| 2309 | |
| 2310 | static PyObject * |
| 2311 | date_isocalendar(PyDateTime_Date *self) |
| 2312 | { |
| 2313 | int year = GET_YEAR(self); |
| 2314 | int week1_monday = iso_week1_monday(year); |
| 2315 | int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); |
| 2316 | int week; |
| 2317 | int day; |
| 2318 | |
| 2319 | week = divmod(today - week1_monday, 7, &day); |
| 2320 | if (week < 0) { |
| 2321 | --year; |
| 2322 | week1_monday = iso_week1_monday(year); |
| 2323 | week = divmod(today - week1_monday, 7, &day); |
| 2324 | } |
| 2325 | else if (week >= 52 && today >= iso_week1_monday(year + 1)) { |
| 2326 | ++year; |
| 2327 | week = 0; |
| 2328 | } |
| 2329 | return Py_BuildValue("iii", year, week + 1, day + 1); |
| 2330 | } |
| 2331 | |
| 2332 | /* Miscellaneous methods. */ |
| 2333 | |
| 2334 | /* This is more natural as a tp_compare, but doesn't work then: for whatever |
| 2335 | * reason, Python's try_3way_compare ignores tp_compare unless |
| 2336 | * PyInstance_Check returns true, but these aren't old-style classes. |
| 2337 | */ |
| 2338 | static PyObject * |
| 2339 | date_richcompare(PyDateTime_Date *self, PyObject *other, int op) |
| 2340 | { |
| 2341 | int diff; |
| 2342 | |
| 2343 | if (! PyDate_Check(other)) { |
| 2344 | PyErr_Format(PyExc_TypeError, |
| 2345 | "can't compare date to %s instance", |
| 2346 | other->ob_type->tp_name); |
| 2347 | return NULL; |
| 2348 | } |
| 2349 | diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, |
| 2350 | _PyDateTime_DATE_DATASIZE); |
| 2351 | return diff_to_bool(diff, op); |
| 2352 | } |
| 2353 | |
| 2354 | static PyObject * |
| 2355 | date_timetuple(PyDateTime_Date *self) |
| 2356 | { |
| 2357 | return build_struct_time(GET_YEAR(self), |
| 2358 | GET_MONTH(self), |
| 2359 | GET_DAY(self), |
| 2360 | 0, 0, 0, -1); |
| 2361 | } |
| 2362 | |
| 2363 | static PyObject *date_getstate(PyDateTime_Date *self); |
| 2364 | |
| 2365 | static long |
| 2366 | date_hash(PyDateTime_Date *self) |
| 2367 | { |
| 2368 | if (self->hashcode == -1) { |
| 2369 | PyObject *temp = date_getstate(self); |
| 2370 | if (temp != NULL) { |
| 2371 | self->hashcode = PyObject_Hash(temp); |
| 2372 | Py_DECREF(temp); |
| 2373 | } |
| 2374 | } |
| 2375 | return self->hashcode; |
| 2376 | } |
| 2377 | |
| 2378 | static PyObject * |
| 2379 | date_toordinal(PyDateTime_Date *self) |
| 2380 | { |
| 2381 | return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self), |
| 2382 | GET_DAY(self))); |
| 2383 | } |
| 2384 | |
| 2385 | static PyObject * |
| 2386 | date_weekday(PyDateTime_Date *self) |
| 2387 | { |
| 2388 | int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); |
| 2389 | |
| 2390 | return PyInt_FromLong(dow); |
| 2391 | } |
| 2392 | |
| 2393 | /* Pickle support. Quite a maze! */ |
| 2394 | |
| 2395 | static PyObject * |
| 2396 | date_getstate(PyDateTime_Date *self) |
| 2397 | { |
| 2398 | return PyString_FromStringAndSize(self->data, |
| 2399 | _PyDateTime_DATE_DATASIZE); |
| 2400 | } |
| 2401 | |
| 2402 | static PyObject * |
| 2403 | date_setstate(PyDateTime_Date *self, PyObject *state) |
| 2404 | { |
| 2405 | const int len = PyString_Size(state); |
| 2406 | unsigned char *pdata = (unsigned char*)PyString_AsString(state); |
| 2407 | |
| 2408 | if (! PyString_Check(state) || |
| 2409 | len != _PyDateTime_DATE_DATASIZE) { |
| 2410 | PyErr_SetString(PyExc_TypeError, |
| 2411 | "bad argument to date.__setstate__"); |
| 2412 | return NULL; |
| 2413 | } |
| 2414 | memcpy(self->data, pdata, _PyDateTime_DATE_DATASIZE); |
| 2415 | self->hashcode = -1; |
| 2416 | |
| 2417 | Py_INCREF(Py_None); |
| 2418 | return Py_None; |
| 2419 | } |
| 2420 | |
| 2421 | /* XXX This seems a ridiculously inefficient way to pickle a short string. */ |
| 2422 | static PyObject * |
| 2423 | date_pickler(PyObject *module, PyDateTime_Date *date) |
| 2424 | { |
| 2425 | PyObject *state; |
| 2426 | PyObject *result = NULL; |
| 2427 | |
| 2428 | if (! PyDate_CheckExact(date)) { |
| 2429 | PyErr_Format(PyExc_TypeError, |
| 2430 | "bad type passed to date pickler: %s", |
| 2431 | date->ob_type->tp_name); |
| 2432 | return NULL; |
| 2433 | } |
| 2434 | state = date_getstate(date); |
| 2435 | if (state) { |
| 2436 | result = Py_BuildValue("O(O)", date_unpickler_object, state); |
| 2437 | Py_DECREF(state); |
| 2438 | } |
| 2439 | return result; |
| 2440 | } |
| 2441 | |
| 2442 | static PyObject * |
| 2443 | date_unpickler(PyObject *module, PyObject *arg) |
| 2444 | { |
| 2445 | PyDateTime_Date *self; |
| 2446 | |
| 2447 | if (! PyString_CheckExact(arg)) { |
| 2448 | PyErr_Format(PyExc_TypeError, |
| 2449 | "bad type passed to date unpickler: %s", |
| 2450 | arg->ob_type->tp_name); |
| 2451 | return NULL; |
| 2452 | } |
| 2453 | self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType); |
| 2454 | if (self != NULL) { |
| 2455 | PyObject *res = date_setstate(self, arg); |
| 2456 | if (res == NULL) { |
| 2457 | Py_DECREF(self); |
| 2458 | return NULL; |
| 2459 | } |
| 2460 | Py_DECREF(res); |
| 2461 | } |
| 2462 | return (PyObject *)self; |
| 2463 | } |
| 2464 | |
| 2465 | static PyMethodDef date_methods[] = { |
| 2466 | /* Class methods: */ |
| 2467 | {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | |
| 2468 | METH_CLASS, |
| 2469 | PyDoc_STR("timestamp -> local date from a POSIX timestamp (like " |
| 2470 | "time.time()).")}, |
| 2471 | |
| 2472 | {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | |
| 2473 | METH_CLASS, |
| 2474 | PyDoc_STR("int -> date corresponding to a proleptic Gregorian " |
| 2475 | "ordinal.")}, |
| 2476 | |
| 2477 | {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS, |
| 2478 | PyDoc_STR("Current date or datetime: same as " |
| 2479 | "self.__class__.fromtimestamp(time.time()).")}, |
| 2480 | |
| 2481 | /* Instance methods: */ |
| 2482 | |
| 2483 | {"ctime", (PyCFunction)date_ctime, METH_NOARGS, |
| 2484 | PyDoc_STR("Return ctime() style string.")}, |
| 2485 | |
| 2486 | {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS, |
| 2487 | PyDoc_STR("format -> strftime() style string.")}, |
| 2488 | |
| 2489 | {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, |
| 2490 | PyDoc_STR("Return time tuple, compatible with time.localtime().")}, |
| 2491 | |
| 2492 | {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, |
| 2493 | PyDoc_STR("Return a 3-tuple containing ISO year, week number, and " |
| 2494 | "weekday.")}, |
| 2495 | |
| 2496 | {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS, |
| 2497 | PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, |
| 2498 | |
| 2499 | {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, |
| 2500 | PyDoc_STR("Return the day of the week represented by the date.\n" |
| 2501 | "Monday == 1 ... Sunday == 7")}, |
| 2502 | |
| 2503 | {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, |
| 2504 | PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year " |
| 2505 | "1 is day 1.")}, |
| 2506 | |
| 2507 | {"weekday", (PyCFunction)date_weekday, METH_NOARGS, |
| 2508 | PyDoc_STR("Return the day of the week represented by the date.\n" |
| 2509 | "Monday == 0 ... Sunday == 6")}, |
| 2510 | |
| 2511 | {"__setstate__", (PyCFunction)date_setstate, METH_O, |
| 2512 | PyDoc_STR("__setstate__(state)")}, |
| 2513 | |
| 2514 | {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, |
| 2515 | PyDoc_STR("__getstate__() -> state")}, |
| 2516 | |
| 2517 | {NULL, NULL} |
| 2518 | }; |
| 2519 | |
| 2520 | static char date_doc[] = |
| 2521 | PyDoc_STR("Basic date type."); |
| 2522 | |
| 2523 | static PyNumberMethods date_as_number = { |
| 2524 | date_add, /* nb_add */ |
| 2525 | date_subtract, /* nb_subtract */ |
| 2526 | 0, /* nb_multiply */ |
| 2527 | 0, /* nb_divide */ |
| 2528 | 0, /* nb_remainder */ |
| 2529 | 0, /* nb_divmod */ |
| 2530 | 0, /* nb_power */ |
| 2531 | 0, /* nb_negative */ |
| 2532 | 0, /* nb_positive */ |
| 2533 | 0, /* nb_absolute */ |
| 2534 | 0, /* nb_nonzero */ |
| 2535 | }; |
| 2536 | |
| 2537 | static PyTypeObject PyDateTime_DateType = { |
| 2538 | PyObject_HEAD_INIT(NULL) |
| 2539 | 0, /* ob_size */ |
| 2540 | "datetime.date", /* tp_name */ |
| 2541 | sizeof(PyDateTime_Date), /* tp_basicsize */ |
| 2542 | 0, /* tp_itemsize */ |
| 2543 | (destructor)PyObject_Del, /* tp_dealloc */ |
| 2544 | 0, /* tp_print */ |
| 2545 | 0, /* tp_getattr */ |
| 2546 | 0, /* tp_setattr */ |
| 2547 | 0, /* tp_compare */ |
| 2548 | (reprfunc)date_repr, /* tp_repr */ |
| 2549 | &date_as_number, /* tp_as_number */ |
| 2550 | 0, /* tp_as_sequence */ |
| 2551 | 0, /* tp_as_mapping */ |
| 2552 | (hashfunc)date_hash, /* tp_hash */ |
| 2553 | 0, /* tp_call */ |
| 2554 | (reprfunc)date_str, /* tp_str */ |
| 2555 | PyObject_GenericGetAttr, /* tp_getattro */ |
| 2556 | 0, /* tp_setattro */ |
| 2557 | 0, /* tp_as_buffer */ |
| 2558 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | |
| 2559 | Py_TPFLAGS_BASETYPE, /* tp_flags */ |
| 2560 | date_doc, /* tp_doc */ |
| 2561 | 0, /* tp_traverse */ |
| 2562 | 0, /* tp_clear */ |
| 2563 | (richcmpfunc)date_richcompare, /* tp_richcompare */ |
| 2564 | 0, /* tp_weaklistoffset */ |
| 2565 | 0, /* tp_iter */ |
| 2566 | 0, /* tp_iternext */ |
| 2567 | date_methods, /* tp_methods */ |
| 2568 | 0, /* tp_members */ |
| 2569 | date_getset, /* tp_getset */ |
| 2570 | 0, /* tp_base */ |
| 2571 | 0, /* tp_dict */ |
| 2572 | 0, /* tp_descr_get */ |
| 2573 | 0, /* tp_descr_set */ |
| 2574 | 0, /* tp_dictoffset */ |
| 2575 | 0, /* tp_init */ |
| 2576 | 0, /* tp_alloc */ |
| 2577 | date_new, /* tp_new */ |
| 2578 | _PyObject_Del, /* tp_free */ |
| 2579 | }; |
| 2580 | |
| 2581 | /* |
| 2582 | * PyDateTime_DateTime implementation. |
| 2583 | */ |
| 2584 | |
| 2585 | /* Accessor properties. */ |
| 2586 | |
| 2587 | static PyObject * |
| 2588 | datetime_hour(PyDateTime_DateTime *self, void *unused) |
| 2589 | { |
| 2590 | return PyInt_FromLong(DATE_GET_HOUR(self)); |
| 2591 | } |
| 2592 | |
| 2593 | static PyObject * |
| 2594 | datetime_minute(PyDateTime_DateTime *self, void *unused) |
| 2595 | { |
| 2596 | return PyInt_FromLong(DATE_GET_MINUTE(self)); |
| 2597 | } |
| 2598 | |
| 2599 | static PyObject * |
| 2600 | datetime_second(PyDateTime_DateTime *self, void *unused) |
| 2601 | { |
| 2602 | return PyInt_FromLong(DATE_GET_SECOND(self)); |
| 2603 | } |
| 2604 | |
| 2605 | static PyObject * |
| 2606 | datetime_microsecond(PyDateTime_DateTime *self, void *unused) |
| 2607 | { |
| 2608 | return PyInt_FromLong(DATE_GET_MICROSECOND(self)); |
| 2609 | } |
| 2610 | |
| 2611 | static PyGetSetDef datetime_getset[] = { |
| 2612 | {"hour", (getter)datetime_hour}, |
| 2613 | {"minute", (getter)datetime_minute}, |
| 2614 | {"second", (getter)datetime_second}, |
| 2615 | {"microsecond", (getter)datetime_microsecond}, |
| 2616 | {NULL} |
| 2617 | }; |
| 2618 | |
| 2619 | /* Constructors. */ |
| 2620 | |
| 2621 | static PyObject * |
| 2622 | datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw) |
| 2623 | { |
| 2624 | PyObject *self = NULL; |
| 2625 | int year; |
| 2626 | int month; |
| 2627 | int day; |
| 2628 | int hour = 0; |
| 2629 | int minute = 0; |
| 2630 | int second = 0; |
| 2631 | int usecond = 0; |
| 2632 | |
| 2633 | static char *keywords[] = { |
| 2634 | "year", "month", "day", "hour", "minute", "second", |
| 2635 | "microsecond", NULL |
| 2636 | }; |
| 2637 | |
| 2638 | if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiii", keywords, |
| 2639 | &year, &month, &day, &hour, &minute, |
| 2640 | &second, &usecond)) { |
| 2641 | if (check_date_args(year, month, day) < 0) |
| 2642 | return NULL; |
| 2643 | if (check_time_args(hour, minute, second, usecond) < 0) |
| 2644 | return NULL; |
| 2645 | self = new_datetime(year, month, day, |
| 2646 | hour, minute, second, usecond); |
| 2647 | } |
| 2648 | return self; |
| 2649 | } |
| 2650 | |
| 2651 | |
| 2652 | /* TM_FUNC is the shared type of localtime() and gmtime(). */ |
| 2653 | typedef struct tm *(*TM_FUNC)(const time_t *timer); |
| 2654 | |
| 2655 | /* Internal helper. |
| 2656 | * Build datetime from a time_t and a distinct count of microseconds. |
| 2657 | * Pass localtime or gmtime for f, to control the interpretation of timet. |
| 2658 | */ |
| 2659 | static PyObject * |
| 2660 | datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us) |
| 2661 | { |
| 2662 | struct tm *tm; |
| 2663 | PyObject *result = NULL; |
| 2664 | |
| 2665 | tm = f(&timet); |
| 2666 | if (tm) |
| 2667 | result = PyObject_CallFunction(cls, "iiiiiii", |
| 2668 | tm->tm_year + 1900, |
| 2669 | tm->tm_mon + 1, |
| 2670 | tm->tm_mday, |
| 2671 | tm->tm_hour, |
| 2672 | tm->tm_min, |
| 2673 | tm->tm_sec, |
| 2674 | us); |
| 2675 | else |
| 2676 | PyErr_SetString(PyExc_ValueError, |
| 2677 | "timestamp out of range for " |
| 2678 | "platform localtime()/gmtime() function"); |
| 2679 | return result; |
| 2680 | } |
| 2681 | |
| 2682 | /* Internal helper. |
| 2683 | * Build datetime from a Python timestamp. Pass localtime or gmtime for f, |
| 2684 | * to control the interpretation of the timestamp. Since a double doesn't |
| 2685 | * have enough bits to cover a datetime's full range of precision, it's |
| 2686 | * better to call datetime_from_timet_and_us provided you have a way |
| 2687 | * to get that much precision (e.g., C time() isn't good enough). |
| 2688 | */ |
| 2689 | static PyObject * |
| 2690 | datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp) |
| 2691 | { |
| 2692 | time_t timet = (time_t)timestamp; |
| 2693 | int us = (int)((timestamp - (double)timet) * 1e6); |
| 2694 | |
| 2695 | return datetime_from_timet_and_us(cls, f, timet, us); |
| 2696 | } |
| 2697 | |
| 2698 | /* Internal helper. |
| 2699 | * Build most accurate possible datetime for current time. Pass localtime or |
| 2700 | * gmtime for f as appropriate. |
| 2701 | */ |
| 2702 | static PyObject * |
| 2703 | datetime_best_possible(PyObject *cls, TM_FUNC f) |
| 2704 | { |
| 2705 | #ifdef HAVE_GETTIMEOFDAY |
| 2706 | struct timeval t; |
| 2707 | |
| 2708 | #ifdef GETTIMEOFDAY_NO_TZ |
| 2709 | gettimeofday(&t); |
| 2710 | #else |
| 2711 | gettimeofday(&t, (struct timezone *)NULL); |
| 2712 | #endif |
| 2713 | return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec); |
| 2714 | |
| 2715 | #else /* ! HAVE_GETTIMEOFDAY */ |
| 2716 | /* No flavor of gettimeofday exists on this platform. Python's |
| 2717 | * time.time() does a lot of other platform tricks to get the |
| 2718 | * best time it can on the platform, and we're not going to do |
| 2719 | * better than that (if we could, the better code would belong |
| 2720 | * in time.time()!) We're limited by the precision of a double, |
| 2721 | * though. |
| 2722 | */ |
| 2723 | PyObject *time; |
| 2724 | double dtime; |
| 2725 | |
| 2726 | time = time_time(); |
| 2727 | if (time == NULL) |
| 2728 | return NULL; |
| 2729 | dtime = PyFloat_AsDouble(time); |
| 2730 | Py_DECREF(time); |
| 2731 | if (dtime == -1.0 && PyErr_Occurred()) |
| 2732 | return NULL; |
| 2733 | return datetime_from_timestamp(cls, f, dtime); |
| 2734 | #endif /* ! HAVE_GETTIMEOFDAY */ |
| 2735 | } |
| 2736 | |
| 2737 | /* Return new local datetime from timestamp (Python timestamp -- a double). */ |
| 2738 | static PyObject * |
| 2739 | datetime_fromtimestamp(PyObject *cls, PyObject *args) |
| 2740 | { |
| 2741 | double timestamp; |
| 2742 | PyObject *result = NULL; |
| 2743 | |
| 2744 | if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) |
| 2745 | result = datetime_from_timestamp(cls, localtime, timestamp); |
| 2746 | return result; |
| 2747 | } |
| 2748 | |
| 2749 | /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ |
| 2750 | static PyObject * |
| 2751 | datetime_utcfromtimestamp(PyObject *cls, PyObject *args) |
| 2752 | { |
| 2753 | double timestamp; |
| 2754 | PyObject *result = NULL; |
| 2755 | |
| 2756 | if (PyArg_ParseTuple(args, "d:utcfromtimestamp", ×tamp)) |
| 2757 | result = datetime_from_timestamp(cls, gmtime, timestamp); |
| 2758 | return result; |
| 2759 | } |
| 2760 | |
| 2761 | /* Return best possible local time -- this isn't constrained by the |
| 2762 | * precision of a timestamp. |
| 2763 | */ |
| 2764 | static PyObject * |
| 2765 | datetime_now(PyObject *cls, PyObject *dummy) |
| 2766 | { |
| 2767 | return datetime_best_possible(cls, localtime); |
| 2768 | } |
| 2769 | |
| 2770 | /* Return best possible UTC time -- this isn't constrained by the |
| 2771 | * precision of a timestamp. |
| 2772 | */ |
| 2773 | static PyObject * |
| 2774 | datetime_utcnow(PyObject *cls, PyObject *dummy) |
| 2775 | { |
| 2776 | return datetime_best_possible(cls, gmtime); |
| 2777 | } |
| 2778 | |
| 2779 | /* Return new datetime or datetimetz from date/datetime/datetimetz and |
| 2780 | * time/timetz arguments. |
| 2781 | */ |
| 2782 | static PyObject * |
| 2783 | datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) |
| 2784 | { |
| 2785 | static char *keywords[] = {"date", "time", NULL}; |
| 2786 | PyObject *date; |
| 2787 | PyObject *time; |
| 2788 | PyObject *result = NULL; |
| 2789 | |
| 2790 | if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords, |
| 2791 | &PyDateTime_DateType, &date, |
| 2792 | &PyDateTime_TimeType, &time)) |
| 2793 | result = PyObject_CallFunction(cls, "iiiiiii", |
| 2794 | GET_YEAR(date), |
| 2795 | GET_MONTH(date), |
| 2796 | GET_DAY(date), |
| 2797 | TIME_GET_HOUR(time), |
| 2798 | TIME_GET_MINUTE(time), |
| 2799 | TIME_GET_SECOND(time), |
| 2800 | TIME_GET_MICROSECOND(time)); |
| 2801 | if (result && PyTimeTZ_Check(time) && PyDateTimeTZ_Check(result)) { |
| 2802 | /* Copy the tzinfo field. */ |
| 2803 | PyObject *tzinfo = ((PyDateTime_TimeTZ *)time)->tzinfo; |
| 2804 | Py_INCREF(tzinfo); |
| 2805 | Py_DECREF(((PyDateTime_DateTimeTZ *)result)->tzinfo); |
| 2806 | ((PyDateTime_DateTimeTZ *)result)->tzinfo = tzinfo; |
| 2807 | } |
| 2808 | return result; |
| 2809 | } |
| 2810 | |
| 2811 | /* datetime arithmetic. */ |
| 2812 | |
| 2813 | static PyObject * |
| 2814 | add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) |
| 2815 | { |
| 2816 | /* Note that the C-level additions can't overflow, because of |
| 2817 | * invariant bounds on the member values. |
| 2818 | */ |
| 2819 | int year = GET_YEAR(date); |
| 2820 | int month = GET_MONTH(date); |
| 2821 | int day = GET_DAY(date) + GET_TD_DAYS(delta); |
| 2822 | int hour = DATE_GET_HOUR(date); |
| 2823 | int minute = DATE_GET_MINUTE(date); |
| 2824 | int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta); |
| 2825 | int microsecond = DATE_GET_MICROSECOND(date) + |
| 2826 | GET_TD_MICROSECONDS(delta); |
| 2827 | |
| 2828 | if (normalize_datetime(&year, &month, &day, |
| 2829 | &hour, &minute, &second, µsecond) < 0) |
| 2830 | return NULL; |
| 2831 | else |
| 2832 | return new_datetime(year, month, day, |
| 2833 | hour, minute, second, microsecond); |
| 2834 | } |
| 2835 | |
| 2836 | static PyObject * |
| 2837 | sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) |
| 2838 | { |
| 2839 | /* Note that the C-level subtractions can't overflow, because of |
| 2840 | * invariant bounds on the member values. |
| 2841 | */ |
| 2842 | int year = GET_YEAR(date); |
| 2843 | int month = GET_MONTH(date); |
| 2844 | int day = GET_DAY(date) - GET_TD_DAYS(delta); |
| 2845 | int hour = DATE_GET_HOUR(date); |
| 2846 | int minute = DATE_GET_MINUTE(date); |
| 2847 | int second = DATE_GET_SECOND(date) - GET_TD_SECONDS(delta); |
| 2848 | int microsecond = DATE_GET_MICROSECOND(date) - |
| 2849 | GET_TD_MICROSECONDS(delta); |
| 2850 | |
| 2851 | if (normalize_datetime(&year, &month, &day, |
| 2852 | &hour, &minute, &second, µsecond) < 0) |
| 2853 | return NULL; |
| 2854 | else |
| 2855 | return new_datetime(year, month, day, |
| 2856 | hour, minute, second, microsecond); |
| 2857 | } |
| 2858 | |
| 2859 | static PyObject * |
| 2860 | sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right) |
| 2861 | { |
| 2862 | int days1 = ymd_to_ord(GET_YEAR(left), GET_MONTH(left), GET_DAY(left)); |
| 2863 | int days2 = ymd_to_ord(GET_YEAR(right), |
| 2864 | GET_MONTH(right), |
| 2865 | GET_DAY(right)); |
| 2866 | /* These can't overflow, since the values are normalized. At most |
| 2867 | * this gives the number of seconds in one day. |
| 2868 | */ |
| 2869 | int delta_s = (DATE_GET_HOUR(left) - DATE_GET_HOUR(right)) * 3600 + |
| 2870 | (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 + |
| 2871 | DATE_GET_SECOND(left) - DATE_GET_SECOND(right); |
| 2872 | int delta_us = DATE_GET_MICROSECOND(left) - |
| 2873 | DATE_GET_MICROSECOND(right); |
| 2874 | |
| 2875 | return new_delta(days1 - days2, delta_s, delta_us, 1); |
| 2876 | } |
| 2877 | |
| 2878 | static PyObject * |
| 2879 | datetime_add(PyObject *left, PyObject *right) |
| 2880 | { |
| 2881 | if (PyDateTime_Check(left)) { |
| 2882 | /* datetime + ??? */ |
| 2883 | if (PyDelta_Check(right)) |
| 2884 | /* datetime + delta */ |
| 2885 | return add_datetime_timedelta( |
| 2886 | (PyDateTime_DateTime *)left, |
| 2887 | (PyDateTime_Delta *)right); |
| 2888 | } |
| 2889 | else if (PyDelta_Check(left)) { |
| 2890 | /* delta + datetime */ |
| 2891 | return add_datetime_timedelta((PyDateTime_DateTime *) right, |
| 2892 | (PyDateTime_Delta *) left); |
| 2893 | } |
| 2894 | Py_INCREF(Py_NotImplemented); |
| 2895 | return Py_NotImplemented; |
| 2896 | } |
| 2897 | |
| 2898 | static PyObject * |
| 2899 | datetime_subtract(PyObject *left, PyObject *right) |
| 2900 | { |
| 2901 | PyObject *result = Py_NotImplemented; |
| 2902 | |
| 2903 | if (PyDateTime_Check(left)) { |
| 2904 | /* datetime - ??? */ |
| 2905 | if (PyDateTime_Check(right)) { |
| 2906 | /* datetime - datetime */ |
| 2907 | result = sub_datetime_datetime( |
| 2908 | (PyDateTime_DateTime *)left, |
| 2909 | (PyDateTime_DateTime *)right); |
| 2910 | } |
| 2911 | else if (PyDelta_Check(right)) { |
| 2912 | /* datetime - delta */ |
| 2913 | result = sub_datetime_timedelta( |
| 2914 | (PyDateTime_DateTime *)left, |
| 2915 | (PyDateTime_Delta *)right); |
| 2916 | } |
| 2917 | } |
| 2918 | |
| 2919 | if (result == Py_NotImplemented) |
| 2920 | Py_INCREF(result); |
| 2921 | return result; |
| 2922 | } |
| 2923 | |
| 2924 | /* Various ways to turn a datetime into a string. */ |
| 2925 | |
| 2926 | static PyObject * |
| 2927 | datetime_repr(PyDateTime_DateTime *self) |
| 2928 | { |
| 2929 | char buffer[1000]; |
| 2930 | char *typename = self->ob_type->tp_name; |
| 2931 | |
| 2932 | if (DATE_GET_MICROSECOND(self)) { |
| 2933 | PyOS_snprintf(buffer, sizeof(buffer), |
| 2934 | "%s(%d, %d, %d, %d, %d, %d, %d)", |
| 2935 | typename, |
| 2936 | GET_YEAR(self), GET_MONTH(self), GET_DAY(self), |
| 2937 | DATE_GET_HOUR(self), DATE_GET_MINUTE(self), |
| 2938 | DATE_GET_SECOND(self), |
| 2939 | DATE_GET_MICROSECOND(self)); |
| 2940 | } |
| 2941 | else if (DATE_GET_SECOND(self)) { |
| 2942 | PyOS_snprintf(buffer, sizeof(buffer), |
| 2943 | "%s(%d, %d, %d, %d, %d, %d)", |
| 2944 | typename, |
| 2945 | GET_YEAR(self), GET_MONTH(self), GET_DAY(self), |
| 2946 | DATE_GET_HOUR(self), DATE_GET_MINUTE(self), |
| 2947 | DATE_GET_SECOND(self)); |
| 2948 | } |
| 2949 | else { |
| 2950 | PyOS_snprintf(buffer, sizeof(buffer), |
| 2951 | "%s(%d, %d, %d, %d, %d)", |
| 2952 | typename, |
| 2953 | GET_YEAR(self), GET_MONTH(self), GET_DAY(self), |
| 2954 | DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); |
| 2955 | } |
| 2956 | return PyString_FromString(buffer); |
| 2957 | } |
| 2958 | |
| 2959 | static PyObject * |
| 2960 | datetime_str(PyDateTime_DateTime *self) |
| 2961 | { |
| 2962 | return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " "); |
| 2963 | } |
| 2964 | |
| 2965 | static PyObject * |
| 2966 | datetime_isoformat(PyDateTime_DateTime *self, |
| 2967 | PyObject *args, PyObject *kw) |
| 2968 | { |
| 2969 | char sep = 'T'; |
| 2970 | static char *keywords[] = {"sep", NULL}; |
| 2971 | char buffer[100]; |
| 2972 | char *cp; |
| 2973 | |
| 2974 | if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords, |
| 2975 | &sep)) |
| 2976 | return NULL; |
| 2977 | cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer)); |
| 2978 | assert(cp != NULL); |
| 2979 | *cp++ = sep; |
| 2980 | isoformat_time(self, cp, sizeof(buffer) - (cp - buffer)); |
| 2981 | return PyString_FromString(buffer); |
| 2982 | } |
| 2983 | |
| 2984 | static PyObject * |
| 2985 | datetime_ctime(PyDateTime_DateTime *self) |
| 2986 | { |
| 2987 | return format_ctime((PyDateTime_Date *)self, |
| 2988 | DATE_GET_HOUR(self), |
| 2989 | DATE_GET_MINUTE(self), |
| 2990 | DATE_GET_SECOND(self)); |
| 2991 | } |
| 2992 | |
| 2993 | /* Miscellaneous methods. */ |
| 2994 | |
| 2995 | /* This is more natural as a tp_compare, but doesn't work then: for whatever |
| 2996 | * reason, Python's try_3way_compare ignores tp_compare unless |
| 2997 | * PyInstance_Check returns true, but these aren't old-style classes. |
| 2998 | * Note that this routine handles all comparisons for datetime and datetimetz. |
| 2999 | */ |
| 3000 | static PyObject * |
| 3001 | datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op) |
| 3002 | { |
| 3003 | int diff; |
| 3004 | naivety n1, n2; |
| 3005 | int offset1, offset2; |
| 3006 | |
| 3007 | if (! PyDateTime_Check(other)) { |
| 3008 | /* Stop this from falling back to address comparison. */ |
| 3009 | PyErr_Format(PyExc_TypeError, |
| 3010 | "can't compare '%s' to '%s'", |
| 3011 | self->ob_type->tp_name, |
| 3012 | other->ob_type->tp_name); |
| 3013 | return NULL; |
| 3014 | } |
| 3015 | n1 = classify_object((PyObject *)self, &offset1); |
| 3016 | assert(n1 != OFFSET_UNKNOWN); |
| 3017 | if (n1 == OFFSET_ERROR) |
| 3018 | return NULL; |
| 3019 | |
| 3020 | n2 = classify_object(other, &offset2); |
| 3021 | assert(n2 != OFFSET_UNKNOWN); |
| 3022 | if (n2 == OFFSET_ERROR) |
| 3023 | return NULL; |
| 3024 | |
| 3025 | /* If they're both naive, or both aware and have the same offsets, |
| 3026 | * we get off cheap. Note that if they're both naive, offset1 == |
| 3027 | * offset2 == 0 at this point. |
| 3028 | */ |
| 3029 | if (n1 == n2 && offset1 == offset2) { |
| 3030 | diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, |
| 3031 | _PyDateTime_DATETIME_DATASIZE); |
| 3032 | return diff_to_bool(diff, op); |
| 3033 | } |
| 3034 | |
| 3035 | if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { |
| 3036 | /* We want the sign of |
| 3037 | * (self - offset1 minutes) - (other - offset2 minutes) = |
| 3038 | * (self - other) + (offset2 - offset1) minutes. |
| 3039 | */ |
| 3040 | PyDateTime_Delta *delta; |
| 3041 | int days, seconds, us; |
| 3042 | |
| 3043 | assert(offset1 != offset2); /* else last "if" handled it */ |
| 3044 | delta = (PyDateTime_Delta *)sub_datetime_datetime(self, |
| 3045 | (PyDateTime_DateTime *)other); |
| 3046 | if (delta == NULL) |
| 3047 | return NULL; |
| 3048 | days = delta->days; |
| 3049 | seconds = delta->seconds + (offset2 - offset1) * 60; |
| 3050 | us = delta->microseconds; |
| 3051 | Py_DECREF(delta); |
| 3052 | normalize_d_s_us(&days, &seconds, &us); |
| 3053 | diff = days; |
| 3054 | if (diff == 0) |
| 3055 | diff = seconds | us; |
| 3056 | return diff_to_bool(diff, op); |
| 3057 | } |
| 3058 | |
| 3059 | assert(n1 != n2); |
| 3060 | PyErr_SetString(PyExc_TypeError, |
| 3061 | "can't compare offset-naive and " |
| 3062 | "offset-aware datetimes"); |
| 3063 | return NULL; |
| 3064 | } |
| 3065 | |
| 3066 | static PyObject *datetime_getstate(PyDateTime_DateTime *self); |
| 3067 | |
| 3068 | static long |
| 3069 | datetime_hash(PyDateTime_DateTime *self) |
| 3070 | { |
| 3071 | if (self->hashcode == -1) { |
| 3072 | naivety n; |
| 3073 | int offset; |
| 3074 | PyObject *temp; |
| 3075 | |
| 3076 | n = classify_object((PyObject *)self, &offset); |
| 3077 | assert(n != OFFSET_UNKNOWN); |
| 3078 | if (n == OFFSET_ERROR) |
| 3079 | return -1; |
| 3080 | |
| 3081 | /* Reduce this to a hash of another object. */ |
| 3082 | if (n == OFFSET_NAIVE) |
| 3083 | temp = datetime_getstate(self); |
| 3084 | else { |
| 3085 | int days; |
| 3086 | int seconds; |
| 3087 | |
| 3088 | assert(n == OFFSET_AWARE); |
| 3089 | assert(PyDateTimeTZ_Check(self)); |
| 3090 | days = ymd_to_ord(GET_YEAR(self), |
| 3091 | GET_MONTH(self), |
| 3092 | GET_DAY(self)); |
| 3093 | seconds = DATE_GET_HOUR(self) * 3600 + |
| 3094 | (DATE_GET_MINUTE(self) - offset) * 60 + |
| 3095 | DATE_GET_SECOND(self); |
| 3096 | temp = new_delta(days, |
| 3097 | seconds, |
| 3098 | DATE_GET_MICROSECOND(self), |
| 3099 | 1); |
| 3100 | } |
| 3101 | if (temp != NULL) { |
| 3102 | self->hashcode = PyObject_Hash(temp); |
| 3103 | Py_DECREF(temp); |
| 3104 | } |
| 3105 | } |
| 3106 | return self->hashcode; |
| 3107 | } |
| 3108 | |
| 3109 | static PyObject * |
| 3110 | datetime_timetuple(PyDateTime_DateTime *self) |
| 3111 | { |
| 3112 | return build_struct_time(GET_YEAR(self), |
| 3113 | GET_MONTH(self), |
| 3114 | GET_DAY(self), |
| 3115 | DATE_GET_HOUR(self), |
| 3116 | DATE_GET_MINUTE(self), |
| 3117 | DATE_GET_SECOND(self), |
| 3118 | -1); |
| 3119 | } |
| 3120 | |
| 3121 | static PyObject * |
| 3122 | datetime_getdate(PyDateTime_DateTime *self) |
| 3123 | { |
| 3124 | return new_date(GET_YEAR(self), |
| 3125 | GET_MONTH(self), |
| 3126 | GET_DAY(self)); |
| 3127 | } |
| 3128 | |
| 3129 | static PyObject * |
| 3130 | datetime_gettime(PyDateTime_DateTime *self) |
| 3131 | { |
| 3132 | return new_time(DATE_GET_HOUR(self), |
| 3133 | DATE_GET_MINUTE(self), |
| 3134 | DATE_GET_SECOND(self), |
| 3135 | DATE_GET_MICROSECOND(self)); |
| 3136 | } |
| 3137 | |
| 3138 | /* Pickle support. Quite a maze! */ |
| 3139 | |
| 3140 | static PyObject * |
| 3141 | datetime_getstate(PyDateTime_DateTime *self) |
| 3142 | { |
| 3143 | return PyString_FromStringAndSize(self->data, |
| 3144 | _PyDateTime_DATETIME_DATASIZE); |
| 3145 | } |
| 3146 | |
| 3147 | static PyObject * |
| 3148 | datetime_setstate(PyDateTime_DateTime *self, PyObject *state) |
| 3149 | { |
| 3150 | const int len = PyString_Size(state); |
| 3151 | unsigned char *pdata = (unsigned char*)PyString_AsString(state); |
| 3152 | |
| 3153 | if (! PyString_Check(state) || |
| 3154 | len != _PyDateTime_DATETIME_DATASIZE) { |
| 3155 | PyErr_SetString(PyExc_TypeError, |
| 3156 | "bad argument to datetime.__setstate__"); |
| 3157 | return NULL; |
| 3158 | } |
| 3159 | memcpy(self->data, pdata, _PyDateTime_DATETIME_DATASIZE); |
| 3160 | self->hashcode = -1; |
| 3161 | |
| 3162 | Py_INCREF(Py_None); |
| 3163 | return Py_None; |
| 3164 | } |
| 3165 | |
| 3166 | /* XXX This seems a ridiculously inefficient way to pickle a short string. */ |
| 3167 | static PyObject * |
| 3168 | datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime) |
| 3169 | { |
| 3170 | PyObject *state; |
| 3171 | PyObject *result = NULL; |
| 3172 | |
| 3173 | if (! PyDateTime_CheckExact(datetime)) { |
| 3174 | PyErr_Format(PyExc_TypeError, |
| 3175 | "bad type passed to datetime pickler: %s", |
| 3176 | datetime->ob_type->tp_name); |
| 3177 | return NULL; |
| 3178 | } |
| 3179 | state = datetime_getstate(datetime); |
| 3180 | if (state) { |
| 3181 | result = Py_BuildValue("O(O)", |
| 3182 | datetime_unpickler_object, |
| 3183 | state); |
| 3184 | Py_DECREF(state); |
| 3185 | } |
| 3186 | return result; |
| 3187 | } |
| 3188 | |
| 3189 | static PyObject * |
| 3190 | datetime_unpickler(PyObject *module, PyObject *arg) |
| 3191 | { |
| 3192 | PyDateTime_DateTime *self; |
| 3193 | |
| 3194 | if (! PyString_CheckExact(arg)) { |
| 3195 | PyErr_Format(PyExc_TypeError, |
| 3196 | "bad type passed to datetime unpickler: %s", |
| 3197 | arg->ob_type->tp_name); |
| 3198 | return NULL; |
| 3199 | } |
| 3200 | self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); |
| 3201 | if (self != NULL) { |
| 3202 | PyObject *res = datetime_setstate(self, arg); |
| 3203 | if (res == NULL) { |
| 3204 | Py_DECREF(self); |
| 3205 | return NULL; |
| 3206 | } |
| 3207 | Py_DECREF(res); |
| 3208 | } |
| 3209 | return (PyObject *)self; |
| 3210 | } |
| 3211 | |
| 3212 | static PyMethodDef datetime_methods[] = { |
| 3213 | /* Class methods: */ |
| 3214 | {"now", (PyCFunction)datetime_now, |
| 3215 | METH_NOARGS | METH_CLASS, |
| 3216 | PyDoc_STR("Return a new datetime representing local day and time.")}, |
| 3217 | |
| 3218 | {"utcnow", (PyCFunction)datetime_utcnow, |
| 3219 | METH_NOARGS | METH_CLASS, |
| 3220 | PyDoc_STR("Return a new datetime representing UTC day and time.")}, |
| 3221 | |
| 3222 | {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, |
| 3223 | METH_VARARGS | METH_CLASS, |
| 3224 | PyDoc_STR("timestamp -> local datetime from a POSIX timestamp " |
| 3225 | "(like time.time()).")}, |
| 3226 | |
| 3227 | {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, |
| 3228 | METH_VARARGS | METH_CLASS, |
| 3229 | PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " |
| 3230 | "(like time.time()).")}, |
| 3231 | |
| 3232 | {"combine", (PyCFunction)datetime_combine, |
| 3233 | METH_VARARGS | METH_KEYWORDS | METH_CLASS, |
| 3234 | PyDoc_STR("date, time -> datetime with same date and time fields")}, |
| 3235 | |
| 3236 | /* Instance methods: */ |
| 3237 | {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, |
| 3238 | PyDoc_STR("Return time tuple, compatible with time.localtime().")}, |
| 3239 | |
| 3240 | {"date", (PyCFunction)datetime_getdate, METH_NOARGS, |
| 3241 | PyDoc_STR("Return date object with same year, month and day.")}, |
| 3242 | |
| 3243 | {"time", (PyCFunction)datetime_gettime, METH_NOARGS, |
| 3244 | PyDoc_STR("Return time object with same hour, minute, second and " |
| 3245 | "microsecond.")}, |
| 3246 | |
| 3247 | {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, |
| 3248 | PyDoc_STR("Return ctime() style string.")}, |
| 3249 | |
| 3250 | {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, |
| 3251 | PyDoc_STR("[sep] -> string in ISO 8601 format, " |
| 3252 | "YYYY-MM-DDTHH:MM:SS[.mmmmmm].\n\n" |
| 3253 | "sep is used to separate the year from the time, and " |
| 3254 | "defaults\n" |
| 3255 | "to 'T'.")}, |
| 3256 | |
| 3257 | {"__setstate__", (PyCFunction)datetime_setstate, METH_O, |
| 3258 | PyDoc_STR("__setstate__(state)")}, |
| 3259 | |
| 3260 | {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, |
| 3261 | PyDoc_STR("__getstate__() -> state")}, |
| 3262 | {NULL, NULL} |
| 3263 | }; |
| 3264 | |
| 3265 | static char datetime_doc[] = |
| 3266 | PyDoc_STR("Basic date/time type."); |
| 3267 | |
| 3268 | static PyNumberMethods datetime_as_number = { |
| 3269 | datetime_add, /* nb_add */ |
| 3270 | datetime_subtract, /* nb_subtract */ |
| 3271 | 0, /* nb_multiply */ |
| 3272 | 0, /* nb_divide */ |
| 3273 | 0, /* nb_remainder */ |
| 3274 | 0, /* nb_divmod */ |
| 3275 | 0, /* nb_power */ |
| 3276 | 0, /* nb_negative */ |
| 3277 | 0, /* nb_positive */ |
| 3278 | 0, /* nb_absolute */ |
| 3279 | 0, /* nb_nonzero */ |
| 3280 | }; |
| 3281 | |
| 3282 | statichere PyTypeObject PyDateTime_DateTimeType = { |
| 3283 | PyObject_HEAD_INIT(NULL) |
| 3284 | 0, /* ob_size */ |
| 3285 | "datetime.datetime", /* tp_name */ |
| 3286 | sizeof(PyDateTime_DateTime), /* tp_basicsize */ |
| 3287 | 0, /* tp_itemsize */ |
| 3288 | (destructor)PyObject_Del, /* tp_dealloc */ |
| 3289 | 0, /* tp_print */ |
| 3290 | 0, /* tp_getattr */ |
| 3291 | 0, /* tp_setattr */ |
| 3292 | 0, /* tp_compare */ |
| 3293 | (reprfunc)datetime_repr, /* tp_repr */ |
| 3294 | &datetime_as_number, /* tp_as_number */ |
| 3295 | 0, /* tp_as_sequence */ |
| 3296 | 0, /* tp_as_mapping */ |
| 3297 | (hashfunc)datetime_hash, /* tp_hash */ |
| 3298 | 0, /* tp_call */ |
| 3299 | (reprfunc)datetime_str, /* tp_str */ |
| 3300 | PyObject_GenericGetAttr, /* tp_getattro */ |
| 3301 | 0, /* tp_setattro */ |
| 3302 | 0, /* tp_as_buffer */ |
| 3303 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | |
| 3304 | Py_TPFLAGS_BASETYPE, /* tp_flags */ |
| 3305 | datetime_doc, /* tp_doc */ |
| 3306 | 0, /* tp_traverse */ |
| 3307 | 0, /* tp_clear */ |
| 3308 | (richcmpfunc)datetime_richcompare, /* tp_richcompare */ |
| 3309 | 0, /* tp_weaklistoffset */ |
| 3310 | 0, /* tp_iter */ |
| 3311 | 0, /* tp_iternext */ |
| 3312 | datetime_methods, /* tp_methods */ |
| 3313 | 0, /* tp_members */ |
| 3314 | datetime_getset, /* tp_getset */ |
| 3315 | &PyDateTime_DateType, /* tp_base */ |
| 3316 | 0, /* tp_dict */ |
| 3317 | 0, /* tp_descr_get */ |
| 3318 | 0, /* tp_descr_set */ |
| 3319 | 0, /* tp_dictoffset */ |
| 3320 | 0, /* tp_init */ |
| 3321 | 0, /* tp_alloc */ |
| 3322 | datetime_new, /* tp_new */ |
| 3323 | _PyObject_Del, /* tp_free */ |
| 3324 | }; |
| 3325 | |
| 3326 | /* |
| 3327 | * PyDateTime_Time implementation. |
| 3328 | */ |
| 3329 | |
| 3330 | /* Accessor properties. */ |
| 3331 | |
| 3332 | static PyObject * |
| 3333 | time_hour(PyDateTime_Time *self, void *unused) |
| 3334 | { |
| 3335 | return PyInt_FromLong(TIME_GET_HOUR(self)); |
| 3336 | } |
| 3337 | |
| 3338 | static PyObject * |
| 3339 | time_minute(PyDateTime_Time *self, void *unused) |
| 3340 | { |
| 3341 | return PyInt_FromLong(TIME_GET_MINUTE(self)); |
| 3342 | } |
| 3343 | |
| 3344 | static PyObject * |
Jack Jansen | 51cd8a2 | 2002-12-17 20:57:24 +0000 | [diff] [blame] | 3345 | py_time_second(PyDateTime_Time *self, void *unused) |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 3346 | { |
| 3347 | return PyInt_FromLong(TIME_GET_SECOND(self)); |
| 3348 | } |
| 3349 | |
| 3350 | static PyObject * |
| 3351 | time_microsecond(PyDateTime_Time *self, void *unused) |
| 3352 | { |
| 3353 | return PyInt_FromLong(TIME_GET_MICROSECOND(self)); |
| 3354 | } |
| 3355 | |
| 3356 | static PyGetSetDef time_getset[] = { |
| 3357 | {"hour", (getter)time_hour}, |
| 3358 | {"minute", (getter)time_minute}, |
Jack Jansen | 51cd8a2 | 2002-12-17 20:57:24 +0000 | [diff] [blame] | 3359 | {"second", (getter)py_time_second}, |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 3360 | {"microsecond", (getter)time_microsecond}, |
| 3361 | {NULL} |
| 3362 | }; |
| 3363 | |
| 3364 | /* Constructors. */ |
| 3365 | |
| 3366 | static PyObject * |
| 3367 | time_new(PyTypeObject *type, PyObject *args, PyObject *kw) |
| 3368 | { |
| 3369 | PyObject *self = NULL; |
| 3370 | int hour = 0; |
| 3371 | int minute = 0; |
| 3372 | int second = 0; |
| 3373 | int usecond = 0; |
| 3374 | |
| 3375 | static char *keywords[] = { |
| 3376 | "hour", "minute", "second", "microsecond", NULL |
| 3377 | }; |
| 3378 | |
| 3379 | if (PyArg_ParseTupleAndKeywords(args, kw, "|iiii", keywords, |
| 3380 | &hour, &minute, &second, &usecond)) { |
| 3381 | if (check_time_args(hour, minute, second, usecond) < 0) |
| 3382 | return NULL; |
| 3383 | self = new_time(hour, minute, second, usecond); |
| 3384 | } |
| 3385 | return self; |
| 3386 | } |
| 3387 | |
| 3388 | /* Various ways to turn a time into a string. */ |
| 3389 | |
| 3390 | static PyObject * |
| 3391 | time_repr(PyDateTime_Time *self) |
| 3392 | { |
| 3393 | char buffer[100]; |
| 3394 | char *typename = self->ob_type->tp_name; |
| 3395 | int h = TIME_GET_HOUR(self); |
| 3396 | int m = TIME_GET_MINUTE(self); |
| 3397 | int s = TIME_GET_SECOND(self); |
| 3398 | int us = TIME_GET_MICROSECOND(self); |
| 3399 | |
| 3400 | if (us) |
| 3401 | PyOS_snprintf(buffer, sizeof(buffer), |
| 3402 | "%s(%d, %d, %d, %d)", typename, h, m, s, us); |
| 3403 | else if (s) |
| 3404 | PyOS_snprintf(buffer, sizeof(buffer), |
| 3405 | "%s(%d, %d, %d)", typename, h, m, s); |
| 3406 | else |
| 3407 | PyOS_snprintf(buffer, sizeof(buffer), |
| 3408 | "%s(%d, %d)", typename, h, m); |
| 3409 | return PyString_FromString(buffer); |
| 3410 | } |
| 3411 | |
| 3412 | static PyObject * |
| 3413 | time_str(PyDateTime_Time *self) |
| 3414 | { |
| 3415 | return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); |
| 3416 | } |
| 3417 | |
| 3418 | static PyObject * |
| 3419 | time_isoformat(PyDateTime_Time *self) |
| 3420 | { |
| 3421 | char buffer[100]; |
| 3422 | /* Reuse the time format code from the datetime type. */ |
| 3423 | PyDateTime_DateTime datetime; |
| 3424 | PyDateTime_DateTime *pdatetime = &datetime; |
| 3425 | |
| 3426 | /* Copy over just the time bytes. */ |
| 3427 | memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE, |
| 3428 | self->data, |
| 3429 | _PyDateTime_TIME_DATASIZE); |
| 3430 | |
| 3431 | isoformat_time(pdatetime, buffer, sizeof(buffer)); |
| 3432 | return PyString_FromString(buffer); |
| 3433 | } |
| 3434 | |
| 3435 | static PyObject * |
| 3436 | time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw) |
| 3437 | { |
| 3438 | PyObject *result; |
| 3439 | PyObject *format; |
| 3440 | PyObject *tuple; |
| 3441 | static char *keywords[] = {"format", NULL}; |
| 3442 | |
| 3443 | if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords, |
| 3444 | &PyString_Type, &format)) |
| 3445 | return NULL; |
| 3446 | |
| 3447 | tuple = Py_BuildValue("iiiiiiiii", |
| 3448 | 0, 0, 0, /* year, month, day */ |
| 3449 | TIME_GET_HOUR(self), |
| 3450 | TIME_GET_MINUTE(self), |
| 3451 | TIME_GET_SECOND(self), |
| 3452 | 0, 0, -1); /* weekday, daynum, dst */ |
| 3453 | if (tuple == NULL) |
| 3454 | return NULL; |
| 3455 | assert(PyTuple_Size(tuple) == 9); |
| 3456 | result = wrap_strftime((PyObject *)self, format, tuple); |
| 3457 | Py_DECREF(tuple); |
| 3458 | return result; |
| 3459 | } |
| 3460 | |
| 3461 | /* Miscellaneous methods. */ |
| 3462 | |
| 3463 | /* This is more natural as a tp_compare, but doesn't work then: for whatever |
| 3464 | * reason, Python's try_3way_compare ignores tp_compare unless |
| 3465 | * PyInstance_Check returns true, but these aren't old-style classes. |
| 3466 | * Note that this routine handles all comparisons for time and timetz. |
| 3467 | */ |
| 3468 | static PyObject * |
| 3469 | time_richcompare(PyDateTime_Time *self, PyObject *other, int op) |
| 3470 | { |
| 3471 | int diff; |
| 3472 | naivety n1, n2; |
| 3473 | int offset1, offset2; |
| 3474 | |
| 3475 | if (! PyTime_Check(other)) { |
| 3476 | /* Stop this from falling back to address comparison. */ |
| 3477 | PyErr_Format(PyExc_TypeError, |
| 3478 | "can't compare '%s' to '%s'", |
| 3479 | self->ob_type->tp_name, |
| 3480 | other->ob_type->tp_name); |
| 3481 | return NULL; |
| 3482 | } |
| 3483 | n1 = classify_object((PyObject *)self, &offset1); |
| 3484 | assert(n1 != OFFSET_UNKNOWN); |
| 3485 | if (n1 == OFFSET_ERROR) |
| 3486 | return NULL; |
| 3487 | |
| 3488 | n2 = classify_object(other, &offset2); |
| 3489 | assert(n2 != OFFSET_UNKNOWN); |
| 3490 | if (n2 == OFFSET_ERROR) |
| 3491 | return NULL; |
| 3492 | |
| 3493 | /* If they're both naive, or both aware and have the same offsets, |
| 3494 | * we get off cheap. Note that if they're both naive, offset1 == |
| 3495 | * offset2 == 0 at this point. |
| 3496 | */ |
| 3497 | if (n1 == n2 && offset1 == offset2) { |
| 3498 | diff = memcmp(self->data, ((PyDateTime_Time *)other)->data, |
| 3499 | _PyDateTime_TIME_DATASIZE); |
| 3500 | return diff_to_bool(diff, op); |
| 3501 | } |
| 3502 | |
| 3503 | if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) { |
| 3504 | assert(offset1 != offset2); /* else last "if" handled it */ |
| 3505 | /* Convert everything except microseconds to seconds. These |
| 3506 | * can't overflow (no more than the # of seconds in 2 days). |
| 3507 | */ |
| 3508 | offset1 = TIME_GET_HOUR(self) * 3600 + |
| 3509 | (TIME_GET_MINUTE(self) - offset1) * 60 + |
| 3510 | TIME_GET_SECOND(self); |
| 3511 | offset2 = TIME_GET_HOUR(other) * 3600 + |
| 3512 | (TIME_GET_MINUTE(other) - offset2) * 60 + |
| 3513 | TIME_GET_SECOND(other); |
| 3514 | diff = offset1 - offset2; |
| 3515 | if (diff == 0) |
| 3516 | diff = TIME_GET_MICROSECOND(self) - |
| 3517 | TIME_GET_MICROSECOND(other); |
| 3518 | return diff_to_bool(diff, op); |
| 3519 | } |
| 3520 | |
| 3521 | assert(n1 != n2); |
| 3522 | PyErr_SetString(PyExc_TypeError, |
| 3523 | "can't compare offset-naive and " |
| 3524 | "offset-aware times"); |
| 3525 | return NULL; |
| 3526 | } |
| 3527 | |
| 3528 | static PyObject *time_getstate(PyDateTime_Time *self); |
| 3529 | |
| 3530 | static long |
| 3531 | time_hash(PyDateTime_Time *self) |
| 3532 | { |
| 3533 | if (self->hashcode == -1) { |
| 3534 | naivety n; |
| 3535 | int offset; |
| 3536 | PyObject *temp; |
| 3537 | |
| 3538 | n = classify_object((PyObject *)self, &offset); |
| 3539 | assert(n != OFFSET_UNKNOWN); |
| 3540 | if (n == OFFSET_ERROR) |
| 3541 | return -1; |
| 3542 | |
| 3543 | /* Reduce this to a hash of another object. */ |
| 3544 | if (offset == 0) |
| 3545 | temp = time_getstate(self); |
| 3546 | else { |
| 3547 | int hour; |
| 3548 | int minute; |
| 3549 | |
| 3550 | assert(n == OFFSET_AWARE); |
| 3551 | assert(PyTimeTZ_Check(self)); |
| 3552 | hour = divmod(TIME_GET_HOUR(self) * 60 + |
| 3553 | TIME_GET_MINUTE(self) - offset, |
| 3554 | 60, |
| 3555 | &minute); |
| 3556 | if (0 <= hour && hour < 24) |
| 3557 | temp = new_time(hour, minute, |
| 3558 | TIME_GET_SECOND(self), |
| 3559 | TIME_GET_MICROSECOND(self)); |
| 3560 | else |
| 3561 | temp = Py_BuildValue("iiii", |
| 3562 | hour, minute, |
| 3563 | TIME_GET_SECOND(self), |
| 3564 | TIME_GET_MICROSECOND(self)); |
| 3565 | } |
| 3566 | if (temp != NULL) { |
| 3567 | self->hashcode = PyObject_Hash(temp); |
| 3568 | Py_DECREF(temp); |
| 3569 | } |
| 3570 | } |
| 3571 | return self->hashcode; |
| 3572 | } |
| 3573 | |
| 3574 | static int |
| 3575 | time_nonzero(PyDateTime_Time *self) |
| 3576 | { |
| 3577 | return TIME_GET_HOUR(self) || |
| 3578 | TIME_GET_MINUTE(self) || |
| 3579 | TIME_GET_SECOND(self) || |
| 3580 | TIME_GET_MICROSECOND(self); |
| 3581 | } |
| 3582 | |
| 3583 | /* Pickle support. Quite a maze! */ |
| 3584 | |
| 3585 | static PyObject * |
| 3586 | time_getstate(PyDateTime_Time *self) |
| 3587 | { |
| 3588 | return PyString_FromStringAndSize(self->data, |
| 3589 | _PyDateTime_TIME_DATASIZE); |
| 3590 | } |
| 3591 | |
| 3592 | static PyObject * |
| 3593 | time_setstate(PyDateTime_Time *self, PyObject *state) |
| 3594 | { |
| 3595 | const int len = PyString_Size(state); |
| 3596 | unsigned char *pdata = (unsigned char*)PyString_AsString(state); |
| 3597 | |
| 3598 | if (! PyString_Check(state) || |
| 3599 | len != _PyDateTime_TIME_DATASIZE) { |
| 3600 | PyErr_SetString(PyExc_TypeError, |
| 3601 | "bad argument to time.__setstate__"); |
| 3602 | return NULL; |
| 3603 | } |
| 3604 | memcpy(self->data, pdata, _PyDateTime_TIME_DATASIZE); |
| 3605 | self->hashcode = -1; |
| 3606 | |
| 3607 | Py_INCREF(Py_None); |
| 3608 | return Py_None; |
| 3609 | } |
| 3610 | |
| 3611 | /* XXX This seems a ridiculously inefficient way to pickle a short string. */ |
| 3612 | static PyObject * |
| 3613 | time_pickler(PyObject *module, PyDateTime_Time *time) |
| 3614 | { |
| 3615 | PyObject *state; |
| 3616 | PyObject *result = NULL; |
| 3617 | |
| 3618 | if (! PyTime_CheckExact(time)) { |
| 3619 | PyErr_Format(PyExc_TypeError, |
| 3620 | "bad type passed to time pickler: %s", |
| 3621 | time->ob_type->tp_name); |
| 3622 | return NULL; |
| 3623 | } |
| 3624 | state = time_getstate(time); |
| 3625 | if (state) { |
| 3626 | result = Py_BuildValue("O(O)", |
| 3627 | time_unpickler_object, |
| 3628 | state); |
| 3629 | Py_DECREF(state); |
| 3630 | } |
| 3631 | return result; |
| 3632 | } |
| 3633 | |
| 3634 | static PyObject * |
| 3635 | time_unpickler(PyObject *module, PyObject *arg) |
| 3636 | { |
| 3637 | PyDateTime_Time *self; |
| 3638 | |
| 3639 | if (! PyString_CheckExact(arg)) { |
| 3640 | PyErr_Format(PyExc_TypeError, |
| 3641 | "bad type passed to time unpickler: %s", |
| 3642 | arg->ob_type->tp_name); |
| 3643 | return NULL; |
| 3644 | } |
| 3645 | self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType); |
| 3646 | if (self != NULL) { |
| 3647 | PyObject *res = time_setstate(self, arg); |
| 3648 | if (res == NULL) { |
| 3649 | Py_DECREF(self); |
| 3650 | return NULL; |
| 3651 | } |
| 3652 | Py_DECREF(res); |
| 3653 | } |
| 3654 | return (PyObject *)self; |
| 3655 | } |
| 3656 | |
| 3657 | static PyMethodDef time_methods[] = { |
| 3658 | {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, |
| 3659 | PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm].")}, |
| 3660 | |
| 3661 | {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS, |
| 3662 | PyDoc_STR("format -> strftime() style string.")}, |
| 3663 | |
| 3664 | {"__setstate__", (PyCFunction)time_setstate, METH_O, |
| 3665 | PyDoc_STR("__setstate__(state)")}, |
| 3666 | |
| 3667 | {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS, |
| 3668 | PyDoc_STR("__getstate__() -> state")}, |
| 3669 | {NULL, NULL} |
| 3670 | }; |
| 3671 | |
| 3672 | static char time_doc[] = |
| 3673 | PyDoc_STR("Basic time type."); |
| 3674 | |
| 3675 | static PyNumberMethods time_as_number = { |
| 3676 | 0, /* nb_add */ |
| 3677 | 0, /* nb_subtract */ |
| 3678 | 0, /* nb_multiply */ |
| 3679 | 0, /* nb_divide */ |
| 3680 | 0, /* nb_remainder */ |
| 3681 | 0, /* nb_divmod */ |
| 3682 | 0, /* nb_power */ |
| 3683 | 0, /* nb_negative */ |
| 3684 | 0, /* nb_positive */ |
| 3685 | 0, /* nb_absolute */ |
| 3686 | (inquiry)time_nonzero, /* nb_nonzero */ |
| 3687 | }; |
| 3688 | |
| 3689 | statichere PyTypeObject PyDateTime_TimeType = { |
| 3690 | PyObject_HEAD_INIT(NULL) |
| 3691 | 0, /* ob_size */ |
| 3692 | "datetime.time", /* tp_name */ |
| 3693 | sizeof(PyDateTime_Time), /* tp_basicsize */ |
| 3694 | 0, /* tp_itemsize */ |
| 3695 | (destructor)PyObject_Del, /* tp_dealloc */ |
| 3696 | 0, /* tp_print */ |
| 3697 | 0, /* tp_getattr */ |
| 3698 | 0, /* tp_setattr */ |
| 3699 | 0, /* tp_compare */ |
| 3700 | (reprfunc)time_repr, /* tp_repr */ |
| 3701 | &time_as_number, /* tp_as_number */ |
| 3702 | 0, /* tp_as_sequence */ |
| 3703 | 0, /* tp_as_mapping */ |
| 3704 | (hashfunc)time_hash, /* tp_hash */ |
| 3705 | 0, /* tp_call */ |
| 3706 | (reprfunc)time_str, /* tp_str */ |
| 3707 | PyObject_GenericGetAttr, /* tp_getattro */ |
| 3708 | 0, /* tp_setattro */ |
| 3709 | 0, /* tp_as_buffer */ |
| 3710 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | |
| 3711 | Py_TPFLAGS_BASETYPE, /* tp_flags */ |
| 3712 | time_doc, /* tp_doc */ |
| 3713 | 0, /* tp_traverse */ |
| 3714 | 0, /* tp_clear */ |
| 3715 | (richcmpfunc)time_richcompare, /* tp_richcompare */ |
| 3716 | 0, /* tp_weaklistoffset */ |
| 3717 | 0, /* tp_iter */ |
| 3718 | 0, /* tp_iternext */ |
| 3719 | time_methods, /* tp_methods */ |
| 3720 | 0, /* tp_members */ |
| 3721 | time_getset, /* tp_getset */ |
| 3722 | 0, /* tp_base */ |
| 3723 | 0, /* tp_dict */ |
| 3724 | 0, /* tp_descr_get */ |
| 3725 | 0, /* tp_descr_set */ |
| 3726 | 0, /* tp_dictoffset */ |
| 3727 | 0, /* tp_init */ |
| 3728 | 0, /* tp_alloc */ |
| 3729 | time_new, /* tp_new */ |
| 3730 | _PyObject_Del, /* tp_free */ |
| 3731 | }; |
| 3732 | |
| 3733 | /* |
| 3734 | * PyDateTime_TZInfo implementation. |
| 3735 | */ |
| 3736 | |
| 3737 | /* This is a pure abstract base class, so doesn't do anything beyond |
| 3738 | * raising NotImplemented exceptions. Real tzinfo classes need |
| 3739 | * to derive from this. This is mostly for clarity, and for efficiency in |
| 3740 | * datetimetz and timetz constructors (their tzinfo arguments need to |
| 3741 | * be subclasses of this tzinfo class, which is easy and quick to check). |
| 3742 | * |
| 3743 | * Note: For reasons having to do with pickling of subclasses, we have |
| 3744 | * to allow tzinfo objects to be instantiated. This wasn't an issue |
| 3745 | * in the Python implementation (__init__() could raise NotImplementedError |
| 3746 | * there without ill effect), but doing so in the C implementation hit a |
| 3747 | * brick wall. |
| 3748 | */ |
| 3749 | |
| 3750 | static PyObject * |
| 3751 | tzinfo_nogo(const char* methodname) |
| 3752 | { |
| 3753 | PyErr_Format(PyExc_NotImplementedError, |
| 3754 | "a tzinfo subclass must implement %s()", |
| 3755 | methodname); |
| 3756 | return NULL; |
| 3757 | } |
| 3758 | |
| 3759 | /* Methods. A subclass must implement these. */ |
| 3760 | |
| 3761 | static PyObject* |
| 3762 | tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt) |
| 3763 | { |
| 3764 | return tzinfo_nogo("tzname"); |
| 3765 | } |
| 3766 | |
| 3767 | static PyObject* |
| 3768 | tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt) |
| 3769 | { |
| 3770 | return tzinfo_nogo("utcoffset"); |
| 3771 | } |
| 3772 | |
| 3773 | static PyObject* |
| 3774 | tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt) |
| 3775 | { |
| 3776 | return tzinfo_nogo("dst"); |
| 3777 | } |
| 3778 | |
| 3779 | /* |
| 3780 | * Pickle support. This is solely so that tzinfo subclasses can use |
| 3781 | * pickling -- tzinfo itself is supposed to be uninstantiable. The |
| 3782 | * pickler and unpickler functions are given module-level private |
| 3783 | * names, and registered with copy_reg, by the module init function. |
| 3784 | */ |
| 3785 | |
| 3786 | static PyObject* |
| 3787 | tzinfo_pickler(PyDateTime_TZInfo *self) { |
| 3788 | return Py_BuildValue("O()", tzinfo_unpickler_object); |
| 3789 | } |
| 3790 | |
| 3791 | static PyObject* |
| 3792 | tzinfo_unpickler(PyObject * unused) { |
| 3793 | return PyType_GenericNew(&PyDateTime_TZInfoType, NULL, NULL); |
| 3794 | } |
| 3795 | |
| 3796 | |
| 3797 | static PyMethodDef tzinfo_methods[] = { |
| 3798 | {"tzname", (PyCFunction)tzinfo_tzname, METH_O, |
| 3799 | PyDoc_STR("datetime -> string name of time zone.")}, |
| 3800 | |
| 3801 | {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O, |
| 3802 | PyDoc_STR("datetime -> minutes east of UTC (negative for " |
| 3803 | "west of UTC).")}, |
| 3804 | |
| 3805 | {"dst", (PyCFunction)tzinfo_dst, METH_O, |
| 3806 | PyDoc_STR("datetime -> DST offset in minutes east of UTC.")}, |
| 3807 | |
| 3808 | {NULL, NULL} |
| 3809 | }; |
| 3810 | |
| 3811 | static char tzinfo_doc[] = |
| 3812 | PyDoc_STR("Abstract base class for time zone info objects."); |
| 3813 | |
| 3814 | statichere PyTypeObject PyDateTime_TZInfoType = { |
| 3815 | PyObject_HEAD_INIT(NULL) |
| 3816 | 0, /* ob_size */ |
| 3817 | "datetime.tzinfo", /* tp_name */ |
| 3818 | sizeof(PyDateTime_TZInfo), /* tp_basicsize */ |
| 3819 | 0, /* tp_itemsize */ |
| 3820 | 0, /* tp_dealloc */ |
| 3821 | 0, /* tp_print */ |
| 3822 | 0, /* tp_getattr */ |
| 3823 | 0, /* tp_setattr */ |
| 3824 | 0, /* tp_compare */ |
| 3825 | 0, /* tp_repr */ |
| 3826 | 0, /* tp_as_number */ |
| 3827 | 0, /* tp_as_sequence */ |
| 3828 | 0, /* tp_as_mapping */ |
| 3829 | 0, /* tp_hash */ |
| 3830 | 0, /* tp_call */ |
| 3831 | 0, /* tp_str */ |
| 3832 | PyObject_GenericGetAttr, /* tp_getattro */ |
| 3833 | 0, /* tp_setattro */ |
| 3834 | 0, /* tp_as_buffer */ |
| 3835 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | |
| 3836 | Py_TPFLAGS_BASETYPE, /* tp_flags */ |
| 3837 | tzinfo_doc, /* tp_doc */ |
| 3838 | 0, /* tp_traverse */ |
| 3839 | 0, /* tp_clear */ |
| 3840 | 0, /* tp_richcompare */ |
| 3841 | 0, /* tp_weaklistoffset */ |
| 3842 | 0, /* tp_iter */ |
| 3843 | 0, /* tp_iternext */ |
| 3844 | tzinfo_methods, /* tp_methods */ |
| 3845 | 0, /* tp_members */ |
| 3846 | 0, /* tp_getset */ |
| 3847 | 0, /* tp_base */ |
| 3848 | 0, /* tp_dict */ |
| 3849 | 0, /* tp_descr_get */ |
| 3850 | 0, /* tp_descr_set */ |
| 3851 | 0, /* tp_dictoffset */ |
| 3852 | 0, /* tp_init */ |
| 3853 | 0, /* tp_alloc */ |
| 3854 | PyType_GenericNew, /* tp_new */ |
| 3855 | 0, /* tp_free */ |
| 3856 | }; |
| 3857 | |
| 3858 | /* |
| 3859 | * PyDateTime_TimeTZ implementation. |
| 3860 | */ |
| 3861 | |
| 3862 | /* Accessor properties. Properties for hour, minute, second and microsecond |
| 3863 | * are inherited from time. |
| 3864 | */ |
| 3865 | |
| 3866 | static PyObject * |
| 3867 | timetz_tzinfo(PyDateTime_TimeTZ *self, void *unused) |
| 3868 | { |
| 3869 | Py_INCREF(self->tzinfo); |
| 3870 | return self->tzinfo; |
| 3871 | } |
| 3872 | |
| 3873 | static PyGetSetDef timetz_getset[] = { |
| 3874 | {"tzinfo", (getter)timetz_tzinfo}, |
| 3875 | {NULL} |
| 3876 | }; |
| 3877 | |
| 3878 | /* |
| 3879 | * Constructors. |
| 3880 | */ |
| 3881 | |
| 3882 | static PyObject * |
| 3883 | timetz_new(PyTypeObject *type, PyObject *args, PyObject *kw) |
| 3884 | { |
| 3885 | PyObject *self = NULL; |
| 3886 | int hour = 0; |
| 3887 | int minute = 0; |
| 3888 | int second = 0; |
| 3889 | int usecond = 0; |
| 3890 | PyObject *tzinfo = Py_None; |
| 3891 | |
| 3892 | static char *keywords[] = { |
| 3893 | "hour", "minute", "second", "microsecond", "tzinfo", NULL |
| 3894 | }; |
| 3895 | |
Neal Norwitz | c296c63 | 2002-12-19 00:42:03 +0000 | [diff] [blame] | 3896 | if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", keywords, |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 3897 | &hour, &minute, &second, &usecond, |
| 3898 | &tzinfo)) { |
| 3899 | if (check_time_args(hour, minute, second, usecond) < 0) |
| 3900 | return NULL; |
| 3901 | if (check_tzinfo_subclass(tzinfo) < 0) |
| 3902 | return NULL; |
| 3903 | self = new_timetz(hour, minute, second, usecond, tzinfo); |
| 3904 | } |
| 3905 | return self; |
| 3906 | } |
| 3907 | |
| 3908 | /* |
| 3909 | * Destructor. |
| 3910 | */ |
| 3911 | |
| 3912 | static void |
| 3913 | timetz_dealloc(PyDateTime_TimeTZ *self) |
| 3914 | { |
| 3915 | Py_XDECREF(self->tzinfo); |
| 3916 | self->ob_type->tp_free((PyObject *)self); |
| 3917 | } |
| 3918 | |
| 3919 | /* |
| 3920 | * Indirect access to tzinfo methods. One more "convenience function" and |
| 3921 | * it won't be possible to find the useful methods anymore <0.5 wink>. |
| 3922 | */ |
| 3923 | |
| 3924 | static PyObject * |
| 3925 | timetz_convienience(PyDateTime_TimeTZ *self, char *name) |
| 3926 | { |
| 3927 | PyObject *result; |
| 3928 | |
| 3929 | if (self->tzinfo == Py_None) { |
| 3930 | result = Py_None; |
| 3931 | Py_INCREF(result); |
| 3932 | } |
| 3933 | else |
| 3934 | result = PyObject_CallMethod(self->tzinfo, name, "O", self); |
| 3935 | return result; |
| 3936 | } |
| 3937 | |
| 3938 | /* These are all METH_NOARGS, so don't need to check the arglist. */ |
| 3939 | static PyObject * |
| 3940 | timetz_utcoffset(PyDateTime_TimeTZ *self, PyObject *unused) { |
| 3941 | return timetz_convienience(self, "utcoffset"); |
| 3942 | } |
| 3943 | |
| 3944 | static PyObject * |
| 3945 | timetz_tzname(PyDateTime_TimeTZ *self, PyObject *unused) { |
| 3946 | return timetz_convienience(self, "tzname"); |
| 3947 | } |
| 3948 | |
| 3949 | static PyObject * |
| 3950 | timetz_dst(PyDateTime_TimeTZ *self, PyObject *unused) { |
| 3951 | return timetz_convienience(self, "dst"); |
| 3952 | } |
| 3953 | |
| 3954 | /* |
| 3955 | * Various ways to turn a timetz into a string. |
| 3956 | */ |
| 3957 | |
| 3958 | static PyObject * |
| 3959 | timetz_repr(PyDateTime_TimeTZ *self) |
| 3960 | { |
| 3961 | PyObject *baserepr = time_repr((PyDateTime_Time *)self); |
| 3962 | |
| 3963 | if (baserepr == NULL) |
| 3964 | return NULL; |
| 3965 | return append_keyword_tzinfo(baserepr, self->tzinfo); |
| 3966 | } |
| 3967 | |
| 3968 | /* Note: tp_str is inherited from time. */ |
| 3969 | |
| 3970 | static PyObject * |
| 3971 | timetz_isoformat(PyDateTime_TimeTZ *self) |
| 3972 | { |
| 3973 | char buf[100]; |
| 3974 | PyObject *result = time_isoformat((PyDateTime_Time *)self); |
| 3975 | |
| 3976 | if (result == NULL || self->tzinfo == Py_None) |
| 3977 | return result; |
| 3978 | |
| 3979 | /* We need to append the UTC offset. */ |
| 3980 | if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, |
| 3981 | (PyObject *)self) < 0) { |
| 3982 | Py_DECREF(result); |
| 3983 | return NULL; |
| 3984 | } |
| 3985 | PyString_ConcatAndDel(&result, PyString_FromString(buf)); |
| 3986 | return result; |
| 3987 | } |
| 3988 | |
| 3989 | /* Note: strftime() is inherited from time. */ |
| 3990 | |
| 3991 | /* |
| 3992 | * Miscellaneous methods. |
| 3993 | */ |
| 3994 | |
| 3995 | /* Note: tp_richcompare and tp_hash are inherited from time. */ |
| 3996 | |
| 3997 | static int |
| 3998 | timetz_nonzero(PyDateTime_TimeTZ *self) |
| 3999 | { |
| 4000 | int offset; |
| 4001 | int none; |
| 4002 | |
| 4003 | if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) { |
| 4004 | /* Since utcoffset is in whole minutes, nothing can |
| 4005 | * alter the conclusion that this is nonzero. |
| 4006 | */ |
| 4007 | return 1; |
| 4008 | } |
| 4009 | offset = 0; |
| 4010 | if (self->tzinfo != Py_None) { |
| 4011 | offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); |
| 4012 | if (offset == -1 && PyErr_Occurred()) |
| 4013 | return -1; |
| 4014 | } |
| 4015 | return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0; |
| 4016 | } |
| 4017 | |
| 4018 | /* |
| 4019 | * Pickle support. Quite a maze! |
| 4020 | */ |
| 4021 | |
| 4022 | /* Let basestate be the state string returned by time_getstate. |
| 4023 | * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo). |
| 4024 | * So it's a tuple in any (non-error) case. |
| 4025 | */ |
| 4026 | static PyObject * |
| 4027 | timetz_getstate(PyDateTime_TimeTZ *self) |
| 4028 | { |
| 4029 | PyObject *basestate; |
| 4030 | PyObject *result = NULL; |
| 4031 | |
| 4032 | basestate = time_getstate((PyDateTime_Time *)self); |
| 4033 | if (basestate != NULL) { |
| 4034 | if (self->tzinfo == Py_None) |
| 4035 | result = Py_BuildValue("(O)", basestate); |
| 4036 | else |
| 4037 | result = Py_BuildValue("OO", basestate, self->tzinfo); |
| 4038 | Py_DECREF(basestate); |
| 4039 | } |
| 4040 | return result; |
| 4041 | } |
| 4042 | |
| 4043 | static PyObject * |
| 4044 | timetz_setstate(PyDateTime_TimeTZ *self, PyObject *state) |
| 4045 | { |
| 4046 | PyObject *temp; |
| 4047 | PyObject *basestate; |
| 4048 | PyObject *tzinfo = Py_None; |
| 4049 | |
| 4050 | if (! PyArg_ParseTuple(state, "O!|O:__setstate__", |
| 4051 | &PyString_Type, &basestate, |
| 4052 | &tzinfo)) |
| 4053 | return NULL; |
| 4054 | temp = time_setstate((PyDateTime_Time *)self, basestate); |
| 4055 | if (temp == NULL) |
| 4056 | return NULL; |
| 4057 | Py_DECREF(temp); |
| 4058 | |
| 4059 | Py_INCREF(tzinfo); |
| 4060 | Py_XDECREF(self->tzinfo); |
| 4061 | self->tzinfo = tzinfo; |
| 4062 | |
| 4063 | Py_INCREF(Py_None); |
| 4064 | return Py_None; |
| 4065 | } |
| 4066 | |
| 4067 | static PyObject * |
| 4068 | timetz_pickler(PyObject *module, PyDateTime_TimeTZ *timetz) |
| 4069 | { |
| 4070 | PyObject *state; |
| 4071 | PyObject *result = NULL; |
| 4072 | |
| 4073 | if (! PyTimeTZ_CheckExact(timetz)) { |
| 4074 | PyErr_Format(PyExc_TypeError, |
| 4075 | "bad type passed to timetz pickler: %s", |
| 4076 | timetz->ob_type->tp_name); |
| 4077 | return NULL; |
| 4078 | } |
| 4079 | state = timetz_getstate(timetz); |
| 4080 | if (state) { |
| 4081 | result = Py_BuildValue("O(O)", |
| 4082 | timetz_unpickler_object, |
| 4083 | state); |
| 4084 | Py_DECREF(state); |
| 4085 | } |
| 4086 | return result; |
| 4087 | } |
| 4088 | |
| 4089 | static PyObject * |
| 4090 | timetz_unpickler(PyObject *module, PyObject *arg) |
| 4091 | { |
| 4092 | PyDateTime_TimeTZ *self; |
| 4093 | |
| 4094 | self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType); |
| 4095 | if (self != NULL) { |
| 4096 | PyObject *res; |
| 4097 | |
| 4098 | self->tzinfo = NULL; |
| 4099 | res = timetz_setstate(self, arg); |
| 4100 | if (res == NULL) { |
| 4101 | Py_DECREF(self); |
| 4102 | return NULL; |
| 4103 | } |
| 4104 | Py_DECREF(res); |
| 4105 | } |
| 4106 | return (PyObject *)self; |
| 4107 | } |
| 4108 | |
| 4109 | static PyMethodDef timetz_methods[] = { |
| 4110 | {"isoformat", (PyCFunction)timetz_isoformat, METH_KEYWORDS, |
| 4111 | PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" |
| 4112 | "[+HH:MM].")}, |
| 4113 | |
| 4114 | {"utcoffset", (PyCFunction)timetz_utcoffset, METH_NOARGS, |
| 4115 | PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, |
| 4116 | |
| 4117 | {"tzname", (PyCFunction)timetz_tzname, METH_NOARGS, |
| 4118 | PyDoc_STR("Return self.tzinfo.tzname(self).")}, |
| 4119 | |
| 4120 | {"dst", (PyCFunction)timetz_dst, METH_NOARGS, |
| 4121 | PyDoc_STR("Return self.tzinfo.dst(self).")}, |
| 4122 | |
| 4123 | {"__setstate__", (PyCFunction)timetz_setstate, METH_O, |
| 4124 | PyDoc_STR("__setstate__(state)")}, |
| 4125 | |
| 4126 | {"__getstate__", (PyCFunction)timetz_getstate, METH_NOARGS, |
| 4127 | PyDoc_STR("__getstate__() -> state")}, |
| 4128 | {NULL, NULL} |
| 4129 | |
| 4130 | }; |
| 4131 | |
| 4132 | static char timetz_doc[] = |
| 4133 | PyDoc_STR("Time type."); |
| 4134 | |
| 4135 | static PyNumberMethods timetz_as_number = { |
| 4136 | 0, /* nb_add */ |
| 4137 | 0, /* nb_subtract */ |
| 4138 | 0, /* nb_multiply */ |
| 4139 | 0, /* nb_divide */ |
| 4140 | 0, /* nb_remainder */ |
| 4141 | 0, /* nb_divmod */ |
| 4142 | 0, /* nb_power */ |
| 4143 | 0, /* nb_negative */ |
| 4144 | 0, /* nb_positive */ |
| 4145 | 0, /* nb_absolute */ |
| 4146 | (inquiry)timetz_nonzero, /* nb_nonzero */ |
| 4147 | }; |
| 4148 | |
| 4149 | statichere PyTypeObject PyDateTime_TimeTZType = { |
| 4150 | PyObject_HEAD_INIT(NULL) |
| 4151 | 0, /* ob_size */ |
| 4152 | "datetime.timetz", /* tp_name */ |
| 4153 | sizeof(PyDateTime_TimeTZ), /* tp_basicsize */ |
| 4154 | 0, /* tp_itemsize */ |
| 4155 | (destructor)timetz_dealloc, /* tp_dealloc */ |
| 4156 | 0, /* tp_print */ |
| 4157 | 0, /* tp_getattr */ |
| 4158 | 0, /* tp_setattr */ |
| 4159 | 0, /* tp_compare */ |
| 4160 | (reprfunc)timetz_repr, /* tp_repr */ |
| 4161 | &timetz_as_number, /* tp_as_number */ |
| 4162 | 0, /* tp_as_sequence */ |
| 4163 | 0, /* tp_as_mapping */ |
| 4164 | 0, /* tp_hash */ |
| 4165 | 0, /* tp_call */ |
| 4166 | 0, /* tp_str */ |
| 4167 | PyObject_GenericGetAttr, /* tp_getattro */ |
| 4168 | 0, /* tp_setattro */ |
| 4169 | 0, /* tp_as_buffer */ |
| 4170 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | |
| 4171 | Py_TPFLAGS_BASETYPE, /* tp_flags */ |
Guido van Rossum | bd43e91 | 2002-12-16 20:34:55 +0000 | [diff] [blame] | 4172 | timetz_doc, /* tp_doc */ |
Tim Peters | 2a799bf | 2002-12-16 20:18:38 +0000 | [diff] [blame] | 4173 | 0, /* tp_traverse */ |
| 4174 | 0, /* tp_clear */ |
| 4175 | 0, /* tp_richcompare */ |
| 4176 | 0, /* tp_weaklistoffset */ |
| 4177 | 0, /* tp_iter */ |
| 4178 | 0, /* tp_iternext */ |
| 4179 | timetz_methods, /* tp_methods */ |
| 4180 | 0, /* tp_members */ |
| 4181 | timetz_getset, /* tp_getset */ |
| 4182 | &PyDateTime_TimeType, /* tp_base */ |
| 4183 | 0, /* tp_dict */ |
| 4184 | 0, /* tp_descr_get */ |
| 4185 | 0, /* tp_descr_set */ |
| 4186 | 0, /* tp_dictoffset */ |
| 4187 | 0, /* tp_init */ |
| 4188 | 0, /* tp_alloc */ |
| 4189 | timetz_new, /* tp_new */ |
| 4190 | _PyObject_Del, /* tp_free */ |
| 4191 | }; |
| 4192 | |
| 4193 | /* |
| 4194 | * PyDateTime_DateTimeTZ implementation. |
| 4195 | */ |
| 4196 | |
| 4197 | /* Accessor properties. Properties for day, month, year, hour, minute, |
| 4198 | * second and microsecond are inherited from datetime. |
| 4199 | */ |
| 4200 | |
| 4201 | static PyObject * |
| 4202 | datetimetz_tzinfo(PyDateTime_DateTimeTZ *self, void *unused) |
| 4203 | { |
| 4204 | Py_INCREF(self->tzinfo); |
| 4205 | return self->tzinfo; |
| 4206 | } |
| 4207 | |
| 4208 | static PyGetSetDef datetimetz_getset[] = { |
| 4209 | {"tzinfo", (getter)datetimetz_tzinfo}, |
| 4210 | {NULL} |
| 4211 | }; |
| 4212 | |
| 4213 | /* |
| 4214 | * Constructors. |
| 4215 | * These are like the datetime methods of the same names, but allow an |
| 4216 | * optional tzinfo argument. |
| 4217 | */ |
| 4218 | |
| 4219 | /* Internal helper. |
| 4220 | * self is a datetimetz. Replace its tzinfo member. |
| 4221 | */ |
| 4222 | void |
| 4223 | replace_tzinfo(PyObject *self, PyObject *newtzinfo) |
| 4224 | { |
| 4225 | assert(self != NULL); |
| 4226 | assert(newtzinfo != NULL); |
| 4227 | assert(PyDateTimeTZ_Check(self)); |
| 4228 | Py_INCREF(newtzinfo); |
| 4229 | Py_DECREF(((PyDateTime_DateTimeTZ *)self)->tzinfo); |
| 4230 | ((PyDateTime_DateTimeTZ *)self)->tzinfo = newtzinfo; |
| 4231 | } |
| 4232 | |
| 4233 | static PyObject * |
| 4234 | datetimetz_new(PyTypeObject *type, PyObject *args, PyObject *kw) |
| 4235 | { |
| 4236 | PyObject *self = NULL; |
| 4237 | int year; |
| 4238 | int month; |
| 4239 | int day; |
| 4240 | int hour = 0; |
| 4241 | int minute = 0; |
| 4242 | int second = 0; |
| 4243 | int usecond = 0; |
| 4244 | PyObject *tzinfo = Py_None; |
| 4245 | |
| 4246 | static char *keywords[] = { |
| 4247 | "year", "month", "day", "hour", "minute", "second", |
| 4248 | "microsecond", "tzinfo", NULL |
| 4249 | }; |
| 4250 | |
| 4251 | if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", keywords, |
| 4252 | &year, &month, &day, &hour, &minute, |
| 4253 | &second, &usecond, &tzinfo)) { |
| 4254 | if (check_date_args(year, month, day) < 0) |
| 4255 | return NULL; |
| 4256 | if (check_time_args(hour, minute, second, usecond) < 0) |
| 4257 | return NULL; |
| 4258 | if (check_tzinfo_subclass(tzinfo) < 0) |
| 4259 | return NULL; |
| 4260 | self = new_datetimetz(year, month, day, |
| 4261 | hour, minute, second, usecond, |
| 4262 | tzinfo); |
| 4263 | } |
| 4264 | return self; |
| 4265 | } |
| 4266 | |
| 4267 | /* Return best possible local time -- this isn't constrained by the |
| 4268 | * precision of a timestamp. |
| 4269 | */ |
| 4270 | static PyObject * |
| 4271 | datetimetz_now(PyObject *cls, PyObject *args, PyObject *kw) |
| 4272 | { |
| 4273 | PyObject *self = NULL; |
| 4274 | PyObject *tzinfo = Py_None; |
| 4275 | static char *keywords[] = {"tzinfo", NULL}; |
| 4276 | |
| 4277 | if (PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords, |
| 4278 | &tzinfo)) { |
| 4279 | if (check_tzinfo_subclass(tzinfo) < 0) |
| 4280 | return NULL; |
| 4281 | self = datetime_best_possible(cls, localtime); |
| 4282 | if (self != NULL) |
| 4283 | replace_tzinfo(self, tzinfo); |
| 4284 | } |
| 4285 | return self; |
| 4286 | } |
| 4287 | |
| 4288 | /* Return new local datetime from timestamp (Python timestamp -- a double). */ |
| 4289 | static PyObject * |
| 4290 | datetimetz_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw) |
| 4291 | { |
| 4292 | PyObject *self = NULL; |
| 4293 | double timestamp; |
| 4294 | PyObject *tzinfo = Py_None; |
| 4295 | static char *keywords[] = {"timestamp", "tzinfo", NULL}; |
| 4296 | |
| 4297 | if (PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp", |
| 4298 | keywords, ×tamp, &tzinfo)) { |
| 4299 | if (check_tzinfo_subclass(tzinfo) < 0) |
| 4300 | return NULL; |
| 4301 | self = datetime_from_timestamp(cls, localtime, timestamp); |
| 4302 | if (self != NULL) |
| 4303 | replace_tzinfo(self, tzinfo); |
| 4304 | } |
| 4305 | return self; |
| 4306 | } |
| 4307 | |
| 4308 | /* Note: utcnow() is inherited, and doesn't accept tzinfo. |
| 4309 | * Ditto utcfromtimestamp(). Ditto combine(). |
| 4310 | */ |
| 4311 | |
| 4312 | |
| 4313 | /* |
| 4314 | * Destructor. |
| 4315 | */ |
| 4316 | |
| 4317 | static void |
| 4318 | datetimetz_dealloc(PyDateTime_DateTimeTZ *self) |
| 4319 | { |
| 4320 | Py_XDECREF(self->tzinfo); |
| 4321 | self->ob_type->tp_free((PyObject *)self); |
| 4322 | } |
| 4323 | |
| 4324 | /* |
| 4325 | * Indirect access to tzinfo methods. |
| 4326 | */ |
| 4327 | |
| 4328 | /* Internal helper. |
| 4329 | * Call a tzinfo object's method, or return None if tzinfo is None. |
| 4330 | */ |
| 4331 | static PyObject * |
| 4332 | datetimetz_convienience(PyDateTime_DateTimeTZ *self, char *name) |
| 4333 | { |
| 4334 | PyObject *result; |
| 4335 | |
| 4336 | if (self->tzinfo == Py_None) { |
| 4337 | result = Py_None; |
| 4338 | Py_INCREF(result); |
| 4339 | } |
| 4340 | else |
| 4341 | result = PyObject_CallMethod(self->tzinfo, name, "O", self); |
| 4342 | return result; |
| 4343 | } |
| 4344 | |
| 4345 | /* These are all METH_NOARGS, so don't need to check the arglist. */ |
| 4346 | static PyObject * |
| 4347 | datetimetz_utcoffset(PyDateTime_DateTimeTZ *self, PyObject *unused) { |
| 4348 | return datetimetz_convienience(self, "utcoffset"); |
| 4349 | } |
| 4350 | |
| 4351 | static PyObject * |
| 4352 | datetimetz_tzname(PyDateTime_DateTimeTZ *self, PyObject *unused) { |
| 4353 | return datetimetz_convienience(self, "tzname"); |
| 4354 | } |
| 4355 | |
| 4356 | static PyObject * |
| 4357 | datetimetz_dst(PyDateTime_DateTimeTZ *self, PyObject *unused) { |
| 4358 | return datetimetz_convienience(self, "dst"); |
| 4359 | } |
| 4360 | |
| 4361 | /* |
| 4362 | * datetimetz arithmetic. |
| 4363 | */ |
| 4364 | |
| 4365 | /* If base is Py_NotImplemented or NULL, just return it. |
| 4366 | * Else base is a datetime, exactly one of {left, right} is a datetimetz, |
| 4367 | * and we want to create a datetimetz with the same date and time fields |
| 4368 | * as base, and with the tzinfo field from left or right. Do that, |
| 4369 | * return it, and decref base. This is used to transform the result of |
| 4370 | * a binary datetime operation (base) into a datetimetz result. |
| 4371 | */ |
| 4372 | static PyObject * |
| 4373 | attach_tzinfo(PyObject *base, PyObject *left, PyObject *right) |
| 4374 | { |
| 4375 | PyDateTime_DateTimeTZ *self; |
| 4376 | PyDateTime_DateTimeTZ *result; |
| 4377 | |
| 4378 | if (base == NULL || base == Py_NotImplemented) |
| 4379 | return base; |
| 4380 | |
| 4381 | assert(PyDateTime_CheckExact(base)); |
| 4382 | |
| 4383 | if (PyDateTimeTZ_Check(left)) { |
| 4384 | assert(! PyDateTimeTZ_Check(right)); |
| 4385 | self = (PyDateTime_DateTimeTZ *)left; |
| 4386 | } |
| 4387 | else { |
| 4388 | assert(PyDateTimeTZ_Check(right)); |
| 4389 | self = (PyDateTime_DateTimeTZ *)right; |
| 4390 | } |
| 4391 | result = PyObject_New(PyDateTime_DateTimeTZ, |
| 4392 | &PyDateTime_DateTimeTZType); |
| 4393 | if (result != NULL) { |
| 4394 | memcpy(result->data, ((PyDateTime_DateTime *)base)->data, |
| 4395 | _PyDateTime_DATETIME_DATASIZE); |
| 4396 | Py_INCREF(self->tzinfo); |
| 4397 | result->tzinfo = self->tzinfo; |
| 4398 | } |
| 4399 | Py_DECREF(base); |
| 4400 | return (PyObject *)result; |
| 4401 | } |
| 4402 | |
| 4403 | static PyObject * |
| 4404 | datetimetz_add(PyObject *left, PyObject *right) |
| 4405 | { |
| 4406 | return attach_tzinfo(datetime_add(left, right), left, right); |
| 4407 | } |
| 4408 | |
| 4409 | static PyObject * |
| 4410 | datetimetz_subtract(PyObject *left, PyObject *right) |
| 4411 | { |
| 4412 | PyObject *result = Py_NotImplemented; |
| 4413 | |
| 4414 | if (PyDateTime_Check(left)) { |
| 4415 | /* datetime - ??? */ |
| 4416 | if (PyDateTime_Check(right)) { |
| 4417 | /* datetime - datetime */ |
| 4418 | naivety n1, n2; |
| 4419 | int offset1, offset2; |
| 4420 | PyDateTime_Delta *delta; |
| 4421 | |
| 4422 | n1 = classify_object(left, &offset1); |
| 4423 | assert(n1 != OFFSET_UNKNOWN); |
| 4424 | if (n1 == OFFSET_ERROR) |
| 4425 | return NULL; |
| 4426 | |
| 4427 | n2 = classify_object(right, &offset2); |
| 4428 | assert(n2 != OFFSET_UNKNOWN); |
| 4429 | if (n2 == OFFSET_ERROR) |
| 4430 | return NULL; |
| 4431 | |
| 4432 | if (n1 != n2) { |
| 4433 | PyErr_SetString(PyExc_TypeError, |
| 4434 | "can't subtract offset-naive and " |
| 4435 | "offset-aware datetimes"); |
| 4436 | return NULL; |
| 4437 | } |
| 4438 | delta = (PyDateTime_Delta *)sub_datetime_datetime( |
| 4439 | (PyDateTime_DateTime *)left, |
| 4440 | (PyDateTime_DateTime *)right); |
| 4441 | if (delta == NULL || offset1 == offset2) |
| 4442 | return (PyObject *)delta; |
| 4443 | /* (left - offset1) - (right - offset2) = |
| 4444 | * (left - right) + (offset2 - offset1) |
| 4445 | */ |
| 4446 | result = new_delta(delta->days, |
| 4447 | delta->seconds + |
| 4448 | (offset2 - offset1) * 60, |
| 4449 | delta->microseconds, |
| 4450 | 1); |
| 4451 | Py_DECREF(delta); |
| 4452 | } |
| 4453 | else if (PyDelta_Check(right)) { |
| 4454 | /* datetimetz - delta */ |
| 4455 | result = sub_datetime_timedelta( |
| 4456 | (PyDateTime_DateTime *)left, |
| 4457 | (PyDateTime_Delta *)right); |
| 4458 | result = attach_tzinfo(result, left, right); |
| 4459 | } |
| 4460 | } |
| 4461 | |
| 4462 | if (result == Py_NotImplemented) |
| 4463 | Py_INCREF(result); |
| 4464 | return result; |
| 4465 | } |
| 4466 | |
| 4467 | /* Various ways to turn a datetime into a string. */ |
| 4468 | |
| 4469 | static PyObject * |
| 4470 | datetimetz_repr(PyDateTime_DateTimeTZ *self) |
| 4471 | { |
| 4472 | PyObject *baserepr = datetime_repr((PyDateTime_DateTime *)self); |
| 4473 | |
| 4474 | if (baserepr == NULL) |
| 4475 | return NULL; |
| 4476 | return append_keyword_tzinfo(baserepr, self->tzinfo); |
| 4477 | } |
| 4478 | |
| 4479 | /* Note: tp_str is inherited from datetime. */ |
| 4480 | |
| 4481 | static PyObject * |
| 4482 | datetimetz_isoformat(PyDateTime_DateTimeTZ *self, |
| 4483 | PyObject *args, PyObject *kw) |
| 4484 | { |
| 4485 | char buf[100]; |
| 4486 | PyObject *result = datetime_isoformat((PyDateTime_DateTime *)self, |
| 4487 | args, kw); |
| 4488 | |
| 4489 | if (result == NULL || self->tzinfo == Py_None) |
| 4490 | return result; |
| 4491 | |
| 4492 | /* We need to append the UTC offset. */ |
| 4493 | if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, |
| 4494 | (PyObject *)self) < 0) { |
| 4495 | Py_DECREF(result); |
| 4496 | return NULL; |
| 4497 | } |
| 4498 | PyString_ConcatAndDel(&result, PyString_FromString(buf)); |
| 4499 | return result; |
| 4500 | } |
| 4501 | |
| 4502 | /* Miscellaneous methods. */ |
| 4503 | |
| 4504 | /* Note: tp_richcompare and tp_hash are inherited from datetime. */ |
| 4505 | |
| 4506 | static PyObject * |
| 4507 | datetimetz_timetuple(PyDateTime_DateTimeTZ *self) |
| 4508 | { |
| 4509 | int dstflag = -1; |
| 4510 | |
| 4511 | if (self->tzinfo != Py_None) { |
| 4512 | int none; |
| 4513 | |
| 4514 | dstflag = call_dst(self->tzinfo, (PyObject *)self, &none); |
| 4515 | if (dstflag == -1 && PyErr_Occurred()) |
| 4516 | return NULL; |
| 4517 | |
| 4518 | if (none) |
| 4519 | dstflag = -1; |
| 4520 | else if (dstflag != 0) |
| 4521 | dstflag = 1; |
| 4522 | |
| 4523 | } |
| 4524 | return build_struct_time(GET_YEAR(self), |
| 4525 | GET_MONTH(self), |
| 4526 | GET_DAY(self), |
| 4527 | DATE_GET_HOUR(self), |
| 4528 | DATE_GET_MINUTE(self), |
| 4529 | DATE_GET_SECOND(self), |
| 4530 | dstflag); |
| 4531 | } |
| 4532 | |
| 4533 | static PyObject * |
| 4534 | datetimetz_utctimetuple(PyDateTime_DateTimeTZ *self) |
| 4535 | { |
| 4536 | int y = GET_YEAR(self); |
| 4537 | int m = GET_MONTH(self); |
| 4538 | int d = GET_DAY(self); |
| 4539 | int hh = DATE_GET_HOUR(self); |
| 4540 | int mm = DATE_GET_MINUTE(self); |
| 4541 | int ss = DATE_GET_SECOND(self); |
| 4542 | int us = 0; /* microseconds are ignored in a timetuple */ |
| 4543 | int offset = 0; |
| 4544 | |
| 4545 | if (self->tzinfo != Py_None) { |
| 4546 | int none; |
| 4547 | |
| 4548 | offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none); |
| 4549 | if (offset == -1 && PyErr_Occurred()) |
| 4550 | return NULL; |
| 4551 | } |
| 4552 | /* Even if offset is 0, don't call timetuple() -- tm_isdst should be |
| 4553 | * 0 in a UTC timetuple regardless of what dst() says. |
| 4554 | */ |
| 4555 | if (offset) { |
| 4556 | /* Subtract offset minutes & normalize. */ |
| 4557 | int stat; |
| 4558 | |
| 4559 | mm -= offset; |
| 4560 | stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us); |
| 4561 | if (stat < 0) { |
| 4562 | /* At the edges, it's possible we overflowed |
| 4563 | * beyond MINYEAR or MAXYEAR. |
| 4564 | */ |
| 4565 | if (PyErr_ExceptionMatches(PyExc_OverflowError)) |
| 4566 | PyErr_Clear(); |
| 4567 | else |
| 4568 | return NULL; |
| 4569 | } |
| 4570 | } |
| 4571 | return build_struct_time(y, m, d, hh, mm, ss, 0); |
| 4572 | } |
| 4573 | |
| 4574 | static PyObject * |
| 4575 | datetimetz_gettimetz(PyDateTime_DateTimeTZ *self) |
| 4576 | { |
| 4577 | return new_timetz(DATE_GET_HOUR(self), |
| 4578 | DATE_GET_MINUTE(self), |
| 4579 | DATE_GET_SECOND(self), |
| 4580 | DATE_GET_MICROSECOND(self), |
| 4581 | self->tzinfo); |
| 4582 | } |
| 4583 | |
| 4584 | /* |
| 4585 | * Pickle support. Quite a maze! |
| 4586 | */ |
| 4587 | |
| 4588 | /* Let basestate be the state string returned by datetime_getstate. |
| 4589 | * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo). |
| 4590 | * So it's a tuple in any (non-error) case. |
| 4591 | */ |
| 4592 | static PyObject * |
| 4593 | datetimetz_getstate(PyDateTime_DateTimeTZ *self) |
| 4594 | { |
| 4595 | PyObject *basestate; |
| 4596 | PyObject *result = NULL; |
| 4597 | |
| 4598 | basestate = datetime_getstate((PyDateTime_DateTime *)self); |
| 4599 | if (basestate != NULL) { |
| 4600 | if (self->tzinfo == Py_None) |
| 4601 | result = Py_BuildValue("(O)", basestate); |
| 4602 | else |
| 4603 | result = Py_BuildValue("OO", basestate, self->tzinfo); |
| 4604 | Py_DECREF(basestate); |
| 4605 | } |
| 4606 | return result; |
| 4607 | } |
| 4608 | |
| 4609 | static PyObject * |
| 4610 | datetimetz_setstate(PyDateTime_DateTimeTZ *self, PyObject *state) |
| 4611 | { |
| 4612 | PyObject *temp; |
| 4613 | PyObject *basestate; |
| 4614 | PyObject *tzinfo = Py_None; |
| 4615 | |
| 4616 | if (! PyArg_ParseTuple(state, "O!|O:__setstate__", |
| 4617 | &PyString_Type, &basestate, |
| 4618 | &tzinfo)) |
| 4619 | return NULL; |
| 4620 | temp = datetime_setstate((PyDateTime_DateTime *)self, basestate); |
| 4621 | if (temp == NULL) |
| 4622 | return NULL; |
| 4623 | Py_DECREF(temp); |
| 4624 | |
| 4625 | Py_INCREF(tzinfo); |
| 4626 | Py_XDECREF(self->tzinfo); |
| 4627 | self->tzinfo = tzinfo; |
| 4628 | |
| 4629 | Py_INCREF(Py_None); |
| 4630 | return Py_None; |
| 4631 | } |
| 4632 | |
| 4633 | static PyObject * |
| 4634 | datetimetz_pickler(PyObject *module, PyDateTime_DateTimeTZ *datetimetz) |
| 4635 | { |
| 4636 | PyObject *state; |
| 4637 | PyObject *result = NULL; |
| 4638 | |
| 4639 | if (! PyDateTimeTZ_CheckExact(datetimetz)) { |
| 4640 | PyErr_Format(PyExc_TypeError, |
| 4641 | "bad type passed to datetimetz pickler: %s", |
| 4642 | datetimetz->ob_type->tp_name); |
| 4643 | return NULL; |
| 4644 | } |
| 4645 | state = datetimetz_getstate(datetimetz); |
| 4646 | if (state) { |
| 4647 | result = Py_BuildValue("O(O)", |
| 4648 | datetimetz_unpickler_object, |
| 4649 | state); |
| 4650 | Py_DECREF(state); |
| 4651 | } |
| 4652 | return result; |
| 4653 | } |
| 4654 | |
| 4655 | static PyObject * |
| 4656 | datetimetz_unpickler(PyObject *module, PyObject *arg) |
| 4657 | { |
| 4658 | PyDateTime_DateTimeTZ *self; |
| 4659 | |
| 4660 | self = PyObject_New(PyDateTime_DateTimeTZ, &PyDateTime_DateTimeTZType); |
| 4661 | if (self != NULL) { |
| 4662 | PyObject *res; |
| 4663 | |
| 4664 | self->tzinfo = NULL; |
| 4665 | res = datetimetz_setstate(self, arg); |
| 4666 | if (res == NULL) { |
| 4667 | Py_DECREF(self); |
| 4668 | return NULL; |
| 4669 | } |
| 4670 | Py_DECREF(res); |
| 4671 | } |
| 4672 | return (PyObject *)self; |
| 4673 | } |
| 4674 | |
| 4675 | |
| 4676 | static PyMethodDef datetimetz_methods[] = { |
| 4677 | /* Class methods: */ |
| 4678 | /* Inherited: combine(), utcnow(), utcfromtimestamp() */ |
| 4679 | |
| 4680 | {"now", (PyCFunction)datetimetz_now, |
| 4681 | METH_KEYWORDS | METH_CLASS, |
| 4682 | PyDoc_STR("[tzinfo] -> new datetimetz with local day and time.")}, |
| 4683 | |
| 4684 | {"fromtimestamp", (PyCFunction)datetimetz_fromtimestamp, |
| 4685 | METH_KEYWORDS | METH_CLASS, |
| 4686 | PyDoc_STR("timestamp[, tzinfo] -> local time from POSIX timestamp.")}, |
| 4687 | |
| 4688 | /* Instance methods: */ |
| 4689 | /* Inherited: date(), time(), ctime(). */ |
| 4690 | {"timetuple", (PyCFunction)datetimetz_timetuple, METH_NOARGS, |
| 4691 | PyDoc_STR("Return time tuple, compatible with time.localtime().")}, |
| 4692 | |
| 4693 | {"utctimetuple", (PyCFunction)datetimetz_utctimetuple, METH_NOARGS, |
| 4694 | PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")}, |
| 4695 | |
| 4696 | {"timetz", (PyCFunction)datetimetz_gettimetz, METH_NOARGS, |
| 4697 | PyDoc_STR("Return timetz object with same hour, minute, second, " |
| 4698 | "microsecond, and tzinfo.")}, |
| 4699 | |
| 4700 | {"isoformat", (PyCFunction)datetimetz_isoformat, METH_KEYWORDS, |
| 4701 | PyDoc_STR("[sep] -> string in ISO 8601 format, " |
| 4702 | "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n" |
| 4703 | "sep is used to separate the year from the time, and " |
| 4704 | "defaults to 'T'.")}, |
| 4705 | |
| 4706 | {"utcoffset", (PyCFunction)datetimetz_utcoffset, METH_NOARGS, |
| 4707 | PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, |
| 4708 | |
| 4709 | {"tzname", (PyCFunction)datetimetz_tzname, METH_NOARGS, |
| 4710 | PyDoc_STR("Return self.tzinfo.tzname(self).")}, |
| 4711 | |
| 4712 | {"dst", (PyCFunction)datetimetz_dst, METH_NOARGS, |
| 4713 | PyDoc_STR("Return self.tzinfo.dst(self).")}, |
| 4714 | |
| 4715 | {"__setstate__", (PyCFunction)datetimetz_setstate, METH_O, |
| 4716 | PyDoc_STR("__setstate__(state)")}, |
| 4717 | |
| 4718 | {"__getstate__", (PyCFunction)datetimetz_getstate, METH_NOARGS, |
| 4719 | PyDoc_STR("__getstate__() -> state")}, |
| 4720 | {NULL, NULL} |
| 4721 | }; |
| 4722 | |
| 4723 | static char datetimetz_doc[] = |
| 4724 | PyDoc_STR("date/time type."); |
| 4725 | |
| 4726 | static PyNumberMethods datetimetz_as_number = { |
| 4727 | datetimetz_add, /* nb_add */ |
| 4728 | datetimetz_subtract, /* nb_subtract */ |
| 4729 | 0, /* nb_multiply */ |
| 4730 | 0, /* nb_divide */ |
| 4731 | 0, /* nb_remainder */ |
| 4732 | 0, /* nb_divmod */ |
| 4733 | 0, /* nb_power */ |
| 4734 | 0, /* nb_negative */ |
| 4735 | 0, /* nb_positive */ |
| 4736 | 0, /* nb_absolute */ |
| 4737 | 0, /* nb_nonzero */ |
| 4738 | }; |
| 4739 | |
| 4740 | statichere PyTypeObject PyDateTime_DateTimeTZType = { |
| 4741 | PyObject_HEAD_INIT(NULL) |
| 4742 | 0, /* ob_size */ |
| 4743 | "datetime.datetimetz", /* tp_name */ |
| 4744 | sizeof(PyDateTime_DateTimeTZ), /* tp_basicsize */ |
| 4745 | 0, /* tp_itemsize */ |
| 4746 | (destructor)datetimetz_dealloc, /* tp_dealloc */ |
| 4747 | 0, /* tp_print */ |
| 4748 | 0, /* tp_getattr */ |
| 4749 | 0, /* tp_setattr */ |
| 4750 | 0, /* tp_compare */ |
| 4751 | (reprfunc)datetimetz_repr, /* tp_repr */ |
| 4752 | &datetimetz_as_number, /* tp_as_number */ |
| 4753 | 0, /* tp_as_sequence */ |
| 4754 | 0, /* tp_as_mapping */ |
| 4755 | 0, /* tp_hash */ |
| 4756 | 0, /* tp_call */ |
| 4757 | 0, /* tp_str */ |
| 4758 | PyObject_GenericGetAttr, /* tp_getattro */ |
| 4759 | 0, /* tp_setattro */ |
| 4760 | 0, /* tp_as_buffer */ |
| 4761 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | |
| 4762 | Py_TPFLAGS_BASETYPE, /* tp_flags */ |
| 4763 | datetimetz_doc, /* tp_doc */ |
| 4764 | 0, /* tp_traverse */ |
| 4765 | 0, /* tp_clear */ |
| 4766 | 0, /* tp_richcompare */ |
| 4767 | 0, /* tp_weaklistoffset */ |
| 4768 | 0, /* tp_iter */ |
| 4769 | 0, /* tp_iternext */ |
| 4770 | datetimetz_methods, /* tp_methods */ |
| 4771 | 0, /* tp_members */ |
| 4772 | datetimetz_getset, /* tp_getset */ |
| 4773 | &PyDateTime_DateTimeType, /* tp_base */ |
| 4774 | 0, /* tp_dict */ |
| 4775 | 0, /* tp_descr_get */ |
| 4776 | 0, /* tp_descr_set */ |
| 4777 | 0, /* tp_dictoffset */ |
| 4778 | 0, /* tp_init */ |
| 4779 | 0, /* tp_alloc */ |
| 4780 | datetimetz_new, /* tp_new */ |
| 4781 | _PyObject_Del, /* tp_free */ |
| 4782 | }; |
| 4783 | |
| 4784 | /* --------------------------------------------------------------------------- |
| 4785 | * Module methods and initialization. |
| 4786 | */ |
| 4787 | |
| 4788 | static PyMethodDef module_methods[] = { |
| 4789 | /* Private functions for pickling support, registered with the |
| 4790 | * copy_reg module by the module init function. |
| 4791 | */ |
| 4792 | {"_date_pickler", (PyCFunction)date_pickler, METH_O, NULL}, |
| 4793 | {"_date_unpickler", (PyCFunction)date_unpickler, METH_O, NULL}, |
| 4794 | {"_datetime_pickler", (PyCFunction)datetime_pickler, METH_O, NULL}, |
| 4795 | {"_datetime_unpickler", (PyCFunction)datetime_unpickler,METH_O, NULL}, |
| 4796 | {"_datetimetz_pickler", (PyCFunction)datetimetz_pickler,METH_O, NULL}, |
| 4797 | {"_datetimetz_unpickler",(PyCFunction)datetimetz_unpickler,METH_O, NULL}, |
| 4798 | {"_time_pickler", (PyCFunction)time_pickler, METH_O, NULL}, |
| 4799 | {"_time_unpickler", (PyCFunction)time_unpickler, METH_O, NULL}, |
| 4800 | {"_timetz_pickler", (PyCFunction)timetz_pickler, METH_O, NULL}, |
| 4801 | {"_timetz_unpickler", (PyCFunction)timetz_unpickler, METH_O, NULL}, |
| 4802 | {"_tzinfo_pickler", (PyCFunction)tzinfo_pickler, METH_O, NULL}, |
| 4803 | {"_tzinfo_unpickler", (PyCFunction)tzinfo_unpickler, METH_NOARGS, |
| 4804 | NULL}, |
| 4805 | {NULL, NULL} |
| 4806 | }; |
| 4807 | |
| 4808 | PyMODINIT_FUNC |
| 4809 | initdatetime(void) |
| 4810 | { |
| 4811 | PyObject *m; /* a module object */ |
| 4812 | PyObject *d; /* its dict */ |
| 4813 | PyObject *x; |
| 4814 | |
| 4815 | /* Types that use __reduce__ for pickling need to set the following |
| 4816 | * magical attr in the type dict, with a true value. |
| 4817 | */ |
| 4818 | PyObject *safepickle = PyString_FromString("__safe_for_unpickling__"); |
| 4819 | if (safepickle == NULL) |
| 4820 | return; |
| 4821 | |
| 4822 | m = Py_InitModule3("datetime", module_methods, |
| 4823 | "Fast implementation of the datetime type."); |
| 4824 | |
| 4825 | if (PyType_Ready(&PyDateTime_DateType) < 0) |
| 4826 | return; |
| 4827 | if (PyType_Ready(&PyDateTime_DateTimeType) < 0) |
| 4828 | return; |
| 4829 | if (PyType_Ready(&PyDateTime_DeltaType) < 0) |
| 4830 | return; |
| 4831 | if (PyType_Ready(&PyDateTime_TimeType) < 0) |
| 4832 | return; |
| 4833 | if (PyType_Ready(&PyDateTime_TZInfoType) < 0) |
| 4834 | return; |
| 4835 | if (PyType_Ready(&PyDateTime_TimeTZType) < 0) |
| 4836 | return; |
| 4837 | if (PyType_Ready(&PyDateTime_DateTimeTZType) < 0) |
| 4838 | return; |
| 4839 | |
| 4840 | /* Pickling support, via registering functions with copy_reg. */ |
| 4841 | { |
| 4842 | PyObject *pickler; |
| 4843 | PyObject *copyreg = PyImport_ImportModule("copy_reg"); |
| 4844 | |
| 4845 | if (copyreg == NULL) return; |
| 4846 | |
| 4847 | pickler = PyObject_GetAttrString(m, "_date_pickler"); |
| 4848 | if (pickler == NULL) return; |
| 4849 | date_unpickler_object = PyObject_GetAttrString(m, |
| 4850 | "_date_unpickler"); |
| 4851 | if (date_unpickler_object == NULL) return; |
| 4852 | x = PyObject_CallMethod(copyreg, "pickle", "OOO", |
| 4853 | &PyDateTime_DateType, |
| 4854 | pickler, |
| 4855 | date_unpickler_object); |
| 4856 | if (x == NULL) return; |
| 4857 | Py_DECREF(x); |
| 4858 | Py_DECREF(pickler); |
| 4859 | |
| 4860 | pickler = PyObject_GetAttrString(m, "_datetime_pickler"); |
| 4861 | if (pickler == NULL) return; |
| 4862 | datetime_unpickler_object = PyObject_GetAttrString(m, |
| 4863 | "_datetime_unpickler"); |
| 4864 | if (datetime_unpickler_object == NULL) return; |
| 4865 | x = PyObject_CallMethod(copyreg, "pickle", "OOO", |
| 4866 | &PyDateTime_DateTimeType, |
| 4867 | pickler, |
| 4868 | datetime_unpickler_object); |
| 4869 | if (x == NULL) return; |
| 4870 | Py_DECREF(x); |
| 4871 | Py_DECREF(pickler); |
| 4872 | |
| 4873 | pickler = PyObject_GetAttrString(m, "_time_pickler"); |
| 4874 | if (pickler == NULL) return; |
| 4875 | time_unpickler_object = PyObject_GetAttrString(m, |
| 4876 | "_time_unpickler"); |
| 4877 | if (time_unpickler_object == NULL) return; |
| 4878 | x = PyObject_CallMethod(copyreg, "pickle", "OOO", |
| 4879 | &PyDateTime_TimeType, |
| 4880 | pickler, |
| 4881 | time_unpickler_object); |
| 4882 | if (x == NULL) return; |
| 4883 | Py_DECREF(x); |
| 4884 | Py_DECREF(pickler); |
| 4885 | |
| 4886 | pickler = PyObject_GetAttrString(m, "_timetz_pickler"); |
| 4887 | if (pickler == NULL) return; |
| 4888 | timetz_unpickler_object = PyObject_GetAttrString(m, |
| 4889 | "_timetz_unpickler"); |
| 4890 | if (timetz_unpickler_object == NULL) return; |
| 4891 | x = PyObject_CallMethod(copyreg, "pickle", "OOO", |
| 4892 | &PyDateTime_TimeTZType, |
| 4893 | pickler, |
| 4894 | timetz_unpickler_object); |
| 4895 | if (x == NULL) return; |
| 4896 | Py_DECREF(x); |
| 4897 | Py_DECREF(pickler); |
| 4898 | |
| 4899 | pickler = PyObject_GetAttrString(m, "_tzinfo_pickler"); |
| 4900 | if (pickler == NULL) return; |
| 4901 | tzinfo_unpickler_object = PyObject_GetAttrString(m, |
| 4902 | "_tzinfo_unpickler"); |
| 4903 | if (tzinfo_unpickler_object == NULL) return; |
| 4904 | x = PyObject_CallMethod(copyreg, "pickle", "OOO", |
| 4905 | &PyDateTime_TZInfoType, |
| 4906 | pickler, |
| 4907 | tzinfo_unpickler_object); |
| 4908 | if (x== NULL) return; |
| 4909 | Py_DECREF(x); |
| 4910 | Py_DECREF(pickler); |
| 4911 | |
| 4912 | pickler = PyObject_GetAttrString(m, "_datetimetz_pickler"); |
| 4913 | if (pickler == NULL) return; |
| 4914 | datetimetz_unpickler_object = PyObject_GetAttrString(m, |
| 4915 | "_datetimetz_unpickler"); |
| 4916 | if (datetimetz_unpickler_object == NULL) return; |
| 4917 | x = PyObject_CallMethod(copyreg, "pickle", "OOO", |
| 4918 | &PyDateTime_DateTimeTZType, |
| 4919 | pickler, |
| 4920 | datetimetz_unpickler_object); |
| 4921 | if (x== NULL) return; |
| 4922 | Py_DECREF(x); |
| 4923 | Py_DECREF(pickler); |
| 4924 | |
| 4925 | Py_DECREF(copyreg); |
| 4926 | } |
| 4927 | |
| 4928 | /* timedelta values */ |
| 4929 | d = PyDateTime_DeltaType.tp_dict; |
| 4930 | |
| 4931 | if (PyDict_SetItem(d, safepickle, Py_True) < 0) |
| 4932 | return; |
| 4933 | |
| 4934 | x = new_delta(0, 0, 1, 0); |
| 4935 | if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) |
| 4936 | return; |
| 4937 | Py_DECREF(x); |
| 4938 | |
| 4939 | x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); |
| 4940 | if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) |
| 4941 | return; |
| 4942 | Py_DECREF(x); |
| 4943 | |
| 4944 | x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); |
| 4945 | if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) |
| 4946 | return; |
| 4947 | Py_DECREF(x); |
| 4948 | |
| 4949 | /* date values */ |
| 4950 | d = PyDateTime_DateType.tp_dict; |
| 4951 | |
| 4952 | x = new_date(1, 1, 1); |
| 4953 | if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) |
| 4954 | return; |
| 4955 | Py_DECREF(x); |
| 4956 | |
| 4957 | x = new_date(MAXYEAR, 12, 31); |
| 4958 | if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) |
| 4959 | return; |
| 4960 | Py_DECREF(x); |
| 4961 | |
| 4962 | x = new_delta(1, 0, 0, 0); |
| 4963 | if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) |
| 4964 | return; |
| 4965 | Py_DECREF(x); |
| 4966 | |
| 4967 | /* datetime values */ |
| 4968 | d = PyDateTime_DateTimeType.tp_dict; |
| 4969 | |
| 4970 | x = new_datetime(1, 1, 1, 0, 0, 0, 0); |
| 4971 | if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) |
| 4972 | return; |
| 4973 | Py_DECREF(x); |
| 4974 | |
| 4975 | x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999); |
| 4976 | if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) |
| 4977 | return; |
| 4978 | Py_DECREF(x); |
| 4979 | |
| 4980 | x = new_delta(0, 0, 1, 0); |
| 4981 | if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) |
| 4982 | return; |
| 4983 | Py_DECREF(x); |
| 4984 | |
| 4985 | /* time values */ |
| 4986 | d = PyDateTime_TimeType.tp_dict; |
| 4987 | |
| 4988 | x = new_time(0, 0, 0, 0); |
| 4989 | if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) |
| 4990 | return; |
| 4991 | Py_DECREF(x); |
| 4992 | |
| 4993 | x = new_time(23, 59, 59, 999999); |
| 4994 | if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) |
| 4995 | return; |
| 4996 | Py_DECREF(x); |
| 4997 | |
| 4998 | x = new_delta(0, 0, 1, 0); |
| 4999 | if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) |
| 5000 | return; |
| 5001 | Py_DECREF(x); |
| 5002 | |
| 5003 | /* timetz values */ |
| 5004 | d = PyDateTime_TimeTZType.tp_dict; |
| 5005 | |
| 5006 | x = new_timetz(0, 0, 0, 0, Py_None); |
| 5007 | if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) |
| 5008 | return; |
| 5009 | Py_DECREF(x); |
| 5010 | |
| 5011 | x = new_timetz(23, 59, 59, 999999, Py_None); |
| 5012 | if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) |
| 5013 | return; |
| 5014 | Py_DECREF(x); |
| 5015 | |
| 5016 | x = new_delta(0, 0, 1, 0); |
| 5017 | if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) |
| 5018 | return; |
| 5019 | Py_DECREF(x); |
| 5020 | |
| 5021 | /* datetimetz values */ |
| 5022 | d = PyDateTime_DateTimeTZType.tp_dict; |
| 5023 | |
| 5024 | x = new_datetimetz(1, 1, 1, 0, 0, 0, 0, Py_None); |
| 5025 | if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) |
| 5026 | return; |
| 5027 | Py_DECREF(x); |
| 5028 | |
| 5029 | x = new_datetimetz(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None); |
| 5030 | if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) |
| 5031 | return; |
| 5032 | Py_DECREF(x); |
| 5033 | |
| 5034 | x = new_delta(0, 0, 1, 0); |
| 5035 | if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) |
| 5036 | return; |
| 5037 | Py_DECREF(x); |
| 5038 | |
| 5039 | Py_DECREF(safepickle); |
| 5040 | |
| 5041 | /* module initialization */ |
| 5042 | PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); |
| 5043 | PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); |
| 5044 | |
| 5045 | Py_INCREF(&PyDateTime_DateType); |
| 5046 | PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType); |
| 5047 | |
| 5048 | Py_INCREF(&PyDateTime_DateTimeType); |
| 5049 | PyModule_AddObject(m, "datetime", |
| 5050 | (PyObject *) &PyDateTime_DateTimeType); |
| 5051 | |
| 5052 | Py_INCREF(&PyDateTime_DeltaType); |
| 5053 | PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType); |
| 5054 | |
| 5055 | Py_INCREF(&PyDateTime_TimeType); |
| 5056 | PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); |
| 5057 | |
| 5058 | Py_INCREF(&PyDateTime_TZInfoType); |
| 5059 | PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType); |
| 5060 | |
| 5061 | Py_INCREF(&PyDateTime_TimeTZType); |
| 5062 | PyModule_AddObject(m, "timetz", (PyObject *) &PyDateTime_TimeTZType); |
| 5063 | |
| 5064 | Py_INCREF(&PyDateTime_DateTimeTZType); |
| 5065 | PyModule_AddObject(m, "datetimetz", |
| 5066 | (PyObject *)&PyDateTime_DateTimeTZType); |
| 5067 | |
| 5068 | /* A 4-year cycle has an extra leap day over what we'd get from |
| 5069 | * pasting together 4 single years. |
| 5070 | */ |
| 5071 | assert(DI4Y == 4 * 365 + 1); |
| 5072 | assert(DI4Y == days_before_year(4+1)); |
| 5073 | |
| 5074 | /* Similarly, a 400-year cycle has an extra leap day over what we'd |
| 5075 | * get from pasting together 4 100-year cycles. |
| 5076 | */ |
| 5077 | assert(DI400Y == 4 * DI100Y + 1); |
| 5078 | assert(DI400Y == days_before_year(400+1)); |
| 5079 | |
| 5080 | /* OTOH, a 100-year cycle has one fewer leap day than we'd get from |
| 5081 | * pasting together 25 4-year cycles. |
| 5082 | */ |
| 5083 | assert(DI100Y == 25 * DI4Y - 1); |
| 5084 | assert(DI100Y == days_before_year(100+1)); |
| 5085 | |
| 5086 | us_per_us = PyInt_FromLong(1); |
| 5087 | us_per_ms = PyInt_FromLong(1000); |
| 5088 | us_per_second = PyInt_FromLong(1000000); |
| 5089 | us_per_minute = PyInt_FromLong(60000000); |
| 5090 | seconds_per_day = PyInt_FromLong(24 * 3600); |
| 5091 | if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL || |
| 5092 | us_per_minute == NULL || seconds_per_day == NULL) |
| 5093 | return; |
| 5094 | |
| 5095 | /* The rest are too big for 32-bit ints, but even |
| 5096 | * us_per_week fits in 40 bits, so doubles should be exact. |
| 5097 | */ |
| 5098 | us_per_hour = PyLong_FromDouble(3600000000.0); |
| 5099 | us_per_day = PyLong_FromDouble(86400000000.0); |
| 5100 | us_per_week = PyLong_FromDouble(604800000000.0); |
| 5101 | if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL) |
| 5102 | return; |
| 5103 | } |