Debian Codegraph @

cpython27/Modules/datetimemodule.c

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