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