1 /* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
6 #include "modsupport.h"
7 #include "structmember.h"
11 #include "timefuncs.h"
13 /* Differentiate between building the core module and building extension
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).
28 # error "datetime.c requires that C int have at least 32 bits"
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
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
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 /* ---------------------------------------------------------------------------
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
126 divmod(int x
, int y
, int *r
)
137 assert(0 <= *r
&& *r
< y
);
141 /* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
145 round_to_long(double 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. */
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 */
187 days_in_month(int year
, int month
)
191 if (month
== 2 && is_leap(year
))
194 return _days_in_month
[month
];
197 /* year, month -> number of days in year preceeding first day of month */
199 days_before_month(int year
, int month
)
205 days
= _days_before_month
[month
];
206 if (month
> 2 && is_leap(year
))
211 /* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
215 days_before_year(int year
)
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.
225 return y
*365 + y
/4 - y
/100 + y
/400;
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. */
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
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
260 * 1 Jan 001 1 0 400-year boundary
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
267 assert(ordinal
>= 1);
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
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.
283 /* Now compute how many 4-year cycles precede it. */
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
294 *year
+= n100
* 100 + n4
* 4 + n1
;
295 if (n1
== 4 || n100
== 4) {
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
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
));
312 /* estimate is too large */
314 preceding
-= days_in_month(*year
, *month
);
318 assert(n
< days_in_month(*year
, *month
));
323 /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
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. */
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.
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 */
354 /* ---------------------------------------------------------------------------
358 /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
362 check_delta_day_range(int days
)
364 if (-MAX_DELTA_DAYS
<= days
&& days
<= MAX_DELTA_DAYS
)
366 PyErr_Format(PyExc_OverflowError
,
367 "days=%d; must have magnitude <= %d",
368 days
, MAX_DELTA_DAYS
);
372 /* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
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");
384 if (month
< 1 || month
> 12) {
385 PyErr_SetString(PyExc_ValueError
,
386 "month must be in 1..12");
389 if (day
< 1 || day
> days_in_month(year
, month
)) {
390 PyErr_SetString(PyExc_ValueError
,
391 "day is out of range for month");
397 /* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
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");
408 if (m
< 0 || m
> 59) {
409 PyErr_SetString(PyExc_ValueError
,
410 "minute must be in 0..59");
413 if (s
< 0 || s
> 59) {
414 PyErr_SetString(PyExc_ValueError
,
415 "second must be in 0..59");
418 if (us
< 0 || us
> 999999) {
419 PyErr_SetString(PyExc_ValueError
,
420 "microsecond must be in 0..999999");
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
437 normalize_pair(int *hi
, int *lo
, int factor
)
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
));
447 assert(0 <= *lo
&& *lo
< factor
);
450 /* Fiddle days (d), seconds (s), and microseconds (us) so that
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.
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
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
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.
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) {
496 normalize_pair(y
, m
, 12);
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).
518 *d
= days_in_month(*y
, *m
);
525 else if (*d
== dim
+ 1) {
526 /* move forward a day */
535 int ordinal
= ymd_to_ord(*y
, *m
, 1) +
537 ord_to_ymd(ordinal
, y
, m
, d
);
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.
549 normalize_date(int *year
, int *month
, int *day
)
553 normalize_y_m_d(year
, month
, day
);
554 if (MINYEAR
<= *year
&& *year
<= MAXYEAR
)
557 PyErr_SetString(PyExc_OverflowError
,
558 "date value out of range");
564 /* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
568 normalize_datetime(int *year
, int *month
, int *day
,
569 int *hour
, int *minute
, int *second
,
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).
601 time_alloc(PyTypeObject
*type
, Py_ssize_t aware
)
606 PyObject_MALLOC(aware
?
607 sizeof(PyDateTime_Time
) :
608 sizeof(_PyDateTime_BaseTime
));
610 return (PyObject
*)PyErr_NoMemory();
611 PyObject_INIT(self
, type
);
616 datetime_alloc(PyTypeObject
*type
, Py_ssize_t aware
)
621 PyObject_MALLOC(aware
?
622 sizeof(PyDateTime_DateTime
) :
623 sizeof(_PyDateTime_BaseDateTime
));
625 return (PyObject
*)PyErr_NoMemory();
626 PyObject_INIT(self
, type
);
630 /* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
635 /* For date and datetime. */
637 set_date_fields(PyDateTime_Date
*self
, int y
, int m
, int d
)
645 /* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
649 /* Create a date instance with no range checking. */
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));
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. */
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
));
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
);
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. */
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
));
702 self
->hastzinfo
= aware
;
704 TIME_SET_HOUR(self
, hour
);
705 TIME_SET_MINUTE(self
, minute
);
706 TIME_SET_SECOND(self
, second
);
707 TIME_SET_MICROSECOND(self
, usecond
);
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
726 new_delta_ex(int days
, int seconds
, int microseconds
, int normalize
,
729 PyDateTime_Delta
*self
;
732 normalize_d_s_us(&days
, &seconds
, µseconds
);
733 assert(0 <= seconds
&& seconds
< 24*3600);
734 assert(0 <= microseconds
&& microseconds
< 1000000);
736 if (check_delta_day_range(days
) < 0)
739 self
= (PyDateTime_Delta
*) (type
->tp_alloc(type
, 0));
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 /* ---------------------------------------------------------------------------
756 /* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
760 check_tzinfo_subclass(PyObject
*p
)
762 if (p
== Py_None
|| PyTZInfo_Check(p
))
764 PyErr_Format(PyExc_TypeError
,
765 "tzinfo argument must be None or of a tzinfo subclass, "
767 Py_TYPE(p
)->tp_name
);
771 /* Return tzinfo.methname(tzinfoarg), without any checking of results.
772 * If tzinfo is None, returns None.
775 call_tzinfo_method(PyObject
*tzinfo
, char *methname
, PyObject
*tzinfoarg
)
779 assert(tzinfo
&& methname
&& tzinfoarg
);
780 assert(check_tzinfo_subclass(tzinfo
) >= 0);
781 if (tzinfo
== Py_None
) {
786 result
= PyObject_CallMethod(tzinfo
, methname
, "O", tzinfoarg
);
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.
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
;
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.
816 call_utc_tzinfo_method(PyObject
*tzinfo
, char *name
, PyObject
*tzinfoarg
,
822 assert(tzinfo
!= NULL
);
823 assert(PyTZInfo_Check(tzinfo
));
824 assert(tzinfoarg
!= NULL
);
827 u
= call_tzinfo_method(tzinfo
, name
, tzinfoarg
);
831 else if (u
== Py_None
) {
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 */
840 /* next line can't overflow because we know days
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",
855 PyErr_Format(PyExc_TypeError
,
856 "tzinfo.%s() must return None or "
857 "timedelta, not '%s'",
858 name
, Py_TYPE(u
)->tp_name
);
862 if (result
< -1439 || result
> 1439) {
863 PyErr_Format(PyExc_ValueError
,
864 "tzinfo.%s() returned %d; must be in "
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).
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.
889 offset_as_timedelta(PyObject
*tzinfo
, char *name
, PyObject
*tzinfoarg
) {
892 assert(tzinfo
&& name
&& tzinfoarg
);
893 if (tzinfo
== Py_None
) {
899 int offset
= call_utc_tzinfo_method(tzinfo
, name
, tzinfoarg
,
901 if (offset
< 0 && PyErr_Occurred())
908 result
= new_delta(0, offset
* 60, 0, 1);
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).
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
933 call_tzname(PyObject
*tzinfo
, PyObject
*tzinfoarg
)
937 assert(tzinfo
!= NULL
);
938 assert(check_tzinfo_subclass(tzinfo
) >= 0);
939 assert(tzinfoarg
!= NULL
);
941 if (tzinfo
== Py_None
) {
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 Py_TYPE(result
)->tp_name
);
959 /* an exception has been set; the caller should pass it on */
962 /* type isn't date, datetime, or time subclass */
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
975 /* time or datetime where utcoffset() doesn't return None */
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.
986 classify_utcoffset(PyObject
*op
, PyObject
*tzinfoarg
, int *offset
)
991 assert(tzinfoarg
!= NULL
);
993 tzinfo
= get_tzinfo_member(op
); /* NULL means no tzinfo, not error */
994 if (tzinfo
== Py_None
)
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.
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
;
1027 *n1
= classify_utcoffset(o1
, tzinfoarg1
, offset1
);
1028 if (*n1
== OFFSET_ERROR
)
1030 *n2
= classify_utcoffset(o2
, tzinfoarg2
, offset2
);
1031 if (*n2
== OFFSET_ERROR
)
1037 /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1039 * ", tzinfo=" + repr(tzinfo)
1040 * before the closing ")".
1043 append_keyword_tzinfo(PyObject
*repr
, PyObject
*tzinfo
)
1047 assert(PyString_Check(repr
));
1049 if (tzinfo
== Py_None
)
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);
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(")"));
1071 /* ---------------------------------------------------------------------------
1072 * String format helpers.
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"
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
,
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
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.
1107 format_utcoffset(char *buf
, size_t buflen
, const char *sep
,
1108 PyObject
*tzinfo
, PyObject
*tzinfoarg
)
1116 offset
= call_utcoffset(tzinfo
, tzinfoarg
, &none
);
1117 if (offset
== -1 && PyErr_Occurred())
1128 hours
= divmod(offset
, 60, &minutes
);
1129 PyOS_snprintf(buf
, buflen
, "%c%02d%s%02d", sign
, hours
, sep
, minutes
);
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
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.
1175 PyObject
*pyyear
= PySequence_GetItem(timetuple
, 0);
1176 if (pyyear
== NULL
) return NULL
;
1177 assert(PyInt_Check(pyyear
));
1178 year
= PyInt_AsLong(pyyear
);
1181 PyErr_Format(PyExc_ValueError
, "year=%ld is before "
1182 "1900; the datetime strftime() "
1183 "methods require year >= 1900",
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
);
1199 pin
= PyString_AsString(format
);
1200 while ((ch
= *pin
++) != '\0') {
1202 ptoappend
= pin
- 1;
1205 else if ((ch
= *pin
++) == '\0') {
1206 /* There's a lone trailing %; doesn't make sense. */
1207 PyErr_SetString(PyExc_ValueError
, "strftime format "
1211 /* A % has been seen and ch is the character after it. */
1212 else if (ch
== 'z') {
1213 if (zreplacement
== NULL
) {
1214 /* format utcoffset */
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
,
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') {
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
) {
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(
1260 if (Zreplacement
== NULL
)
1262 if (!PyString_Check(Zreplacement
)) {
1263 PyErr_SetString(PyExc_TypeError
, "tzname.replace() did not return a string");
1271 assert(Zreplacement
!= NULL
);
1272 ptoappend
= PyString_AS_STRING(Zreplacement
);
1273 ntoappend
= PyString_GET_SIZE(Zreplacement
);
1276 /* percent followed by neither z nor Z */
1277 ptoappend
= pin
- 2;
1281 /* Append the ntoappend chars starting at ptoappend to
1284 assert(ptoappend
!= NULL
);
1285 assert(ntoappend
>= 0);
1288 while (usednew
+ ntoappend
> totalnew
) {
1289 int bigger
= totalnew
<< 1;
1290 if ((bigger
>> 1) != totalnew
) { /* overflow */
1294 if (_PyString_Resize(&newfmt
, bigger
) < 0)
1297 pnew
= PyString_AsString(newfmt
) + usednew
;
1299 memcpy(pnew
, ptoappend
, ntoappend
);
1301 usednew
+= ntoappend
;
1302 assert(usednew
<= totalnew
);
1305 if (_PyString_Resize(&newfmt
, usednew
) < 0)
1308 PyObject
*time
= PyImport_ImportModuleNoBlock("time");
1311 result
= PyObject_CallMethod(time
, "strftime", "OO",
1316 Py_XDECREF(zreplacement
);
1317 Py_XDECREF(Zreplacement
);
1323 isoformat_date(PyDateTime_Date
*dt
, char buffer
[], int bufflen
)
1326 x
= PyOS_snprintf(buffer
, bufflen
,
1328 GET_YEAR(dt
), GET_MONTH(dt
), GET_DAY(dt
));
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 */
1340 DATE_GET_MINUTE(dt
),
1341 DATE_GET_SECOND(dt
));
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). */
1355 PyObject
*result
= NULL
;
1356 PyObject
*time
= PyImport_ImportModuleNoBlock("time");
1359 result
= PyObject_CallMethod(time
, "time", "()");
1365 /* Build a time.struct_time. The weekday and day number are automatically
1366 * computed from the y,m,d args.
1369 build_struct_time(int y
, int m
, int d
, int hh
, int mm
, int ss
, int dstflag
)
1372 PyObject
*result
= NULL
;
1374 time
= PyImport_ImportModuleNoBlock("time");
1376 result
= PyObject_CallMethod(time
, "struct_time",
1381 days_before_month(y
, m
) + d
,
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.
1397 diff_to_bool(int diff
, int 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;
1410 assert(! "op unknown");
1411 istrue
= 0; /* To shut up compiler */
1413 result
= istrue
? Py_True
: Py_False
;
1418 /* Raises a "can't compare" TypeError and returns NULL. */
1420 cmperror(PyObject
*a
, PyObject
*b
)
1422 PyErr_Format(PyExc_TypeError
,
1423 "can't compare %s to %s",
1424 Py_TYPE(a
)->tp_name
, Py_TYPE(b
)->tp_name
);
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.
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
));
1467 x2
= PyNumber_Multiply(x1
, seconds_per_day
); /* days in seconds */
1473 /* x2 has days in seconds */
1474 x1
= PyInt_FromLong(GET_TD_SECONDS(self
)); /* seconds */
1477 x3
= PyNumber_Add(x1
, x2
); /* days and seconds in seconds */
1484 /* x3 has days+seconds in seconds */
1485 x1
= PyNumber_Multiply(x3
, us_per_second
); /* us */
1491 /* x1 has days+seconds in us */
1492 x2
= PyInt_FromLong(GET_TD_MICROSECONDS(self
));
1495 result
= PyNumber_Add(x1
, x2
);
1504 /* Convert a number of us (as a Python int or long) to a timedelta.
1507 microseconds_to_delta_ex(PyObject
*pyus
, PyTypeObject
*type
)
1514 PyObject
*tuple
= NULL
;
1515 PyObject
*num
= NULL
;
1516 PyObject
*result
= NULL
;
1518 tuple
= PyNumber_Divmod(pyus
, us_per_second
);
1522 num
= PyTuple_GetItem(tuple
, 1); /* us */
1525 temp
= PyLong_AsLong(num
);
1527 if (temp
== -1 && PyErr_Occurred())
1529 assert(0 <= temp
&& temp
< 1000000);
1532 /* The divisor was positive, so this must be an error. */
1533 assert(PyErr_Occurred());
1537 num
= PyTuple_GetItem(tuple
, 0); /* leftover seconds */
1543 tuple
= PyNumber_Divmod(num
, seconds_per_day
);
1548 num
= PyTuple_GetItem(tuple
, 1); /* seconds */
1551 temp
= PyLong_AsLong(num
);
1553 if (temp
== -1 && PyErr_Occurred())
1555 assert(0 <= temp
&& temp
< 24*3600);
1559 /* The divisor was positive, so this must be an error. */
1560 assert(PyErr_Occurred());
1564 num
= PyTuple_GetItem(tuple
, 0); /* leftover days */
1568 temp
= PyLong_AsLong(num
);
1569 if (temp
== -1 && PyErr_Occurred())
1572 if ((long)d
!= temp
) {
1573 PyErr_SetString(PyExc_OverflowError
, "normalized days too "
1574 "large to fit in a C int");
1577 result
= new_delta_ex(d
, s
, us
, 0, type
);
1585 #define microseconds_to_delta(pymicros) \
1586 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1589 multiply_int_timedelta(PyObject
*intobj
, PyDateTime_Delta
*delta
)
1595 pyus_in
= delta_to_microseconds(delta
);
1596 if (pyus_in
== NULL
)
1599 pyus_out
= PyNumber_Multiply(pyus_in
, intobj
);
1601 if (pyus_out
== NULL
)
1604 result
= microseconds_to_delta(pyus_out
);
1605 Py_DECREF(pyus_out
);
1610 divide_timedelta_int(PyDateTime_Delta
*delta
, PyObject
*intobj
)
1616 pyus_in
= delta_to_microseconds(delta
);
1617 if (pyus_in
== NULL
)
1620 pyus_out
= PyNumber_FloorDivide(pyus_in
, intobj
);
1622 if (pyus_out
== NULL
)
1625 result
= microseconds_to_delta(pyus_out
);
1626 Py_DECREF(pyus_out
);
1631 delta_add(PyObject
*left
, PyObject
*right
)
1633 PyObject
*result
= Py_NotImplemented
;
1635 if (PyDelta_Check(left
) && PyDelta_Check(right
)) {
1637 /* The C-level additions can't overflow because of the
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
)
1653 delta_negative(PyDateTime_Delta
*self
)
1655 return new_delta(-GET_TD_DAYS(self
),
1656 -GET_TD_SECONDS(self
),
1657 -GET_TD_MICROSECONDS(self
),
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
),
1674 delta_abs(PyDateTime_Delta
*self
)
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
);
1684 result
= delta_positive(self
);
1690 delta_subtract(PyObject
*left
, PyObject
*right
)
1692 PyObject
*result
= Py_NotImplemented
;
1694 if (PyDelta_Check(left
) && PyDelta_Check(right
)) {
1696 PyObject
*minus_right
= PyNumber_Negative(right
);
1698 result
= delta_add(left
, minus_right
);
1699 Py_DECREF(minus_right
);
1705 if (result
== Py_NotImplemented
)
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.
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
);
1722 diff
= GET_TD_SECONDS(self
) - GET_TD_SECONDS(other
);
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
);
1740 delta_hash(PyDateTime_Delta
*self
)
1742 if (self
->hashcode
== -1) {
1743 PyObject
*temp
= delta_getstate(self
);
1745 self
->hashcode
= PyObject_Hash(temp
);
1749 return self
->hashcode
;
1753 delta_multiply(PyObject
*left
, PyObject
*right
)
1755 PyObject
*result
= Py_NotImplemented
;
1757 if (PyDelta_Check(left
)) {
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
)
1773 delta_divide(PyObject
*left
, PyObject
*right
)
1775 PyObject
*result
= Py_NotImplemented
;
1777 if (PyDelta_Check(left
)) {
1779 if (PyInt_Check(right
) || PyLong_Check(right
))
1780 result
= divide_timedelta_int(
1781 (PyDateTime_Delta
*)left
,
1785 if (result
== Py_NotImplemented
)
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.
1800 accum(const char* tag
, PyObject
*sofar
, PyObject
*num
, PyObject
*factor
,
1806 assert(num
!= NULL
);
1808 if (PyInt_Check(num
) || PyLong_Check(num
)) {
1809 prod
= PyNumber_Multiply(num
, factor
);
1812 sum
= PyNumber_Add(sofar
, prod
);
1817 if (PyFloat_Check(num
)) {
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())
1835 fracpart
= modf(dnum
, &intpart
);
1836 x
= PyLong_FromDouble(intpart
);
1840 prod
= PyNumber_Multiply(x
, factor
);
1845 sum
= PyNumber_Add(sofar
, prod
);
1850 if (fracpart
== 0.0)
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
);
1860 dnum
= PyLong_AsDouble(factor
);
1863 fracpart
= modf(dnum
, &intpart
);
1864 x
= PyLong_FromDouble(intpart
);
1870 y
= PyNumber_Add(sum
, x
);
1873 *leftover
+= fracpart
;
1877 PyErr_Format(PyExc_TypeError
,
1878 "unsupported type for timedelta %s component: %s",
1879 tag
, Py_TYPE(num
)->tp_name
);
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__",
1909 &ms
, &minute
, &hour
, &week
) == 0)
1912 x
= PyInt_FromLong(0);
1923 y
= accum("microseconds", x
, us
, us_per_us
, &leftover_us
);
1927 y
= accum("milliseconds", x
, ms
, us_per_ms
, &leftover_us
);
1931 y
= accum("seconds", x
, second
, us_per_second
, &leftover_us
);
1935 y
= accum("minutes", x
, minute
, us_per_minute
, &leftover_us
);
1939 y
= accum("hours", x
, hour
, us_per_hour
, &leftover_us
);
1943 y
= accum("days", x
, day
, us_per_day
, &leftover_us
);
1947 y
= accum("weeks", x
, week
, us_per_week
, &leftover_us
);
1951 /* Round to nearest whole # of us, and add into x. */
1952 PyObject
*temp
= PyLong_FromLong(round_to_long(leftover_us
));
1957 y
= PyNumber_Add(x
, temp
);
1962 self
= microseconds_to_delta_ex(x
, type
);
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);
1979 delta_repr(PyDateTime_Delta
*self
)
1981 if (GET_TD_MICROSECONDS(self
) != 0)
1982 return PyString_FromFormat("%s(%d, %d, %d)",
1983 Py_TYPE(self
)->tp_name
,
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 Py_TYPE(self
)->tp_name
,
1991 GET_TD_SECONDS(self
));
1993 return PyString_FromFormat("%s(%d)",
1994 Py_TYPE(self
)->tp_name
,
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
);
2008 size_t buflen
= sizeof(buf
);
2011 minutes
= divmod(seconds
, 60, &seconds
);
2012 hours
= divmod(minutes
, 60, &minutes
);
2015 n
= PyOS_snprintf(pbuf
, buflen
, "%d day%s, ", days
,
2016 (days
== 1 || days
== -1) ? "" : "s");
2017 if (n
< 0 || (size_t)n
>= buflen
)
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
)
2028 buflen
-= (size_t)n
;
2031 n
= PyOS_snprintf(pbuf
, buflen
, ".%06d", us
);
2032 if (n
< 0 || (size_t)n
>= buflen
)
2037 return PyString_FromStringAndSize(buf
, pbuf
- buf
);
2040 PyErr_SetString(PyExc_SystemError
, "goofy result from PyOS_snprintf");
2044 /* Pickle support, a simple use of __reduce__. */
2046 /* __getstate__ isn't exposed */
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
));
2056 delta_reduce(PyDateTime_Delta
* self
)
2058 return Py_BuildValue("ON", Py_TYPE(self
), 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).")},
2076 static PyMethodDef delta_methods
[] = {
2077 {"__reduce__", (PyCFunction
)delta_reduce
, METH_NOARGS
,
2078 PyDoc_STR("__reduce__() -> (cls, state)")},
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 */
2094 (unaryfunc
)delta_negative
, /* nb_negative */
2095 (unaryfunc
)delta_positive
, /* nb_positive */
2096 (unaryfunc
)delta_abs
, /* nb_absolute */
2097 (inquiry
)delta_nonzero
, /* nb_nonzero */
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 PyVarObject_HEAD_INIT(NULL
, 0)
2129 "datetime.timedelta", /* tp_name */
2130 sizeof(PyDateTime_Delta
), /* tp_basicsize */
2131 0, /* tp_itemsize */
2137 (reprfunc
)delta_repr
, /* tp_repr */
2138 &delta_as_number
, /* tp_as_number */
2139 0, /* tp_as_sequence */
2140 0, /* tp_as_mapping */
2141 (hashfunc
)delta_hash
, /* tp_hash */
2143 (reprfunc
)delta_str
, /* tp_str */
2144 PyObject_GenericGetAttr
, /* tp_getattro */
2145 0, /* tp_setattro */
2146 0, /* tp_as_buffer */
2147 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
2148 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2149 delta_doc
, /* tp_doc */
2150 0, /* tp_traverse */
2152 (richcmpfunc
)delta_richcompare
, /* tp_richcompare */
2153 0, /* tp_weaklistoffset */
2155 0, /* tp_iternext */
2156 delta_methods
, /* tp_methods */
2157 delta_members
, /* tp_members */
2161 0, /* tp_descr_get */
2162 0, /* tp_descr_set */
2163 0, /* tp_dictoffset */
2166 delta_new
, /* tp_new */
2171 * PyDateTime_Date implementation.
2174 /* Accessor properties. */
2177 date_year(PyDateTime_Date
*self
, void *unused
)
2179 return PyInt_FromLong(GET_YEAR(self
));
2183 date_month(PyDateTime_Date
*self
, void *unused
)
2185 return PyInt_FromLong(GET_MONTH(self
));
2189 date_day(PyDateTime_Date
*self
, void *unused
)
2191 return PyInt_FromLong(GET_DAY(self
));
2194 static PyGetSetDef date_getset
[] = {
2195 {"year", (getter
)date_year
},
2196 {"month", (getter
)date_month
},
2197 {"day", (getter
)date_day
},
2203 static char *date_kws
[] = {"year", "month", "day", NULL
};
2206 date_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
2208 PyObject
*self
= NULL
;
2214 /* Check for invocation from pickle with __getstate__ state */
2215 if (PyTuple_GET_SIZE(args
) == 1 &&
2216 PyString_Check(state
= PyTuple_GET_ITEM(args
, 0)) &&
2217 PyString_GET_SIZE(state
) == _PyDateTime_DATE_DATASIZE
&&
2218 MONTH_IS_SANE(PyString_AS_STRING(state
)[2]))
2220 PyDateTime_Date
*me
;
2222 me
= (PyDateTime_Date
*) (type
->tp_alloc(type
, 0));
2224 char *pdata
= PyString_AS_STRING(state
);
2225 memcpy(me
->data
, pdata
, _PyDateTime_DATE_DATASIZE
);
2228 return (PyObject
*)me
;
2231 if (PyArg_ParseTupleAndKeywords(args
, kw
, "iii", date_kws
,
2232 &year
, &month
, &day
)) {
2233 if (check_date_args(year
, month
, day
) < 0)
2235 self
= new_date_ex(year
, month
, day
, type
);
2240 /* Return new date from localtime(t). */
2242 date_local_from_time_t(PyObject
*cls
, double ts
)
2246 PyObject
*result
= NULL
;
2248 t
= _PyTime_DoubleToTimet(ts
);
2249 if (t
== (time_t)-1 && PyErr_Occurred())
2253 result
= PyObject_CallFunction(cls
, "iii",
2258 PyErr_SetString(PyExc_ValueError
,
2259 "timestamp out of range for "
2260 "platform localtime() function");
2264 /* Return new date from current time.
2265 * We say this is equivalent to fromtimestamp(time.time()), and the
2266 * only way to be sure of that is to *call* time.time(). That's not
2267 * generally the same as calling C's time.
2270 date_today(PyObject
*cls
, PyObject
*dummy
)
2279 /* Note well: today() is a class method, so this may not call
2280 * date.fromtimestamp. For example, it may call
2281 * datetime.fromtimestamp. That's why we need all the accuracy
2282 * time.time() delivers; if someone were gonzo about optimization,
2283 * date.today() could get away with plain C time().
2285 result
= PyObject_CallMethod(cls
, "fromtimestamp", "O", time
);
2290 /* Return new date from given timestamp (Python timestamp -- a double). */
2292 date_fromtimestamp(PyObject
*cls
, PyObject
*args
)
2295 PyObject
*result
= NULL
;
2297 if (PyArg_ParseTuple(args
, "d:fromtimestamp", ×tamp
))
2298 result
= date_local_from_time_t(cls
, timestamp
);
2302 /* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2303 * the ordinal is out of range.
2306 date_fromordinal(PyObject
*cls
, PyObject
*args
)
2308 PyObject
*result
= NULL
;
2311 if (PyArg_ParseTuple(args
, "i:fromordinal", &ordinal
)) {
2317 PyErr_SetString(PyExc_ValueError
, "ordinal must be "
2320 ord_to_ymd(ordinal
, &year
, &month
, &day
);
2321 result
= PyObject_CallFunction(cls
, "iii",
2332 /* date + timedelta -> date. If arg negate is true, subtract the timedelta
2336 add_date_timedelta(PyDateTime_Date
*date
, PyDateTime_Delta
*delta
, int negate
)
2338 PyObject
*result
= NULL
;
2339 int year
= GET_YEAR(date
);
2340 int month
= GET_MONTH(date
);
2341 int deltadays
= GET_TD_DAYS(delta
);
2342 /* C-level overflow is impossible because |deltadays| < 1e9. */
2343 int day
= GET_DAY(date
) + (negate
? -deltadays
: deltadays
);
2345 if (normalize_date(&year
, &month
, &day
) >= 0)
2346 result
= new_date(year
, month
, day
);
2351 date_add(PyObject
*left
, PyObject
*right
)
2353 if (PyDateTime_Check(left
) || PyDateTime_Check(right
)) {
2354 Py_INCREF(Py_NotImplemented
);
2355 return Py_NotImplemented
;
2357 if (PyDate_Check(left
)) {
2359 if (PyDelta_Check(right
))
2361 return add_date_timedelta((PyDateTime_Date
*) left
,
2362 (PyDateTime_Delta
*) right
,
2367 * 'right' must be one of us, or we wouldn't have been called
2369 if (PyDelta_Check(left
))
2371 return add_date_timedelta((PyDateTime_Date
*) right
,
2372 (PyDateTime_Delta
*) left
,
2375 Py_INCREF(Py_NotImplemented
);
2376 return Py_NotImplemented
;
2380 date_subtract(PyObject
*left
, PyObject
*right
)
2382 if (PyDateTime_Check(left
) || PyDateTime_Check(right
)) {
2383 Py_INCREF(Py_NotImplemented
);
2384 return Py_NotImplemented
;
2386 if (PyDate_Check(left
)) {
2387 if (PyDate_Check(right
)) {
2389 int left_ord
= ymd_to_ord(GET_YEAR(left
),
2392 int right_ord
= ymd_to_ord(GET_YEAR(right
),
2395 return new_delta(left_ord
- right_ord
, 0, 0, 0);
2397 if (PyDelta_Check(right
)) {
2399 return add_date_timedelta((PyDateTime_Date
*) left
,
2400 (PyDateTime_Delta
*) right
,
2404 Py_INCREF(Py_NotImplemented
);
2405 return Py_NotImplemented
;
2409 /* Various ways to turn a date into a string. */
2412 date_repr(PyDateTime_Date
*self
)
2415 const char *type_name
;
2417 type_name
= Py_TYPE(self
)->tp_name
;
2418 PyOS_snprintf(buffer
, sizeof(buffer
), "%s(%d, %d, %d)",
2420 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
));
2422 return PyString_FromString(buffer
);
2426 date_isoformat(PyDateTime_Date
*self
)
2430 isoformat_date(self
, buffer
, sizeof(buffer
));
2431 return PyString_FromString(buffer
);
2434 /* str() calls the appropriate isoformat() method. */
2436 date_str(PyDateTime_Date
*self
)
2438 return PyObject_CallMethod((PyObject
*)self
, "isoformat", "()");
2443 date_ctime(PyDateTime_Date
*self
)
2445 return format_ctime(self
, 0, 0, 0);
2449 date_strftime(PyDateTime_Date
*self
, PyObject
*args
, PyObject
*kw
)
2451 /* This method can be inherited, and needs to call the
2452 * timetuple() method appropriate to self's class.
2457 static char *keywords
[] = {"format", NULL
};
2459 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "O!:strftime", keywords
,
2460 &PyString_Type
, &format
))
2463 tuple
= PyObject_CallMethod((PyObject
*)self
, "timetuple", "()");
2466 result
= wrap_strftime((PyObject
*)self
, format
, tuple
,
2475 date_isoweekday(PyDateTime_Date
*self
)
2477 int dow
= weekday(GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
));
2479 return PyInt_FromLong(dow
+ 1);
2483 date_isocalendar(PyDateTime_Date
*self
)
2485 int year
= GET_YEAR(self
);
2486 int week1_monday
= iso_week1_monday(year
);
2487 int today
= ymd_to_ord(year
, GET_MONTH(self
), GET_DAY(self
));
2491 week
= divmod(today
- week1_monday
, 7, &day
);
2494 week1_monday
= iso_week1_monday(year
);
2495 week
= divmod(today
- week1_monday
, 7, &day
);
2497 else if (week
>= 52 && today
>= iso_week1_monday(year
+ 1)) {
2501 return Py_BuildValue("iii", year
, week
+ 1, day
+ 1);
2504 /* Miscellaneous methods. */
2506 /* This is more natural as a tp_compare, but doesn't work then: for whatever
2507 * reason, Python's try_3way_compare ignores tp_compare unless
2508 * PyInstance_Check returns true, but these aren't old-style classes.
2511 date_richcompare(PyDateTime_Date
*self
, PyObject
*other
, int op
)
2513 int diff
= 42; /* nonsense */
2515 if (PyDate_Check(other
))
2516 diff
= memcmp(self
->data
, ((PyDateTime_Date
*)other
)->data
,
2517 _PyDateTime_DATE_DATASIZE
);
2519 else if (PyObject_HasAttrString(other
, "timetuple")) {
2520 /* A hook for other kinds of date objects. */
2521 Py_INCREF(Py_NotImplemented
);
2522 return Py_NotImplemented
;
2524 else if (op
== Py_EQ
|| op
== Py_NE
)
2525 diff
= 1; /* any non-zero value will do */
2527 else /* stop this from falling back to address comparison */
2528 return cmperror((PyObject
*)self
, other
);
2530 return diff_to_bool(diff
, op
);
2534 date_timetuple(PyDateTime_Date
*self
)
2536 return build_struct_time(GET_YEAR(self
),
2543 date_replace(PyDateTime_Date
*self
, PyObject
*args
, PyObject
*kw
)
2547 int year
= GET_YEAR(self
);
2548 int month
= GET_MONTH(self
);
2549 int day
= GET_DAY(self
);
2551 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "|iii:replace", date_kws
,
2552 &year
, &month
, &day
))
2554 tuple
= Py_BuildValue("iii", year
, month
, day
);
2557 clone
= date_new(Py_TYPE(self
), tuple
, NULL
);
2562 static PyObject
*date_getstate(PyDateTime_Date
*self
);
2565 date_hash(PyDateTime_Date
*self
)
2567 if (self
->hashcode
== -1) {
2568 PyObject
*temp
= date_getstate(self
);
2570 self
->hashcode
= PyObject_Hash(temp
);
2574 return self
->hashcode
;
2578 date_toordinal(PyDateTime_Date
*self
)
2580 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self
), GET_MONTH(self
),
2585 date_weekday(PyDateTime_Date
*self
)
2587 int dow
= weekday(GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
));
2589 return PyInt_FromLong(dow
);
2592 /* Pickle support, a simple use of __reduce__. */
2594 /* __getstate__ isn't exposed */
2596 date_getstate(PyDateTime_Date
*self
)
2598 return Py_BuildValue(
2600 PyString_FromStringAndSize((char *)self
->data
,
2601 _PyDateTime_DATE_DATASIZE
));
2605 date_reduce(PyDateTime_Date
*self
, PyObject
*arg
)
2607 return Py_BuildValue("(ON)", Py_TYPE(self
), date_getstate(self
));
2610 static PyMethodDef date_methods
[] = {
2612 /* Class methods: */
2614 {"fromtimestamp", (PyCFunction
)date_fromtimestamp
, METH_VARARGS
|
2616 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2619 {"fromordinal", (PyCFunction
)date_fromordinal
, METH_VARARGS
|
2621 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2624 {"today", (PyCFunction
)date_today
, METH_NOARGS
| METH_CLASS
,
2625 PyDoc_STR("Current date or datetime: same as "
2626 "self.__class__.fromtimestamp(time.time()).")},
2628 /* Instance methods: */
2630 {"ctime", (PyCFunction
)date_ctime
, METH_NOARGS
,
2631 PyDoc_STR("Return ctime() style string.")},
2633 {"strftime", (PyCFunction
)date_strftime
, METH_VARARGS
| METH_KEYWORDS
,
2634 PyDoc_STR("format -> strftime() style string.")},
2636 {"timetuple", (PyCFunction
)date_timetuple
, METH_NOARGS
,
2637 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2639 {"isocalendar", (PyCFunction
)date_isocalendar
, METH_NOARGS
,
2640 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2643 {"isoformat", (PyCFunction
)date_isoformat
, METH_NOARGS
,
2644 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2646 {"isoweekday", (PyCFunction
)date_isoweekday
, METH_NOARGS
,
2647 PyDoc_STR("Return the day of the week represented by the date.\n"
2648 "Monday == 1 ... Sunday == 7")},
2650 {"toordinal", (PyCFunction
)date_toordinal
, METH_NOARGS
,
2651 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2654 {"weekday", (PyCFunction
)date_weekday
, METH_NOARGS
,
2655 PyDoc_STR("Return the day of the week represented by the date.\n"
2656 "Monday == 0 ... Sunday == 6")},
2658 {"replace", (PyCFunction
)date_replace
, METH_VARARGS
| METH_KEYWORDS
,
2659 PyDoc_STR("Return date with new specified fields.")},
2661 {"__reduce__", (PyCFunction
)date_reduce
, METH_NOARGS
,
2662 PyDoc_STR("__reduce__() -> (cls, state)")},
2667 static char date_doc
[] =
2668 PyDoc_STR("date(year, month, day) --> date object");
2670 static PyNumberMethods date_as_number
= {
2671 date_add
, /* nb_add */
2672 date_subtract
, /* nb_subtract */
2673 0, /* nb_multiply */
2675 0, /* nb_remainder */
2678 0, /* nb_negative */
2679 0, /* nb_positive */
2680 0, /* nb_absolute */
2684 static PyTypeObject PyDateTime_DateType
= {
2685 PyVarObject_HEAD_INIT(NULL
, 0)
2686 "datetime.date", /* tp_name */
2687 sizeof(PyDateTime_Date
), /* tp_basicsize */
2688 0, /* tp_itemsize */
2694 (reprfunc
)date_repr
, /* tp_repr */
2695 &date_as_number
, /* tp_as_number */
2696 0, /* tp_as_sequence */
2697 0, /* tp_as_mapping */
2698 (hashfunc
)date_hash
, /* tp_hash */
2700 (reprfunc
)date_str
, /* tp_str */
2701 PyObject_GenericGetAttr
, /* tp_getattro */
2702 0, /* tp_setattro */
2703 0, /* tp_as_buffer */
2704 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
2705 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2706 date_doc
, /* tp_doc */
2707 0, /* tp_traverse */
2709 (richcmpfunc
)date_richcompare
, /* tp_richcompare */
2710 0, /* tp_weaklistoffset */
2712 0, /* tp_iternext */
2713 date_methods
, /* tp_methods */
2715 date_getset
, /* tp_getset */
2718 0, /* tp_descr_get */
2719 0, /* tp_descr_set */
2720 0, /* tp_dictoffset */
2723 date_new
, /* tp_new */
2728 * PyDateTime_TZInfo implementation.
2731 /* This is a pure abstract base class, so doesn't do anything beyond
2732 * raising NotImplemented exceptions. Real tzinfo classes need
2733 * to derive from this. This is mostly for clarity, and for efficiency in
2734 * datetime and time constructors (their tzinfo arguments need to
2735 * be subclasses of this tzinfo class, which is easy and quick to check).
2737 * Note: For reasons having to do with pickling of subclasses, we have
2738 * to allow tzinfo objects to be instantiated. This wasn't an issue
2739 * in the Python implementation (__init__() could raise NotImplementedError
2740 * there without ill effect), but doing so in the C implementation hit a
2745 tzinfo_nogo(const char* methodname
)
2747 PyErr_Format(PyExc_NotImplementedError
,
2748 "a tzinfo subclass must implement %s()",
2753 /* Methods. A subclass must implement these. */
2756 tzinfo_tzname(PyDateTime_TZInfo
*self
, PyObject
*dt
)
2758 return tzinfo_nogo("tzname");
2762 tzinfo_utcoffset(PyDateTime_TZInfo
*self
, PyObject
*dt
)
2764 return tzinfo_nogo("utcoffset");
2768 tzinfo_dst(PyDateTime_TZInfo
*self
, PyObject
*dt
)
2770 return tzinfo_nogo("dst");
2774 tzinfo_fromutc(PyDateTime_TZInfo
*self
, PyDateTime_DateTime
*dt
)
2776 int y
, m
, d
, hh
, mm
, ss
, us
;
2783 if (! PyDateTime_Check(dt
)) {
2784 PyErr_SetString(PyExc_TypeError
,
2785 "fromutc: argument must be a datetime");
2788 if (! HASTZINFO(dt
) || dt
->tzinfo
!= (PyObject
*)self
) {
2789 PyErr_SetString(PyExc_ValueError
, "fromutc: dt.tzinfo "
2794 off
= call_utcoffset(dt
->tzinfo
, (PyObject
*)dt
, &none
);
2795 if (off
== -1 && PyErr_Occurred())
2798 PyErr_SetString(PyExc_ValueError
, "fromutc: non-None "
2799 "utcoffset() result required");
2803 dst
= call_dst(dt
->tzinfo
, (PyObject
*)dt
, &none
);
2804 if (dst
== -1 && PyErr_Occurred())
2807 PyErr_SetString(PyExc_ValueError
, "fromutc: non-None "
2808 "dst() result required");
2815 hh
= DATE_GET_HOUR(dt
);
2816 mm
= DATE_GET_MINUTE(dt
);
2817 ss
= DATE_GET_SECOND(dt
);
2818 us
= DATE_GET_MICROSECOND(dt
);
2822 if ((mm
< 0 || mm
>= 60) &&
2823 normalize_datetime(&y
, &m
, &d
, &hh
, &mm
, &ss
, &us
) < 0)
2825 result
= new_datetime(y
, m
, d
, hh
, mm
, ss
, us
, dt
->tzinfo
);
2829 dst
= call_dst(dt
->tzinfo
, result
, &none
);
2830 if (dst
== -1 && PyErr_Occurred())
2838 if ((mm
< 0 || mm
>= 60) &&
2839 normalize_datetime(&y
, &m
, &d
, &hh
, &mm
, &ss
, &us
) < 0)
2842 result
= new_datetime(y
, m
, d
, hh
, mm
, ss
, us
, dt
->tzinfo
);
2846 PyErr_SetString(PyExc_ValueError
, "fromutc: tz.dst() gave"
2847 "inconsistent results; cannot convert");
2849 /* fall thru to failure */
2856 * Pickle support. This is solely so that tzinfo subclasses can use
2857 * pickling -- tzinfo itself is supposed to be uninstantiable.
2861 tzinfo_reduce(PyObject
*self
)
2863 PyObject
*args
, *state
, *tmp
;
2864 PyObject
*getinitargs
, *getstate
;
2866 tmp
= PyTuple_New(0);
2870 getinitargs
= PyObject_GetAttrString(self
, "__getinitargs__");
2871 if (getinitargs
!= NULL
) {
2872 args
= PyObject_CallObject(getinitargs
, tmp
);
2873 Py_DECREF(getinitargs
);
2885 getstate
= PyObject_GetAttrString(self
, "__getstate__");
2886 if (getstate
!= NULL
) {
2887 state
= PyObject_CallObject(getstate
, tmp
);
2888 Py_DECREF(getstate
);
2889 if (state
== NULL
) {
2899 dictptr
= _PyObject_GetDictPtr(self
);
2900 if (dictptr
&& *dictptr
&& PyDict_Size(*dictptr
))
2907 if (state
== Py_None
) {
2909 return Py_BuildValue("(ON)", Py_TYPE(self
), args
);
2912 return Py_BuildValue("(ONN)", Py_TYPE(self
), args
, state
);
2915 static PyMethodDef tzinfo_methods
[] = {
2917 {"tzname", (PyCFunction
)tzinfo_tzname
, METH_O
,
2918 PyDoc_STR("datetime -> string name of time zone.")},
2920 {"utcoffset", (PyCFunction
)tzinfo_utcoffset
, METH_O
,
2921 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2924 {"dst", (PyCFunction
)tzinfo_dst
, METH_O
,
2925 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2927 {"fromutc", (PyCFunction
)tzinfo_fromutc
, METH_O
,
2928 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2930 {"__reduce__", (PyCFunction
)tzinfo_reduce
, METH_NOARGS
,
2931 PyDoc_STR("-> (cls, state)")},
2936 static char tzinfo_doc
[] =
2937 PyDoc_STR("Abstract base class for time zone info objects.");
2939 statichere PyTypeObject PyDateTime_TZInfoType
= {
2940 PyObject_HEAD_INIT(NULL
)
2942 "datetime.tzinfo", /* tp_name */
2943 sizeof(PyDateTime_TZInfo
), /* tp_basicsize */
2944 0, /* tp_itemsize */
2951 0, /* tp_as_number */
2952 0, /* tp_as_sequence */
2953 0, /* tp_as_mapping */
2957 PyObject_GenericGetAttr
, /* tp_getattro */
2958 0, /* tp_setattro */
2959 0, /* tp_as_buffer */
2960 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
2961 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2962 tzinfo_doc
, /* tp_doc */
2963 0, /* tp_traverse */
2965 0, /* tp_richcompare */
2966 0, /* tp_weaklistoffset */
2968 0, /* tp_iternext */
2969 tzinfo_methods
, /* tp_methods */
2974 0, /* tp_descr_get */
2975 0, /* tp_descr_set */
2976 0, /* tp_dictoffset */
2979 PyType_GenericNew
, /* tp_new */
2984 * PyDateTime_Time implementation.
2987 /* Accessor properties.
2991 time_hour(PyDateTime_Time
*self
, void *unused
)
2993 return PyInt_FromLong(TIME_GET_HOUR(self
));
2997 time_minute(PyDateTime_Time
*self
, void *unused
)
2999 return PyInt_FromLong(TIME_GET_MINUTE(self
));
3002 /* The name time_second conflicted with some platform header file. */
3004 py_time_second(PyDateTime_Time
*self
, void *unused
)
3006 return PyInt_FromLong(TIME_GET_SECOND(self
));
3010 time_microsecond(PyDateTime_Time
*self
, void *unused
)
3012 return PyInt_FromLong(TIME_GET_MICROSECOND(self
));
3016 time_tzinfo(PyDateTime_Time
*self
, void *unused
)
3018 PyObject
*result
= HASTZINFO(self
) ? self
->tzinfo
: Py_None
;
3023 static PyGetSetDef time_getset
[] = {
3024 {"hour", (getter
)time_hour
},
3025 {"minute", (getter
)time_minute
},
3026 {"second", (getter
)py_time_second
},
3027 {"microsecond", (getter
)time_microsecond
},
3028 {"tzinfo", (getter
)time_tzinfo
},
3036 static char *time_kws
[] = {"hour", "minute", "second", "microsecond",
3040 time_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
3042 PyObject
*self
= NULL
;
3048 PyObject
*tzinfo
= Py_None
;
3050 /* Check for invocation from pickle with __getstate__ state */
3051 if (PyTuple_GET_SIZE(args
) >= 1 &&
3052 PyTuple_GET_SIZE(args
) <= 2 &&
3053 PyString_Check(state
= PyTuple_GET_ITEM(args
, 0)) &&
3054 PyString_GET_SIZE(state
) == _PyDateTime_TIME_DATASIZE
&&
3055 ((unsigned char) (PyString_AS_STRING(state
)[0])) < 24)
3057 PyDateTime_Time
*me
;
3060 if (PyTuple_GET_SIZE(args
) == 2) {
3061 tzinfo
= PyTuple_GET_ITEM(args
, 1);
3062 if (check_tzinfo_subclass(tzinfo
) < 0) {
3063 PyErr_SetString(PyExc_TypeError
, "bad "
3064 "tzinfo state arg");
3068 aware
= (char)(tzinfo
!= Py_None
);
3069 me
= (PyDateTime_Time
*) (type
->tp_alloc(type
, aware
));
3071 char *pdata
= PyString_AS_STRING(state
);
3073 memcpy(me
->data
, pdata
, _PyDateTime_TIME_DATASIZE
);
3075 me
->hastzinfo
= aware
;
3078 me
->tzinfo
= tzinfo
;
3081 return (PyObject
*)me
;
3084 if (PyArg_ParseTupleAndKeywords(args
, kw
, "|iiiiO", time_kws
,
3085 &hour
, &minute
, &second
, &usecond
,
3087 if (check_time_args(hour
, minute
, second
, usecond
) < 0)
3089 if (check_tzinfo_subclass(tzinfo
) < 0)
3091 self
= new_time_ex(hour
, minute
, second
, usecond
, tzinfo
,
3102 time_dealloc(PyDateTime_Time
*self
)
3104 if (HASTZINFO(self
)) {
3105 Py_XDECREF(self
->tzinfo
);
3107 Py_TYPE(self
)->tp_free((PyObject
*)self
);
3111 * Indirect access to tzinfo methods.
3114 /* These are all METH_NOARGS, so don't need to check the arglist. */
3116 time_utcoffset(PyDateTime_Time
*self
, PyObject
*unused
) {
3117 return offset_as_timedelta(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3118 "utcoffset", Py_None
);
3122 time_dst(PyDateTime_Time
*self
, PyObject
*unused
) {
3123 return offset_as_timedelta(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3128 time_tzname(PyDateTime_Time
*self
, PyObject
*unused
) {
3129 return call_tzname(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3134 * Various ways to turn a time into a string.
3138 time_repr(PyDateTime_Time
*self
)
3141 const char *type_name
= Py_TYPE(self
)->tp_name
;
3142 int h
= TIME_GET_HOUR(self
);
3143 int m
= TIME_GET_MINUTE(self
);
3144 int s
= TIME_GET_SECOND(self
);
3145 int us
= TIME_GET_MICROSECOND(self
);
3146 PyObject
*result
= NULL
;
3149 PyOS_snprintf(buffer
, sizeof(buffer
),
3150 "%s(%d, %d, %d, %d)", type_name
, h
, m
, s
, us
);
3152 PyOS_snprintf(buffer
, sizeof(buffer
),
3153 "%s(%d, %d, %d)", type_name
, h
, m
, s
);
3155 PyOS_snprintf(buffer
, sizeof(buffer
),
3156 "%s(%d, %d)", type_name
, h
, m
);
3157 result
= PyString_FromString(buffer
);
3158 if (result
!= NULL
&& HASTZINFO(self
))
3159 result
= append_keyword_tzinfo(result
, self
->tzinfo
);
3164 time_str(PyDateTime_Time
*self
)
3166 return PyObject_CallMethod((PyObject
*)self
, "isoformat", "()");
3170 time_isoformat(PyDateTime_Time
*self
, PyObject
*unused
)
3174 /* Reuse the time format code from the datetime type. */
3175 PyDateTime_DateTime datetime
;
3176 PyDateTime_DateTime
*pdatetime
= &datetime
;
3178 /* Copy over just the time bytes. */
3179 memcpy(pdatetime
->data
+ _PyDateTime_DATE_DATASIZE
,
3181 _PyDateTime_TIME_DATASIZE
);
3183 isoformat_time(pdatetime
, buf
, sizeof(buf
));
3184 result
= PyString_FromString(buf
);
3185 if (result
== NULL
|| ! HASTZINFO(self
) || self
->tzinfo
== Py_None
)
3188 /* We need to append the UTC offset. */
3189 if (format_utcoffset(buf
, sizeof(buf
), ":", self
->tzinfo
,
3194 PyString_ConcatAndDel(&result
, PyString_FromString(buf
));
3199 time_strftime(PyDateTime_Time
*self
, PyObject
*args
, PyObject
*kw
)
3204 static char *keywords
[] = {"format", NULL
};
3206 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "O!:strftime", keywords
,
3207 &PyString_Type
, &format
))
3210 /* Python's strftime does insane things with the year part of the
3211 * timetuple. The year is forced to (the otherwise nonsensical)
3212 * 1900 to worm around that.
3214 tuple
= Py_BuildValue("iiiiiiiii",
3215 1900, 1, 1, /* year, month, day */
3216 TIME_GET_HOUR(self
),
3217 TIME_GET_MINUTE(self
),
3218 TIME_GET_SECOND(self
),
3219 0, 1, -1); /* weekday, daynum, dst */
3222 assert(PyTuple_Size(tuple
) == 9);
3223 result
= wrap_strftime((PyObject
*)self
, format
, tuple
, Py_None
);
3229 * Miscellaneous methods.
3232 /* This is more natural as a tp_compare, but doesn't work then: for whatever
3233 * reason, Python's try_3way_compare ignores tp_compare unless
3234 * PyInstance_Check returns true, but these aren't old-style classes.
3237 time_richcompare(PyDateTime_Time
*self
, PyObject
*other
, int op
)
3241 int offset1
, offset2
;
3243 if (! PyTime_Check(other
)) {
3244 if (op
== Py_EQ
|| op
== Py_NE
) {
3245 PyObject
*result
= op
== Py_EQ
? Py_False
: Py_True
;
3249 /* Stop this from falling back to address comparison. */
3250 return cmperror((PyObject
*)self
, other
);
3252 if (classify_two_utcoffsets((PyObject
*)self
, &offset1
, &n1
, Py_None
,
3253 other
, &offset2
, &n2
, Py_None
) < 0)
3255 assert(n1
!= OFFSET_UNKNOWN
&& n2
!= OFFSET_UNKNOWN
);
3256 /* If they're both naive, or both aware and have the same offsets,
3257 * we get off cheap. Note that if they're both naive, offset1 ==
3258 * offset2 == 0 at this point.
3260 if (n1
== n2
&& offset1
== offset2
) {
3261 diff
= memcmp(self
->data
, ((PyDateTime_Time
*)other
)->data
,
3262 _PyDateTime_TIME_DATASIZE
);
3263 return diff_to_bool(diff
, op
);
3266 if (n1
== OFFSET_AWARE
&& n2
== OFFSET_AWARE
) {
3267 assert(offset1
!= offset2
); /* else last "if" handled it */
3268 /* Convert everything except microseconds to seconds. These
3269 * can't overflow (no more than the # of seconds in 2 days).
3271 offset1
= TIME_GET_HOUR(self
) * 3600 +
3272 (TIME_GET_MINUTE(self
) - offset1
) * 60 +
3273 TIME_GET_SECOND(self
);
3274 offset2
= TIME_GET_HOUR(other
) * 3600 +
3275 (TIME_GET_MINUTE(other
) - offset2
) * 60 +
3276 TIME_GET_SECOND(other
);
3277 diff
= offset1
- offset2
;
3279 diff
= TIME_GET_MICROSECOND(self
) -
3280 TIME_GET_MICROSECOND(other
);
3281 return diff_to_bool(diff
, op
);
3285 PyErr_SetString(PyExc_TypeError
,
3286 "can't compare offset-naive and "
3287 "offset-aware times");
3292 time_hash(PyDateTime_Time
*self
)
3294 if (self
->hashcode
== -1) {
3299 n
= classify_utcoffset((PyObject
*)self
, Py_None
, &offset
);
3300 assert(n
!= OFFSET_UNKNOWN
);
3301 if (n
== OFFSET_ERROR
)
3304 /* Reduce this to a hash of another object. */
3306 temp
= PyString_FromStringAndSize((char *)self
->data
,
3307 _PyDateTime_TIME_DATASIZE
);
3312 assert(n
== OFFSET_AWARE
);
3313 assert(HASTZINFO(self
));
3314 hour
= divmod(TIME_GET_HOUR(self
) * 60 +
3315 TIME_GET_MINUTE(self
) - offset
,
3318 if (0 <= hour
&& hour
< 24)
3319 temp
= new_time(hour
, minute
,
3320 TIME_GET_SECOND(self
),
3321 TIME_GET_MICROSECOND(self
),
3324 temp
= Py_BuildValue("iiii",
3326 TIME_GET_SECOND(self
),
3327 TIME_GET_MICROSECOND(self
));
3330 self
->hashcode
= PyObject_Hash(temp
);
3334 return self
->hashcode
;
3338 time_replace(PyDateTime_Time
*self
, PyObject
*args
, PyObject
*kw
)
3342 int hh
= TIME_GET_HOUR(self
);
3343 int mm
= TIME_GET_MINUTE(self
);
3344 int ss
= TIME_GET_SECOND(self
);
3345 int us
= TIME_GET_MICROSECOND(self
);
3346 PyObject
*tzinfo
= HASTZINFO(self
) ? self
->tzinfo
: Py_None
;
3348 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "|iiiiO:replace",
3350 &hh
, &mm
, &ss
, &us
, &tzinfo
))
3352 tuple
= Py_BuildValue("iiiiO", hh
, mm
, ss
, us
, tzinfo
);
3355 clone
= time_new(Py_TYPE(self
), tuple
, NULL
);
3361 time_nonzero(PyDateTime_Time
*self
)
3366 if (TIME_GET_SECOND(self
) || TIME_GET_MICROSECOND(self
)) {
3367 /* Since utcoffset is in whole minutes, nothing can
3368 * alter the conclusion that this is nonzero.
3373 if (HASTZINFO(self
) && self
->tzinfo
!= Py_None
) {
3374 offset
= call_utcoffset(self
->tzinfo
, Py_None
, &none
);
3375 if (offset
== -1 && PyErr_Occurred())
3378 return (TIME_GET_MINUTE(self
) - offset
+ TIME_GET_HOUR(self
)*60) != 0;
3381 /* Pickle support, a simple use of __reduce__. */
3383 /* Let basestate be the non-tzinfo data string.
3384 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3385 * So it's a tuple in any (non-error) case.
3386 * __getstate__ isn't exposed.
3389 time_getstate(PyDateTime_Time
*self
)
3391 PyObject
*basestate
;
3392 PyObject
*result
= NULL
;
3394 basestate
= PyString_FromStringAndSize((char *)self
->data
,
3395 _PyDateTime_TIME_DATASIZE
);
3396 if (basestate
!= NULL
) {
3397 if (! HASTZINFO(self
) || self
->tzinfo
== Py_None
)
3398 result
= PyTuple_Pack(1, basestate
);
3400 result
= PyTuple_Pack(2, basestate
, self
->tzinfo
);
3401 Py_DECREF(basestate
);
3407 time_reduce(PyDateTime_Time
*self
, PyObject
*arg
)
3409 return Py_BuildValue("(ON)", Py_TYPE(self
), time_getstate(self
));
3412 static PyMethodDef time_methods
[] = {
3414 {"isoformat", (PyCFunction
)time_isoformat
, METH_NOARGS
,
3415 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3418 {"strftime", (PyCFunction
)time_strftime
, METH_VARARGS
| METH_KEYWORDS
,
3419 PyDoc_STR("format -> strftime() style string.")},
3421 {"utcoffset", (PyCFunction
)time_utcoffset
, METH_NOARGS
,
3422 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3424 {"tzname", (PyCFunction
)time_tzname
, METH_NOARGS
,
3425 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3427 {"dst", (PyCFunction
)time_dst
, METH_NOARGS
,
3428 PyDoc_STR("Return self.tzinfo.dst(self).")},
3430 {"replace", (PyCFunction
)time_replace
, METH_VARARGS
| METH_KEYWORDS
,
3431 PyDoc_STR("Return time with new specified fields.")},
3433 {"__reduce__", (PyCFunction
)time_reduce
, METH_NOARGS
,
3434 PyDoc_STR("__reduce__() -> (cls, state)")},
3439 static char time_doc
[] =
3440 PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3442 All arguments are optional. tzinfo may be None, or an instance of\n\
3443 a tzinfo subclass. The remaining arguments may be ints or longs.\n");
3445 static PyNumberMethods time_as_number
= {
3447 0, /* nb_subtract */
3448 0, /* nb_multiply */
3450 0, /* nb_remainder */
3453 0, /* nb_negative */
3454 0, /* nb_positive */
3455 0, /* nb_absolute */
3456 (inquiry
)time_nonzero
, /* nb_nonzero */
3459 statichere PyTypeObject PyDateTime_TimeType
= {
3460 PyObject_HEAD_INIT(NULL
)
3462 "datetime.time", /* tp_name */
3463 sizeof(PyDateTime_Time
), /* tp_basicsize */
3464 0, /* tp_itemsize */
3465 (destructor
)time_dealloc
, /* tp_dealloc */
3470 (reprfunc
)time_repr
, /* tp_repr */
3471 &time_as_number
, /* tp_as_number */
3472 0, /* tp_as_sequence */
3473 0, /* tp_as_mapping */
3474 (hashfunc
)time_hash
, /* tp_hash */
3476 (reprfunc
)time_str
, /* tp_str */
3477 PyObject_GenericGetAttr
, /* tp_getattro */
3478 0, /* tp_setattro */
3479 0, /* tp_as_buffer */
3480 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
3481 Py_TPFLAGS_BASETYPE
, /* tp_flags */
3482 time_doc
, /* tp_doc */
3483 0, /* tp_traverse */
3485 (richcmpfunc
)time_richcompare
, /* tp_richcompare */
3486 0, /* tp_weaklistoffset */
3488 0, /* tp_iternext */
3489 time_methods
, /* tp_methods */
3491 time_getset
, /* tp_getset */
3494 0, /* tp_descr_get */
3495 0, /* tp_descr_set */
3496 0, /* tp_dictoffset */
3498 time_alloc
, /* tp_alloc */
3499 time_new
, /* tp_new */
3504 * PyDateTime_DateTime implementation.
3507 /* Accessor properties. Properties for day, month, and year are inherited
3512 datetime_hour(PyDateTime_DateTime
*self
, void *unused
)
3514 return PyInt_FromLong(DATE_GET_HOUR(self
));
3518 datetime_minute(PyDateTime_DateTime
*self
, void *unused
)
3520 return PyInt_FromLong(DATE_GET_MINUTE(self
));
3524 datetime_second(PyDateTime_DateTime
*self
, void *unused
)
3526 return PyInt_FromLong(DATE_GET_SECOND(self
));
3530 datetime_microsecond(PyDateTime_DateTime
*self
, void *unused
)
3532 return PyInt_FromLong(DATE_GET_MICROSECOND(self
));
3536 datetime_tzinfo(PyDateTime_DateTime
*self
, void *unused
)
3538 PyObject
*result
= HASTZINFO(self
) ? self
->tzinfo
: Py_None
;
3543 static PyGetSetDef datetime_getset
[] = {
3544 {"hour", (getter
)datetime_hour
},
3545 {"minute", (getter
)datetime_minute
},
3546 {"second", (getter
)datetime_second
},
3547 {"microsecond", (getter
)datetime_microsecond
},
3548 {"tzinfo", (getter
)datetime_tzinfo
},
3556 static char *datetime_kws
[] = {
3557 "year", "month", "day", "hour", "minute", "second",
3558 "microsecond", "tzinfo", NULL
3562 datetime_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
3564 PyObject
*self
= NULL
;
3573 PyObject
*tzinfo
= Py_None
;
3575 /* Check for invocation from pickle with __getstate__ state */
3576 if (PyTuple_GET_SIZE(args
) >= 1 &&
3577 PyTuple_GET_SIZE(args
) <= 2 &&
3578 PyString_Check(state
= PyTuple_GET_ITEM(args
, 0)) &&
3579 PyString_GET_SIZE(state
) == _PyDateTime_DATETIME_DATASIZE
&&
3580 MONTH_IS_SANE(PyString_AS_STRING(state
)[2]))
3582 PyDateTime_DateTime
*me
;
3585 if (PyTuple_GET_SIZE(args
) == 2) {
3586 tzinfo
= PyTuple_GET_ITEM(args
, 1);
3587 if (check_tzinfo_subclass(tzinfo
) < 0) {
3588 PyErr_SetString(PyExc_TypeError
, "bad "
3589 "tzinfo state arg");
3593 aware
= (char)(tzinfo
!= Py_None
);
3594 me
= (PyDateTime_DateTime
*) (type
->tp_alloc(type
, aware
));
3596 char *pdata
= PyString_AS_STRING(state
);
3598 memcpy(me
->data
, pdata
, _PyDateTime_DATETIME_DATASIZE
);
3600 me
->hastzinfo
= aware
;
3603 me
->tzinfo
= tzinfo
;
3606 return (PyObject
*)me
;
3609 if (PyArg_ParseTupleAndKeywords(args
, kw
, "iii|iiiiO", datetime_kws
,
3610 &year
, &month
, &day
, &hour
, &minute
,
3611 &second
, &usecond
, &tzinfo
)) {
3612 if (check_date_args(year
, month
, day
) < 0)
3614 if (check_time_args(hour
, minute
, second
, usecond
) < 0)
3616 if (check_tzinfo_subclass(tzinfo
) < 0)
3618 self
= new_datetime_ex(year
, month
, day
,
3619 hour
, minute
, second
, usecond
,
3625 /* TM_FUNC is the shared type of localtime() and gmtime(). */
3626 typedef struct tm
*(*TM_FUNC
)(const time_t *timer
);
3629 * Build datetime from a time_t and a distinct count of microseconds.
3630 * Pass localtime or gmtime for f, to control the interpretation of timet.
3633 datetime_from_timet_and_us(PyObject
*cls
, TM_FUNC f
, time_t timet
, int us
,
3637 PyObject
*result
= NULL
;
3641 /* The platform localtime/gmtime may insert leap seconds,
3642 * indicated by tm->tm_sec > 59. We don't care about them,
3643 * except to the extent that passing them on to the datetime
3644 * constructor would raise ValueError for a reason that
3645 * made no sense to the user.
3647 if (tm
->tm_sec
> 59)
3649 result
= PyObject_CallFunction(cls
, "iiiiiiiO",
3660 PyErr_SetString(PyExc_ValueError
,
3661 "timestamp out of range for "
3662 "platform localtime()/gmtime() function");
3667 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3668 * to control the interpretation of the timestamp. Since a double doesn't
3669 * have enough bits to cover a datetime's full range of precision, it's
3670 * better to call datetime_from_timet_and_us provided you have a way
3671 * to get that much precision (e.g., C time() isn't good enough).
3674 datetime_from_timestamp(PyObject
*cls
, TM_FUNC f
, double timestamp
,
3681 timet
= _PyTime_DoubleToTimet(timestamp
);
3682 if (timet
== (time_t)-1 && PyErr_Occurred())
3684 fraction
= timestamp
- (double)timet
;
3685 us
= (int)round_to_long(fraction
* 1e6
);
3687 /* Truncation towards zero is not what we wanted
3688 for negative numbers (Python's mod semantics) */
3692 /* If timestamp is less than one microsecond smaller than a
3693 * full second, round up. Otherwise, ValueErrors are raised
3694 * for some floats. */
3695 if (us
== 1000000) {
3699 return datetime_from_timet_and_us(cls
, f
, timet
, us
, tzinfo
);
3703 * Build most accurate possible datetime for current time. Pass localtime or
3704 * gmtime for f as appropriate.
3707 datetime_best_possible(PyObject
*cls
, TM_FUNC f
, PyObject
*tzinfo
)
3709 #ifdef HAVE_GETTIMEOFDAY
3712 #ifdef GETTIMEOFDAY_NO_TZ
3715 gettimeofday(&t
, (struct timezone
*)NULL
);
3717 return datetime_from_timet_and_us(cls
, f
, t
.tv_sec
, (int)t
.tv_usec
,
3720 #else /* ! HAVE_GETTIMEOFDAY */
3721 /* No flavor of gettimeofday exists on this platform. Python's
3722 * time.time() does a lot of other platform tricks to get the
3723 * best time it can on the platform, and we're not going to do
3724 * better than that (if we could, the better code would belong
3725 * in time.time()!) We're limited by the precision of a double,
3734 dtime
= PyFloat_AsDouble(time
);
3736 if (dtime
== -1.0 && PyErr_Occurred())
3738 return datetime_from_timestamp(cls
, f
, dtime
, tzinfo
);
3739 #endif /* ! HAVE_GETTIMEOFDAY */
3742 /* Return best possible local time -- this isn't constrained by the
3743 * precision of a timestamp.
3746 datetime_now(PyObject
*cls
, PyObject
*args
, PyObject
*kw
)
3749 PyObject
*tzinfo
= Py_None
;
3750 static char *keywords
[] = {"tz", NULL
};
3752 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "|O:now", keywords
,
3755 if (check_tzinfo_subclass(tzinfo
) < 0)
3758 self
= datetime_best_possible(cls
,
3759 tzinfo
== Py_None
? localtime
: gmtime
,
3761 if (self
!= NULL
&& tzinfo
!= Py_None
) {
3762 /* Convert UTC to tzinfo's zone. */
3763 PyObject
*temp
= self
;
3764 self
= PyObject_CallMethod(tzinfo
, "fromutc", "O", self
);
3770 /* Return best possible UTC time -- this isn't constrained by the
3771 * precision of a timestamp.
3774 datetime_utcnow(PyObject
*cls
, PyObject
*dummy
)
3776 return datetime_best_possible(cls
, gmtime
, Py_None
);
3779 /* Return new local datetime from timestamp (Python timestamp -- a double). */
3781 datetime_fromtimestamp(PyObject
*cls
, PyObject
*args
, PyObject
*kw
)
3785 PyObject
*tzinfo
= Py_None
;
3786 static char *keywords
[] = {"timestamp", "tz", NULL
};
3788 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "d|O:fromtimestamp",
3789 keywords
, ×tamp
, &tzinfo
))
3791 if (check_tzinfo_subclass(tzinfo
) < 0)
3794 self
= datetime_from_timestamp(cls
,
3795 tzinfo
== Py_None
? localtime
: gmtime
,
3798 if (self
!= NULL
&& tzinfo
!= Py_None
) {
3799 /* Convert UTC to tzinfo's zone. */
3800 PyObject
*temp
= self
;
3801 self
= PyObject_CallMethod(tzinfo
, "fromutc", "O", self
);
3807 /* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3809 datetime_utcfromtimestamp(PyObject
*cls
, PyObject
*args
)
3812 PyObject
*result
= NULL
;
3814 if (PyArg_ParseTuple(args
, "d:utcfromtimestamp", ×tamp
))
3815 result
= datetime_from_timestamp(cls
, gmtime
, timestamp
,
3820 /* Return new datetime from time.strptime(). */
3822 datetime_strptime(PyObject
*cls
, PyObject
*args
)
3824 PyObject
*result
= NULL
, *obj
, *module
;
3825 const char *string
, *format
;
3827 if (!PyArg_ParseTuple(args
, "ss:strptime", &string
, &format
))
3830 if ((module
= PyImport_ImportModuleNoBlock("time")) == NULL
)
3832 obj
= PyObject_CallMethod(module
, "strptime", "ss", string
, format
);
3836 int i
, good_timetuple
= 1;
3838 if (PySequence_Check(obj
) && PySequence_Size(obj
) >= 6)
3839 for (i
=0; i
< 6; i
++) {
3840 PyObject
*p
= PySequence_GetItem(obj
, i
);
3846 ia
[i
] = PyInt_AsLong(p
);
3854 result
= PyObject_CallFunction(cls
, "iiiiii",
3855 ia
[0], ia
[1], ia
[2], ia
[3], ia
[4], ia
[5]);
3857 PyErr_SetString(PyExc_ValueError
,
3858 "unexpected value from time.strptime");
3864 /* Return new datetime from date/datetime and time arguments. */
3866 datetime_combine(PyObject
*cls
, PyObject
*args
, PyObject
*kw
)
3868 static char *keywords
[] = {"date", "time", NULL
};
3871 PyObject
*result
= NULL
;
3873 if (PyArg_ParseTupleAndKeywords(args
, kw
, "O!O!:combine", keywords
,
3874 &PyDateTime_DateType
, &date
,
3875 &PyDateTime_TimeType
, &time
)) {
3876 PyObject
*tzinfo
= Py_None
;
3878 if (HASTZINFO(time
))
3879 tzinfo
= ((PyDateTime_Time
*)time
)->tzinfo
;
3880 result
= PyObject_CallFunction(cls
, "iiiiiiiO",
3884 TIME_GET_HOUR(time
),
3885 TIME_GET_MINUTE(time
),
3886 TIME_GET_SECOND(time
),
3887 TIME_GET_MICROSECOND(time
),
3898 datetime_dealloc(PyDateTime_DateTime
*self
)
3900 if (HASTZINFO(self
)) {
3901 Py_XDECREF(self
->tzinfo
);
3903 Py_TYPE(self
)->tp_free((PyObject
*)self
);
3907 * Indirect access to tzinfo methods.
3910 /* These are all METH_NOARGS, so don't need to check the arglist. */
3912 datetime_utcoffset(PyDateTime_DateTime
*self
, PyObject
*unused
) {
3913 return offset_as_timedelta(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3914 "utcoffset", (PyObject
*)self
);
3918 datetime_dst(PyDateTime_DateTime
*self
, PyObject
*unused
) {
3919 return offset_as_timedelta(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3920 "dst", (PyObject
*)self
);
3924 datetime_tzname(PyDateTime_DateTime
*self
, PyObject
*unused
) {
3925 return call_tzname(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3930 * datetime arithmetic.
3933 /* factor must be 1 (to add) or -1 (to subtract). The result inherits
3934 * the tzinfo state of date.
3937 add_datetime_timedelta(PyDateTime_DateTime
*date
, PyDateTime_Delta
*delta
,
3940 /* Note that the C-level additions can't overflow, because of
3941 * invariant bounds on the member values.
3943 int year
= GET_YEAR(date
);
3944 int month
= GET_MONTH(date
);
3945 int day
= GET_DAY(date
) + GET_TD_DAYS(delta
) * factor
;
3946 int hour
= DATE_GET_HOUR(date
);
3947 int minute
= DATE_GET_MINUTE(date
);
3948 int second
= DATE_GET_SECOND(date
) + GET_TD_SECONDS(delta
) * factor
;
3949 int microsecond
= DATE_GET_MICROSECOND(date
) +
3950 GET_TD_MICROSECONDS(delta
) * factor
;
3952 assert(factor
== 1 || factor
== -1);
3953 if (normalize_datetime(&year
, &month
, &day
,
3954 &hour
, &minute
, &second
, µsecond
) < 0)
3957 return new_datetime(year
, month
, day
,
3958 hour
, minute
, second
, microsecond
,
3959 HASTZINFO(date
) ? date
->tzinfo
: Py_None
);
3963 datetime_add(PyObject
*left
, PyObject
*right
)
3965 if (PyDateTime_Check(left
)) {
3966 /* datetime + ??? */
3967 if (PyDelta_Check(right
))
3968 /* datetime + delta */
3969 return add_datetime_timedelta(
3970 (PyDateTime_DateTime
*)left
,
3971 (PyDateTime_Delta
*)right
,
3974 else if (PyDelta_Check(left
)) {
3975 /* delta + datetime */
3976 return add_datetime_timedelta((PyDateTime_DateTime
*) right
,
3977 (PyDateTime_Delta
*) left
,
3980 Py_INCREF(Py_NotImplemented
);
3981 return Py_NotImplemented
;
3985 datetime_subtract(PyObject
*left
, PyObject
*right
)
3987 PyObject
*result
= Py_NotImplemented
;
3989 if (PyDateTime_Check(left
)) {
3990 /* datetime - ??? */
3991 if (PyDateTime_Check(right
)) {
3992 /* datetime - datetime */
3994 int offset1
, offset2
;
3995 int delta_d
, delta_s
, delta_us
;
3997 if (classify_two_utcoffsets(left
, &offset1
, &n1
, left
,
3998 right
, &offset2
, &n2
,
4001 assert(n1
!= OFFSET_UNKNOWN
&& n2
!= OFFSET_UNKNOWN
);
4003 PyErr_SetString(PyExc_TypeError
,
4004 "can't subtract offset-naive and "
4005 "offset-aware datetimes");
4008 delta_d
= ymd_to_ord(GET_YEAR(left
),
4011 ymd_to_ord(GET_YEAR(right
),
4014 /* These can't overflow, since the values are
4015 * normalized. At most this gives the number of
4016 * seconds in one day.
4018 delta_s
= (DATE_GET_HOUR(left
) -
4019 DATE_GET_HOUR(right
)) * 3600 +
4020 (DATE_GET_MINUTE(left
) -
4021 DATE_GET_MINUTE(right
)) * 60 +
4022 (DATE_GET_SECOND(left
) -
4023 DATE_GET_SECOND(right
));
4024 delta_us
= DATE_GET_MICROSECOND(left
) -
4025 DATE_GET_MICROSECOND(right
);
4026 /* (left - offset1) - (right - offset2) =
4027 * (left - right) + (offset2 - offset1)
4029 delta_s
+= (offset2
- offset1
) * 60;
4030 result
= new_delta(delta_d
, delta_s
, delta_us
, 1);
4032 else if (PyDelta_Check(right
)) {
4033 /* datetime - delta */
4034 result
= add_datetime_timedelta(
4035 (PyDateTime_DateTime
*)left
,
4036 (PyDateTime_Delta
*)right
,
4041 if (result
== Py_NotImplemented
)
4046 /* Various ways to turn a datetime into a string. */
4049 datetime_repr(PyDateTime_DateTime
*self
)
4052 const char *type_name
= Py_TYPE(self
)->tp_name
;
4055 if (DATE_GET_MICROSECOND(self
)) {
4056 PyOS_snprintf(buffer
, sizeof(buffer
),
4057 "%s(%d, %d, %d, %d, %d, %d, %d)",
4059 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
),
4060 DATE_GET_HOUR(self
), DATE_GET_MINUTE(self
),
4061 DATE_GET_SECOND(self
),
4062 DATE_GET_MICROSECOND(self
));
4064 else if (DATE_GET_SECOND(self
)) {
4065 PyOS_snprintf(buffer
, sizeof(buffer
),
4066 "%s(%d, %d, %d, %d, %d, %d)",
4068 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
),
4069 DATE_GET_HOUR(self
), DATE_GET_MINUTE(self
),
4070 DATE_GET_SECOND(self
));
4073 PyOS_snprintf(buffer
, sizeof(buffer
),
4074 "%s(%d, %d, %d, %d, %d)",
4076 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
),
4077 DATE_GET_HOUR(self
), DATE_GET_MINUTE(self
));
4079 baserepr
= PyString_FromString(buffer
);
4080 if (baserepr
== NULL
|| ! HASTZINFO(self
))
4082 return append_keyword_tzinfo(baserepr
, self
->tzinfo
);
4086 datetime_str(PyDateTime_DateTime
*self
)
4088 return PyObject_CallMethod((PyObject
*)self
, "isoformat", "(s)", " ");
4092 datetime_isoformat(PyDateTime_DateTime
*self
, PyObject
*args
, PyObject
*kw
)
4095 static char *keywords
[] = {"sep", NULL
};
4100 if (!PyArg_ParseTupleAndKeywords(args
, kw
, "|c:isoformat", keywords
,
4103 cp
= isoformat_date((PyDateTime_Date
*)self
, buffer
, sizeof(buffer
));
4106 isoformat_time(self
, cp
, sizeof(buffer
) - (cp
- buffer
));
4107 result
= PyString_FromString(buffer
);
4108 if (result
== NULL
|| ! HASTZINFO(self
))
4111 /* We need to append the UTC offset. */
4112 if (format_utcoffset(buffer
, sizeof(buffer
), ":", self
->tzinfo
,
4113 (PyObject
*)self
) < 0) {
4117 PyString_ConcatAndDel(&result
, PyString_FromString(buffer
));
4122 datetime_ctime(PyDateTime_DateTime
*self
)
4124 return format_ctime((PyDateTime_Date
*)self
,
4125 DATE_GET_HOUR(self
),
4126 DATE_GET_MINUTE(self
),
4127 DATE_GET_SECOND(self
));
4130 /* Miscellaneous methods. */
4132 /* This is more natural as a tp_compare, but doesn't work then: for whatever
4133 * reason, Python's try_3way_compare ignores tp_compare unless
4134 * PyInstance_Check returns true, but these aren't old-style classes.
4137 datetime_richcompare(PyDateTime_DateTime
*self
, PyObject
*other
, int op
)
4141 int offset1
, offset2
;
4143 if (! PyDateTime_Check(other
)) {
4144 /* If other has a "timetuple" attr, that's an advertised
4145 * hook for other classes to ask to get comparison control.
4146 * However, date instances have a timetuple attr, and we
4147 * don't want to allow that comparison. Because datetime
4148 * is a subclass of date, when mixing date and datetime
4149 * in a comparison, Python gives datetime the first shot
4150 * (it's the more specific subtype). So we can stop that
4151 * combination here reliably.
4153 if (PyObject_HasAttrString(other
, "timetuple") &&
4154 ! PyDate_Check(other
)) {
4155 /* A hook for other kinds of datetime objects. */
4156 Py_INCREF(Py_NotImplemented
);
4157 return Py_NotImplemented
;
4159 if (op
== Py_EQ
|| op
== Py_NE
) {
4160 PyObject
*result
= op
== Py_EQ
? Py_False
: Py_True
;
4164 /* Stop this from falling back to address comparison. */
4165 return cmperror((PyObject
*)self
, other
);
4168 if (classify_two_utcoffsets((PyObject
*)self
, &offset1
, &n1
,
4170 other
, &offset2
, &n2
,
4173 assert(n1
!= OFFSET_UNKNOWN
&& n2
!= OFFSET_UNKNOWN
);
4174 /* If they're both naive, or both aware and have the same offsets,
4175 * we get off cheap. Note that if they're both naive, offset1 ==
4176 * offset2 == 0 at this point.
4178 if (n1
== n2
&& offset1
== offset2
) {
4179 diff
= memcmp(self
->data
, ((PyDateTime_DateTime
*)other
)->data
,
4180 _PyDateTime_DATETIME_DATASIZE
);
4181 return diff_to_bool(diff
, op
);
4184 if (n1
== OFFSET_AWARE
&& n2
== OFFSET_AWARE
) {
4185 PyDateTime_Delta
*delta
;
4187 assert(offset1
!= offset2
); /* else last "if" handled it */
4188 delta
= (PyDateTime_Delta
*)datetime_subtract((PyObject
*)self
,
4192 diff
= GET_TD_DAYS(delta
);
4194 diff
= GET_TD_SECONDS(delta
) |
4195 GET_TD_MICROSECONDS(delta
);
4197 return diff_to_bool(diff
, op
);
4201 PyErr_SetString(PyExc_TypeError
,
4202 "can't compare offset-naive and "
4203 "offset-aware datetimes");
4208 datetime_hash(PyDateTime_DateTime
*self
)
4210 if (self
->hashcode
== -1) {
4215 n
= classify_utcoffset((PyObject
*)self
, (PyObject
*)self
,
4217 assert(n
!= OFFSET_UNKNOWN
);
4218 if (n
== OFFSET_ERROR
)
4221 /* Reduce this to a hash of another object. */
4222 if (n
== OFFSET_NAIVE
)
4223 temp
= PyString_FromStringAndSize(
4225 _PyDateTime_DATETIME_DATASIZE
);
4230 assert(n
== OFFSET_AWARE
);
4231 assert(HASTZINFO(self
));
4232 days
= ymd_to_ord(GET_YEAR(self
),
4235 seconds
= DATE_GET_HOUR(self
) * 3600 +
4236 (DATE_GET_MINUTE(self
) - offset
) * 60 +
4237 DATE_GET_SECOND(self
);
4238 temp
= new_delta(days
,
4240 DATE_GET_MICROSECOND(self
),
4244 self
->hashcode
= PyObject_Hash(temp
);
4248 return self
->hashcode
;
4252 datetime_replace(PyDateTime_DateTime
*self
, PyObject
*args
, PyObject
*kw
)
4256 int y
= GET_YEAR(self
);
4257 int m
= GET_MONTH(self
);
4258 int d
= GET_DAY(self
);
4259 int hh
= DATE_GET_HOUR(self
);
4260 int mm
= DATE_GET_MINUTE(self
);
4261 int ss
= DATE_GET_SECOND(self
);
4262 int us
= DATE_GET_MICROSECOND(self
);
4263 PyObject
*tzinfo
= HASTZINFO(self
) ? self
->tzinfo
: Py_None
;
4265 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "|iiiiiiiO:replace",
4267 &y
, &m
, &d
, &hh
, &mm
, &ss
, &us
,
4270 tuple
= Py_BuildValue("iiiiiiiO", y
, m
, d
, hh
, mm
, ss
, us
, tzinfo
);
4273 clone
= datetime_new(Py_TYPE(self
), tuple
, NULL
);
4279 datetime_astimezone(PyDateTime_DateTime
*self
, PyObject
*args
, PyObject
*kw
)
4281 int y
, m
, d
, hh
, mm
, ss
, us
;
4286 static char *keywords
[] = {"tz", NULL
};
4288 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "O!:astimezone", keywords
,
4289 &PyDateTime_TZInfoType
, &tzinfo
))
4292 if (!HASTZINFO(self
) || self
->tzinfo
== Py_None
)
4295 /* Conversion to self's own time zone is a NOP. */
4296 if (self
->tzinfo
== tzinfo
) {
4298 return (PyObject
*)self
;
4301 /* Convert self to UTC. */
4302 offset
= call_utcoffset(self
->tzinfo
, (PyObject
*)self
, &none
);
4303 if (offset
== -1 && PyErr_Occurred())
4309 m
= GET_MONTH(self
);
4311 hh
= DATE_GET_HOUR(self
);
4312 mm
= DATE_GET_MINUTE(self
);
4313 ss
= DATE_GET_SECOND(self
);
4314 us
= DATE_GET_MICROSECOND(self
);
4317 if ((mm
< 0 || mm
>= 60) &&
4318 normalize_datetime(&y
, &m
, &d
, &hh
, &mm
, &ss
, &us
) < 0)
4321 /* Attach new tzinfo and let fromutc() do the rest. */
4322 result
= new_datetime(y
, m
, d
, hh
, mm
, ss
, us
, tzinfo
);
4323 if (result
!= NULL
) {
4324 PyObject
*temp
= result
;
4326 result
= PyObject_CallMethod(tzinfo
, "fromutc", "O", temp
);
4332 PyErr_SetString(PyExc_ValueError
, "astimezone() cannot be applied to "
4333 "a naive datetime");
4338 datetime_timetuple(PyDateTime_DateTime
*self
)
4342 if (HASTZINFO(self
) && self
->tzinfo
!= Py_None
) {
4345 dstflag
= call_dst(self
->tzinfo
, (PyObject
*)self
, &none
);
4346 if (dstflag
== -1 && PyErr_Occurred())
4351 else if (dstflag
!= 0)
4355 return build_struct_time(GET_YEAR(self
),
4358 DATE_GET_HOUR(self
),
4359 DATE_GET_MINUTE(self
),
4360 DATE_GET_SECOND(self
),
4365 datetime_getdate(PyDateTime_DateTime
*self
)
4367 return new_date(GET_YEAR(self
),
4373 datetime_gettime(PyDateTime_DateTime
*self
)
4375 return new_time(DATE_GET_HOUR(self
),
4376 DATE_GET_MINUTE(self
),
4377 DATE_GET_SECOND(self
),
4378 DATE_GET_MICROSECOND(self
),
4383 datetime_gettimetz(PyDateTime_DateTime
*self
)
4385 return new_time(DATE_GET_HOUR(self
),
4386 DATE_GET_MINUTE(self
),
4387 DATE_GET_SECOND(self
),
4388 DATE_GET_MICROSECOND(self
),
4389 HASTZINFO(self
) ? self
->tzinfo
: Py_None
);
4393 datetime_utctimetuple(PyDateTime_DateTime
*self
)
4395 int y
= GET_YEAR(self
);
4396 int m
= GET_MONTH(self
);
4397 int d
= GET_DAY(self
);
4398 int hh
= DATE_GET_HOUR(self
);
4399 int mm
= DATE_GET_MINUTE(self
);
4400 int ss
= DATE_GET_SECOND(self
);
4401 int us
= 0; /* microseconds are ignored in a timetuple */
4404 if (HASTZINFO(self
) && self
->tzinfo
!= Py_None
) {
4407 offset
= call_utcoffset(self
->tzinfo
, (PyObject
*)self
, &none
);
4408 if (offset
== -1 && PyErr_Occurred())
4411 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4412 * 0 in a UTC timetuple regardless of what dst() says.
4415 /* Subtract offset minutes & normalize. */
4419 stat
= normalize_datetime(&y
, &m
, &d
, &hh
, &mm
, &ss
, &us
);
4421 /* At the edges, it's possible we overflowed
4422 * beyond MINYEAR or MAXYEAR.
4424 if (PyErr_ExceptionMatches(PyExc_OverflowError
))
4430 return build_struct_time(y
, m
, d
, hh
, mm
, ss
, 0);
4433 /* Pickle support, a simple use of __reduce__. */
4435 /* Let basestate be the non-tzinfo data string.
4436 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4437 * So it's a tuple in any (non-error) case.
4438 * __getstate__ isn't exposed.
4441 datetime_getstate(PyDateTime_DateTime
*self
)
4443 PyObject
*basestate
;
4444 PyObject
*result
= NULL
;
4446 basestate
= PyString_FromStringAndSize((char *)self
->data
,
4447 _PyDateTime_DATETIME_DATASIZE
);
4448 if (basestate
!= NULL
) {
4449 if (! HASTZINFO(self
) || self
->tzinfo
== Py_None
)
4450 result
= PyTuple_Pack(1, basestate
);
4452 result
= PyTuple_Pack(2, basestate
, self
->tzinfo
);
4453 Py_DECREF(basestate
);
4459 datetime_reduce(PyDateTime_DateTime
*self
, PyObject
*arg
)
4461 return Py_BuildValue("(ON)", Py_TYPE(self
), datetime_getstate(self
));
4464 static PyMethodDef datetime_methods
[] = {
4466 /* Class methods: */
4468 {"now", (PyCFunction
)datetime_now
,
4469 METH_VARARGS
| METH_KEYWORDS
| METH_CLASS
,
4470 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
4472 {"utcnow", (PyCFunction
)datetime_utcnow
,
4473 METH_NOARGS
| METH_CLASS
,
4474 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4476 {"fromtimestamp", (PyCFunction
)datetime_fromtimestamp
,
4477 METH_VARARGS
| METH_KEYWORDS
| METH_CLASS
,
4478 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
4480 {"utcfromtimestamp", (PyCFunction
)datetime_utcfromtimestamp
,
4481 METH_VARARGS
| METH_CLASS
,
4482 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4483 "(like time.time()).")},
4485 {"strptime", (PyCFunction
)datetime_strptime
,
4486 METH_VARARGS
| METH_CLASS
,
4487 PyDoc_STR("string, format -> new datetime parsed from a string "
4488 "(like time.strptime()).")},
4490 {"combine", (PyCFunction
)datetime_combine
,
4491 METH_VARARGS
| METH_KEYWORDS
| METH_CLASS
,
4492 PyDoc_STR("date, time -> datetime with same date and time fields")},
4494 /* Instance methods: */
4496 {"date", (PyCFunction
)datetime_getdate
, METH_NOARGS
,
4497 PyDoc_STR("Return date object with same year, month and day.")},
4499 {"time", (PyCFunction
)datetime_gettime
, METH_NOARGS
,
4500 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4502 {"timetz", (PyCFunction
)datetime_gettimetz
, METH_NOARGS
,
4503 PyDoc_STR("Return time object with same time and tzinfo.")},
4505 {"ctime", (PyCFunction
)datetime_ctime
, METH_NOARGS
,
4506 PyDoc_STR("Return ctime() style string.")},
4508 {"timetuple", (PyCFunction
)datetime_timetuple
, METH_NOARGS
,
4509 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4511 {"utctimetuple", (PyCFunction
)datetime_utctimetuple
, METH_NOARGS
,
4512 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4514 {"isoformat", (PyCFunction
)datetime_isoformat
, METH_VARARGS
| METH_KEYWORDS
,
4515 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4516 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4517 "sep is used to separate the year from the time, and "
4518 "defaults to 'T'.")},
4520 {"utcoffset", (PyCFunction
)datetime_utcoffset
, METH_NOARGS
,
4521 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4523 {"tzname", (PyCFunction
)datetime_tzname
, METH_NOARGS
,
4524 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4526 {"dst", (PyCFunction
)datetime_dst
, METH_NOARGS
,
4527 PyDoc_STR("Return self.tzinfo.dst(self).")},
4529 {"replace", (PyCFunction
)datetime_replace
, METH_VARARGS
| METH_KEYWORDS
,
4530 PyDoc_STR("Return datetime with new specified fields.")},
4532 {"astimezone", (PyCFunction
)datetime_astimezone
, METH_VARARGS
| METH_KEYWORDS
,
4533 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4535 {"__reduce__", (PyCFunction
)datetime_reduce
, METH_NOARGS
,
4536 PyDoc_STR("__reduce__() -> (cls, state)")},
4541 static char datetime_doc
[] =
4542 PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4544 The year, month and day arguments are required. tzinfo may be None, or an\n\
4545 instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
4547 static PyNumberMethods datetime_as_number
= {
4548 datetime_add
, /* nb_add */
4549 datetime_subtract
, /* nb_subtract */
4550 0, /* nb_multiply */
4552 0, /* nb_remainder */
4555 0, /* nb_negative */
4556 0, /* nb_positive */
4557 0, /* nb_absolute */
4561 statichere PyTypeObject PyDateTime_DateTimeType
= {
4562 PyObject_HEAD_INIT(NULL
)
4564 "datetime.datetime", /* tp_name */
4565 sizeof(PyDateTime_DateTime
), /* tp_basicsize */
4566 0, /* tp_itemsize */
4567 (destructor
)datetime_dealloc
, /* tp_dealloc */
4572 (reprfunc
)datetime_repr
, /* tp_repr */
4573 &datetime_as_number
, /* tp_as_number */
4574 0, /* tp_as_sequence */
4575 0, /* tp_as_mapping */
4576 (hashfunc
)datetime_hash
, /* tp_hash */
4578 (reprfunc
)datetime_str
, /* tp_str */
4579 PyObject_GenericGetAttr
, /* tp_getattro */
4580 0, /* tp_setattro */
4581 0, /* tp_as_buffer */
4582 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
4583 Py_TPFLAGS_BASETYPE
, /* tp_flags */
4584 datetime_doc
, /* tp_doc */
4585 0, /* tp_traverse */
4587 (richcmpfunc
)datetime_richcompare
, /* tp_richcompare */
4588 0, /* tp_weaklistoffset */
4590 0, /* tp_iternext */
4591 datetime_methods
, /* tp_methods */
4593 datetime_getset
, /* tp_getset */
4594 &PyDateTime_DateType
, /* tp_base */
4596 0, /* tp_descr_get */
4597 0, /* tp_descr_set */
4598 0, /* tp_dictoffset */
4600 datetime_alloc
, /* tp_alloc */
4601 datetime_new
, /* tp_new */
4605 /* ---------------------------------------------------------------------------
4606 * Module methods and initialization.
4609 static PyMethodDef module_methods
[] = {
4613 /* C API. Clients get at this via PyDateTime_IMPORT, defined in
4616 static PyDateTime_CAPI CAPI
= {
4617 &PyDateTime_DateType
,
4618 &PyDateTime_DateTimeType
,
4619 &PyDateTime_TimeType
,
4620 &PyDateTime_DeltaType
,
4621 &PyDateTime_TZInfoType
,
4626 datetime_fromtimestamp
,
4634 PyObject
*m
; /* a module object */
4635 PyObject
*d
; /* its dict */
4638 m
= Py_InitModule3("datetime", module_methods
,
4639 "Fast implementation of the datetime type.");
4643 if (PyType_Ready(&PyDateTime_DateType
) < 0)
4645 if (PyType_Ready(&PyDateTime_DateTimeType
) < 0)
4647 if (PyType_Ready(&PyDateTime_DeltaType
) < 0)
4649 if (PyType_Ready(&PyDateTime_TimeType
) < 0)
4651 if (PyType_Ready(&PyDateTime_TZInfoType
) < 0)
4654 /* timedelta values */
4655 d
= PyDateTime_DeltaType
.tp_dict
;
4657 x
= new_delta(0, 0, 1, 0);
4658 if (x
== NULL
|| PyDict_SetItemString(d
, "resolution", x
) < 0)
4662 x
= new_delta(-MAX_DELTA_DAYS
, 0, 0, 0);
4663 if (x
== NULL
|| PyDict_SetItemString(d
, "min", x
) < 0)
4667 x
= new_delta(MAX_DELTA_DAYS
, 24*3600-1, 1000000-1, 0);
4668 if (x
== NULL
|| PyDict_SetItemString(d
, "max", x
) < 0)
4673 d
= PyDateTime_DateType
.tp_dict
;
4675 x
= new_date(1, 1, 1);
4676 if (x
== NULL
|| PyDict_SetItemString(d
, "min", x
) < 0)
4680 x
= new_date(MAXYEAR
, 12, 31);
4681 if (x
== NULL
|| PyDict_SetItemString(d
, "max", x
) < 0)
4685 x
= new_delta(1, 0, 0, 0);
4686 if (x
== NULL
|| PyDict_SetItemString(d
, "resolution", x
) < 0)
4691 d
= PyDateTime_TimeType
.tp_dict
;
4693 x
= new_time(0, 0, 0, 0, Py_None
);
4694 if (x
== NULL
|| PyDict_SetItemString(d
, "min", x
) < 0)
4698 x
= new_time(23, 59, 59, 999999, Py_None
);
4699 if (x
== NULL
|| PyDict_SetItemString(d
, "max", x
) < 0)
4703 x
= new_delta(0, 0, 1, 0);
4704 if (x
== NULL
|| PyDict_SetItemString(d
, "resolution", x
) < 0)
4708 /* datetime values */
4709 d
= PyDateTime_DateTimeType
.tp_dict
;
4711 x
= new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None
);
4712 if (x
== NULL
|| PyDict_SetItemString(d
, "min", x
) < 0)
4716 x
= new_datetime(MAXYEAR
, 12, 31, 23, 59, 59, 999999, Py_None
);
4717 if (x
== NULL
|| PyDict_SetItemString(d
, "max", x
) < 0)
4721 x
= new_delta(0, 0, 1, 0);
4722 if (x
== NULL
|| PyDict_SetItemString(d
, "resolution", x
) < 0)
4726 /* module initialization */
4727 PyModule_AddIntConstant(m
, "MINYEAR", MINYEAR
);
4728 PyModule_AddIntConstant(m
, "MAXYEAR", MAXYEAR
);
4730 Py_INCREF(&PyDateTime_DateType
);
4731 PyModule_AddObject(m
, "date", (PyObject
*) &PyDateTime_DateType
);
4733 Py_INCREF(&PyDateTime_DateTimeType
);
4734 PyModule_AddObject(m
, "datetime",
4735 (PyObject
*)&PyDateTime_DateTimeType
);
4737 Py_INCREF(&PyDateTime_TimeType
);
4738 PyModule_AddObject(m
, "time", (PyObject
*) &PyDateTime_TimeType
);
4740 Py_INCREF(&PyDateTime_DeltaType
);
4741 PyModule_AddObject(m
, "timedelta", (PyObject
*) &PyDateTime_DeltaType
);
4743 Py_INCREF(&PyDateTime_TZInfoType
);
4744 PyModule_AddObject(m
, "tzinfo", (PyObject
*) &PyDateTime_TZInfoType
);
4746 x
= PyCObject_FromVoidPtrAndDesc(&CAPI
, (void*) DATETIME_API_MAGIC
,
4750 PyModule_AddObject(m
, "datetime_CAPI", x
);
4752 /* A 4-year cycle has an extra leap day over what we'd get from
4753 * pasting together 4 single years.
4755 assert(DI4Y
== 4 * 365 + 1);
4756 assert(DI4Y
== days_before_year(4+1));
4758 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4759 * get from pasting together 4 100-year cycles.
4761 assert(DI400Y
== 4 * DI100Y
+ 1);
4762 assert(DI400Y
== days_before_year(400+1));
4764 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4765 * pasting together 25 4-year cycles.
4767 assert(DI100Y
== 25 * DI4Y
- 1);
4768 assert(DI100Y
== days_before_year(100+1));
4770 us_per_us
= PyInt_FromLong(1);
4771 us_per_ms
= PyInt_FromLong(1000);
4772 us_per_second
= PyInt_FromLong(1000000);
4773 us_per_minute
= PyInt_FromLong(60000000);
4774 seconds_per_day
= PyInt_FromLong(24 * 3600);
4775 if (us_per_us
== NULL
|| us_per_ms
== NULL
|| us_per_second
== NULL
||
4776 us_per_minute
== NULL
|| seconds_per_day
== NULL
)
4779 /* The rest are too big for 32-bit ints, but even
4780 * us_per_week fits in 40 bits, so doubles should be exact.
4782 us_per_hour
= PyLong_FromDouble(3600000000.0);
4783 us_per_day
= PyLong_FromDouble(86400000000.0);
4784 us_per_week
= PyLong_FromDouble(604800000000.0);
4785 if (us_per_hour
== NULL
|| us_per_day
== NULL
|| us_per_week
== NULL
)
4789 /* ---------------------------------------------------------------------------
4790 Some time zone algebra. For a datetime x, let
4791 x.n = x stripped of its timezone -- its naive time.
4792 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4794 x.d = x.dst(), and assuming that doesn't raise an exception or
4796 x.s = x's standard offset, x.o - x.d
4798 Now some derived rules, where k is a duration (timedelta).
4801 This follows from the definition of x.s.
4803 2. If x and y have the same tzinfo member, x.s = y.s.
4804 This is actually a requirement, an assumption we need to make about
4805 sane tzinfo classes.
4807 3. The naive UTC time corresponding to x is x.n - x.o.
4808 This is again a requirement for a sane tzinfo class.
4811 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
4813 5. (x+k).n = x.n + k
4814 Again follows from how arithmetic is defined.
4816 Now we can explain tz.fromutc(x). Let's assume it's an interesting case
4817 (meaning that the various tzinfo methods exist, and don't blow up or return
4820 The function wants to return a datetime y with timezone tz, equivalent to x.
4821 x is already in UTC.
4827 The algorithm starts by attaching tz to x.n, and calling that y. So
4828 x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4829 becomes true; in effect, we want to solve [2] for k:
4831 (y+k).n - (y+k).o = x.n [2]
4833 By #1, this is the same as
4835 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
4837 By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4838 Substituting that into [3],
4840 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4841 k - (y+k).s - (y+k).d = 0; rearranging,
4842 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4845 On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4846 approximate k by ignoring the (y+k).d term at first. Note that k can't be
4847 very large, since all offset-returning methods return a duration of magnitude
4848 less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4849 be 0, so ignoring it has no consequence then.
4851 In any case, the new value is
4855 It's helpful to step back at look at [4] from a higher level: it's simply
4856 mapping from UTC to tz's standard time.
4862 we have an equivalent time, and are almost done. The insecurity here is
4863 at the start of daylight time. Picture US Eastern for concreteness. The wall
4864 time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
4865 sense then. The docs ask that an Eastern tzinfo class consider such a time to
4866 be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4867 on the day DST starts. We want to return the 1:MM EST spelling because that's
4868 the only spelling that makes sense on the local wall clock.
4870 In fact, if [5] holds at this point, we do have the standard-time spelling,
4871 but that takes a bit of proof. We first prove a stronger result. What's the
4872 difference between the LHS and RHS of [5]? Let
4874 diff = x.n - (z.n - z.o) [6]
4879 y.n + y.s = since y.n = x.n
4880 x.n + y.s = since z and y are have the same tzinfo member,
4884 Plugging that back into [6] gives
4887 x.n - ((x.n + z.s) - z.o) = expanding
4888 x.n - x.n - z.s + z.o = cancelling
4894 If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
4895 spelling we wanted in the endcase described above. We're done. Contrarily,
4896 if z.d = 0, then we have a UTC equivalent, and are also done.
4898 If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4899 add to z (in effect, z is in tz's standard time, and we need to shift the
4900 local clock into tz's daylight time).
4904 z' = z + z.d = z + diff [7]
4906 and we can again ask whether
4908 z'.n - z'.o = x.n [8]
4910 If so, we're done. If not, the tzinfo class is insane, according to the
4911 assumptions we've made. This also requires a bit of proof. As before, let's
4912 compute the difference between the LHS and RHS of [8] (and skipping some of
4913 the justifications for the kinds of substitutions we've done several times
4916 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4917 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4918 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4919 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4920 - z.n + z.n - z.o + z'.o = cancel z.n
4921 - z.o + z'.o = #1 twice
4922 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4925 So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
4926 we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4927 return z', not bothering to compute z'.d.
4929 How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4930 a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4931 would have to change the result dst() returns: we start in DST, and moving
4932 a little further into it takes us out of DST.
4934 There isn't a sane case where this can happen. The closest it gets is at
4935 the end of DST, where there's an hour in UTC with no spelling in a hybrid
4936 tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4937 that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4938 UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4939 time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4940 clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4941 standard time. Since that's what the local clock *does*, we want to map both
4942 UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
4943 in local time, but so it goes -- it's the way the local clock works.
4945 When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4946 so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4947 z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
4948 (correctly) concludes that z' is not UTC-equivalent to x.
4950 Because we know z.d said z was in daylight time (else [5] would have held and
4951 we would have stopped then), and we know z.d != z'.d (else [8] would have held
4952 and we would have stopped then), and there are only 2 possible values dst() can
4953 return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4954 but the reasoning doesn't depend on the example -- it depends on there being
4955 two possible dst() outcomes, one zero and the other non-zero). Therefore
4956 z' must be in standard time, and is the spelling we want in this case.
4958 Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4959 concerned (because it takes z' as being in standard time rather than the
4960 daylight time we intend here), but returning it gives the real-life "local
4961 clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4964 When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4965 the 1:MM standard time spelling we want.
4967 So how can this break? One of the assumptions must be violated. Two
4970 1) [2] effectively says that y.s is invariant across all y belong to a given
4971 time zone. This isn't true if, for political reasons or continental drift,
4972 a region decides to change its base offset from UTC.
4974 2) There may be versions of "double daylight" time where the tail end of
4975 the analysis gives up a step too early. I haven't thought about that
4978 In any case, it's clear that the default fromutc() is strong enough to handle
4979 "almost all" time zones: so long as the standard offset is invariant, it
4980 doesn't matter if daylight time transition points change from year to year, or
4981 if daylight time is skipped in some years; it doesn't matter how large or
4982 small dst() may get within its bounds; and it doesn't even matter if some
4983 perverse time zone returns a negative dst()). So a breaking case must be
4984 pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
4985 --------------------------------------------------------------------------- */