Fix off-by-one error that resulted in missed characters
[pytest.git] / Modules / datetimemodule.c
bloba67c35de4e91fd6ce3b81a44c22dadae9f4bf252
1 /* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
5 #include "Python.h"
6 #include "modsupport.h"
7 #include "structmember.h"
9 #include <time.h>
11 #include "timefuncs.h"
13 /* Differentiate between building the core module and building extension
14 * modules.
16 #ifndef Py_BUILD_CORE
17 #define Py_BUILD_CORE
18 #endif
19 #include "datetime.h"
20 #undef Py_BUILD_CORE
22 /* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
27 #if SIZEOF_INT < 4
28 # error "datetime.c requires that C int have at least 32 bits"
29 #endif
31 #define MINYEAR 1
32 #define MAXYEAR 9999
34 /* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
39 #define MAX_DELTA_DAYS 999999999
41 /* Rename the long macros in datetime.h to more reasonable short names. */
42 #define GET_YEAR PyDateTime_GET_YEAR
43 #define GET_MONTH PyDateTime_GET_MONTH
44 #define GET_DAY PyDateTime_GET_DAY
45 #define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46 #define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47 #define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48 #define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
50 /* Date accessors for date and datetime. */
51 #define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53 #define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54 #define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
56 /* Date/Time accessors for datetime. */
57 #define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58 #define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59 #define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60 #define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
65 /* Time accessors for time. */
66 #define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67 #define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68 #define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69 #define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70 #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71 #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72 #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73 #define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
78 /* Delta accessors for timedelta. */
79 #define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80 #define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81 #define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
83 #define SET_TD_DAYS(o, v) ((o)->days = (v))
84 #define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
85 #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
87 /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
90 #define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
92 /* M is a char or int claiming to be a valid month. The macro is equivalent
93 * to the two-sided Python test
94 * 1 <= M <= 12
96 #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
98 /* Forward declarations. */
99 static PyTypeObject PyDateTime_DateType;
100 static PyTypeObject PyDateTime_DateTimeType;
101 static PyTypeObject PyDateTime_DeltaType;
102 static PyTypeObject PyDateTime_TimeType;
103 static PyTypeObject PyDateTime_TZInfoType;
105 /* ---------------------------------------------------------------------------
106 * Math utilities.
109 /* k = i+j overflows iff k differs in sign from both inputs,
110 * iff k^i has sign bit set and k^j has sign bit set,
111 * iff (k^i)&(k^j) has sign bit set.
113 #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
114 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
116 /* Compute Python divmod(x, y), returning the quotient and storing the
117 * remainder into *r. The quotient is the floor of x/y, and that's
118 * the real point of this. C will probably truncate instead (C99
119 * requires truncation; C89 left it implementation-defined).
120 * Simplification: we *require* that y > 0 here. That's appropriate
121 * for all the uses made of it. This simplifies the code and makes
122 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
123 * overflow case).
125 static int
126 divmod(int x, int y, int *r)
128 int quo;
130 assert(y > 0);
131 quo = x / y;
132 *r = x - quo * y;
133 if (*r < 0) {
134 --quo;
135 *r += y;
137 assert(0 <= *r && *r < y);
138 return quo;
141 /* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
144 static long
145 round_to_long(double x)
147 if (x >= 0.0)
148 x = floor(x + 0.5);
149 else
150 x = ceil(x - 0.5);
151 return (long)x;
154 /* ---------------------------------------------------------------------------
155 * General calendrical helper functions
158 /* For each month ordinal in 1..12, the number of days in that month,
159 * and the number of days before that month in the same year. These
160 * are correct for non-leap years only.
162 static int _days_in_month[] = {
163 0, /* unused; this vector uses 1-based indexing */
164 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
167 static int _days_before_month[] = {
168 0, /* unused; this vector uses 1-based indexing */
169 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
172 /* year -> 1 if leap year, else 0. */
173 static int
174 is_leap(int year)
176 /* Cast year to unsigned. The result is the same either way, but
177 * C can generate faster code for unsigned mod than for signed
178 * mod (especially for % 4 -- a good compiler should just grab
179 * the last 2 bits when the LHS is unsigned).
181 const unsigned int ayear = (unsigned int)year;
182 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
185 /* year, month -> number of days in that month in that year */
186 static int
187 days_in_month(int year, int month)
189 assert(month >= 1);
190 assert(month <= 12);
191 if (month == 2 && is_leap(year))
192 return 29;
193 else
194 return _days_in_month[month];
197 /* year, month -> number of days in year preceeding first day of month */
198 static int
199 days_before_month(int year, int month)
201 int days;
203 assert(month >= 1);
204 assert(month <= 12);
205 days = _days_before_month[month];
206 if (month > 2 && is_leap(year))
207 ++days;
208 return days;
211 /* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
214 static int
215 days_before_year(int year)
217 int y = year - 1;
218 /* This is incorrect if year <= 0; we really want the floor
219 * here. But so long as MINYEAR is 1, the smallest year this
220 * can see is 0 (this can happen in some normalization endcases),
221 * so we'll just special-case that.
223 assert (year >= 0);
224 if (y >= 0)
225 return y*365 + y/4 - y/100 + y/400;
226 else {
227 assert(y == -1);
228 return -366;
232 /* Number of days in 4, 100, and 400 year cycles. That these have
233 * the correct values is asserted in the module init function.
235 #define DI4Y 1461 /* days_before_year(5); days in 4 years */
236 #define DI100Y 36524 /* days_before_year(101); days in 100 years */
237 #define DI400Y 146097 /* days_before_year(401); days in 400 years */
239 /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
240 static void
241 ord_to_ymd(int ordinal, int *year, int *month, int *day)
243 int n, n1, n4, n100, n400, leapyear, preceding;
245 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
246 * leap years repeats exactly every 400 years. The basic strategy is
247 * to find the closest 400-year boundary at or before ordinal, then
248 * work with the offset from that boundary to ordinal. Life is much
249 * clearer if we subtract 1 from ordinal first -- then the values
250 * of ordinal at 400-year boundaries are exactly those divisible
251 * by DI400Y:
253 * D M Y n n-1
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
257 * ...
258 * 30 Dec 000 -1 -2
259 * 31 Dec 000 0 -1
260 * 1 Jan 001 1 0 400-year boundary
261 * 2 Jan 001 2 1
262 * 3 Jan 001 3 2
263 * ...
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
267 assert(ordinal >= 1);
268 --ordinal;
269 n400 = ordinal / DI400Y;
270 n = ordinal % DI400Y;
271 *year = n400 * 400 + 1;
273 /* Now n is the (non-negative) offset, in days, from January 1 of
274 * year, to the desired date. Now compute how many 100-year cycles
275 * precede n.
276 * Note that it's possible for n100 to equal 4! In that case 4 full
277 * 100-year cycles precede the desired day, which implies the
278 * desired day is December 31 at the end of a 400-year cycle.
280 n100 = n / DI100Y;
281 n = n % DI100Y;
283 /* Now compute how many 4-year cycles precede it. */
284 n4 = n / DI4Y;
285 n = n % DI4Y;
287 /* And now how many single years. Again n1 can be 4, and again
288 * meaning that the desired day is December 31 at the end of the
289 * 4-year cycle.
291 n1 = n / 365;
292 n = n % 365;
294 *year += n100 * 100 + n4 * 4 + n1;
295 if (n1 == 4 || n100 == 4) {
296 assert(n == 0);
297 *year -= 1;
298 *month = 12;
299 *day = 31;
300 return;
303 /* Now the year is correct, and n is the offset from January 1. We
304 * find the month via an estimate that's either exact or one too
305 * large.
307 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
308 assert(leapyear == is_leap(*year));
309 *month = (n + 50) >> 5;
310 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
311 if (preceding > n) {
312 /* estimate is too large */
313 *month -= 1;
314 preceding -= days_in_month(*year, *month);
316 n -= preceding;
317 assert(0 <= n);
318 assert(n < days_in_month(*year, *month));
320 *day = n + 1;
323 /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
324 static int
325 ymd_to_ord(int year, int month, int day)
327 return days_before_year(year) + days_before_month(year, month) + day;
330 /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
331 static int
332 weekday(int year, int month, int day)
334 return (ymd_to_ord(year, month, day) + 6) % 7;
337 /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
338 * first calendar week containing a Thursday.
340 static int
341 iso_week1_monday(int year)
343 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
344 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
345 int first_weekday = (first_day + 6) % 7;
346 /* ordinal of closest Monday at or before 1/1 */
347 int week1_monday = first_day - first_weekday;
349 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
350 week1_monday += 7;
351 return week1_monday;
354 /* ---------------------------------------------------------------------------
355 * Range checkers.
358 /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
361 static int
362 check_delta_day_range(int days)
364 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
365 return 0;
366 PyErr_Format(PyExc_OverflowError,
367 "days=%d; must have magnitude <= %d",
368 days, MAX_DELTA_DAYS);
369 return -1;
372 /* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
375 static int
376 check_date_args(int year, int month, int day)
379 if (year < MINYEAR || year > MAXYEAR) {
380 PyErr_SetString(PyExc_ValueError,
381 "year is out of range");
382 return -1;
384 if (month < 1 || month > 12) {
385 PyErr_SetString(PyExc_ValueError,
386 "month must be in 1..12");
387 return -1;
389 if (day < 1 || day > days_in_month(year, month)) {
390 PyErr_SetString(PyExc_ValueError,
391 "day is out of range for month");
392 return -1;
394 return 0;
397 /* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
400 static int
401 check_time_args(int h, int m, int s, int us)
403 if (h < 0 || h > 23) {
404 PyErr_SetString(PyExc_ValueError,
405 "hour must be in 0..23");
406 return -1;
408 if (m < 0 || m > 59) {
409 PyErr_SetString(PyExc_ValueError,
410 "minute must be in 0..59");
411 return -1;
413 if (s < 0 || s > 59) {
414 PyErr_SetString(PyExc_ValueError,
415 "second must be in 0..59");
416 return -1;
418 if (us < 0 || us > 999999) {
419 PyErr_SetString(PyExc_ValueError,
420 "microsecond must be in 0..999999");
421 return -1;
423 return 0;
426 /* ---------------------------------------------------------------------------
427 * Normalization utilities.
430 /* One step of a mixed-radix conversion. A "hi" unit is equivalent to
431 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
432 * at least factor, enough of *lo is converted into "hi" units so that
433 * 0 <= *lo < factor. The input values must be such that int overflow
434 * is impossible.
436 static void
437 normalize_pair(int *hi, int *lo, int factor)
439 assert(factor > 0);
440 assert(lo != hi);
441 if (*lo < 0 || *lo >= factor) {
442 const int num_hi = divmod(*lo, factor, lo);
443 const int new_hi = *hi + num_hi;
444 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
445 *hi = new_hi;
447 assert(0 <= *lo && *lo < factor);
450 /* Fiddle days (d), seconds (s), and microseconds (us) so that
451 * 0 <= *s < 24*3600
452 * 0 <= *us < 1000000
453 * The input values must be such that the internals don't overflow.
454 * The way this routine is used, we don't get close.
456 static void
457 normalize_d_s_us(int *d, int *s, int *us)
459 if (*us < 0 || *us >= 1000000) {
460 normalize_pair(s, us, 1000000);
461 /* |s| can't be bigger than about
462 * |original s| + |original us|/1000000 now.
466 if (*s < 0 || *s >= 24*3600) {
467 normalize_pair(d, s, 24*3600);
468 /* |d| can't be bigger than about
469 * |original d| +
470 * (|original s| + |original us|/1000000) / (24*3600) now.
473 assert(0 <= *s && *s < 24*3600);
474 assert(0 <= *us && *us < 1000000);
477 /* Fiddle years (y), months (m), and days (d) so that
478 * 1 <= *m <= 12
479 * 1 <= *d <= days_in_month(*y, *m)
480 * The input values must be such that the internals don't overflow.
481 * The way this routine is used, we don't get close.
483 static void
484 normalize_y_m_d(int *y, int *m, int *d)
486 int dim; /* # of days in month */
488 /* This gets muddy: the proper range for day can't be determined
489 * without knowing the correct month and year, but if day is, e.g.,
490 * plus or minus a million, the current month and year values make
491 * no sense (and may also be out of bounds themselves).
492 * Saying 12 months == 1 year should be non-controversial.
494 if (*m < 1 || *m > 12) {
495 --*m;
496 normalize_pair(y, m, 12);
497 ++*m;
498 /* |y| can't be bigger than about
499 * |original y| + |original m|/12 now.
502 assert(1 <= *m && *m <= 12);
504 /* Now only day can be out of bounds (year may also be out of bounds
505 * for a datetime object, but we don't care about that here).
506 * If day is out of bounds, what to do is arguable, but at least the
507 * method here is principled and explainable.
509 dim = days_in_month(*y, *m);
510 if (*d < 1 || *d > dim) {
511 /* Move day-1 days from the first of the month. First try to
512 * get off cheap if we're only one day out of range
513 * (adjustments for timezone alone can't be worse than that).
515 if (*d == 0) {
516 --*m;
517 if (*m > 0)
518 *d = days_in_month(*y, *m);
519 else {
520 --*y;
521 *m = 12;
522 *d = 31;
525 else if (*d == dim + 1) {
526 /* move forward a day */
527 ++*m;
528 *d = 1;
529 if (*m > 12) {
530 *m = 1;
531 ++*y;
534 else {
535 int ordinal = ymd_to_ord(*y, *m, 1) +
536 *d - 1;
537 ord_to_ymd(ordinal, y, m, d);
540 assert(*m > 0);
541 assert(*d > 0);
544 /* Fiddle out-of-bounds months and days so that the result makes some kind
545 * of sense. The parameters are both inputs and outputs. Returns < 0 on
546 * failure, where failure means the adjusted year is out of bounds.
548 static int
549 normalize_date(int *year, int *month, int *day)
551 int result;
553 normalize_y_m_d(year, month, day);
554 if (MINYEAR <= *year && *year <= MAXYEAR)
555 result = 0;
556 else {
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 result = -1;
561 return result;
564 /* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
567 static int
568 normalize_datetime(int *year, int *month, int *day,
569 int *hour, int *minute, int *second,
570 int *microsecond)
572 normalize_pair(second, microsecond, 1000000);
573 normalize_pair(minute, second, 60);
574 normalize_pair(hour, minute, 60);
575 normalize_pair(day, hour, 24);
576 return normalize_date(year, month, day);
579 /* ---------------------------------------------------------------------------
580 * Basic object allocation: tp_alloc implementations. These allocate
581 * Python objects of the right size and type, and do the Python object-
582 * initialization bit. If there's not enough memory, they return NULL after
583 * setting MemoryError. All data members remain uninitialized trash.
585 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
586 * member is needed. This is ugly, imprecise, and possibly insecure.
587 * tp_basicsize for the time and datetime types is set to the size of the
588 * struct that has room for the tzinfo member, so subclasses in Python will
589 * allocate enough space for a tzinfo member whether or not one is actually
590 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
591 * part is that PyType_GenericAlloc() (which subclasses in Python end up
592 * using) just happens today to effectively ignore the nitems argument
593 * when tp_itemsize is 0, which it is for these type objects. If that
594 * changes, perhaps the callers of tp_alloc slots in this file should
595 * be changed to force a 0 nitems argument unless the type being allocated
596 * is a base type implemented in this file (so that tp_alloc is time_alloc
597 * or datetime_alloc below, which know about the nitems abuse).
600 static PyObject *
601 time_alloc(PyTypeObject *type, Py_ssize_t aware)
603 PyObject *self;
605 self = (PyObject *)
606 PyObject_MALLOC(aware ?
607 sizeof(PyDateTime_Time) :
608 sizeof(_PyDateTime_BaseTime));
609 if (self == NULL)
610 return (PyObject *)PyErr_NoMemory();
611 PyObject_INIT(self, type);
612 return self;
615 static PyObject *
616 datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
618 PyObject *self;
620 self = (PyObject *)
621 PyObject_MALLOC(aware ?
622 sizeof(PyDateTime_DateTime) :
623 sizeof(_PyDateTime_BaseDateTime));
624 if (self == NULL)
625 return (PyObject *)PyErr_NoMemory();
626 PyObject_INIT(self, type);
627 return self;
630 /* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
635 /* For date and datetime. */
636 static void
637 set_date_fields(PyDateTime_Date *self, int y, int m, int d)
639 self->hashcode = -1;
640 SET_YEAR(self, y);
641 SET_MONTH(self, m);
642 SET_DAY(self, d);
645 /* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
649 /* Create a date instance with no range checking. */
650 static PyObject *
651 new_date_ex(int year, int month, int day, PyTypeObject *type)
653 PyDateTime_Date *self;
655 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
656 if (self != NULL)
657 set_date_fields(self, year, month, day);
658 return (PyObject *) self;
661 #define new_date(year, month, day) \
662 new_date_ex(year, month, day, &PyDateTime_DateType)
664 /* Create a datetime instance with no range checking. */
665 static PyObject *
666 new_datetime_ex(int year, int month, int day, int hour, int minute,
667 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
669 PyDateTime_DateTime *self;
670 char aware = tzinfo != Py_None;
672 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
673 if (self != NULL) {
674 self->hastzinfo = aware;
675 set_date_fields((PyDateTime_Date *)self, year, month, day);
676 DATE_SET_HOUR(self, hour);
677 DATE_SET_MINUTE(self, minute);
678 DATE_SET_SECOND(self, second);
679 DATE_SET_MICROSECOND(self, usecond);
680 if (aware) {
681 Py_INCREF(tzinfo);
682 self->tzinfo = tzinfo;
685 return (PyObject *)self;
688 #define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
689 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
690 &PyDateTime_DateTimeType)
692 /* Create a time instance with no range checking. */
693 static PyObject *
694 new_time_ex(int hour, int minute, int second, int usecond,
695 PyObject *tzinfo, PyTypeObject *type)
697 PyDateTime_Time *self;
698 char aware = tzinfo != Py_None;
700 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
701 if (self != NULL) {
702 self->hastzinfo = aware;
703 self->hashcode = -1;
704 TIME_SET_HOUR(self, hour);
705 TIME_SET_MINUTE(self, minute);
706 TIME_SET_SECOND(self, second);
707 TIME_SET_MICROSECOND(self, usecond);
708 if (aware) {
709 Py_INCREF(tzinfo);
710 self->tzinfo = tzinfo;
713 return (PyObject *)self;
716 #define new_time(hh, mm, ss, us, tzinfo) \
717 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
719 /* Create a timedelta instance. Normalize the members iff normalize is
720 * true. Passing false is a speed optimization, if you know for sure
721 * that seconds and microseconds are already in their proper ranges. In any
722 * case, raises OverflowError and returns NULL if the normalized days is out
723 * of range).
725 static PyObject *
726 new_delta_ex(int days, int seconds, int microseconds, int normalize,
727 PyTypeObject *type)
729 PyDateTime_Delta *self;
731 if (normalize)
732 normalize_d_s_us(&days, &seconds, &microseconds);
733 assert(0 <= seconds && seconds < 24*3600);
734 assert(0 <= microseconds && microseconds < 1000000);
736 if (check_delta_day_range(days) < 0)
737 return NULL;
739 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
740 if (self != NULL) {
741 self->hashcode = -1;
742 SET_TD_DAYS(self, days);
743 SET_TD_SECONDS(self, seconds);
744 SET_TD_MICROSECONDS(self, microseconds);
746 return (PyObject *) self;
749 #define new_delta(d, s, us, normalize) \
750 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
752 /* ---------------------------------------------------------------------------
753 * tzinfo helpers.
756 /* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
759 static int
760 check_tzinfo_subclass(PyObject *p)
762 if (p == Py_None || PyTZInfo_Check(p))
763 return 0;
764 PyErr_Format(PyExc_TypeError,
765 "tzinfo argument must be None or of a tzinfo subclass, "
766 "not type '%s'",
767 p->ob_type->tp_name);
768 return -1;
771 /* Return tzinfo.methname(tzinfoarg), without any checking of results.
772 * If tzinfo is None, returns None.
774 static PyObject *
775 call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
777 PyObject *result;
779 assert(tzinfo && methname && tzinfoarg);
780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
785 else
786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
787 return result;
790 /* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
794 static PyObject *
795 get_tzinfo_member(PyObject *self)
797 PyObject *tzinfo = NULL;
799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
801 else if (PyTime_Check(self) && HASTZINFO(self))
802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
804 return tzinfo;
807 /* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
813 * Else *none is set to 0 and the integer method result is returned.
815 static int
816 call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
819 PyObject *u;
820 int result = -1;
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
826 *none = 0;
827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
828 if (u == NULL)
829 return -1;
831 else if (u == Py_None) {
832 result = 0;
833 *none = 1;
835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
854 else {
855 PyErr_Format(PyExc_TypeError,
856 "tzinfo.%s() must return None or "
857 "timedelta, not '%s'",
858 name, u->ob_type->tp_name);
861 Py_DECREF(u);
862 if (result < -1439 || result > 1439) {
863 PyErr_Format(PyExc_ValueError,
864 "tzinfo.%s() returned %d; must be in "
865 "-1439 .. 1439",
866 name, result);
867 result = -1;
869 return result;
872 /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
873 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
874 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
875 * doesn't return None or timedelta, TypeError is raised and this returns -1.
876 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
877 * # of minutes), ValueError is raised and this returns -1. Else *none is
878 * set to 0 and the offset is returned (as int # of minutes east of UTC).
880 static int
881 call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
883 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
886 /* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
888 static PyObject *
889 offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
890 PyObject *result;
892 assert(tzinfo && name && tzinfoarg);
893 if (tzinfo == Py_None) {
894 result = Py_None;
895 Py_INCREF(result);
897 else {
898 int none;
899 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
900 &none);
901 if (offset < 0 && PyErr_Occurred())
902 return NULL;
903 if (none) {
904 result = Py_None;
905 Py_INCREF(result);
907 else
908 result = new_delta(0, offset * 60, 0, 1);
910 return result;
913 /* Call tzinfo.dst(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If dst()
915 * returns None, call_dst returns 0 and sets *none to 1. If dst()
916 & doesn't return None or timedelta, TypeError is raised and this
917 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
918 * ValueError is raised and this returns -1. Else *none is set to 0 and
919 * the offset is returned (as an int # of minutes east of UTC).
921 static int
922 call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
924 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
927 /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
928 * an instance of the tzinfo class or None. If tzinfo isn't None, and
929 * tzname() doesn't return None or a string, TypeError is raised and this
930 * returns NULL.
932 static PyObject *
933 call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
935 PyObject *result;
937 assert(tzinfo != NULL);
938 assert(check_tzinfo_subclass(tzinfo) >= 0);
939 assert(tzinfoarg != NULL);
941 if (tzinfo == Py_None) {
942 result = Py_None;
943 Py_INCREF(result);
945 else
946 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
948 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
949 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
950 "return None or a string, not '%s'",
951 result->ob_type->tp_name);
952 Py_DECREF(result);
953 result = NULL;
955 return result;
958 typedef enum {
959 /* an exception has been set; the caller should pass it on */
960 OFFSET_ERROR,
962 /* type isn't date, datetime, or time subclass */
963 OFFSET_UNKNOWN,
965 /* date,
966 * datetime with !hastzinfo
967 * datetime with None tzinfo,
968 * datetime where utcoffset() returns None
969 * time with !hastzinfo
970 * time with None tzinfo,
971 * time where utcoffset() returns None
973 OFFSET_NAIVE,
975 /* time or datetime where utcoffset() doesn't return None */
976 OFFSET_AWARE
977 } naivety;
979 /* Classify an object as to whether it's naive or offset-aware. See
980 * the "naivety" typedef for details. If the type is aware, *offset is set
981 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
982 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
983 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
985 static naivety
986 classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
988 int none;
989 PyObject *tzinfo;
991 assert(tzinfoarg != NULL);
992 *offset = 0;
993 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
994 if (tzinfo == Py_None)
995 return OFFSET_NAIVE;
996 if (tzinfo == NULL) {
997 /* note that a datetime passes the PyDate_Check test */
998 return (PyTime_Check(op) || PyDate_Check(op)) ?
999 OFFSET_NAIVE : OFFSET_UNKNOWN;
1001 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1002 if (*offset == -1 && PyErr_Occurred())
1003 return OFFSET_ERROR;
1004 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1007 /* Classify two objects as to whether they're naive or offset-aware.
1008 * This isn't quite the same as calling classify_utcoffset() twice: for
1009 * binary operations (comparison and subtraction), we generally want to
1010 * ignore the tzinfo members if they're identical. This is by design,
1011 * so that results match "naive" expectations when mixing objects from a
1012 * single timezone. So in that case, this sets both offsets to 0 and
1013 * both naiveties to OFFSET_NAIVE.
1014 * The function returns 0 if everything's OK, and -1 on error.
1016 static int
1017 classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
1018 PyObject *tzinfoarg1,
1019 PyObject *o2, int *offset2, naivety *n2,
1020 PyObject *tzinfoarg2)
1022 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1023 *offset1 = *offset2 = 0;
1024 *n1 = *n2 = OFFSET_NAIVE;
1026 else {
1027 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
1028 if (*n1 == OFFSET_ERROR)
1029 return -1;
1030 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
1031 if (*n2 == OFFSET_ERROR)
1032 return -1;
1034 return 0;
1037 /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1038 * stuff
1039 * ", tzinfo=" + repr(tzinfo)
1040 * before the closing ")".
1042 static PyObject *
1043 append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1045 PyObject *temp;
1047 assert(PyString_Check(repr));
1048 assert(tzinfo);
1049 if (tzinfo == Py_None)
1050 return repr;
1051 /* Get rid of the trailing ')'. */
1052 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1053 temp = PyString_FromStringAndSize(PyString_AsString(repr),
1054 PyString_Size(repr) - 1);
1055 Py_DECREF(repr);
1056 if (temp == NULL)
1057 return NULL;
1058 repr = temp;
1060 /* Append ", tzinfo=". */
1061 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
1063 /* Append repr(tzinfo). */
1064 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
1066 /* Add a closing paren. */
1067 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1068 return repr;
1071 /* ---------------------------------------------------------------------------
1072 * String format helpers.
1075 static PyObject *
1076 format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
1078 static const char *DayNames[] = {
1079 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1081 static const char *MonthNames[] = {
1082 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1083 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1086 char buffer[128];
1087 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1089 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1090 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1091 GET_DAY(date), hours, minutes, seconds,
1092 GET_YEAR(date));
1093 return PyString_FromString(buffer);
1096 /* Add an hours & minutes UTC offset string to buf. buf has no more than
1097 * buflen bytes remaining. The UTC offset is gotten by calling
1098 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1099 * *buf, and that's all. Else the returned value is checked for sanity (an
1100 * integer in range), and if that's OK it's converted to an hours & minutes
1101 * string of the form
1102 * sign HH sep MM
1103 * Returns 0 if everything is OK. If the return value from utcoffset() is
1104 * bogus, an appropriate exception is set and -1 is returned.
1106 static int
1107 format_utcoffset(char *buf, size_t buflen, const char *sep,
1108 PyObject *tzinfo, PyObject *tzinfoarg)
1110 int offset;
1111 int hours;
1112 int minutes;
1113 char sign;
1114 int none;
1116 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1117 if (offset == -1 && PyErr_Occurred())
1118 return -1;
1119 if (none) {
1120 *buf = '\0';
1121 return 0;
1123 sign = '+';
1124 if (offset < 0) {
1125 sign = '-';
1126 offset = - offset;
1128 hours = divmod(offset, 60, &minutes);
1129 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1130 return 0;
1133 /* I sure don't want to reproduce the strftime code from the time module,
1134 * so this imports the module and calls it. All the hair is due to
1135 * giving special meanings to the %z and %Z format codes via a preprocessing
1136 * step on the format string.
1137 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1138 * needed.
1140 static PyObject *
1141 wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1142 PyObject *tzinfoarg)
1144 PyObject *result = NULL; /* guilty until proved innocent */
1146 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1147 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1149 char *pin; /* pointer to next char in input format */
1150 char ch; /* next char in input format */
1152 PyObject *newfmt = NULL; /* py string, the output format */
1153 char *pnew; /* pointer to available byte in output format */
1154 int totalnew; /* number bytes total in output format buffer,
1155 exclusive of trailing \0 */
1156 int usednew; /* number bytes used so far in output format buffer */
1158 char *ptoappend; /* pointer to string to append to output buffer */
1159 int ntoappend; /* # of bytes to append to output buffer */
1161 assert(object && format && timetuple);
1162 assert(PyString_Check(format));
1164 /* Give up if the year is before 1900.
1165 * Python strftime() plays games with the year, and different
1166 * games depending on whether envar PYTHON2K is set. This makes
1167 * years before 1900 a nightmare, even if the platform strftime
1168 * supports them (and not all do).
1169 * We could get a lot farther here by avoiding Python's strftime
1170 * wrapper and calling the C strftime() directly, but that isn't
1171 * an option in the Python implementation of this module.
1174 long year;
1175 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1176 if (pyyear == NULL) return NULL;
1177 assert(PyInt_Check(pyyear));
1178 year = PyInt_AsLong(pyyear);
1179 Py_DECREF(pyyear);
1180 if (year < 1900) {
1181 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1182 "1900; the datetime strftime() "
1183 "methods require year >= 1900",
1184 year);
1185 return NULL;
1189 /* Scan the input format, looking for %z and %Z escapes, building
1190 * a new format. Since computing the replacements for those codes
1191 * is expensive, don't unless they're actually used.
1193 totalnew = PyString_Size(format) + 1; /* realistic if no %z/%Z */
1194 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1195 if (newfmt == NULL) goto Done;
1196 pnew = PyString_AsString(newfmt);
1197 usednew = 0;
1199 pin = PyString_AsString(format);
1200 while ((ch = *pin++) != '\0') {
1201 if (ch != '%') {
1202 ptoappend = pin - 1;
1203 ntoappend = 1;
1205 else if ((ch = *pin++) == '\0') {
1206 /* There's a lone trailing %; doesn't make sense. */
1207 PyErr_SetString(PyExc_ValueError, "strftime format "
1208 "ends with raw %");
1209 goto Done;
1211 /* A % has been seen and ch is the character after it. */
1212 else if (ch == 'z') {
1213 if (zreplacement == NULL) {
1214 /* format utcoffset */
1215 char buf[100];
1216 PyObject *tzinfo = get_tzinfo_member(object);
1217 zreplacement = PyString_FromString("");
1218 if (zreplacement == NULL) goto Done;
1219 if (tzinfo != Py_None && tzinfo != NULL) {
1220 assert(tzinfoarg != NULL);
1221 if (format_utcoffset(buf,
1222 sizeof(buf),
1224 tzinfo,
1225 tzinfoarg) < 0)
1226 goto Done;
1227 Py_DECREF(zreplacement);
1228 zreplacement = PyString_FromString(buf);
1229 if (zreplacement == NULL) goto Done;
1232 assert(zreplacement != NULL);
1233 ptoappend = PyString_AS_STRING(zreplacement);
1234 ntoappend = PyString_GET_SIZE(zreplacement);
1236 else if (ch == 'Z') {
1237 /* format tzname */
1238 if (Zreplacement == NULL) {
1239 PyObject *tzinfo = get_tzinfo_member(object);
1240 Zreplacement = PyString_FromString("");
1241 if (Zreplacement == NULL) goto Done;
1242 if (tzinfo != Py_None && tzinfo != NULL) {
1243 PyObject *temp;
1244 assert(tzinfoarg != NULL);
1245 temp = call_tzname(tzinfo, tzinfoarg);
1246 if (temp == NULL) goto Done;
1247 if (temp != Py_None) {
1248 assert(PyString_Check(temp));
1249 /* Since the tzname is getting
1250 * stuffed into the format, we
1251 * have to double any % signs
1252 * so that strftime doesn't
1253 * treat them as format codes.
1255 Py_DECREF(Zreplacement);
1256 Zreplacement = PyObject_CallMethod(
1257 temp, "replace",
1258 "ss", "%", "%%");
1259 Py_DECREF(temp);
1260 if (Zreplacement == NULL)
1261 goto Done;
1262 if (!PyString_Check(Zreplacement)) {
1263 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1264 goto Done;
1267 else
1268 Py_DECREF(temp);
1271 assert(Zreplacement != NULL);
1272 ptoappend = PyString_AS_STRING(Zreplacement);
1273 ntoappend = PyString_GET_SIZE(Zreplacement);
1275 else {
1276 /* percent followed by neither z nor Z */
1277 ptoappend = pin - 2;
1278 ntoappend = 2;
1281 /* Append the ntoappend chars starting at ptoappend to
1282 * the new format.
1284 assert(ptoappend != NULL);
1285 assert(ntoappend >= 0);
1286 if (ntoappend == 0)
1287 continue;
1288 while (usednew + ntoappend > totalnew) {
1289 int bigger = totalnew << 1;
1290 if ((bigger >> 1) != totalnew) { /* overflow */
1291 PyErr_NoMemory();
1292 goto Done;
1294 if (_PyString_Resize(&newfmt, bigger) < 0)
1295 goto Done;
1296 totalnew = bigger;
1297 pnew = PyString_AsString(newfmt) + usednew;
1299 memcpy(pnew, ptoappend, ntoappend);
1300 pnew += ntoappend;
1301 usednew += ntoappend;
1302 assert(usednew <= totalnew);
1303 } /* end while() */
1305 if (_PyString_Resize(&newfmt, usednew) < 0)
1306 goto Done;
1308 PyObject *time = PyImport_ImportModule("time");
1309 if (time == NULL)
1310 goto Done;
1311 result = PyObject_CallMethod(time, "strftime", "OO",
1312 newfmt, timetuple);
1313 Py_DECREF(time);
1315 Done:
1316 Py_XDECREF(zreplacement);
1317 Py_XDECREF(Zreplacement);
1318 Py_XDECREF(newfmt);
1319 return result;
1322 static char *
1323 isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1325 int x;
1326 x = PyOS_snprintf(buffer, bufflen,
1327 "%04d-%02d-%02d",
1328 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1329 return buffer + x;
1332 static void
1333 isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1335 int us = DATE_GET_MICROSECOND(dt);
1337 PyOS_snprintf(buffer, bufflen,
1338 "%02d:%02d:%02d", /* 8 characters */
1339 DATE_GET_HOUR(dt),
1340 DATE_GET_MINUTE(dt),
1341 DATE_GET_SECOND(dt));
1342 if (us)
1343 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1346 /* ---------------------------------------------------------------------------
1347 * Wrap functions from the time module. These aren't directly available
1348 * from C. Perhaps they should be.
1351 /* Call time.time() and return its result (a Python float). */
1352 static PyObject *
1353 time_time(void)
1355 PyObject *result = NULL;
1356 PyObject *time = PyImport_ImportModule("time");
1358 if (time != NULL) {
1359 result = PyObject_CallMethod(time, "time", "()");
1360 Py_DECREF(time);
1362 return result;
1365 /* Build a time.struct_time. The weekday and day number are automatically
1366 * computed from the y,m,d args.
1368 static PyObject *
1369 build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1371 PyObject *time;
1372 PyObject *result = NULL;
1374 time = PyImport_ImportModule("time");
1375 if (time != NULL) {
1376 result = PyObject_CallMethod(time, "struct_time",
1377 "((iiiiiiiii))",
1378 y, m, d,
1379 hh, mm, ss,
1380 weekday(y, m, d),
1381 days_before_month(y, m) + d,
1382 dstflag);
1383 Py_DECREF(time);
1385 return result;
1388 /* ---------------------------------------------------------------------------
1389 * Miscellaneous helpers.
1392 /* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1393 * The comparisons here all most naturally compute a cmp()-like result.
1394 * This little helper turns that into a bool result for rich comparisons.
1396 static PyObject *
1397 diff_to_bool(int diff, int op)
1399 PyObject *result;
1400 int istrue;
1402 switch (op) {
1403 case Py_EQ: istrue = diff == 0; break;
1404 case Py_NE: istrue = diff != 0; break;
1405 case Py_LE: istrue = diff <= 0; break;
1406 case Py_GE: istrue = diff >= 0; break;
1407 case Py_LT: istrue = diff < 0; break;
1408 case Py_GT: istrue = diff > 0; break;
1409 default:
1410 assert(! "op unknown");
1411 istrue = 0; /* To shut up compiler */
1413 result = istrue ? Py_True : Py_False;
1414 Py_INCREF(result);
1415 return result;
1418 /* Raises a "can't compare" TypeError and returns NULL. */
1419 static PyObject *
1420 cmperror(PyObject *a, PyObject *b)
1422 PyErr_Format(PyExc_TypeError,
1423 "can't compare %s to %s",
1424 a->ob_type->tp_name, b->ob_type->tp_name);
1425 return NULL;
1428 /* ---------------------------------------------------------------------------
1429 * Cached Python objects; these are set by the module init function.
1432 /* Conversion factors. */
1433 static PyObject *us_per_us = NULL; /* 1 */
1434 static PyObject *us_per_ms = NULL; /* 1000 */
1435 static PyObject *us_per_second = NULL; /* 1000000 */
1436 static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1437 static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1438 static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1439 static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1440 static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1442 /* ---------------------------------------------------------------------------
1443 * Class implementations.
1447 * PyDateTime_Delta implementation.
1450 /* Convert a timedelta to a number of us,
1451 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1452 * as a Python int or long.
1453 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1454 * due to ubiquitous overflow possibilities.
1456 static PyObject *
1457 delta_to_microseconds(PyDateTime_Delta *self)
1459 PyObject *x1 = NULL;
1460 PyObject *x2 = NULL;
1461 PyObject *x3 = NULL;
1462 PyObject *result = NULL;
1464 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1465 if (x1 == NULL)
1466 goto Done;
1467 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1468 if (x2 == NULL)
1469 goto Done;
1470 Py_DECREF(x1);
1471 x1 = NULL;
1473 /* x2 has days in seconds */
1474 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1475 if (x1 == NULL)
1476 goto Done;
1477 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1478 if (x3 == NULL)
1479 goto Done;
1480 Py_DECREF(x1);
1481 Py_DECREF(x2);
1482 x1 = x2 = NULL;
1484 /* x3 has days+seconds in seconds */
1485 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1486 if (x1 == NULL)
1487 goto Done;
1488 Py_DECREF(x3);
1489 x3 = NULL;
1491 /* x1 has days+seconds in us */
1492 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1493 if (x2 == NULL)
1494 goto Done;
1495 result = PyNumber_Add(x1, x2);
1497 Done:
1498 Py_XDECREF(x1);
1499 Py_XDECREF(x2);
1500 Py_XDECREF(x3);
1501 return result;
1504 /* Convert a number of us (as a Python int or long) to a timedelta.
1506 static PyObject *
1507 microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
1509 int us;
1510 int s;
1511 int d;
1512 long temp;
1514 PyObject *tuple = NULL;
1515 PyObject *num = NULL;
1516 PyObject *result = NULL;
1518 tuple = PyNumber_Divmod(pyus, us_per_second);
1519 if (tuple == NULL)
1520 goto Done;
1522 num = PyTuple_GetItem(tuple, 1); /* us */
1523 if (num == NULL)
1524 goto Done;
1525 temp = PyLong_AsLong(num);
1526 num = NULL;
1527 if (temp == -1 && PyErr_Occurred())
1528 goto Done;
1529 assert(0 <= temp && temp < 1000000);
1530 us = (int)temp;
1531 if (us < 0) {
1532 /* The divisor was positive, so this must be an error. */
1533 assert(PyErr_Occurred());
1534 goto Done;
1537 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1538 if (num == NULL)
1539 goto Done;
1540 Py_INCREF(num);
1541 Py_DECREF(tuple);
1543 tuple = PyNumber_Divmod(num, seconds_per_day);
1544 if (tuple == NULL)
1545 goto Done;
1546 Py_DECREF(num);
1548 num = PyTuple_GetItem(tuple, 1); /* seconds */
1549 if (num == NULL)
1550 goto Done;
1551 temp = PyLong_AsLong(num);
1552 num = NULL;
1553 if (temp == -1 && PyErr_Occurred())
1554 goto Done;
1555 assert(0 <= temp && temp < 24*3600);
1556 s = (int)temp;
1558 if (s < 0) {
1559 /* The divisor was positive, so this must be an error. */
1560 assert(PyErr_Occurred());
1561 goto Done;
1564 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1565 if (num == NULL)
1566 goto Done;
1567 Py_INCREF(num);
1568 temp = PyLong_AsLong(num);
1569 if (temp == -1 && PyErr_Occurred())
1570 goto Done;
1571 d = (int)temp;
1572 if ((long)d != temp) {
1573 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1574 "large to fit in a C int");
1575 goto Done;
1577 result = new_delta_ex(d, s, us, 0, type);
1579 Done:
1580 Py_XDECREF(tuple);
1581 Py_XDECREF(num);
1582 return result;
1585 #define microseconds_to_delta(pymicros) \
1586 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1588 static PyObject *
1589 multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1591 PyObject *pyus_in;
1592 PyObject *pyus_out;
1593 PyObject *result;
1595 pyus_in = delta_to_microseconds(delta);
1596 if (pyus_in == NULL)
1597 return NULL;
1599 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1600 Py_DECREF(pyus_in);
1601 if (pyus_out == NULL)
1602 return NULL;
1604 result = microseconds_to_delta(pyus_out);
1605 Py_DECREF(pyus_out);
1606 return result;
1609 static PyObject *
1610 divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1612 PyObject *pyus_in;
1613 PyObject *pyus_out;
1614 PyObject *result;
1616 pyus_in = delta_to_microseconds(delta);
1617 if (pyus_in == NULL)
1618 return NULL;
1620 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1621 Py_DECREF(pyus_in);
1622 if (pyus_out == NULL)
1623 return NULL;
1625 result = microseconds_to_delta(pyus_out);
1626 Py_DECREF(pyus_out);
1627 return result;
1630 static PyObject *
1631 delta_add(PyObject *left, PyObject *right)
1633 PyObject *result = Py_NotImplemented;
1635 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1636 /* delta + delta */
1637 /* The C-level additions can't overflow because of the
1638 * invariant bounds.
1640 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1641 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1642 int microseconds = GET_TD_MICROSECONDS(left) +
1643 GET_TD_MICROSECONDS(right);
1644 result = new_delta(days, seconds, microseconds, 1);
1647 if (result == Py_NotImplemented)
1648 Py_INCREF(result);
1649 return result;
1652 static PyObject *
1653 delta_negative(PyDateTime_Delta *self)
1655 return new_delta(-GET_TD_DAYS(self),
1656 -GET_TD_SECONDS(self),
1657 -GET_TD_MICROSECONDS(self),
1661 static PyObject *
1662 delta_positive(PyDateTime_Delta *self)
1664 /* Could optimize this (by returning self) if this isn't a
1665 * subclass -- but who uses unary + ? Approximately nobody.
1667 return new_delta(GET_TD_DAYS(self),
1668 GET_TD_SECONDS(self),
1669 GET_TD_MICROSECONDS(self),
1673 static PyObject *
1674 delta_abs(PyDateTime_Delta *self)
1676 PyObject *result;
1678 assert(GET_TD_MICROSECONDS(self) >= 0);
1679 assert(GET_TD_SECONDS(self) >= 0);
1681 if (GET_TD_DAYS(self) < 0)
1682 result = delta_negative(self);
1683 else
1684 result = delta_positive(self);
1686 return result;
1689 static PyObject *
1690 delta_subtract(PyObject *left, PyObject *right)
1692 PyObject *result = Py_NotImplemented;
1694 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1695 /* delta - delta */
1696 PyObject *minus_right = PyNumber_Negative(right);
1697 if (minus_right) {
1698 result = delta_add(left, minus_right);
1699 Py_DECREF(minus_right);
1701 else
1702 result = NULL;
1705 if (result == Py_NotImplemented)
1706 Py_INCREF(result);
1707 return result;
1710 /* This is more natural as a tp_compare, but doesn't work then: for whatever
1711 * reason, Python's try_3way_compare ignores tp_compare unless
1712 * PyInstance_Check returns true, but these aren't old-style classes.
1714 static PyObject *
1715 delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1717 int diff = 42; /* nonsense */
1719 if (PyDelta_Check(other)) {
1720 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1721 if (diff == 0) {
1722 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1723 if (diff == 0)
1724 diff = GET_TD_MICROSECONDS(self) -
1725 GET_TD_MICROSECONDS(other);
1728 else if (op == Py_EQ || op == Py_NE)
1729 diff = 1; /* any non-zero value will do */
1731 else /* stop this from falling back to address comparison */
1732 return cmperror((PyObject *)self, other);
1734 return diff_to_bool(diff, op);
1737 static PyObject *delta_getstate(PyDateTime_Delta *self);
1739 static long
1740 delta_hash(PyDateTime_Delta *self)
1742 if (self->hashcode == -1) {
1743 PyObject *temp = delta_getstate(self);
1744 if (temp != NULL) {
1745 self->hashcode = PyObject_Hash(temp);
1746 Py_DECREF(temp);
1749 return self->hashcode;
1752 static PyObject *
1753 delta_multiply(PyObject *left, PyObject *right)
1755 PyObject *result = Py_NotImplemented;
1757 if (PyDelta_Check(left)) {
1758 /* delta * ??? */
1759 if (PyInt_Check(right) || PyLong_Check(right))
1760 result = multiply_int_timedelta(right,
1761 (PyDateTime_Delta *) left);
1763 else if (PyInt_Check(left) || PyLong_Check(left))
1764 result = multiply_int_timedelta(left,
1765 (PyDateTime_Delta *) right);
1767 if (result == Py_NotImplemented)
1768 Py_INCREF(result);
1769 return result;
1772 static PyObject *
1773 delta_divide(PyObject *left, PyObject *right)
1775 PyObject *result = Py_NotImplemented;
1777 if (PyDelta_Check(left)) {
1778 /* delta * ??? */
1779 if (PyInt_Check(right) || PyLong_Check(right))
1780 result = divide_timedelta_int(
1781 (PyDateTime_Delta *)left,
1782 right);
1785 if (result == Py_NotImplemented)
1786 Py_INCREF(result);
1787 return result;
1790 /* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1791 * timedelta constructor. sofar is the # of microseconds accounted for
1792 * so far, and there are factor microseconds per current unit, the number
1793 * of which is given by num. num * factor is added to sofar in a
1794 * numerically careful way, and that's the result. Any fractional
1795 * microseconds left over (this can happen if num is a float type) are
1796 * added into *leftover.
1797 * Note that there are many ways this can give an error (NULL) return.
1799 static PyObject *
1800 accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1801 double *leftover)
1803 PyObject *prod;
1804 PyObject *sum;
1806 assert(num != NULL);
1808 if (PyInt_Check(num) || PyLong_Check(num)) {
1809 prod = PyNumber_Multiply(num, factor);
1810 if (prod == NULL)
1811 return NULL;
1812 sum = PyNumber_Add(sofar, prod);
1813 Py_DECREF(prod);
1814 return sum;
1817 if (PyFloat_Check(num)) {
1818 double dnum;
1819 double fracpart;
1820 double intpart;
1821 PyObject *x;
1822 PyObject *y;
1824 /* The Plan: decompose num into an integer part and a
1825 * fractional part, num = intpart + fracpart.
1826 * Then num * factor ==
1827 * intpart * factor + fracpart * factor
1828 * and the LHS can be computed exactly in long arithmetic.
1829 * The RHS is again broken into an int part and frac part.
1830 * and the frac part is added into *leftover.
1832 dnum = PyFloat_AsDouble(num);
1833 if (dnum == -1.0 && PyErr_Occurred())
1834 return NULL;
1835 fracpart = modf(dnum, &intpart);
1836 x = PyLong_FromDouble(intpart);
1837 if (x == NULL)
1838 return NULL;
1840 prod = PyNumber_Multiply(x, factor);
1841 Py_DECREF(x);
1842 if (prod == NULL)
1843 return NULL;
1845 sum = PyNumber_Add(sofar, prod);
1846 Py_DECREF(prod);
1847 if (sum == NULL)
1848 return NULL;
1850 if (fracpart == 0.0)
1851 return sum;
1852 /* So far we've lost no information. Dealing with the
1853 * fractional part requires float arithmetic, and may
1854 * lose a little info.
1856 assert(PyInt_Check(factor) || PyLong_Check(factor));
1857 if (PyInt_Check(factor))
1858 dnum = (double)PyInt_AsLong(factor);
1859 else
1860 dnum = PyLong_AsDouble(factor);
1862 dnum *= fracpart;
1863 fracpart = modf(dnum, &intpart);
1864 x = PyLong_FromDouble(intpart);
1865 if (x == NULL) {
1866 Py_DECREF(sum);
1867 return NULL;
1870 y = PyNumber_Add(sum, x);
1871 Py_DECREF(sum);
1872 Py_DECREF(x);
1873 *leftover += fracpart;
1874 return y;
1877 PyErr_Format(PyExc_TypeError,
1878 "unsupported type for timedelta %s component: %s",
1879 tag, num->ob_type->tp_name);
1880 return NULL;
1883 static PyObject *
1884 delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1886 PyObject *self = NULL;
1888 /* Argument objects. */
1889 PyObject *day = NULL;
1890 PyObject *second = NULL;
1891 PyObject *us = NULL;
1892 PyObject *ms = NULL;
1893 PyObject *minute = NULL;
1894 PyObject *hour = NULL;
1895 PyObject *week = NULL;
1897 PyObject *x = NULL; /* running sum of microseconds */
1898 PyObject *y = NULL; /* temp sum of microseconds */
1899 double leftover_us = 0.0;
1901 static char *keywords[] = {
1902 "days", "seconds", "microseconds", "milliseconds",
1903 "minutes", "hours", "weeks", NULL
1906 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1907 keywords,
1908 &day, &second, &us,
1909 &ms, &minute, &hour, &week) == 0)
1910 goto Done;
1912 x = PyInt_FromLong(0);
1913 if (x == NULL)
1914 goto Done;
1916 #define CLEANUP \
1917 Py_DECREF(x); \
1918 x = y; \
1919 if (x == NULL) \
1920 goto Done
1922 if (us) {
1923 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1924 CLEANUP;
1926 if (ms) {
1927 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1928 CLEANUP;
1930 if (second) {
1931 y = accum("seconds", x, second, us_per_second, &leftover_us);
1932 CLEANUP;
1934 if (minute) {
1935 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1936 CLEANUP;
1938 if (hour) {
1939 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1940 CLEANUP;
1942 if (day) {
1943 y = accum("days", x, day, us_per_day, &leftover_us);
1944 CLEANUP;
1946 if (week) {
1947 y = accum("weeks", x, week, us_per_week, &leftover_us);
1948 CLEANUP;
1950 if (leftover_us) {
1951 /* Round to nearest whole # of us, and add into x. */
1952 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
1953 if (temp == NULL) {
1954 Py_DECREF(x);
1955 goto Done;
1957 y = PyNumber_Add(x, temp);
1958 Py_DECREF(temp);
1959 CLEANUP;
1962 self = microseconds_to_delta_ex(x, type);
1963 Py_DECREF(x);
1964 Done:
1965 return self;
1967 #undef CLEANUP
1970 static int
1971 delta_nonzero(PyDateTime_Delta *self)
1973 return (GET_TD_DAYS(self) != 0
1974 || GET_TD_SECONDS(self) != 0
1975 || GET_TD_MICROSECONDS(self) != 0);
1978 static PyObject *
1979 delta_repr(PyDateTime_Delta *self)
1981 if (GET_TD_MICROSECONDS(self) != 0)
1982 return PyString_FromFormat("%s(%d, %d, %d)",
1983 self->ob_type->tp_name,
1984 GET_TD_DAYS(self),
1985 GET_TD_SECONDS(self),
1986 GET_TD_MICROSECONDS(self));
1987 if (GET_TD_SECONDS(self) != 0)
1988 return PyString_FromFormat("%s(%d, %d)",
1989 self->ob_type->tp_name,
1990 GET_TD_DAYS(self),
1991 GET_TD_SECONDS(self));
1993 return PyString_FromFormat("%s(%d)",
1994 self->ob_type->tp_name,
1995 GET_TD_DAYS(self));
1998 static PyObject *
1999 delta_str(PyDateTime_Delta *self)
2001 int days = GET_TD_DAYS(self);
2002 int seconds = GET_TD_SECONDS(self);
2003 int us = GET_TD_MICROSECONDS(self);
2004 int hours;
2005 int minutes;
2006 char buf[100];
2007 char *pbuf = buf;
2008 size_t buflen = sizeof(buf);
2009 int n;
2011 minutes = divmod(seconds, 60, &seconds);
2012 hours = divmod(minutes, 60, &minutes);
2014 if (days) {
2015 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2016 (days == 1 || days == -1) ? "" : "s");
2017 if (n < 0 || (size_t)n >= buflen)
2018 goto Fail;
2019 pbuf += n;
2020 buflen -= (size_t)n;
2023 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2024 hours, minutes, seconds);
2025 if (n < 0 || (size_t)n >= buflen)
2026 goto Fail;
2027 pbuf += n;
2028 buflen -= (size_t)n;
2030 if (us) {
2031 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2032 if (n < 0 || (size_t)n >= buflen)
2033 goto Fail;
2034 pbuf += n;
2037 return PyString_FromStringAndSize(buf, pbuf - buf);
2039 Fail:
2040 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2041 return NULL;
2044 /* Pickle support, a simple use of __reduce__. */
2046 /* __getstate__ isn't exposed */
2047 static PyObject *
2048 delta_getstate(PyDateTime_Delta *self)
2050 return Py_BuildValue("iii", GET_TD_DAYS(self),
2051 GET_TD_SECONDS(self),
2052 GET_TD_MICROSECONDS(self));
2055 static PyObject *
2056 delta_reduce(PyDateTime_Delta* self)
2058 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
2061 #define OFFSET(field) offsetof(PyDateTime_Delta, field)
2063 static PyMemberDef delta_members[] = {
2065 {"days", T_INT, OFFSET(days), READONLY,
2066 PyDoc_STR("Number of days.")},
2068 {"seconds", T_INT, OFFSET(seconds), READONLY,
2069 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2071 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2072 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2073 {NULL}
2076 static PyMethodDef delta_methods[] = {
2077 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2078 PyDoc_STR("__reduce__() -> (cls, state)")},
2080 {NULL, NULL},
2083 static char delta_doc[] =
2084 PyDoc_STR("Difference between two datetime values.");
2086 static PyNumberMethods delta_as_number = {
2087 delta_add, /* nb_add */
2088 delta_subtract, /* nb_subtract */
2089 delta_multiply, /* nb_multiply */
2090 delta_divide, /* nb_divide */
2091 0, /* nb_remainder */
2092 0, /* nb_divmod */
2093 0, /* nb_power */
2094 (unaryfunc)delta_negative, /* nb_negative */
2095 (unaryfunc)delta_positive, /* nb_positive */
2096 (unaryfunc)delta_abs, /* nb_absolute */
2097 (inquiry)delta_nonzero, /* nb_nonzero */
2098 0, /*nb_invert*/
2099 0, /*nb_lshift*/
2100 0, /*nb_rshift*/
2101 0, /*nb_and*/
2102 0, /*nb_xor*/
2103 0, /*nb_or*/
2104 0, /*nb_coerce*/
2105 0, /*nb_int*/
2106 0, /*nb_long*/
2107 0, /*nb_float*/
2108 0, /*nb_oct*/
2109 0, /*nb_hex*/
2110 0, /*nb_inplace_add*/
2111 0, /*nb_inplace_subtract*/
2112 0, /*nb_inplace_multiply*/
2113 0, /*nb_inplace_divide*/
2114 0, /*nb_inplace_remainder*/
2115 0, /*nb_inplace_power*/
2116 0, /*nb_inplace_lshift*/
2117 0, /*nb_inplace_rshift*/
2118 0, /*nb_inplace_and*/
2119 0, /*nb_inplace_xor*/
2120 0, /*nb_inplace_or*/
2121 delta_divide, /* nb_floor_divide */
2122 0, /* nb_true_divide */
2123 0, /* nb_inplace_floor_divide */
2124 0, /* nb_inplace_true_divide */
2127 static PyTypeObject PyDateTime_DeltaType = {
2128 PyObject_HEAD_INIT(NULL)
2129 0, /* ob_size */
2130 "datetime.timedelta", /* tp_name */
2131 sizeof(PyDateTime_Delta), /* tp_basicsize */
2132 0, /* tp_itemsize */
2133 0, /* tp_dealloc */
2134 0, /* tp_print */
2135 0, /* tp_getattr */
2136 0, /* tp_setattr */
2137 0, /* tp_compare */
2138 (reprfunc)delta_repr, /* tp_repr */
2139 &delta_as_number, /* tp_as_number */
2140 0, /* tp_as_sequence */
2141 0, /* tp_as_mapping */
2142 (hashfunc)delta_hash, /* tp_hash */
2143 0, /* tp_call */
2144 (reprfunc)delta_str, /* tp_str */
2145 PyObject_GenericGetAttr, /* tp_getattro */
2146 0, /* tp_setattro */
2147 0, /* tp_as_buffer */
2148 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2149 Py_TPFLAGS_BASETYPE, /* tp_flags */
2150 delta_doc, /* tp_doc */
2151 0, /* tp_traverse */
2152 0, /* tp_clear */
2153 (richcmpfunc)delta_richcompare, /* tp_richcompare */
2154 0, /* tp_weaklistoffset */
2155 0, /* tp_iter */
2156 0, /* tp_iternext */
2157 delta_methods, /* tp_methods */
2158 delta_members, /* tp_members */
2159 0, /* tp_getset */
2160 0, /* tp_base */
2161 0, /* tp_dict */
2162 0, /* tp_descr_get */
2163 0, /* tp_descr_set */
2164 0, /* tp_dictoffset */
2165 0, /* tp_init */
2166 0, /* tp_alloc */
2167 delta_new, /* tp_new */
2168 0, /* tp_free */
2172 * PyDateTime_Date implementation.
2175 /* Accessor properties. */
2177 static PyObject *
2178 date_year(PyDateTime_Date *self, void *unused)
2180 return PyInt_FromLong(GET_YEAR(self));
2183 static PyObject *
2184 date_month(PyDateTime_Date *self, void *unused)
2186 return PyInt_FromLong(GET_MONTH(self));
2189 static PyObject *
2190 date_day(PyDateTime_Date *self, void *unused)
2192 return PyInt_FromLong(GET_DAY(self));
2195 static PyGetSetDef date_getset[] = {
2196 {"year", (getter)date_year},
2197 {"month", (getter)date_month},
2198 {"day", (getter)date_day},
2199 {NULL}
2202 /* Constructors. */
2204 static char *date_kws[] = {"year", "month", "day", NULL};
2206 static PyObject *
2207 date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2209 PyObject *self = NULL;
2210 PyObject *state;
2211 int year;
2212 int month;
2213 int day;
2215 /* Check for invocation from pickle with __getstate__ state */
2216 if (PyTuple_GET_SIZE(args) == 1 &&
2217 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2218 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2219 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
2221 PyDateTime_Date *me;
2223 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2224 if (me != NULL) {
2225 char *pdata = PyString_AS_STRING(state);
2226 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2227 me->hashcode = -1;
2229 return (PyObject *)me;
2232 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2233 &year, &month, &day)) {
2234 if (check_date_args(year, month, day) < 0)
2235 return NULL;
2236 self = new_date_ex(year, month, day, type);
2238 return self;
2241 /* Return new date from localtime(t). */
2242 static PyObject *
2243 date_local_from_time_t(PyObject *cls, double ts)
2245 struct tm *tm;
2246 time_t t;
2247 PyObject *result = NULL;
2249 t = _PyTime_DoubleToTimet(ts);
2250 if (t == (time_t)-1 && PyErr_Occurred())
2251 return NULL;
2252 tm = localtime(&t);
2253 if (tm)
2254 result = PyObject_CallFunction(cls, "iii",
2255 tm->tm_year + 1900,
2256 tm->tm_mon + 1,
2257 tm->tm_mday);
2258 else
2259 PyErr_SetString(PyExc_ValueError,
2260 "timestamp out of range for "
2261 "platform localtime() function");
2262 return result;
2265 /* Return new date from current time.
2266 * We say this is equivalent to fromtimestamp(time.time()), and the
2267 * only way to be sure of that is to *call* time.time(). That's not
2268 * generally the same as calling C's time.
2270 static PyObject *
2271 date_today(PyObject *cls, PyObject *dummy)
2273 PyObject *time;
2274 PyObject *result;
2276 time = time_time();
2277 if (time == NULL)
2278 return NULL;
2280 /* Note well: today() is a class method, so this may not call
2281 * date.fromtimestamp. For example, it may call
2282 * datetime.fromtimestamp. That's why we need all the accuracy
2283 * time.time() delivers; if someone were gonzo about optimization,
2284 * date.today() could get away with plain C time().
2286 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2287 Py_DECREF(time);
2288 return result;
2291 /* Return new date from given timestamp (Python timestamp -- a double). */
2292 static PyObject *
2293 date_fromtimestamp(PyObject *cls, PyObject *args)
2295 double timestamp;
2296 PyObject *result = NULL;
2298 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2299 result = date_local_from_time_t(cls, timestamp);
2300 return result;
2303 /* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2304 * the ordinal is out of range.
2306 static PyObject *
2307 date_fromordinal(PyObject *cls, PyObject *args)
2309 PyObject *result = NULL;
2310 int ordinal;
2312 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2313 int year;
2314 int month;
2315 int day;
2317 if (ordinal < 1)
2318 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2319 ">= 1");
2320 else {
2321 ord_to_ymd(ordinal, &year, &month, &day);
2322 result = PyObject_CallFunction(cls, "iii",
2323 year, month, day);
2326 return result;
2330 * Date arithmetic.
2333 /* date + timedelta -> date. If arg negate is true, subtract the timedelta
2334 * instead.
2336 static PyObject *
2337 add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2339 PyObject *result = NULL;
2340 int year = GET_YEAR(date);
2341 int month = GET_MONTH(date);
2342 int deltadays = GET_TD_DAYS(delta);
2343 /* C-level overflow is impossible because |deltadays| < 1e9. */
2344 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2346 if (normalize_date(&year, &month, &day) >= 0)
2347 result = new_date(year, month, day);
2348 return result;
2351 static PyObject *
2352 date_add(PyObject *left, PyObject *right)
2354 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2355 Py_INCREF(Py_NotImplemented);
2356 return Py_NotImplemented;
2358 if (PyDate_Check(left)) {
2359 /* date + ??? */
2360 if (PyDelta_Check(right))
2361 /* date + delta */
2362 return add_date_timedelta((PyDateTime_Date *) left,
2363 (PyDateTime_Delta *) right,
2366 else {
2367 /* ??? + date
2368 * 'right' must be one of us, or we wouldn't have been called
2370 if (PyDelta_Check(left))
2371 /* delta + date */
2372 return add_date_timedelta((PyDateTime_Date *) right,
2373 (PyDateTime_Delta *) left,
2376 Py_INCREF(Py_NotImplemented);
2377 return Py_NotImplemented;
2380 static PyObject *
2381 date_subtract(PyObject *left, PyObject *right)
2383 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2384 Py_INCREF(Py_NotImplemented);
2385 return Py_NotImplemented;
2387 if (PyDate_Check(left)) {
2388 if (PyDate_Check(right)) {
2389 /* date - date */
2390 int left_ord = ymd_to_ord(GET_YEAR(left),
2391 GET_MONTH(left),
2392 GET_DAY(left));
2393 int right_ord = ymd_to_ord(GET_YEAR(right),
2394 GET_MONTH(right),
2395 GET_DAY(right));
2396 return new_delta(left_ord - right_ord, 0, 0, 0);
2398 if (PyDelta_Check(right)) {
2399 /* date - delta */
2400 return add_date_timedelta((PyDateTime_Date *) left,
2401 (PyDateTime_Delta *) right,
2405 Py_INCREF(Py_NotImplemented);
2406 return Py_NotImplemented;
2410 /* Various ways to turn a date into a string. */
2412 static PyObject *
2413 date_repr(PyDateTime_Date *self)
2415 char buffer[1028];
2416 const char *type_name;
2418 type_name = self->ob_type->tp_name;
2419 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
2420 type_name,
2421 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2423 return PyString_FromString(buffer);
2426 static PyObject *
2427 date_isoformat(PyDateTime_Date *self)
2429 char buffer[128];
2431 isoformat_date(self, buffer, sizeof(buffer));
2432 return PyString_FromString(buffer);
2435 /* str() calls the appropriate isoformat() method. */
2436 static PyObject *
2437 date_str(PyDateTime_Date *self)
2439 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2443 static PyObject *
2444 date_ctime(PyDateTime_Date *self)
2446 return format_ctime(self, 0, 0, 0);
2449 static PyObject *
2450 date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2452 /* This method can be inherited, and needs to call the
2453 * timetuple() method appropriate to self's class.
2455 PyObject *result;
2456 PyObject *format;
2457 PyObject *tuple;
2458 static char *keywords[] = {"format", NULL};
2460 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2461 &PyString_Type, &format))
2462 return NULL;
2464 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2465 if (tuple == NULL)
2466 return NULL;
2467 result = wrap_strftime((PyObject *)self, format, tuple,
2468 (PyObject *)self);
2469 Py_DECREF(tuple);
2470 return result;
2473 /* ISO methods. */
2475 static PyObject *
2476 date_isoweekday(PyDateTime_Date *self)
2478 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2480 return PyInt_FromLong(dow + 1);
2483 static PyObject *
2484 date_isocalendar(PyDateTime_Date *self)
2486 int year = GET_YEAR(self);
2487 int week1_monday = iso_week1_monday(year);
2488 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2489 int week;
2490 int day;
2492 week = divmod(today - week1_monday, 7, &day);
2493 if (week < 0) {
2494 --year;
2495 week1_monday = iso_week1_monday(year);
2496 week = divmod(today - week1_monday, 7, &day);
2498 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2499 ++year;
2500 week = 0;
2502 return Py_BuildValue("iii", year, week + 1, day + 1);
2505 /* Miscellaneous methods. */
2507 /* This is more natural as a tp_compare, but doesn't work then: for whatever
2508 * reason, Python's try_3way_compare ignores tp_compare unless
2509 * PyInstance_Check returns true, but these aren't old-style classes.
2511 static PyObject *
2512 date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2514 int diff = 42; /* nonsense */
2516 if (PyDate_Check(other))
2517 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2518 _PyDateTime_DATE_DATASIZE);
2520 else if (PyObject_HasAttrString(other, "timetuple")) {
2521 /* A hook for other kinds of date objects. */
2522 Py_INCREF(Py_NotImplemented);
2523 return Py_NotImplemented;
2525 else if (op == Py_EQ || op == Py_NE)
2526 diff = 1; /* any non-zero value will do */
2528 else /* stop this from falling back to address comparison */
2529 return cmperror((PyObject *)self, other);
2531 return diff_to_bool(diff, op);
2534 static PyObject *
2535 date_timetuple(PyDateTime_Date *self)
2537 return build_struct_time(GET_YEAR(self),
2538 GET_MONTH(self),
2539 GET_DAY(self),
2540 0, 0, 0, -1);
2543 static PyObject *
2544 date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2546 PyObject *clone;
2547 PyObject *tuple;
2548 int year = GET_YEAR(self);
2549 int month = GET_MONTH(self);
2550 int day = GET_DAY(self);
2552 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2553 &year, &month, &day))
2554 return NULL;
2555 tuple = Py_BuildValue("iii", year, month, day);
2556 if (tuple == NULL)
2557 return NULL;
2558 clone = date_new(self->ob_type, tuple, NULL);
2559 Py_DECREF(tuple);
2560 return clone;
2563 static PyObject *date_getstate(PyDateTime_Date *self);
2565 static long
2566 date_hash(PyDateTime_Date *self)
2568 if (self->hashcode == -1) {
2569 PyObject *temp = date_getstate(self);
2570 if (temp != NULL) {
2571 self->hashcode = PyObject_Hash(temp);
2572 Py_DECREF(temp);
2575 return self->hashcode;
2578 static PyObject *
2579 date_toordinal(PyDateTime_Date *self)
2581 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2582 GET_DAY(self)));
2585 static PyObject *
2586 date_weekday(PyDateTime_Date *self)
2588 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2590 return PyInt_FromLong(dow);
2593 /* Pickle support, a simple use of __reduce__. */
2595 /* __getstate__ isn't exposed */
2596 static PyObject *
2597 date_getstate(PyDateTime_Date *self)
2599 return Py_BuildValue(
2600 "(N)",
2601 PyString_FromStringAndSize((char *)self->data,
2602 _PyDateTime_DATE_DATASIZE));
2605 static PyObject *
2606 date_reduce(PyDateTime_Date *self, PyObject *arg)
2608 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
2611 static PyMethodDef date_methods[] = {
2613 /* Class methods: */
2615 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2616 METH_CLASS,
2617 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2618 "time.time()).")},
2620 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2621 METH_CLASS,
2622 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2623 "ordinal.")},
2625 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2626 PyDoc_STR("Current date or datetime: same as "
2627 "self.__class__.fromtimestamp(time.time()).")},
2629 /* Instance methods: */
2631 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2632 PyDoc_STR("Return ctime() style string.")},
2634 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2635 PyDoc_STR("format -> strftime() style string.")},
2637 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2638 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2640 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2641 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2642 "weekday.")},
2644 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2645 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2647 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2648 PyDoc_STR("Return the day of the week represented by the date.\n"
2649 "Monday == 1 ... Sunday == 7")},
2651 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2652 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2653 "1 is day 1.")},
2655 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2656 PyDoc_STR("Return the day of the week represented by the date.\n"
2657 "Monday == 0 ... Sunday == 6")},
2659 {"replace", (PyCFunction)date_replace, METH_KEYWORDS,
2660 PyDoc_STR("Return date with new specified fields.")},
2662 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2663 PyDoc_STR("__reduce__() -> (cls, state)")},
2665 {NULL, NULL}
2668 static char date_doc[] =
2669 PyDoc_STR("date(year, month, day) --> date object");
2671 static PyNumberMethods date_as_number = {
2672 date_add, /* nb_add */
2673 date_subtract, /* nb_subtract */
2674 0, /* nb_multiply */
2675 0, /* nb_divide */
2676 0, /* nb_remainder */
2677 0, /* nb_divmod */
2678 0, /* nb_power */
2679 0, /* nb_negative */
2680 0, /* nb_positive */
2681 0, /* nb_absolute */
2682 0, /* nb_nonzero */
2685 static PyTypeObject PyDateTime_DateType = {
2686 PyObject_HEAD_INIT(NULL)
2687 0, /* ob_size */
2688 "datetime.date", /* tp_name */
2689 sizeof(PyDateTime_Date), /* tp_basicsize */
2690 0, /* tp_itemsize */
2691 0, /* tp_dealloc */
2692 0, /* tp_print */
2693 0, /* tp_getattr */
2694 0, /* tp_setattr */
2695 0, /* tp_compare */
2696 (reprfunc)date_repr, /* tp_repr */
2697 &date_as_number, /* tp_as_number */
2698 0, /* tp_as_sequence */
2699 0, /* tp_as_mapping */
2700 (hashfunc)date_hash, /* tp_hash */
2701 0, /* tp_call */
2702 (reprfunc)date_str, /* tp_str */
2703 PyObject_GenericGetAttr, /* tp_getattro */
2704 0, /* tp_setattro */
2705 0, /* tp_as_buffer */
2706 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2707 Py_TPFLAGS_BASETYPE, /* tp_flags */
2708 date_doc, /* tp_doc */
2709 0, /* tp_traverse */
2710 0, /* tp_clear */
2711 (richcmpfunc)date_richcompare, /* tp_richcompare */
2712 0, /* tp_weaklistoffset */
2713 0, /* tp_iter */
2714 0, /* tp_iternext */
2715 date_methods, /* tp_methods */
2716 0, /* tp_members */
2717 date_getset, /* tp_getset */
2718 0, /* tp_base */
2719 0, /* tp_dict */
2720 0, /* tp_descr_get */
2721 0, /* tp_descr_set */
2722 0, /* tp_dictoffset */
2723 0, /* tp_init */
2724 0, /* tp_alloc */
2725 date_new, /* tp_new */
2726 0, /* tp_free */
2730 * PyDateTime_TZInfo implementation.
2733 /* This is a pure abstract base class, so doesn't do anything beyond
2734 * raising NotImplemented exceptions. Real tzinfo classes need
2735 * to derive from this. This is mostly for clarity, and for efficiency in
2736 * datetime and time constructors (their tzinfo arguments need to
2737 * be subclasses of this tzinfo class, which is easy and quick to check).
2739 * Note: For reasons having to do with pickling of subclasses, we have
2740 * to allow tzinfo objects to be instantiated. This wasn't an issue
2741 * in the Python implementation (__init__() could raise NotImplementedError
2742 * there without ill effect), but doing so in the C implementation hit a
2743 * brick wall.
2746 static PyObject *
2747 tzinfo_nogo(const char* methodname)
2749 PyErr_Format(PyExc_NotImplementedError,
2750 "a tzinfo subclass must implement %s()",
2751 methodname);
2752 return NULL;
2755 /* Methods. A subclass must implement these. */
2757 static PyObject *
2758 tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2760 return tzinfo_nogo("tzname");
2763 static PyObject *
2764 tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2766 return tzinfo_nogo("utcoffset");
2769 static PyObject *
2770 tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2772 return tzinfo_nogo("dst");
2775 static PyObject *
2776 tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2778 int y, m, d, hh, mm, ss, us;
2780 PyObject *result;
2781 int off, dst;
2782 int none;
2783 int delta;
2785 if (! PyDateTime_Check(dt)) {
2786 PyErr_SetString(PyExc_TypeError,
2787 "fromutc: argument must be a datetime");
2788 return NULL;
2790 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2791 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2792 "is not self");
2793 return NULL;
2796 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2797 if (off == -1 && PyErr_Occurred())
2798 return NULL;
2799 if (none) {
2800 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2801 "utcoffset() result required");
2802 return NULL;
2805 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2806 if (dst == -1 && PyErr_Occurred())
2807 return NULL;
2808 if (none) {
2809 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2810 "dst() result required");
2811 return NULL;
2814 y = GET_YEAR(dt);
2815 m = GET_MONTH(dt);
2816 d = GET_DAY(dt);
2817 hh = DATE_GET_HOUR(dt);
2818 mm = DATE_GET_MINUTE(dt);
2819 ss = DATE_GET_SECOND(dt);
2820 us = DATE_GET_MICROSECOND(dt);
2822 delta = off - dst;
2823 mm += delta;
2824 if ((mm < 0 || mm >= 60) &&
2825 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2826 return NULL;
2827 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2828 if (result == NULL)
2829 return result;
2831 dst = call_dst(dt->tzinfo, result, &none);
2832 if (dst == -1 && PyErr_Occurred())
2833 goto Fail;
2834 if (none)
2835 goto Inconsistent;
2836 if (dst == 0)
2837 return result;
2839 mm += dst;
2840 if ((mm < 0 || mm >= 60) &&
2841 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2842 goto Fail;
2843 Py_DECREF(result);
2844 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2845 return result;
2847 Inconsistent:
2848 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2849 "inconsistent results; cannot convert");
2851 /* fall thru to failure */
2852 Fail:
2853 Py_DECREF(result);
2854 return NULL;
2858 * Pickle support. This is solely so that tzinfo subclasses can use
2859 * pickling -- tzinfo itself is supposed to be uninstantiable.
2862 static PyObject *
2863 tzinfo_reduce(PyObject *self)
2865 PyObject *args, *state, *tmp;
2866 PyObject *getinitargs, *getstate;
2868 tmp = PyTuple_New(0);
2869 if (tmp == NULL)
2870 return NULL;
2872 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2873 if (getinitargs != NULL) {
2874 args = PyObject_CallObject(getinitargs, tmp);
2875 Py_DECREF(getinitargs);
2876 if (args == NULL) {
2877 Py_DECREF(tmp);
2878 return NULL;
2881 else {
2882 PyErr_Clear();
2883 args = tmp;
2884 Py_INCREF(args);
2887 getstate = PyObject_GetAttrString(self, "__getstate__");
2888 if (getstate != NULL) {
2889 state = PyObject_CallObject(getstate, tmp);
2890 Py_DECREF(getstate);
2891 if (state == NULL) {
2892 Py_DECREF(args);
2893 Py_DECREF(tmp);
2894 return NULL;
2897 else {
2898 PyObject **dictptr;
2899 PyErr_Clear();
2900 state = Py_None;
2901 dictptr = _PyObject_GetDictPtr(self);
2902 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2903 state = *dictptr;
2904 Py_INCREF(state);
2907 Py_DECREF(tmp);
2909 if (state == Py_None) {
2910 Py_DECREF(state);
2911 return Py_BuildValue("(ON)", self->ob_type, args);
2913 else
2914 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2917 static PyMethodDef tzinfo_methods[] = {
2919 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2920 PyDoc_STR("datetime -> string name of time zone.")},
2922 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2923 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2924 "west of UTC).")},
2926 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2927 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2929 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2930 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2932 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2933 PyDoc_STR("-> (cls, state)")},
2935 {NULL, NULL}
2938 static char tzinfo_doc[] =
2939 PyDoc_STR("Abstract base class for time zone info objects.");
2941 statichere PyTypeObject PyDateTime_TZInfoType = {
2942 PyObject_HEAD_INIT(NULL)
2943 0, /* ob_size */
2944 "datetime.tzinfo", /* tp_name */
2945 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2946 0, /* tp_itemsize */
2947 0, /* tp_dealloc */
2948 0, /* tp_print */
2949 0, /* tp_getattr */
2950 0, /* tp_setattr */
2951 0, /* tp_compare */
2952 0, /* tp_repr */
2953 0, /* tp_as_number */
2954 0, /* tp_as_sequence */
2955 0, /* tp_as_mapping */
2956 0, /* tp_hash */
2957 0, /* tp_call */
2958 0, /* tp_str */
2959 PyObject_GenericGetAttr, /* tp_getattro */
2960 0, /* tp_setattro */
2961 0, /* tp_as_buffer */
2962 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2963 Py_TPFLAGS_BASETYPE, /* tp_flags */
2964 tzinfo_doc, /* tp_doc */
2965 0, /* tp_traverse */
2966 0, /* tp_clear */
2967 0, /* tp_richcompare */
2968 0, /* tp_weaklistoffset */
2969 0, /* tp_iter */
2970 0, /* tp_iternext */
2971 tzinfo_methods, /* tp_methods */
2972 0, /* tp_members */
2973 0, /* tp_getset */
2974 0, /* tp_base */
2975 0, /* tp_dict */
2976 0, /* tp_descr_get */
2977 0, /* tp_descr_set */
2978 0, /* tp_dictoffset */
2979 0, /* tp_init */
2980 0, /* tp_alloc */
2981 PyType_GenericNew, /* tp_new */
2982 0, /* tp_free */
2986 * PyDateTime_Time implementation.
2989 /* Accessor properties.
2992 static PyObject *
2993 time_hour(PyDateTime_Time *self, void *unused)
2995 return PyInt_FromLong(TIME_GET_HOUR(self));
2998 static PyObject *
2999 time_minute(PyDateTime_Time *self, void *unused)
3001 return PyInt_FromLong(TIME_GET_MINUTE(self));
3004 /* The name time_second conflicted with some platform header file. */
3005 static PyObject *
3006 py_time_second(PyDateTime_Time *self, void *unused)
3008 return PyInt_FromLong(TIME_GET_SECOND(self));
3011 static PyObject *
3012 time_microsecond(PyDateTime_Time *self, void *unused)
3014 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3017 static PyObject *
3018 time_tzinfo(PyDateTime_Time *self, void *unused)
3020 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3021 Py_INCREF(result);
3022 return result;
3025 static PyGetSetDef time_getset[] = {
3026 {"hour", (getter)time_hour},
3027 {"minute", (getter)time_minute},
3028 {"second", (getter)py_time_second},
3029 {"microsecond", (getter)time_microsecond},
3030 {"tzinfo", (getter)time_tzinfo},
3031 {NULL}
3035 * Constructors.
3038 static char *time_kws[] = {"hour", "minute", "second", "microsecond",
3039 "tzinfo", NULL};
3041 static PyObject *
3042 time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3044 PyObject *self = NULL;
3045 PyObject *state;
3046 int hour = 0;
3047 int minute = 0;
3048 int second = 0;
3049 int usecond = 0;
3050 PyObject *tzinfo = Py_None;
3052 /* Check for invocation from pickle with __getstate__ state */
3053 if (PyTuple_GET_SIZE(args) >= 1 &&
3054 PyTuple_GET_SIZE(args) <= 2 &&
3055 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3056 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3057 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
3059 PyDateTime_Time *me;
3060 char aware;
3062 if (PyTuple_GET_SIZE(args) == 2) {
3063 tzinfo = PyTuple_GET_ITEM(args, 1);
3064 if (check_tzinfo_subclass(tzinfo) < 0) {
3065 PyErr_SetString(PyExc_TypeError, "bad "
3066 "tzinfo state arg");
3067 return NULL;
3070 aware = (char)(tzinfo != Py_None);
3071 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3072 if (me != NULL) {
3073 char *pdata = PyString_AS_STRING(state);
3075 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3076 me->hashcode = -1;
3077 me->hastzinfo = aware;
3078 if (aware) {
3079 Py_INCREF(tzinfo);
3080 me->tzinfo = tzinfo;
3083 return (PyObject *)me;
3086 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3087 &hour, &minute, &second, &usecond,
3088 &tzinfo)) {
3089 if (check_time_args(hour, minute, second, usecond) < 0)
3090 return NULL;
3091 if (check_tzinfo_subclass(tzinfo) < 0)
3092 return NULL;
3093 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3094 type);
3096 return self;
3100 * Destructor.
3103 static void
3104 time_dealloc(PyDateTime_Time *self)
3106 if (HASTZINFO(self)) {
3107 Py_XDECREF(self->tzinfo);
3109 self->ob_type->tp_free((PyObject *)self);
3113 * Indirect access to tzinfo methods.
3116 /* These are all METH_NOARGS, so don't need to check the arglist. */
3117 static PyObject *
3118 time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
3119 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3120 "utcoffset", Py_None);
3123 static PyObject *
3124 time_dst(PyDateTime_Time *self, PyObject *unused) {
3125 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3126 "dst", Py_None);
3129 static PyObject *
3130 time_tzname(PyDateTime_Time *self, PyObject *unused) {
3131 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3132 Py_None);
3136 * Various ways to turn a time into a string.
3139 static PyObject *
3140 time_repr(PyDateTime_Time *self)
3142 char buffer[100];
3143 const char *type_name = self->ob_type->tp_name;
3144 int h = TIME_GET_HOUR(self);
3145 int m = TIME_GET_MINUTE(self);
3146 int s = TIME_GET_SECOND(self);
3147 int us = TIME_GET_MICROSECOND(self);
3148 PyObject *result = NULL;
3150 if (us)
3151 PyOS_snprintf(buffer, sizeof(buffer),
3152 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
3153 else if (s)
3154 PyOS_snprintf(buffer, sizeof(buffer),
3155 "%s(%d, %d, %d)", type_name, h, m, s);
3156 else
3157 PyOS_snprintf(buffer, sizeof(buffer),
3158 "%s(%d, %d)", type_name, h, m);
3159 result = PyString_FromString(buffer);
3160 if (result != NULL && HASTZINFO(self))
3161 result = append_keyword_tzinfo(result, self->tzinfo);
3162 return result;
3165 static PyObject *
3166 time_str(PyDateTime_Time *self)
3168 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3171 /* Even though this silently ignores all arguments, it cannot
3172 be fixed to reject them in release25-maint */
3173 static PyObject *
3174 time_isoformat(PyDateTime_Time *self, PyObject *unused_args,
3175 PyObject *unused_keywords)
3177 char buf[100];
3178 PyObject *result;
3179 /* Reuse the time format code from the datetime type. */
3180 PyDateTime_DateTime datetime;
3181 PyDateTime_DateTime *pdatetime = &datetime;
3183 /* Copy over just the time bytes. */
3184 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3185 self->data,
3186 _PyDateTime_TIME_DATASIZE);
3188 isoformat_time(pdatetime, buf, sizeof(buf));
3189 result = PyString_FromString(buf);
3190 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
3191 return result;
3193 /* We need to append the UTC offset. */
3194 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3195 Py_None) < 0) {
3196 Py_DECREF(result);
3197 return NULL;
3199 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3200 return result;
3203 static PyObject *
3204 time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3206 PyObject *result;
3207 PyObject *format;
3208 PyObject *tuple;
3209 static char *keywords[] = {"format", NULL};
3211 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3212 &PyString_Type, &format))
3213 return NULL;
3215 /* Python's strftime does insane things with the year part of the
3216 * timetuple. The year is forced to (the otherwise nonsensical)
3217 * 1900 to worm around that.
3219 tuple = Py_BuildValue("iiiiiiiii",
3220 1900, 1, 1, /* year, month, day */
3221 TIME_GET_HOUR(self),
3222 TIME_GET_MINUTE(self),
3223 TIME_GET_SECOND(self),
3224 0, 1, -1); /* weekday, daynum, dst */
3225 if (tuple == NULL)
3226 return NULL;
3227 assert(PyTuple_Size(tuple) == 9);
3228 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3229 Py_DECREF(tuple);
3230 return result;
3234 * Miscellaneous methods.
3237 /* This is more natural as a tp_compare, but doesn't work then: for whatever
3238 * reason, Python's try_3way_compare ignores tp_compare unless
3239 * PyInstance_Check returns true, but these aren't old-style classes.
3241 static PyObject *
3242 time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3244 int diff;
3245 naivety n1, n2;
3246 int offset1, offset2;
3248 if (! PyTime_Check(other)) {
3249 if (op == Py_EQ || op == Py_NE) {
3250 PyObject *result = op == Py_EQ ? Py_False : Py_True;
3251 Py_INCREF(result);
3252 return result;
3254 /* Stop this from falling back to address comparison. */
3255 return cmperror((PyObject *)self, other);
3257 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
3258 other, &offset2, &n2, Py_None) < 0)
3259 return NULL;
3260 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3261 /* If they're both naive, or both aware and have the same offsets,
3262 * we get off cheap. Note that if they're both naive, offset1 ==
3263 * offset2 == 0 at this point.
3265 if (n1 == n2 && offset1 == offset2) {
3266 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3267 _PyDateTime_TIME_DATASIZE);
3268 return diff_to_bool(diff, op);
3271 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3272 assert(offset1 != offset2); /* else last "if" handled it */
3273 /* Convert everything except microseconds to seconds. These
3274 * can't overflow (no more than the # of seconds in 2 days).
3276 offset1 = TIME_GET_HOUR(self) * 3600 +
3277 (TIME_GET_MINUTE(self) - offset1) * 60 +
3278 TIME_GET_SECOND(self);
3279 offset2 = TIME_GET_HOUR(other) * 3600 +
3280 (TIME_GET_MINUTE(other) - offset2) * 60 +
3281 TIME_GET_SECOND(other);
3282 diff = offset1 - offset2;
3283 if (diff == 0)
3284 diff = TIME_GET_MICROSECOND(self) -
3285 TIME_GET_MICROSECOND(other);
3286 return diff_to_bool(diff, op);
3289 assert(n1 != n2);
3290 PyErr_SetString(PyExc_TypeError,
3291 "can't compare offset-naive and "
3292 "offset-aware times");
3293 return NULL;
3296 static long
3297 time_hash(PyDateTime_Time *self)
3299 if (self->hashcode == -1) {
3300 naivety n;
3301 int offset;
3302 PyObject *temp;
3304 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3305 assert(n != OFFSET_UNKNOWN);
3306 if (n == OFFSET_ERROR)
3307 return -1;
3309 /* Reduce this to a hash of another object. */
3310 if (offset == 0)
3311 temp = PyString_FromStringAndSize((char *)self->data,
3312 _PyDateTime_TIME_DATASIZE);
3313 else {
3314 int hour;
3315 int minute;
3317 assert(n == OFFSET_AWARE);
3318 assert(HASTZINFO(self));
3319 hour = divmod(TIME_GET_HOUR(self) * 60 +
3320 TIME_GET_MINUTE(self) - offset,
3322 &minute);
3323 if (0 <= hour && hour < 24)
3324 temp = new_time(hour, minute,
3325 TIME_GET_SECOND(self),
3326 TIME_GET_MICROSECOND(self),
3327 Py_None);
3328 else
3329 temp = Py_BuildValue("iiii",
3330 hour, minute,
3331 TIME_GET_SECOND(self),
3332 TIME_GET_MICROSECOND(self));
3334 if (temp != NULL) {
3335 self->hashcode = PyObject_Hash(temp);
3336 Py_DECREF(temp);
3339 return self->hashcode;
3342 static PyObject *
3343 time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3345 PyObject *clone;
3346 PyObject *tuple;
3347 int hh = TIME_GET_HOUR(self);
3348 int mm = TIME_GET_MINUTE(self);
3349 int ss = TIME_GET_SECOND(self);
3350 int us = TIME_GET_MICROSECOND(self);
3351 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
3353 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3354 time_kws,
3355 &hh, &mm, &ss, &us, &tzinfo))
3356 return NULL;
3357 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3358 if (tuple == NULL)
3359 return NULL;
3360 clone = time_new(self->ob_type, tuple, NULL);
3361 Py_DECREF(tuple);
3362 return clone;
3365 static int
3366 time_nonzero(PyDateTime_Time *self)
3368 int offset;
3369 int none;
3371 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3372 /* Since utcoffset is in whole minutes, nothing can
3373 * alter the conclusion that this is nonzero.
3375 return 1;
3377 offset = 0;
3378 if (HASTZINFO(self) && self->tzinfo != Py_None) {
3379 offset = call_utcoffset(self->tzinfo, Py_None, &none);
3380 if (offset == -1 && PyErr_Occurred())
3381 return -1;
3383 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3386 /* Pickle support, a simple use of __reduce__. */
3388 /* Let basestate be the non-tzinfo data string.
3389 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3390 * So it's a tuple in any (non-error) case.
3391 * __getstate__ isn't exposed.
3393 static PyObject *
3394 time_getstate(PyDateTime_Time *self)
3396 PyObject *basestate;
3397 PyObject *result = NULL;
3399 basestate = PyString_FromStringAndSize((char *)self->data,
3400 _PyDateTime_TIME_DATASIZE);
3401 if (basestate != NULL) {
3402 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3403 result = PyTuple_Pack(1, basestate);
3404 else
3405 result = PyTuple_Pack(2, basestate, self->tzinfo);
3406 Py_DECREF(basestate);
3408 return result;
3411 static PyObject *
3412 time_reduce(PyDateTime_Time *self, PyObject *arg)
3414 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
3417 static PyMethodDef time_methods[] = {
3419 {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
3420 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3421 "[+HH:MM].")},
3423 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3424 PyDoc_STR("format -> strftime() style string.")},
3426 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3427 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3429 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3430 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3432 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3433 PyDoc_STR("Return self.tzinfo.dst(self).")},
3435 {"replace", (PyCFunction)time_replace, METH_KEYWORDS,
3436 PyDoc_STR("Return time with new specified fields.")},
3438 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3439 PyDoc_STR("__reduce__() -> (cls, state)")},
3441 {NULL, NULL}
3444 static char time_doc[] =
3445 PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3447 All arguments are optional. tzinfo may be None, or an instance of\n\
3448 a tzinfo subclass. The remaining arguments may be ints or longs.\n");
3450 static PyNumberMethods time_as_number = {
3451 0, /* nb_add */
3452 0, /* nb_subtract */
3453 0, /* nb_multiply */
3454 0, /* nb_divide */
3455 0, /* nb_remainder */
3456 0, /* nb_divmod */
3457 0, /* nb_power */
3458 0, /* nb_negative */
3459 0, /* nb_positive */
3460 0, /* nb_absolute */
3461 (inquiry)time_nonzero, /* nb_nonzero */
3464 statichere PyTypeObject PyDateTime_TimeType = {
3465 PyObject_HEAD_INIT(NULL)
3466 0, /* ob_size */
3467 "datetime.time", /* tp_name */
3468 sizeof(PyDateTime_Time), /* tp_basicsize */
3469 0, /* tp_itemsize */
3470 (destructor)time_dealloc, /* tp_dealloc */
3471 0, /* tp_print */
3472 0, /* tp_getattr */
3473 0, /* tp_setattr */
3474 0, /* tp_compare */
3475 (reprfunc)time_repr, /* tp_repr */
3476 &time_as_number, /* tp_as_number */
3477 0, /* tp_as_sequence */
3478 0, /* tp_as_mapping */
3479 (hashfunc)time_hash, /* tp_hash */
3480 0, /* tp_call */
3481 (reprfunc)time_str, /* tp_str */
3482 PyObject_GenericGetAttr, /* tp_getattro */
3483 0, /* tp_setattro */
3484 0, /* tp_as_buffer */
3485 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3486 Py_TPFLAGS_BASETYPE, /* tp_flags */
3487 time_doc, /* tp_doc */
3488 0, /* tp_traverse */
3489 0, /* tp_clear */
3490 (richcmpfunc)time_richcompare, /* tp_richcompare */
3491 0, /* tp_weaklistoffset */
3492 0, /* tp_iter */
3493 0, /* tp_iternext */
3494 time_methods, /* tp_methods */
3495 0, /* tp_members */
3496 time_getset, /* tp_getset */
3497 0, /* tp_base */
3498 0, /* tp_dict */
3499 0, /* tp_descr_get */
3500 0, /* tp_descr_set */
3501 0, /* tp_dictoffset */
3502 0, /* tp_init */
3503 time_alloc, /* tp_alloc */
3504 time_new, /* tp_new */
3505 0, /* tp_free */
3509 * PyDateTime_DateTime implementation.
3512 /* Accessor properties. Properties for day, month, and year are inherited
3513 * from date.
3516 static PyObject *
3517 datetime_hour(PyDateTime_DateTime *self, void *unused)
3519 return PyInt_FromLong(DATE_GET_HOUR(self));
3522 static PyObject *
3523 datetime_minute(PyDateTime_DateTime *self, void *unused)
3525 return PyInt_FromLong(DATE_GET_MINUTE(self));
3528 static PyObject *
3529 datetime_second(PyDateTime_DateTime *self, void *unused)
3531 return PyInt_FromLong(DATE_GET_SECOND(self));
3534 static PyObject *
3535 datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3537 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3540 static PyObject *
3541 datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3543 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3544 Py_INCREF(result);
3545 return result;
3548 static PyGetSetDef datetime_getset[] = {
3549 {"hour", (getter)datetime_hour},
3550 {"minute", (getter)datetime_minute},
3551 {"second", (getter)datetime_second},
3552 {"microsecond", (getter)datetime_microsecond},
3553 {"tzinfo", (getter)datetime_tzinfo},
3554 {NULL}
3558 * Constructors.
3561 static char *datetime_kws[] = {
3562 "year", "month", "day", "hour", "minute", "second",
3563 "microsecond", "tzinfo", NULL
3566 static PyObject *
3567 datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3569 PyObject *self = NULL;
3570 PyObject *state;
3571 int year;
3572 int month;
3573 int day;
3574 int hour = 0;
3575 int minute = 0;
3576 int second = 0;
3577 int usecond = 0;
3578 PyObject *tzinfo = Py_None;
3580 /* Check for invocation from pickle with __getstate__ state */
3581 if (PyTuple_GET_SIZE(args) >= 1 &&
3582 PyTuple_GET_SIZE(args) <= 2 &&
3583 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3584 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3585 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
3587 PyDateTime_DateTime *me;
3588 char aware;
3590 if (PyTuple_GET_SIZE(args) == 2) {
3591 tzinfo = PyTuple_GET_ITEM(args, 1);
3592 if (check_tzinfo_subclass(tzinfo) < 0) {
3593 PyErr_SetString(PyExc_TypeError, "bad "
3594 "tzinfo state arg");
3595 return NULL;
3598 aware = (char)(tzinfo != Py_None);
3599 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
3600 if (me != NULL) {
3601 char *pdata = PyString_AS_STRING(state);
3603 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3604 me->hashcode = -1;
3605 me->hastzinfo = aware;
3606 if (aware) {
3607 Py_INCREF(tzinfo);
3608 me->tzinfo = tzinfo;
3611 return (PyObject *)me;
3614 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
3615 &year, &month, &day, &hour, &minute,
3616 &second, &usecond, &tzinfo)) {
3617 if (check_date_args(year, month, day) < 0)
3618 return NULL;
3619 if (check_time_args(hour, minute, second, usecond) < 0)
3620 return NULL;
3621 if (check_tzinfo_subclass(tzinfo) < 0)
3622 return NULL;
3623 self = new_datetime_ex(year, month, day,
3624 hour, minute, second, usecond,
3625 tzinfo, type);
3627 return self;
3630 /* TM_FUNC is the shared type of localtime() and gmtime(). */
3631 typedef struct tm *(*TM_FUNC)(const time_t *timer);
3633 /* Internal helper.
3634 * Build datetime from a time_t and a distinct count of microseconds.
3635 * Pass localtime or gmtime for f, to control the interpretation of timet.
3637 static PyObject *
3638 datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3639 PyObject *tzinfo)
3641 struct tm *tm;
3642 PyObject *result = NULL;
3644 tm = f(&timet);
3645 if (tm) {
3646 /* The platform localtime/gmtime may insert leap seconds,
3647 * indicated by tm->tm_sec > 59. We don't care about them,
3648 * except to the extent that passing them on to the datetime
3649 * constructor would raise ValueError for a reason that
3650 * made no sense to the user.
3652 if (tm->tm_sec > 59)
3653 tm->tm_sec = 59;
3654 result = PyObject_CallFunction(cls, "iiiiiiiO",
3655 tm->tm_year + 1900,
3656 tm->tm_mon + 1,
3657 tm->tm_mday,
3658 tm->tm_hour,
3659 tm->tm_min,
3660 tm->tm_sec,
3662 tzinfo);
3664 else
3665 PyErr_SetString(PyExc_ValueError,
3666 "timestamp out of range for "
3667 "platform localtime()/gmtime() function");
3668 return result;
3671 /* Internal helper.
3672 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3673 * to control the interpretation of the timestamp. Since a double doesn't
3674 * have enough bits to cover a datetime's full range of precision, it's
3675 * better to call datetime_from_timet_and_us provided you have a way
3676 * to get that much precision (e.g., C time() isn't good enough).
3678 static PyObject *
3679 datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3680 PyObject *tzinfo)
3682 time_t timet;
3683 double fraction;
3684 int us;
3686 timet = _PyTime_DoubleToTimet(timestamp);
3687 if (timet == (time_t)-1 && PyErr_Occurred())
3688 return NULL;
3689 fraction = timestamp - (double)timet;
3690 us = (int)round_to_long(fraction * 1e6);
3691 if (us < 0) {
3692 /* Truncation towards zero is not what we wanted
3693 for negative numbers (Python's mod semantics) */
3694 timet -= 1;
3695 us += 1000000;
3697 /* If timestamp is less than one microsecond smaller than a
3698 * full second, round up. Otherwise, ValueErrors are raised
3699 * for some floats. */
3700 if (us == 1000000) {
3701 timet += 1;
3702 us = 0;
3704 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3707 /* Internal helper.
3708 * Build most accurate possible datetime for current time. Pass localtime or
3709 * gmtime for f as appropriate.
3711 static PyObject *
3712 datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3714 #ifdef HAVE_GETTIMEOFDAY
3715 struct timeval t;
3717 #ifdef GETTIMEOFDAY_NO_TZ
3718 gettimeofday(&t);
3719 #else
3720 gettimeofday(&t, (struct timezone *)NULL);
3721 #endif
3722 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3723 tzinfo);
3725 #else /* ! HAVE_GETTIMEOFDAY */
3726 /* No flavor of gettimeofday exists on this platform. Python's
3727 * time.time() does a lot of other platform tricks to get the
3728 * best time it can on the platform, and we're not going to do
3729 * better than that (if we could, the better code would belong
3730 * in time.time()!) We're limited by the precision of a double,
3731 * though.
3733 PyObject *time;
3734 double dtime;
3736 time = time_time();
3737 if (time == NULL)
3738 return NULL;
3739 dtime = PyFloat_AsDouble(time);
3740 Py_DECREF(time);
3741 if (dtime == -1.0 && PyErr_Occurred())
3742 return NULL;
3743 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3744 #endif /* ! HAVE_GETTIMEOFDAY */
3747 /* Return best possible local time -- this isn't constrained by the
3748 * precision of a timestamp.
3750 static PyObject *
3751 datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
3753 PyObject *self;
3754 PyObject *tzinfo = Py_None;
3755 static char *keywords[] = {"tz", NULL};
3757 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3758 &tzinfo))
3759 return NULL;
3760 if (check_tzinfo_subclass(tzinfo) < 0)
3761 return NULL;
3763 self = datetime_best_possible(cls,
3764 tzinfo == Py_None ? localtime : gmtime,
3765 tzinfo);
3766 if (self != NULL && tzinfo != Py_None) {
3767 /* Convert UTC to tzinfo's zone. */
3768 PyObject *temp = self;
3769 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3770 Py_DECREF(temp);
3772 return self;
3775 /* Return best possible UTC time -- this isn't constrained by the
3776 * precision of a timestamp.
3778 static PyObject *
3779 datetime_utcnow(PyObject *cls, PyObject *dummy)
3781 return datetime_best_possible(cls, gmtime, Py_None);
3784 /* Return new local datetime from timestamp (Python timestamp -- a double). */
3785 static PyObject *
3786 datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
3788 PyObject *self;
3789 double timestamp;
3790 PyObject *tzinfo = Py_None;
3791 static char *keywords[] = {"timestamp", "tz", NULL};
3793 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3794 keywords, &timestamp, &tzinfo))
3795 return NULL;
3796 if (check_tzinfo_subclass(tzinfo) < 0)
3797 return NULL;
3799 self = datetime_from_timestamp(cls,
3800 tzinfo == Py_None ? localtime : gmtime,
3801 timestamp,
3802 tzinfo);
3803 if (self != NULL && tzinfo != Py_None) {
3804 /* Convert UTC to tzinfo's zone. */
3805 PyObject *temp = self;
3806 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3807 Py_DECREF(temp);
3809 return self;
3812 /* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3813 static PyObject *
3814 datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3816 double timestamp;
3817 PyObject *result = NULL;
3819 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3820 result = datetime_from_timestamp(cls, gmtime, timestamp,
3821 Py_None);
3822 return result;
3825 /* Return new datetime from time.strptime(). */
3826 static PyObject *
3827 datetime_strptime(PyObject *cls, PyObject *args)
3829 PyObject *result = NULL, *obj, *module;
3830 const char *string, *format;
3832 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3833 return NULL;
3835 if ((module = PyImport_ImportModule("time")) == NULL)
3836 return NULL;
3837 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3838 Py_DECREF(module);
3840 if (obj != NULL) {
3841 int i, good_timetuple = 1;
3842 long int ia[6];
3843 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3844 for (i=0; i < 6; i++) {
3845 PyObject *p = PySequence_GetItem(obj, i);
3846 if (p == NULL) {
3847 Py_DECREF(obj);
3848 return NULL;
3850 if (PyInt_Check(p))
3851 ia[i] = PyInt_AsLong(p);
3852 else
3853 good_timetuple = 0;
3854 Py_DECREF(p);
3856 else
3857 good_timetuple = 0;
3858 if (good_timetuple)
3859 result = PyObject_CallFunction(cls, "iiiiii",
3860 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3861 else
3862 PyErr_SetString(PyExc_ValueError,
3863 "unexpected value from time.strptime");
3864 Py_DECREF(obj);
3866 return result;
3869 /* Return new datetime from date/datetime and time arguments. */
3870 static PyObject *
3871 datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3873 static char *keywords[] = {"date", "time", NULL};
3874 PyObject *date;
3875 PyObject *time;
3876 PyObject *result = NULL;
3878 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3879 &PyDateTime_DateType, &date,
3880 &PyDateTime_TimeType, &time)) {
3881 PyObject *tzinfo = Py_None;
3883 if (HASTZINFO(time))
3884 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3885 result = PyObject_CallFunction(cls, "iiiiiiiO",
3886 GET_YEAR(date),
3887 GET_MONTH(date),
3888 GET_DAY(date),
3889 TIME_GET_HOUR(time),
3890 TIME_GET_MINUTE(time),
3891 TIME_GET_SECOND(time),
3892 TIME_GET_MICROSECOND(time),
3893 tzinfo);
3895 return result;
3899 * Destructor.
3902 static void
3903 datetime_dealloc(PyDateTime_DateTime *self)
3905 if (HASTZINFO(self)) {
3906 Py_XDECREF(self->tzinfo);
3908 self->ob_type->tp_free((PyObject *)self);
3912 * Indirect access to tzinfo methods.
3915 /* These are all METH_NOARGS, so don't need to check the arglist. */
3916 static PyObject *
3917 datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3918 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3919 "utcoffset", (PyObject *)self);
3922 static PyObject *
3923 datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3924 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3925 "dst", (PyObject *)self);
3928 static PyObject *
3929 datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3930 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3931 (PyObject *)self);
3935 * datetime arithmetic.
3938 /* factor must be 1 (to add) or -1 (to subtract). The result inherits
3939 * the tzinfo state of date.
3941 static PyObject *
3942 add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3943 int factor)
3945 /* Note that the C-level additions can't overflow, because of
3946 * invariant bounds on the member values.
3948 int year = GET_YEAR(date);
3949 int month = GET_MONTH(date);
3950 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3951 int hour = DATE_GET_HOUR(date);
3952 int minute = DATE_GET_MINUTE(date);
3953 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3954 int microsecond = DATE_GET_MICROSECOND(date) +
3955 GET_TD_MICROSECONDS(delta) * factor;
3957 assert(factor == 1 || factor == -1);
3958 if (normalize_datetime(&year, &month, &day,
3959 &hour, &minute, &second, &microsecond) < 0)
3960 return NULL;
3961 else
3962 return new_datetime(year, month, day,
3963 hour, minute, second, microsecond,
3964 HASTZINFO(date) ? date->tzinfo : Py_None);
3967 static PyObject *
3968 datetime_add(PyObject *left, PyObject *right)
3970 if (PyDateTime_Check(left)) {
3971 /* datetime + ??? */
3972 if (PyDelta_Check(right))
3973 /* datetime + delta */
3974 return add_datetime_timedelta(
3975 (PyDateTime_DateTime *)left,
3976 (PyDateTime_Delta *)right,
3979 else if (PyDelta_Check(left)) {
3980 /* delta + datetime */
3981 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3982 (PyDateTime_Delta *) left,
3985 Py_INCREF(Py_NotImplemented);
3986 return Py_NotImplemented;
3989 static PyObject *
3990 datetime_subtract(PyObject *left, PyObject *right)
3992 PyObject *result = Py_NotImplemented;
3994 if (PyDateTime_Check(left)) {
3995 /* datetime - ??? */
3996 if (PyDateTime_Check(right)) {
3997 /* datetime - datetime */
3998 naivety n1, n2;
3999 int offset1, offset2;
4000 int delta_d, delta_s, delta_us;
4002 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4003 right, &offset2, &n2,
4004 right) < 0)
4005 return NULL;
4006 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4007 if (n1 != n2) {
4008 PyErr_SetString(PyExc_TypeError,
4009 "can't subtract offset-naive and "
4010 "offset-aware datetimes");
4011 return NULL;
4013 delta_d = ymd_to_ord(GET_YEAR(left),
4014 GET_MONTH(left),
4015 GET_DAY(left)) -
4016 ymd_to_ord(GET_YEAR(right),
4017 GET_MONTH(right),
4018 GET_DAY(right));
4019 /* These can't overflow, since the values are
4020 * normalized. At most this gives the number of
4021 * seconds in one day.
4023 delta_s = (DATE_GET_HOUR(left) -
4024 DATE_GET_HOUR(right)) * 3600 +
4025 (DATE_GET_MINUTE(left) -
4026 DATE_GET_MINUTE(right)) * 60 +
4027 (DATE_GET_SECOND(left) -
4028 DATE_GET_SECOND(right));
4029 delta_us = DATE_GET_MICROSECOND(left) -
4030 DATE_GET_MICROSECOND(right);
4031 /* (left - offset1) - (right - offset2) =
4032 * (left - right) + (offset2 - offset1)
4034 delta_s += (offset2 - offset1) * 60;
4035 result = new_delta(delta_d, delta_s, delta_us, 1);
4037 else if (PyDelta_Check(right)) {
4038 /* datetime - delta */
4039 result = add_datetime_timedelta(
4040 (PyDateTime_DateTime *)left,
4041 (PyDateTime_Delta *)right,
4042 -1);
4046 if (result == Py_NotImplemented)
4047 Py_INCREF(result);
4048 return result;
4051 /* Various ways to turn a datetime into a string. */
4053 static PyObject *
4054 datetime_repr(PyDateTime_DateTime *self)
4056 char buffer[1000];
4057 const char *type_name = self->ob_type->tp_name;
4058 PyObject *baserepr;
4060 if (DATE_GET_MICROSECOND(self)) {
4061 PyOS_snprintf(buffer, sizeof(buffer),
4062 "%s(%d, %d, %d, %d, %d, %d, %d)",
4063 type_name,
4064 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4065 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4066 DATE_GET_SECOND(self),
4067 DATE_GET_MICROSECOND(self));
4069 else if (DATE_GET_SECOND(self)) {
4070 PyOS_snprintf(buffer, sizeof(buffer),
4071 "%s(%d, %d, %d, %d, %d, %d)",
4072 type_name,
4073 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4074 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4075 DATE_GET_SECOND(self));
4077 else {
4078 PyOS_snprintf(buffer, sizeof(buffer),
4079 "%s(%d, %d, %d, %d, %d)",
4080 type_name,
4081 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4082 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4084 baserepr = PyString_FromString(buffer);
4085 if (baserepr == NULL || ! HASTZINFO(self))
4086 return baserepr;
4087 return append_keyword_tzinfo(baserepr, self->tzinfo);
4090 static PyObject *
4091 datetime_str(PyDateTime_DateTime *self)
4093 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4096 static PyObject *
4097 datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
4099 char sep = 'T';
4100 static char *keywords[] = {"sep", NULL};
4101 char buffer[100];
4102 char *cp;
4103 PyObject *result;
4105 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4106 &sep))
4107 return NULL;
4108 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4109 assert(cp != NULL);
4110 *cp++ = sep;
4111 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4112 result = PyString_FromString(buffer);
4113 if (result == NULL || ! HASTZINFO(self))
4114 return result;
4116 /* We need to append the UTC offset. */
4117 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4118 (PyObject *)self) < 0) {
4119 Py_DECREF(result);
4120 return NULL;
4122 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
4123 return result;
4126 static PyObject *
4127 datetime_ctime(PyDateTime_DateTime *self)
4129 return format_ctime((PyDateTime_Date *)self,
4130 DATE_GET_HOUR(self),
4131 DATE_GET_MINUTE(self),
4132 DATE_GET_SECOND(self));
4135 /* Miscellaneous methods. */
4137 /* This is more natural as a tp_compare, but doesn't work then: for whatever
4138 * reason, Python's try_3way_compare ignores tp_compare unless
4139 * PyInstance_Check returns true, but these aren't old-style classes.
4141 static PyObject *
4142 datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
4144 int diff;
4145 naivety n1, n2;
4146 int offset1, offset2;
4148 if (! PyDateTime_Check(other)) {
4149 /* If other has a "timetuple" attr, that's an advertised
4150 * hook for other classes to ask to get comparison control.
4151 * However, date instances have a timetuple attr, and we
4152 * don't want to allow that comparison. Because datetime
4153 * is a subclass of date, when mixing date and datetime
4154 * in a comparison, Python gives datetime the first shot
4155 * (it's the more specific subtype). So we can stop that
4156 * combination here reliably.
4158 if (PyObject_HasAttrString(other, "timetuple") &&
4159 ! PyDate_Check(other)) {
4160 /* A hook for other kinds of datetime objects. */
4161 Py_INCREF(Py_NotImplemented);
4162 return Py_NotImplemented;
4164 if (op == Py_EQ || op == Py_NE) {
4165 PyObject *result = op == Py_EQ ? Py_False : Py_True;
4166 Py_INCREF(result);
4167 return result;
4169 /* Stop this from falling back to address comparison. */
4170 return cmperror((PyObject *)self, other);
4173 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
4174 (PyObject *)self,
4175 other, &offset2, &n2,
4176 other) < 0)
4177 return NULL;
4178 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4179 /* If they're both naive, or both aware and have the same offsets,
4180 * we get off cheap. Note that if they're both naive, offset1 ==
4181 * offset2 == 0 at this point.
4183 if (n1 == n2 && offset1 == offset2) {
4184 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
4185 _PyDateTime_DATETIME_DATASIZE);
4186 return diff_to_bool(diff, op);
4189 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4190 PyDateTime_Delta *delta;
4192 assert(offset1 != offset2); /* else last "if" handled it */
4193 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4194 other);
4195 if (delta == NULL)
4196 return NULL;
4197 diff = GET_TD_DAYS(delta);
4198 if (diff == 0)
4199 diff = GET_TD_SECONDS(delta) |
4200 GET_TD_MICROSECONDS(delta);
4201 Py_DECREF(delta);
4202 return diff_to_bool(diff, op);
4205 assert(n1 != n2);
4206 PyErr_SetString(PyExc_TypeError,
4207 "can't compare offset-naive and "
4208 "offset-aware datetimes");
4209 return NULL;
4212 static long
4213 datetime_hash(PyDateTime_DateTime *self)
4215 if (self->hashcode == -1) {
4216 naivety n;
4217 int offset;
4218 PyObject *temp;
4220 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4221 &offset);
4222 assert(n != OFFSET_UNKNOWN);
4223 if (n == OFFSET_ERROR)
4224 return -1;
4226 /* Reduce this to a hash of another object. */
4227 if (n == OFFSET_NAIVE)
4228 temp = PyString_FromStringAndSize(
4229 (char *)self->data,
4230 _PyDateTime_DATETIME_DATASIZE);
4231 else {
4232 int days;
4233 int seconds;
4235 assert(n == OFFSET_AWARE);
4236 assert(HASTZINFO(self));
4237 days = ymd_to_ord(GET_YEAR(self),
4238 GET_MONTH(self),
4239 GET_DAY(self));
4240 seconds = DATE_GET_HOUR(self) * 3600 +
4241 (DATE_GET_MINUTE(self) - offset) * 60 +
4242 DATE_GET_SECOND(self);
4243 temp = new_delta(days,
4244 seconds,
4245 DATE_GET_MICROSECOND(self),
4248 if (temp != NULL) {
4249 self->hashcode = PyObject_Hash(temp);
4250 Py_DECREF(temp);
4253 return self->hashcode;
4256 static PyObject *
4257 datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
4259 PyObject *clone;
4260 PyObject *tuple;
4261 int y = GET_YEAR(self);
4262 int m = GET_MONTH(self);
4263 int d = GET_DAY(self);
4264 int hh = DATE_GET_HOUR(self);
4265 int mm = DATE_GET_MINUTE(self);
4266 int ss = DATE_GET_SECOND(self);
4267 int us = DATE_GET_MICROSECOND(self);
4268 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
4270 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4271 datetime_kws,
4272 &y, &m, &d, &hh, &mm, &ss, &us,
4273 &tzinfo))
4274 return NULL;
4275 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4276 if (tuple == NULL)
4277 return NULL;
4278 clone = datetime_new(self->ob_type, tuple, NULL);
4279 Py_DECREF(tuple);
4280 return clone;
4283 static PyObject *
4284 datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
4286 int y, m, d, hh, mm, ss, us;
4287 PyObject *result;
4288 int offset, none;
4290 PyObject *tzinfo;
4291 static char *keywords[] = {"tz", NULL};
4293 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4294 &PyDateTime_TZInfoType, &tzinfo))
4295 return NULL;
4297 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4298 goto NeedAware;
4300 /* Conversion to self's own time zone is a NOP. */
4301 if (self->tzinfo == tzinfo) {
4302 Py_INCREF(self);
4303 return (PyObject *)self;
4306 /* Convert self to UTC. */
4307 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4308 if (offset == -1 && PyErr_Occurred())
4309 return NULL;
4310 if (none)
4311 goto NeedAware;
4313 y = GET_YEAR(self);
4314 m = GET_MONTH(self);
4315 d = GET_DAY(self);
4316 hh = DATE_GET_HOUR(self);
4317 mm = DATE_GET_MINUTE(self);
4318 ss = DATE_GET_SECOND(self);
4319 us = DATE_GET_MICROSECOND(self);
4321 mm -= offset;
4322 if ((mm < 0 || mm >= 60) &&
4323 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
4324 return NULL;
4326 /* Attach new tzinfo and let fromutc() do the rest. */
4327 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4328 if (result != NULL) {
4329 PyObject *temp = result;
4331 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4332 Py_DECREF(temp);
4334 return result;
4336 NeedAware:
4337 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4338 "a naive datetime");
4339 return NULL;
4342 static PyObject *
4343 datetime_timetuple(PyDateTime_DateTime *self)
4345 int dstflag = -1;
4347 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4348 int none;
4350 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4351 if (dstflag == -1 && PyErr_Occurred())
4352 return NULL;
4354 if (none)
4355 dstflag = -1;
4356 else if (dstflag != 0)
4357 dstflag = 1;
4360 return build_struct_time(GET_YEAR(self),
4361 GET_MONTH(self),
4362 GET_DAY(self),
4363 DATE_GET_HOUR(self),
4364 DATE_GET_MINUTE(self),
4365 DATE_GET_SECOND(self),
4366 dstflag);
4369 static PyObject *
4370 datetime_getdate(PyDateTime_DateTime *self)
4372 return new_date(GET_YEAR(self),
4373 GET_MONTH(self),
4374 GET_DAY(self));
4377 static PyObject *
4378 datetime_gettime(PyDateTime_DateTime *self)
4380 return new_time(DATE_GET_HOUR(self),
4381 DATE_GET_MINUTE(self),
4382 DATE_GET_SECOND(self),
4383 DATE_GET_MICROSECOND(self),
4384 Py_None);
4387 static PyObject *
4388 datetime_gettimetz(PyDateTime_DateTime *self)
4390 return new_time(DATE_GET_HOUR(self),
4391 DATE_GET_MINUTE(self),
4392 DATE_GET_SECOND(self),
4393 DATE_GET_MICROSECOND(self),
4394 HASTZINFO(self) ? self->tzinfo : Py_None);
4397 static PyObject *
4398 datetime_utctimetuple(PyDateTime_DateTime *self)
4400 int y = GET_YEAR(self);
4401 int m = GET_MONTH(self);
4402 int d = GET_DAY(self);
4403 int hh = DATE_GET_HOUR(self);
4404 int mm = DATE_GET_MINUTE(self);
4405 int ss = DATE_GET_SECOND(self);
4406 int us = 0; /* microseconds are ignored in a timetuple */
4407 int offset = 0;
4409 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4410 int none;
4412 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4413 if (offset == -1 && PyErr_Occurred())
4414 return NULL;
4416 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4417 * 0 in a UTC timetuple regardless of what dst() says.
4419 if (offset) {
4420 /* Subtract offset minutes & normalize. */
4421 int stat;
4423 mm -= offset;
4424 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4425 if (stat < 0) {
4426 /* At the edges, it's possible we overflowed
4427 * beyond MINYEAR or MAXYEAR.
4429 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4430 PyErr_Clear();
4431 else
4432 return NULL;
4435 return build_struct_time(y, m, d, hh, mm, ss, 0);
4438 /* Pickle support, a simple use of __reduce__. */
4440 /* Let basestate be the non-tzinfo data string.
4441 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4442 * So it's a tuple in any (non-error) case.
4443 * __getstate__ isn't exposed.
4445 static PyObject *
4446 datetime_getstate(PyDateTime_DateTime *self)
4448 PyObject *basestate;
4449 PyObject *result = NULL;
4451 basestate = PyString_FromStringAndSize((char *)self->data,
4452 _PyDateTime_DATETIME_DATASIZE);
4453 if (basestate != NULL) {
4454 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4455 result = PyTuple_Pack(1, basestate);
4456 else
4457 result = PyTuple_Pack(2, basestate, self->tzinfo);
4458 Py_DECREF(basestate);
4460 return result;
4463 static PyObject *
4464 datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
4466 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
4469 static PyMethodDef datetime_methods[] = {
4471 /* Class methods: */
4473 {"now", (PyCFunction)datetime_now,
4474 METH_KEYWORDS | METH_CLASS,
4475 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
4477 {"utcnow", (PyCFunction)datetime_utcnow,
4478 METH_NOARGS | METH_CLASS,
4479 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4481 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4482 METH_KEYWORDS | METH_CLASS,
4483 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
4485 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4486 METH_VARARGS | METH_CLASS,
4487 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4488 "(like time.time()).")},
4490 {"strptime", (PyCFunction)datetime_strptime,
4491 METH_VARARGS | METH_CLASS,
4492 PyDoc_STR("string, format -> new datetime parsed from a string "
4493 "(like time.strptime()).")},
4495 {"combine", (PyCFunction)datetime_combine,
4496 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4497 PyDoc_STR("date, time -> datetime with same date and time fields")},
4499 /* Instance methods: */
4501 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4502 PyDoc_STR("Return date object with same year, month and day.")},
4504 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4505 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4507 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4508 PyDoc_STR("Return time object with same time and tzinfo.")},
4510 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4511 PyDoc_STR("Return ctime() style string.")},
4513 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
4514 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4516 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4517 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4519 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
4520 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4521 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4522 "sep is used to separate the year from the time, and "
4523 "defaults to 'T'.")},
4525 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
4526 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4528 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
4529 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4531 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
4532 PyDoc_STR("Return self.tzinfo.dst(self).")},
4534 {"replace", (PyCFunction)datetime_replace, METH_KEYWORDS,
4535 PyDoc_STR("Return datetime with new specified fields.")},
4537 {"astimezone", (PyCFunction)datetime_astimezone, METH_KEYWORDS,
4538 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4540 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4541 PyDoc_STR("__reduce__() -> (cls, state)")},
4543 {NULL, NULL}
4546 static char datetime_doc[] =
4547 PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4549 The year, month and day arguments are required. tzinfo may be None, or an\n\
4550 instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
4552 static PyNumberMethods datetime_as_number = {
4553 datetime_add, /* nb_add */
4554 datetime_subtract, /* nb_subtract */
4555 0, /* nb_multiply */
4556 0, /* nb_divide */
4557 0, /* nb_remainder */
4558 0, /* nb_divmod */
4559 0, /* nb_power */
4560 0, /* nb_negative */
4561 0, /* nb_positive */
4562 0, /* nb_absolute */
4563 0, /* nb_nonzero */
4566 statichere PyTypeObject PyDateTime_DateTimeType = {
4567 PyObject_HEAD_INIT(NULL)
4568 0, /* ob_size */
4569 "datetime.datetime", /* tp_name */
4570 sizeof(PyDateTime_DateTime), /* tp_basicsize */
4571 0, /* tp_itemsize */
4572 (destructor)datetime_dealloc, /* tp_dealloc */
4573 0, /* tp_print */
4574 0, /* tp_getattr */
4575 0, /* tp_setattr */
4576 0, /* tp_compare */
4577 (reprfunc)datetime_repr, /* tp_repr */
4578 &datetime_as_number, /* tp_as_number */
4579 0, /* tp_as_sequence */
4580 0, /* tp_as_mapping */
4581 (hashfunc)datetime_hash, /* tp_hash */
4582 0, /* tp_call */
4583 (reprfunc)datetime_str, /* tp_str */
4584 PyObject_GenericGetAttr, /* tp_getattro */
4585 0, /* tp_setattro */
4586 0, /* tp_as_buffer */
4587 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4588 Py_TPFLAGS_BASETYPE, /* tp_flags */
4589 datetime_doc, /* tp_doc */
4590 0, /* tp_traverse */
4591 0, /* tp_clear */
4592 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
4593 0, /* tp_weaklistoffset */
4594 0, /* tp_iter */
4595 0, /* tp_iternext */
4596 datetime_methods, /* tp_methods */
4597 0, /* tp_members */
4598 datetime_getset, /* tp_getset */
4599 &PyDateTime_DateType, /* tp_base */
4600 0, /* tp_dict */
4601 0, /* tp_descr_get */
4602 0, /* tp_descr_set */
4603 0, /* tp_dictoffset */
4604 0, /* tp_init */
4605 datetime_alloc, /* tp_alloc */
4606 datetime_new, /* tp_new */
4607 0, /* tp_free */
4610 /* ---------------------------------------------------------------------------
4611 * Module methods and initialization.
4614 static PyMethodDef module_methods[] = {
4615 {NULL, NULL}
4618 /* C API. Clients get at this via PyDateTime_IMPORT, defined in
4619 * datetime.h.
4621 static PyDateTime_CAPI CAPI = {
4622 &PyDateTime_DateType,
4623 &PyDateTime_DateTimeType,
4624 &PyDateTime_TimeType,
4625 &PyDateTime_DeltaType,
4626 &PyDateTime_TZInfoType,
4627 new_date_ex,
4628 new_datetime_ex,
4629 new_time_ex,
4630 new_delta_ex,
4631 datetime_fromtimestamp,
4632 date_fromtimestamp
4636 PyMODINIT_FUNC
4637 initdatetime(void)
4639 PyObject *m; /* a module object */
4640 PyObject *d; /* its dict */
4641 PyObject *x;
4643 m = Py_InitModule3("datetime", module_methods,
4644 "Fast implementation of the datetime type.");
4645 if (m == NULL)
4646 return;
4648 if (PyType_Ready(&PyDateTime_DateType) < 0)
4649 return;
4650 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4651 return;
4652 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4653 return;
4654 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4655 return;
4656 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4657 return;
4659 /* timedelta values */
4660 d = PyDateTime_DeltaType.tp_dict;
4662 x = new_delta(0, 0, 1, 0);
4663 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4664 return;
4665 Py_DECREF(x);
4667 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4668 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4669 return;
4670 Py_DECREF(x);
4672 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4673 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4674 return;
4675 Py_DECREF(x);
4677 /* date values */
4678 d = PyDateTime_DateType.tp_dict;
4680 x = new_date(1, 1, 1);
4681 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4682 return;
4683 Py_DECREF(x);
4685 x = new_date(MAXYEAR, 12, 31);
4686 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4687 return;
4688 Py_DECREF(x);
4690 x = new_delta(1, 0, 0, 0);
4691 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4692 return;
4693 Py_DECREF(x);
4695 /* time values */
4696 d = PyDateTime_TimeType.tp_dict;
4698 x = new_time(0, 0, 0, 0, Py_None);
4699 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4700 return;
4701 Py_DECREF(x);
4703 x = new_time(23, 59, 59, 999999, Py_None);
4704 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4705 return;
4706 Py_DECREF(x);
4708 x = new_delta(0, 0, 1, 0);
4709 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4710 return;
4711 Py_DECREF(x);
4713 /* datetime values */
4714 d = PyDateTime_DateTimeType.tp_dict;
4716 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
4717 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4718 return;
4719 Py_DECREF(x);
4721 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
4722 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4723 return;
4724 Py_DECREF(x);
4726 x = new_delta(0, 0, 1, 0);
4727 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4728 return;
4729 Py_DECREF(x);
4731 /* module initialization */
4732 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4733 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4735 Py_INCREF(&PyDateTime_DateType);
4736 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4738 Py_INCREF(&PyDateTime_DateTimeType);
4739 PyModule_AddObject(m, "datetime",
4740 (PyObject *)&PyDateTime_DateTimeType);
4742 Py_INCREF(&PyDateTime_TimeType);
4743 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4745 Py_INCREF(&PyDateTime_DeltaType);
4746 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4748 Py_INCREF(&PyDateTime_TZInfoType);
4749 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4751 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4752 NULL);
4753 if (x == NULL)
4754 return;
4755 PyModule_AddObject(m, "datetime_CAPI", x);
4757 /* A 4-year cycle has an extra leap day over what we'd get from
4758 * pasting together 4 single years.
4760 assert(DI4Y == 4 * 365 + 1);
4761 assert(DI4Y == days_before_year(4+1));
4763 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4764 * get from pasting together 4 100-year cycles.
4766 assert(DI400Y == 4 * DI100Y + 1);
4767 assert(DI400Y == days_before_year(400+1));
4769 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4770 * pasting together 25 4-year cycles.
4772 assert(DI100Y == 25 * DI4Y - 1);
4773 assert(DI100Y == days_before_year(100+1));
4775 us_per_us = PyInt_FromLong(1);
4776 us_per_ms = PyInt_FromLong(1000);
4777 us_per_second = PyInt_FromLong(1000000);
4778 us_per_minute = PyInt_FromLong(60000000);
4779 seconds_per_day = PyInt_FromLong(24 * 3600);
4780 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4781 us_per_minute == NULL || seconds_per_day == NULL)
4782 return;
4784 /* The rest are too big for 32-bit ints, but even
4785 * us_per_week fits in 40 bits, so doubles should be exact.
4787 us_per_hour = PyLong_FromDouble(3600000000.0);
4788 us_per_day = PyLong_FromDouble(86400000000.0);
4789 us_per_week = PyLong_FromDouble(604800000000.0);
4790 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4791 return;
4794 /* ---------------------------------------------------------------------------
4795 Some time zone algebra. For a datetime x, let
4796 x.n = x stripped of its timezone -- its naive time.
4797 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4798 return None
4799 x.d = x.dst(), and assuming that doesn't raise an exception or
4800 return None
4801 x.s = x's standard offset, x.o - x.d
4803 Now some derived rules, where k is a duration (timedelta).
4805 1. x.o = x.s + x.d
4806 This follows from the definition of x.s.
4808 2. If x and y have the same tzinfo member, x.s = y.s.
4809 This is actually a requirement, an assumption we need to make about
4810 sane tzinfo classes.
4812 3. The naive UTC time corresponding to x is x.n - x.o.
4813 This is again a requirement for a sane tzinfo class.
4815 4. (x+k).s = x.s
4816 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
4818 5. (x+k).n = x.n + k
4819 Again follows from how arithmetic is defined.
4821 Now we can explain tz.fromutc(x). Let's assume it's an interesting case
4822 (meaning that the various tzinfo methods exist, and don't blow up or return
4823 None when called).
4825 The function wants to return a datetime y with timezone tz, equivalent to x.
4826 x is already in UTC.
4828 By #3, we want
4830 y.n - y.o = x.n [1]
4832 The algorithm starts by attaching tz to x.n, and calling that y. So
4833 x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4834 becomes true; in effect, we want to solve [2] for k:
4836 (y+k).n - (y+k).o = x.n [2]
4838 By #1, this is the same as
4840 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
4842 By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4843 Substituting that into [3],
4845 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4846 k - (y+k).s - (y+k).d = 0; rearranging,
4847 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4848 k = y.s - (y+k).d
4850 On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4851 approximate k by ignoring the (y+k).d term at first. Note that k can't be
4852 very large, since all offset-returning methods return a duration of magnitude
4853 less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4854 be 0, so ignoring it has no consequence then.
4856 In any case, the new value is
4858 z = y + y.s [4]
4860 It's helpful to step back at look at [4] from a higher level: it's simply
4861 mapping from UTC to tz's standard time.
4863 At this point, if
4865 z.n - z.o = x.n [5]
4867 we have an equivalent time, and are almost done. The insecurity here is
4868 at the start of daylight time. Picture US Eastern for concreteness. The wall
4869 time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
4870 sense then. The docs ask that an Eastern tzinfo class consider such a time to
4871 be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4872 on the day DST starts. We want to return the 1:MM EST spelling because that's
4873 the only spelling that makes sense on the local wall clock.
4875 In fact, if [5] holds at this point, we do have the standard-time spelling,
4876 but that takes a bit of proof. We first prove a stronger result. What's the
4877 difference between the LHS and RHS of [5]? Let
4879 diff = x.n - (z.n - z.o) [6]
4882 z.n = by [4]
4883 (y + y.s).n = by #5
4884 y.n + y.s = since y.n = x.n
4885 x.n + y.s = since z and y are have the same tzinfo member,
4886 y.s = z.s by #2
4887 x.n + z.s
4889 Plugging that back into [6] gives
4891 diff =
4892 x.n - ((x.n + z.s) - z.o) = expanding
4893 x.n - x.n - z.s + z.o = cancelling
4894 - z.s + z.o = by #2
4897 So diff = z.d.
4899 If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
4900 spelling we wanted in the endcase described above. We're done. Contrarily,
4901 if z.d = 0, then we have a UTC equivalent, and are also done.
4903 If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4904 add to z (in effect, z is in tz's standard time, and we need to shift the
4905 local clock into tz's daylight time).
4909 z' = z + z.d = z + diff [7]
4911 and we can again ask whether
4913 z'.n - z'.o = x.n [8]
4915 If so, we're done. If not, the tzinfo class is insane, according to the
4916 assumptions we've made. This also requires a bit of proof. As before, let's
4917 compute the difference between the LHS and RHS of [8] (and skipping some of
4918 the justifications for the kinds of substitutions we've done several times
4919 already):
4921 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4922 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4923 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4924 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4925 - z.n + z.n - z.o + z'.o = cancel z.n
4926 - z.o + z'.o = #1 twice
4927 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4928 z'.d - z.d
4930 So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
4931 we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4932 return z', not bothering to compute z'.d.
4934 How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4935 a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4936 would have to change the result dst() returns: we start in DST, and moving
4937 a little further into it takes us out of DST.
4939 There isn't a sane case where this can happen. The closest it gets is at
4940 the end of DST, where there's an hour in UTC with no spelling in a hybrid
4941 tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4942 that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4943 UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4944 time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4945 clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4946 standard time. Since that's what the local clock *does*, we want to map both
4947 UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
4948 in local time, but so it goes -- it's the way the local clock works.
4950 When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4951 so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4952 z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
4953 (correctly) concludes that z' is not UTC-equivalent to x.
4955 Because we know z.d said z was in daylight time (else [5] would have held and
4956 we would have stopped then), and we know z.d != z'.d (else [8] would have held
4957 and we would have stopped then), and there are only 2 possible values dst() can
4958 return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4959 but the reasoning doesn't depend on the example -- it depends on there being
4960 two possible dst() outcomes, one zero and the other non-zero). Therefore
4961 z' must be in standard time, and is the spelling we want in this case.
4963 Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4964 concerned (because it takes z' as being in standard time rather than the
4965 daylight time we intend here), but returning it gives the real-life "local
4966 clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4969 When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4970 the 1:MM standard time spelling we want.
4972 So how can this break? One of the assumptions must be violated. Two
4973 possibilities:
4975 1) [2] effectively says that y.s is invariant across all y belong to a given
4976 time zone. This isn't true if, for political reasons or continental drift,
4977 a region decides to change its base offset from UTC.
4979 2) There may be versions of "double daylight" time where the tail end of
4980 the analysis gives up a step too early. I haven't thought about that
4981 enough to say.
4983 In any case, it's clear that the default fromutc() is strong enough to handle
4984 "almost all" time zones: so long as the standard offset is invariant, it
4985 doesn't matter if daylight time transition points change from year to year, or
4986 if daylight time is skipped in some years; it doesn't matter how large or
4987 small dst() may get within its bounds; and it doesn't even matter if some
4988 perverse time zone returns a negative dst()). So a breaking case must be
4989 pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
4990 --------------------------------------------------------------------------- */