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"
33 #define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
35 /* Nine decimal digits is easy to communicate, and leaves enough room
36 * so that two delta days can be added w/o fear of overflowing a signed
37 * 32-bit int, and with plenty of room left over to absorb any possible
38 * carries from adding seconds.
40 #define MAX_DELTA_DAYS 999999999
42 /* Rename the long macros in datetime.h to more reasonable short names. */
43 #define GET_YEAR PyDateTime_GET_YEAR
44 #define GET_MONTH PyDateTime_GET_MONTH
45 #define GET_DAY PyDateTime_GET_DAY
46 #define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
47 #define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
48 #define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
49 #define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
51 /* Date accessors for date and datetime. */
52 #define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
53 ((o)->data[1] = ((v) & 0x00ff)))
54 #define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
55 #define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
57 /* Date/Time accessors for datetime. */
58 #define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
59 #define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
60 #define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
61 #define DATE_SET_MICROSECOND(o, v) \
62 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
63 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
64 ((o)->data[9] = ((v) & 0x0000ff)))
66 /* Time accessors for time. */
67 #define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
68 #define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
69 #define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
70 #define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
71 #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
72 #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
73 #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
74 #define TIME_SET_MICROSECOND(o, v) \
75 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
76 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
77 ((o)->data[5] = ((v) & 0x0000ff)))
79 /* Delta accessors for timedelta. */
80 #define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
81 #define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
82 #define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
84 #define SET_TD_DAYS(o, v) ((o)->days = (v))
85 #define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
86 #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
88 /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
91 #define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
93 /* M is a char or int claiming to be a valid month. The macro is equivalent
94 * to the two-sided Python test
97 #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
99 /* Forward declarations. */
100 static PyTypeObject PyDateTime_DateType
;
101 static PyTypeObject PyDateTime_DateTimeType
;
102 static PyTypeObject PyDateTime_DeltaType
;
103 static PyTypeObject PyDateTime_TimeType
;
104 static PyTypeObject PyDateTime_TZInfoType
;
106 /* ---------------------------------------------------------------------------
110 /* k = i+j overflows iff k differs in sign from both inputs,
111 * iff k^i has sign bit set and k^j has sign bit set,
112 * iff (k^i)&(k^j) has sign bit set.
114 #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
115 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
117 /* Compute Python divmod(x, y), returning the quotient and storing the
118 * remainder into *r. The quotient is the floor of x/y, and that's
119 * the real point of this. C will probably truncate instead (C99
120 * requires truncation; C89 left it implementation-defined).
121 * Simplification: we *require* that y > 0 here. That's appropriate
122 * for all the uses made of it. This simplifies the code and makes
123 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
127 divmod(int x
, int y
, int *r
)
138 assert(0 <= *r
&& *r
< y
);
142 /* Round a double to the nearest long. |x| must be small enough to fit
143 * in a C long; this is not checked.
146 round_to_long(double x
)
155 /* ---------------------------------------------------------------------------
156 * General calendrical helper functions
159 /* For each month ordinal in 1..12, the number of days in that month,
160 * and the number of days before that month in the same year. These
161 * are correct for non-leap years only.
163 static int _days_in_month
[] = {
164 0, /* unused; this vector uses 1-based indexing */
165 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
168 static int _days_before_month
[] = {
169 0, /* unused; this vector uses 1-based indexing */
170 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
173 /* year -> 1 if leap year, else 0. */
177 /* Cast year to unsigned. The result is the same either way, but
178 * C can generate faster code for unsigned mod than for signed
179 * mod (especially for % 4 -- a good compiler should just grab
180 * the last 2 bits when the LHS is unsigned).
182 const unsigned int ayear
= (unsigned int)year
;
183 return ayear
% 4 == 0 && (ayear
% 100 != 0 || ayear
% 400 == 0);
186 /* year, month -> number of days in that month in that year */
188 days_in_month(int year
, int month
)
192 if (month
== 2 && is_leap(year
))
195 return _days_in_month
[month
];
198 /* year, month -> number of days in year preceeding first day of month */
200 days_before_month(int year
, int month
)
206 days
= _days_before_month
[month
];
207 if (month
> 2 && is_leap(year
))
212 /* year -> number of days before January 1st of year. Remember that we
213 * start with year 1, so days_before_year(1) == 0.
216 days_before_year(int year
)
219 /* This is incorrect if year <= 0; we really want the floor
220 * here. But so long as MINYEAR is 1, the smallest year this
221 * can see is 0 (this can happen in some normalization endcases),
222 * so we'll just special-case that.
226 return y
*365 + y
/4 - y
/100 + y
/400;
233 /* Number of days in 4, 100, and 400 year cycles. That these have
234 * the correct values is asserted in the module init function.
236 #define DI4Y 1461 /* days_before_year(5); days in 4 years */
237 #define DI100Y 36524 /* days_before_year(101); days in 100 years */
238 #define DI400Y 146097 /* days_before_year(401); days in 400 years */
240 /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
242 ord_to_ymd(int ordinal
, int *year
, int *month
, int *day
)
244 int n
, n1
, n4
, n100
, n400
, leapyear
, preceding
;
246 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
247 * leap years repeats exactly every 400 years. The basic strategy is
248 * to find the closest 400-year boundary at or before ordinal, then
249 * work with the offset from that boundary to ordinal. Life is much
250 * clearer if we subtract 1 from ordinal first -- then the values
251 * of ordinal at 400-year boundaries are exactly those divisible
255 * -- --- ---- ---------- ----------------
256 * 31 Dec -400 -DI400Y -DI400Y -1
257 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
261 * 1 Jan 001 1 0 400-year boundary
265 * 31 Dec 400 DI400Y DI400Y -1
266 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
268 assert(ordinal
>= 1);
270 n400
= ordinal
/ DI400Y
;
271 n
= ordinal
% DI400Y
;
272 *year
= n400
* 400 + 1;
274 /* Now n is the (non-negative) offset, in days, from January 1 of
275 * year, to the desired date. Now compute how many 100-year cycles
277 * Note that it's possible for n100 to equal 4! In that case 4 full
278 * 100-year cycles precede the desired day, which implies the
279 * desired day is December 31 at the end of a 400-year cycle.
284 /* Now compute how many 4-year cycles precede it. */
288 /* And now how many single years. Again n1 can be 4, and again
289 * meaning that the desired day is December 31 at the end of the
295 *year
+= n100
* 100 + n4
* 4 + n1
;
296 if (n1
== 4 || n100
== 4) {
304 /* Now the year is correct, and n is the offset from January 1. We
305 * find the month via an estimate that's either exact or one too
308 leapyear
= n1
== 3 && (n4
!= 24 || n100
== 3);
309 assert(leapyear
== is_leap(*year
));
310 *month
= (n
+ 50) >> 5;
311 preceding
= (_days_before_month
[*month
] + (*month
> 2 && leapyear
));
313 /* estimate is too large */
315 preceding
-= days_in_month(*year
, *month
);
319 assert(n
< days_in_month(*year
, *month
));
324 /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
326 ymd_to_ord(int year
, int month
, int day
)
328 return days_before_year(year
) + days_before_month(year
, month
) + day
;
331 /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
333 weekday(int year
, int month
, int day
)
335 return (ymd_to_ord(year
, month
, day
) + 6) % 7;
338 /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
339 * first calendar week containing a Thursday.
342 iso_week1_monday(int year
)
344 int first_day
= ymd_to_ord(year
, 1, 1); /* ord of 1/1 */
345 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
346 int first_weekday
= (first_day
+ 6) % 7;
347 /* ordinal of closest Monday at or before 1/1 */
348 int week1_monday
= first_day
- first_weekday
;
350 if (first_weekday
> 3) /* if 1/1 was Fri, Sat, Sun */
355 /* ---------------------------------------------------------------------------
359 /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
360 * If not, raise OverflowError and return -1.
363 check_delta_day_range(int days
)
365 if (-MAX_DELTA_DAYS
<= days
&& days
<= MAX_DELTA_DAYS
)
367 PyErr_Format(PyExc_OverflowError
,
368 "days=%d; must have magnitude <= %d",
369 days
, MAX_DELTA_DAYS
);
373 /* Check that date arguments are in range. Return 0 if they are. If they
374 * aren't, raise ValueError and return -1.
377 check_date_args(int year
, int month
, int day
)
380 if (year
< MINYEAR
|| year
> MAXYEAR
) {
381 PyErr_SetString(PyExc_ValueError
,
382 "year is out of range");
385 if (month
< 1 || month
> 12) {
386 PyErr_SetString(PyExc_ValueError
,
387 "month must be in 1..12");
390 if (day
< 1 || day
> days_in_month(year
, month
)) {
391 PyErr_SetString(PyExc_ValueError
,
392 "day is out of range for month");
398 /* Check that time arguments are in range. Return 0 if they are. If they
399 * aren't, raise ValueError and return -1.
402 check_time_args(int h
, int m
, int s
, int us
)
404 if (h
< 0 || h
> 23) {
405 PyErr_SetString(PyExc_ValueError
,
406 "hour must be in 0..23");
409 if (m
< 0 || m
> 59) {
410 PyErr_SetString(PyExc_ValueError
,
411 "minute must be in 0..59");
414 if (s
< 0 || s
> 59) {
415 PyErr_SetString(PyExc_ValueError
,
416 "second must be in 0..59");
419 if (us
< 0 || us
> 999999) {
420 PyErr_SetString(PyExc_ValueError
,
421 "microsecond must be in 0..999999");
427 /* ---------------------------------------------------------------------------
428 * Normalization utilities.
431 /* One step of a mixed-radix conversion. A "hi" unit is equivalent to
432 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
433 * at least factor, enough of *lo is converted into "hi" units so that
434 * 0 <= *lo < factor. The input values must be such that int overflow
438 normalize_pair(int *hi
, int *lo
, int factor
)
442 if (*lo
< 0 || *lo
>= factor
) {
443 const int num_hi
= divmod(*lo
, factor
, lo
);
444 const int new_hi
= *hi
+ num_hi
;
445 assert(! SIGNED_ADD_OVERFLOWED(new_hi
, *hi
, num_hi
));
448 assert(0 <= *lo
&& *lo
< factor
);
451 /* Fiddle days (d), seconds (s), and microseconds (us) so that
454 * The input values must be such that the internals don't overflow.
455 * The way this routine is used, we don't get close.
458 normalize_d_s_us(int *d
, int *s
, int *us
)
460 if (*us
< 0 || *us
>= 1000000) {
461 normalize_pair(s
, us
, 1000000);
462 /* |s| can't be bigger than about
463 * |original s| + |original us|/1000000 now.
467 if (*s
< 0 || *s
>= 24*3600) {
468 normalize_pair(d
, s
, 24*3600);
469 /* |d| can't be bigger than about
471 * (|original s| + |original us|/1000000) / (24*3600) now.
474 assert(0 <= *s
&& *s
< 24*3600);
475 assert(0 <= *us
&& *us
< 1000000);
478 /* Fiddle years (y), months (m), and days (d) so that
480 * 1 <= *d <= days_in_month(*y, *m)
481 * The input values must be such that the internals don't overflow.
482 * The way this routine is used, we don't get close.
485 normalize_y_m_d(int *y
, int *m
, int *d
)
487 int dim
; /* # of days in month */
489 /* This gets muddy: the proper range for day can't be determined
490 * without knowing the correct month and year, but if day is, e.g.,
491 * plus or minus a million, the current month and year values make
492 * no sense (and may also be out of bounds themselves).
493 * Saying 12 months == 1 year should be non-controversial.
495 if (*m
< 1 || *m
> 12) {
497 normalize_pair(y
, m
, 12);
499 /* |y| can't be bigger than about
500 * |original y| + |original m|/12 now.
503 assert(1 <= *m
&& *m
<= 12);
505 /* Now only day can be out of bounds (year may also be out of bounds
506 * for a datetime object, but we don't care about that here).
507 * If day is out of bounds, what to do is arguable, but at least the
508 * method here is principled and explainable.
510 dim
= days_in_month(*y
, *m
);
511 if (*d
< 1 || *d
> dim
) {
512 /* Move day-1 days from the first of the month. First try to
513 * get off cheap if we're only one day out of range
514 * (adjustments for timezone alone can't be worse than that).
519 *d
= days_in_month(*y
, *m
);
526 else if (*d
== dim
+ 1) {
527 /* move forward a day */
536 int ordinal
= ymd_to_ord(*y
, *m
, 1) +
538 if (ordinal
< 1 || ordinal
> MAXORDINAL
) {
541 ord_to_ymd(ordinal
, y
, m
, d
);
548 if (MINYEAR
<= *y
&& *y
<= MAXYEAR
)
551 PyErr_SetString(PyExc_OverflowError
,
552 "date value out of range");
557 /* Fiddle out-of-bounds months and days so that the result makes some kind
558 * of sense. The parameters are both inputs and outputs. Returns < 0 on
559 * failure, where failure means the adjusted year is out of bounds.
562 normalize_date(int *year
, int *month
, int *day
)
564 return normalize_y_m_d(year
, month
, day
);
567 /* Force all the datetime fields into range. The parameters are both
568 * inputs and outputs. Returns < 0 on error.
571 normalize_datetime(int *year
, int *month
, int *day
,
572 int *hour
, int *minute
, int *second
,
575 normalize_pair(second
, microsecond
, 1000000);
576 normalize_pair(minute
, second
, 60);
577 normalize_pair(hour
, minute
, 60);
578 normalize_pair(day
, hour
, 24);
579 return normalize_date(year
, month
, day
);
582 /* ---------------------------------------------------------------------------
583 * Basic object allocation: tp_alloc implementations. These allocate
584 * Python objects of the right size and type, and do the Python object-
585 * initialization bit. If there's not enough memory, they return NULL after
586 * setting MemoryError. All data members remain uninitialized trash.
588 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
589 * member is needed. This is ugly, imprecise, and possibly insecure.
590 * tp_basicsize for the time and datetime types is set to the size of the
591 * struct that has room for the tzinfo member, so subclasses in Python will
592 * allocate enough space for a tzinfo member whether or not one is actually
593 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
594 * part is that PyType_GenericAlloc() (which subclasses in Python end up
595 * using) just happens today to effectively ignore the nitems argument
596 * when tp_itemsize is 0, which it is for these type objects. If that
597 * changes, perhaps the callers of tp_alloc slots in this file should
598 * be changed to force a 0 nitems argument unless the type being allocated
599 * is a base type implemented in this file (so that tp_alloc is time_alloc
600 * or datetime_alloc below, which know about the nitems abuse).
604 time_alloc(PyTypeObject
*type
, Py_ssize_t aware
)
609 PyObject_MALLOC(aware
?
610 sizeof(PyDateTime_Time
) :
611 sizeof(_PyDateTime_BaseTime
));
613 return (PyObject
*)PyErr_NoMemory();
614 PyObject_INIT(self
, type
);
619 datetime_alloc(PyTypeObject
*type
, Py_ssize_t aware
)
624 PyObject_MALLOC(aware
?
625 sizeof(PyDateTime_DateTime
) :
626 sizeof(_PyDateTime_BaseDateTime
));
628 return (PyObject
*)PyErr_NoMemory();
629 PyObject_INIT(self
, type
);
633 /* ---------------------------------------------------------------------------
634 * Helpers for setting object fields. These work on pointers to the
635 * appropriate base class.
638 /* For date and datetime. */
640 set_date_fields(PyDateTime_Date
*self
, int y
, int m
, int d
)
648 /* ---------------------------------------------------------------------------
649 * Create various objects, mostly without range checking.
652 /* Create a date instance with no range checking. */
654 new_date_ex(int year
, int month
, int day
, PyTypeObject
*type
)
656 PyDateTime_Date
*self
;
658 self
= (PyDateTime_Date
*) (type
->tp_alloc(type
, 0));
660 set_date_fields(self
, year
, month
, day
);
661 return (PyObject
*) self
;
664 #define new_date(year, month, day) \
665 new_date_ex(year, month, day, &PyDateTime_DateType)
667 /* Create a datetime instance with no range checking. */
669 new_datetime_ex(int year
, int month
, int day
, int hour
, int minute
,
670 int second
, int usecond
, PyObject
*tzinfo
, PyTypeObject
*type
)
672 PyDateTime_DateTime
*self
;
673 char aware
= tzinfo
!= Py_None
;
675 self
= (PyDateTime_DateTime
*) (type
->tp_alloc(type
, aware
));
677 self
->hastzinfo
= aware
;
678 set_date_fields((PyDateTime_Date
*)self
, year
, month
, day
);
679 DATE_SET_HOUR(self
, hour
);
680 DATE_SET_MINUTE(self
, minute
);
681 DATE_SET_SECOND(self
, second
);
682 DATE_SET_MICROSECOND(self
, usecond
);
685 self
->tzinfo
= tzinfo
;
688 return (PyObject
*)self
;
691 #define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
692 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
693 &PyDateTime_DateTimeType)
695 /* Create a time instance with no range checking. */
697 new_time_ex(int hour
, int minute
, int second
, int usecond
,
698 PyObject
*tzinfo
, PyTypeObject
*type
)
700 PyDateTime_Time
*self
;
701 char aware
= tzinfo
!= Py_None
;
703 self
= (PyDateTime_Time
*) (type
->tp_alloc(type
, aware
));
705 self
->hastzinfo
= aware
;
707 TIME_SET_HOUR(self
, hour
);
708 TIME_SET_MINUTE(self
, minute
);
709 TIME_SET_SECOND(self
, second
);
710 TIME_SET_MICROSECOND(self
, usecond
);
713 self
->tzinfo
= tzinfo
;
716 return (PyObject
*)self
;
719 #define new_time(hh, mm, ss, us, tzinfo) \
720 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
722 /* Create a timedelta instance. Normalize the members iff normalize is
723 * true. Passing false is a speed optimization, if you know for sure
724 * that seconds and microseconds are already in their proper ranges. In any
725 * case, raises OverflowError and returns NULL if the normalized days is out
729 new_delta_ex(int days
, int seconds
, int microseconds
, int normalize
,
732 PyDateTime_Delta
*self
;
735 normalize_d_s_us(&days
, &seconds
, µseconds
);
736 assert(0 <= seconds
&& seconds
< 24*3600);
737 assert(0 <= microseconds
&& microseconds
< 1000000);
739 if (check_delta_day_range(days
) < 0)
742 self
= (PyDateTime_Delta
*) (type
->tp_alloc(type
, 0));
745 SET_TD_DAYS(self
, days
);
746 SET_TD_SECONDS(self
, seconds
);
747 SET_TD_MICROSECONDS(self
, microseconds
);
749 return (PyObject
*) self
;
752 #define new_delta(d, s, us, normalize) \
753 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
755 /* ---------------------------------------------------------------------------
759 /* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
760 * raise TypeError and return -1.
763 check_tzinfo_subclass(PyObject
*p
)
765 if (p
== Py_None
|| PyTZInfo_Check(p
))
767 PyErr_Format(PyExc_TypeError
,
768 "tzinfo argument must be None or of a tzinfo subclass, "
770 Py_TYPE(p
)->tp_name
);
774 /* Return tzinfo.methname(tzinfoarg), without any checking of results.
775 * If tzinfo is None, returns None.
778 call_tzinfo_method(PyObject
*tzinfo
, char *methname
, PyObject
*tzinfoarg
)
782 assert(tzinfo
&& methname
&& tzinfoarg
);
783 assert(check_tzinfo_subclass(tzinfo
) >= 0);
784 if (tzinfo
== Py_None
) {
789 result
= PyObject_CallMethod(tzinfo
, methname
, "O", tzinfoarg
);
793 /* If self has a tzinfo member, return a BORROWED reference to it. Else
794 * return NULL, which is NOT AN ERROR. There are no error returns here,
795 * and the caller must not decref the result.
798 get_tzinfo_member(PyObject
*self
)
800 PyObject
*tzinfo
= NULL
;
802 if (PyDateTime_Check(self
) && HASTZINFO(self
))
803 tzinfo
= ((PyDateTime_DateTime
*)self
)->tzinfo
;
804 else if (PyTime_Check(self
) && HASTZINFO(self
))
805 tzinfo
= ((PyDateTime_Time
*)self
)->tzinfo
;
810 /* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
811 * result. tzinfo must be an instance of the tzinfo class. If the method
812 * returns None, this returns 0 and sets *none to 1. If the method doesn't
813 * return None or timedelta, TypeError is raised and this returns -1. If it
814 * returnsa timedelta and the value is out of range or isn't a whole number
815 * of minutes, ValueError is raised and this returns -1.
816 * Else *none is set to 0 and the integer method result is returned.
819 call_utc_tzinfo_method(PyObject
*tzinfo
, char *name
, PyObject
*tzinfoarg
,
825 assert(tzinfo
!= NULL
);
826 assert(PyTZInfo_Check(tzinfo
));
827 assert(tzinfoarg
!= NULL
);
830 u
= call_tzinfo_method(tzinfo
, name
, tzinfoarg
);
834 else if (u
== Py_None
) {
838 else if (PyDelta_Check(u
)) {
839 const int days
= GET_TD_DAYS(u
);
840 if (days
< -1 || days
> 0)
841 result
= 24*60; /* trigger ValueError below */
843 /* next line can't overflow because we know days
846 int ss
= days
* 24 * 3600 + GET_TD_SECONDS(u
);
847 result
= divmod(ss
, 60, &ss
);
848 if (ss
|| GET_TD_MICROSECONDS(u
)) {
849 PyErr_Format(PyExc_ValueError
,
850 "tzinfo.%s() must return a "
851 "whole number of minutes",
858 PyErr_Format(PyExc_TypeError
,
859 "tzinfo.%s() must return None or "
860 "timedelta, not '%s'",
861 name
, Py_TYPE(u
)->tp_name
);
865 if (result
< -1439 || result
> 1439) {
866 PyErr_Format(PyExc_ValueError
,
867 "tzinfo.%s() returned %d; must be in "
875 /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
876 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
877 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
878 * doesn't return None or timedelta, TypeError is raised and this returns -1.
879 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
880 * # of minutes), ValueError is raised and this returns -1. Else *none is
881 * set to 0 and the offset is returned (as int # of minutes east of UTC).
884 call_utcoffset(PyObject
*tzinfo
, PyObject
*tzinfoarg
, int *none
)
886 return call_utc_tzinfo_method(tzinfo
, "utcoffset", tzinfoarg
, none
);
889 /* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
892 offset_as_timedelta(PyObject
*tzinfo
, char *name
, PyObject
*tzinfoarg
) {
895 assert(tzinfo
&& name
&& tzinfoarg
);
896 if (tzinfo
== Py_None
) {
902 int offset
= call_utc_tzinfo_method(tzinfo
, name
, tzinfoarg
,
904 if (offset
< 0 && PyErr_Occurred())
911 result
= new_delta(0, offset
* 60, 0, 1);
916 /* Call tzinfo.dst(tzinfoarg), and extract an integer from the
917 * result. tzinfo must be an instance of the tzinfo class. If dst()
918 * returns None, call_dst returns 0 and sets *none to 1. If dst()
919 & doesn't return None or timedelta, TypeError is raised and this
920 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
921 * ValueError is raised and this returns -1. Else *none is set to 0 and
922 * the offset is returned (as an int # of minutes east of UTC).
925 call_dst(PyObject
*tzinfo
, PyObject
*tzinfoarg
, int *none
)
927 return call_utc_tzinfo_method(tzinfo
, "dst", tzinfoarg
, none
);
930 /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
931 * an instance of the tzinfo class or None. If tzinfo isn't None, and
932 * tzname() doesn't return None or a string, TypeError is raised and this
933 * returns NULL. If the result is a string, we ensure it is a Unicode
937 call_tzname(PyObject
*tzinfo
, PyObject
*tzinfoarg
)
941 assert(tzinfo
!= NULL
);
942 assert(check_tzinfo_subclass(tzinfo
) >= 0);
943 assert(tzinfoarg
!= NULL
);
945 if (tzinfo
== Py_None
) {
950 result
= PyObject_CallMethod(tzinfo
, "tzname", "O", tzinfoarg
);
952 if (result
!= NULL
&& result
!= Py_None
) {
953 if (!PyUnicode_Check(result
)) {
954 PyErr_Format(PyExc_TypeError
, "tzinfo.tzname() must "
955 "return None or a string, not '%s'",
956 Py_TYPE(result
)->tp_name
);
965 /* an exception has been set; the caller should pass it on */
968 /* type isn't date, datetime, or time subclass */
972 * datetime with !hastzinfo
973 * datetime with None tzinfo,
974 * datetime where utcoffset() returns None
975 * time with !hastzinfo
976 * time with None tzinfo,
977 * time where utcoffset() returns None
981 /* time or datetime where utcoffset() doesn't return None */
985 /* Classify an object as to whether it's naive or offset-aware. See
986 * the "naivety" typedef for details. If the type is aware, *offset is set
987 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
988 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
989 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
992 classify_utcoffset(PyObject
*op
, PyObject
*tzinfoarg
, int *offset
)
997 assert(tzinfoarg
!= NULL
);
999 tzinfo
= get_tzinfo_member(op
); /* NULL means no tzinfo, not error */
1000 if (tzinfo
== Py_None
)
1001 return OFFSET_NAIVE
;
1002 if (tzinfo
== NULL
) {
1003 /* note that a datetime passes the PyDate_Check test */
1004 return (PyTime_Check(op
) || PyDate_Check(op
)) ?
1005 OFFSET_NAIVE
: OFFSET_UNKNOWN
;
1007 *offset
= call_utcoffset(tzinfo
, tzinfoarg
, &none
);
1008 if (*offset
== -1 && PyErr_Occurred())
1009 return OFFSET_ERROR
;
1010 return none
? OFFSET_NAIVE
: OFFSET_AWARE
;
1013 /* Classify two objects as to whether they're naive or offset-aware.
1014 * This isn't quite the same as calling classify_utcoffset() twice: for
1015 * binary operations (comparison and subtraction), we generally want to
1016 * ignore the tzinfo members if they're identical. This is by design,
1017 * so that results match "naive" expectations when mixing objects from a
1018 * single timezone. So in that case, this sets both offsets to 0 and
1019 * both naiveties to OFFSET_NAIVE.
1020 * The function returns 0 if everything's OK, and -1 on error.
1023 classify_two_utcoffsets(PyObject
*o1
, int *offset1
, naivety
*n1
,
1024 PyObject
*tzinfoarg1
,
1025 PyObject
*o2
, int *offset2
, naivety
*n2
,
1026 PyObject
*tzinfoarg2
)
1028 if (get_tzinfo_member(o1
) == get_tzinfo_member(o2
)) {
1029 *offset1
= *offset2
= 0;
1030 *n1
= *n2
= OFFSET_NAIVE
;
1033 *n1
= classify_utcoffset(o1
, tzinfoarg1
, offset1
);
1034 if (*n1
== OFFSET_ERROR
)
1036 *n2
= classify_utcoffset(o2
, tzinfoarg2
, offset2
);
1037 if (*n2
== OFFSET_ERROR
)
1043 /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1045 * ", tzinfo=" + repr(tzinfo)
1046 * before the closing ")".
1049 append_keyword_tzinfo(PyObject
*repr
, PyObject
*tzinfo
)
1053 assert(PyUnicode_Check(repr
));
1055 if (tzinfo
== Py_None
)
1057 /* Get rid of the trailing ')'. */
1058 assert(PyUnicode_AS_UNICODE(repr
)[PyUnicode_GET_SIZE(repr
)-1] == ')');
1059 temp
= PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr
),
1060 PyUnicode_GET_SIZE(repr
) - 1);
1064 repr
= PyUnicode_FromFormat("%U, tzinfo=%R)", temp
, tzinfo
);
1069 /* ---------------------------------------------------------------------------
1070 * String format helpers.
1074 format_ctime(PyDateTime_Date
*date
, int hours
, int minutes
, int seconds
)
1076 static const char *DayNames
[] = {
1077 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1079 static const char *MonthNames
[] = {
1080 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1081 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1084 int wday
= weekday(GET_YEAR(date
), GET_MONTH(date
), GET_DAY(date
));
1086 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1087 DayNames
[wday
], MonthNames
[GET_MONTH(date
)-1],
1088 GET_DAY(date
), hours
, minutes
, seconds
,
1092 /* Add an hours & minutes UTC offset string to buf. buf has no more than
1093 * buflen bytes remaining. The UTC offset is gotten by calling
1094 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1095 * *buf, and that's all. Else the returned value is checked for sanity (an
1096 * integer in range), and if that's OK it's converted to an hours & minutes
1097 * string of the form
1099 * Returns 0 if everything is OK. If the return value from utcoffset() is
1100 * bogus, an appropriate exception is set and -1 is returned.
1103 format_utcoffset(char *buf
, size_t buflen
, const char *sep
,
1104 PyObject
*tzinfo
, PyObject
*tzinfoarg
)
1112 assert(buflen
>= 1);
1114 offset
= call_utcoffset(tzinfo
, tzinfoarg
, &none
);
1115 if (offset
== -1 && PyErr_Occurred())
1126 hours
= divmod(offset
, 60, &minutes
);
1127 PyOS_snprintf(buf
, buflen
, "%c%02d%s%02d", sign
, hours
, sep
, minutes
);
1132 make_Zreplacement(PyObject
*object
, PyObject
*tzinfoarg
)
1135 PyObject
*tzinfo
= get_tzinfo_member(object
);
1136 PyObject
*Zreplacement
= PyUnicode_FromStringAndSize(NULL
, 0);
1137 if (Zreplacement
== NULL
)
1139 if (tzinfo
== Py_None
|| tzinfo
== NULL
)
1140 return Zreplacement
;
1142 assert(tzinfoarg
!= NULL
);
1143 temp
= call_tzname(tzinfo
, tzinfoarg
);
1146 if (temp
== Py_None
) {
1148 return Zreplacement
;
1151 assert(PyUnicode_Check(temp
));
1152 /* Since the tzname is getting stuffed into the
1153 * format, we have to double any % signs so that
1154 * strftime doesn't treat them as format codes.
1156 Py_DECREF(Zreplacement
);
1157 Zreplacement
= PyObject_CallMethod(temp
, "replace", "ss", "%", "%%");
1159 if (Zreplacement
== NULL
)
1161 if (!PyUnicode_Check(Zreplacement
)) {
1162 PyErr_SetString(PyExc_TypeError
,
1163 "tzname.replace() did not return a string");
1166 return Zreplacement
;
1169 Py_DECREF(Zreplacement
);
1174 make_freplacement(PyObject
*object
)
1176 char freplacement
[64];
1177 if (PyTime_Check(object
))
1178 sprintf(freplacement
, "%06d", TIME_GET_MICROSECOND(object
));
1179 else if (PyDateTime_Check(object
))
1180 sprintf(freplacement
, "%06d", DATE_GET_MICROSECOND(object
));
1182 sprintf(freplacement
, "%06d", 0);
1184 return PyBytes_FromStringAndSize(freplacement
, strlen(freplacement
));
1187 /* I sure don't want to reproduce the strftime code from the time module,
1188 * so this imports the module and calls it. All the hair is due to
1189 * giving special meanings to the %z, %Z and %f format codes via a
1190 * preprocessing step on the format string.
1191 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1195 wrap_strftime(PyObject
*object
, PyObject
*format
, PyObject
*timetuple
,
1196 PyObject
*tzinfoarg
)
1198 PyObject
*result
= NULL
; /* guilty until proved innocent */
1200 PyObject
*zreplacement
= NULL
; /* py string, replacement for %z */
1201 PyObject
*Zreplacement
= NULL
; /* py string, replacement for %Z */
1202 PyObject
*freplacement
= NULL
; /* py string, replacement for %f */
1204 const char *pin
; /* pointer to next char in input format */
1205 Py_ssize_t flen
; /* length of input format */
1206 char ch
; /* next char in input format */
1208 PyObject
*newfmt
= NULL
; /* py string, the output format */
1209 char *pnew
; /* pointer to available byte in output format */
1210 size_t totalnew
; /* number bytes total in output format buffer,
1211 exclusive of trailing \0 */
1212 size_t usednew
; /* number bytes used so far in output format buffer */
1214 const char *ptoappend
; /* ptr to string to append to output buffer */
1215 Py_ssize_t ntoappend
; /* # of bytes to append to output buffer */
1217 assert(object
&& format
&& timetuple
);
1218 assert(PyUnicode_Check(format
));
1219 /* Convert the input format to a C string and size */
1220 pin
= _PyUnicode_AsStringAndSize(format
, &flen
);
1224 /* Give up if the year is before 1900.
1225 * Python strftime() plays games with the year, and different
1226 * games depending on whether envar PYTHON2K is set. This makes
1227 * years before 1900 a nightmare, even if the platform strftime
1228 * supports them (and not all do).
1229 * We could get a lot farther here by avoiding Python's strftime
1230 * wrapper and calling the C strftime() directly, but that isn't
1231 * an option in the Python implementation of this module.
1235 PyObject
*pyyear
= PySequence_GetItem(timetuple
, 0);
1236 if (pyyear
== NULL
) return NULL
;
1237 assert(PyLong_Check(pyyear
));
1238 year
= PyLong_AsLong(pyyear
);
1241 PyErr_Format(PyExc_ValueError
, "year=%ld is before "
1242 "1900; the datetime strftime() "
1243 "methods require year >= 1900",
1249 /* Scan the input format, looking for %z/%Z/%f escapes, building
1250 * a new format. Since computing the replacements for those codes
1251 * is expensive, don't unless they're actually used.
1253 if (flen
> INT_MAX
- 1) {
1258 totalnew
= flen
+ 1; /* realistic if no %z/%Z */
1259 newfmt
= PyBytes_FromStringAndSize(NULL
, totalnew
);
1260 if (newfmt
== NULL
) goto Done
;
1261 pnew
= PyBytes_AsString(newfmt
);
1264 while ((ch
= *pin
++) != '\0') {
1266 ptoappend
= pin
- 1;
1269 else if ((ch
= *pin
++) == '\0') {
1270 /* There's a lone trailing %; doesn't make sense. */
1271 PyErr_SetString(PyExc_ValueError
, "strftime format "
1275 /* A % has been seen and ch is the character after it. */
1276 else if (ch
== 'z') {
1277 if (zreplacement
== NULL
) {
1278 /* format utcoffset */
1280 PyObject
*tzinfo
= get_tzinfo_member(object
);
1281 zreplacement
= PyBytes_FromStringAndSize("", 0);
1282 if (zreplacement
== NULL
) goto Done
;
1283 if (tzinfo
!= Py_None
&& tzinfo
!= NULL
) {
1284 assert(tzinfoarg
!= NULL
);
1285 if (format_utcoffset(buf
,
1291 Py_DECREF(zreplacement
);
1293 PyBytes_FromStringAndSize(buf
,
1295 if (zreplacement
== NULL
)
1299 assert(zreplacement
!= NULL
);
1300 ptoappend
= PyBytes_AS_STRING(zreplacement
);
1301 ntoappend
= PyBytes_GET_SIZE(zreplacement
);
1303 else if (ch
== 'Z') {
1305 if (Zreplacement
== NULL
) {
1306 Zreplacement
= make_Zreplacement(object
,
1308 if (Zreplacement
== NULL
)
1311 assert(Zreplacement
!= NULL
);
1312 assert(PyUnicode_Check(Zreplacement
));
1313 ptoappend
= _PyUnicode_AsStringAndSize(Zreplacement
,
1315 ntoappend
= Py_SIZE(Zreplacement
);
1317 else if (ch
== 'f') {
1318 /* format microseconds */
1319 if (freplacement
== NULL
) {
1320 freplacement
= make_freplacement(object
);
1321 if (freplacement
== NULL
)
1324 assert(freplacement
!= NULL
);
1325 assert(PyBytes_Check(freplacement
));
1326 ptoappend
= PyBytes_AS_STRING(freplacement
);
1327 ntoappend
= PyBytes_GET_SIZE(freplacement
);
1330 /* percent followed by neither z nor Z */
1331 ptoappend
= pin
- 2;
1335 /* Append the ntoappend chars starting at ptoappend to
1340 assert(ptoappend
!= NULL
);
1341 assert(ntoappend
> 0);
1342 while (usednew
+ ntoappend
> totalnew
) {
1343 size_t bigger
= totalnew
<< 1;
1344 if ((bigger
>> 1) != totalnew
) { /* overflow */
1348 if (_PyBytes_Resize(&newfmt
, bigger
) < 0)
1351 pnew
= PyBytes_AsString(newfmt
) + usednew
;
1353 memcpy(pnew
, ptoappend
, ntoappend
);
1355 usednew
+= ntoappend
;
1356 assert(usednew
<= totalnew
);
1359 if (_PyBytes_Resize(&newfmt
, usednew
) < 0)
1363 PyObject
*time
= PyImport_ImportModuleNoBlock("time");
1366 format
= PyUnicode_FromString(PyBytes_AS_STRING(newfmt
));
1367 if (format
!= NULL
) {
1368 result
= PyObject_CallMethod(time
, "strftime", "OO",
1375 Py_XDECREF(freplacement
);
1376 Py_XDECREF(zreplacement
);
1377 Py_XDECREF(Zreplacement
);
1382 /* ---------------------------------------------------------------------------
1383 * Wrap functions from the time module. These aren't directly available
1384 * from C. Perhaps they should be.
1387 /* Call time.time() and return its result (a Python float). */
1391 PyObject
*result
= NULL
;
1392 PyObject
*time
= PyImport_ImportModuleNoBlock("time");
1395 result
= PyObject_CallMethod(time
, "time", "()");
1401 /* Build a time.struct_time. The weekday and day number are automatically
1402 * computed from the y,m,d args.
1405 build_struct_time(int y
, int m
, int d
, int hh
, int mm
, int ss
, int dstflag
)
1408 PyObject
*result
= NULL
;
1410 time
= PyImport_ImportModuleNoBlock("time");
1412 result
= PyObject_CallMethod(time
, "struct_time",
1417 days_before_month(y
, m
) + d
,
1424 /* ---------------------------------------------------------------------------
1425 * Miscellaneous helpers.
1428 /* For various reasons, we need to use tp_richcompare instead of tp_reserved.
1429 * The comparisons here all most naturally compute a cmp()-like result.
1430 * This little helper turns that into a bool result for rich comparisons.
1433 diff_to_bool(int diff
, int op
)
1439 case Py_EQ
: istrue
= diff
== 0; break;
1440 case Py_NE
: istrue
= diff
!= 0; break;
1441 case Py_LE
: istrue
= diff
<= 0; break;
1442 case Py_GE
: istrue
= diff
>= 0; break;
1443 case Py_LT
: istrue
= diff
< 0; break;
1444 case Py_GT
: istrue
= diff
> 0; break;
1446 assert(! "op unknown");
1447 istrue
= 0; /* To shut up compiler */
1449 result
= istrue
? Py_True
: Py_False
;
1454 /* Raises a "can't compare" TypeError and returns NULL. */
1456 cmperror(PyObject
*a
, PyObject
*b
)
1458 PyErr_Format(PyExc_TypeError
,
1459 "can't compare %s to %s",
1460 Py_TYPE(a
)->tp_name
, Py_TYPE(b
)->tp_name
);
1464 /* ---------------------------------------------------------------------------
1465 * Cached Python objects; these are set by the module init function.
1468 /* Conversion factors. */
1469 static PyObject
*us_per_us
= NULL
; /* 1 */
1470 static PyObject
*us_per_ms
= NULL
; /* 1000 */
1471 static PyObject
*us_per_second
= NULL
; /* 1000000 */
1472 static PyObject
*us_per_minute
= NULL
; /* 1e6 * 60 as Python int */
1473 static PyObject
*us_per_hour
= NULL
; /* 1e6 * 3600 as Python long */
1474 static PyObject
*us_per_day
= NULL
; /* 1e6 * 3600 * 24 as Python long */
1475 static PyObject
*us_per_week
= NULL
; /* 1e6*3600*24*7 as Python long */
1476 static PyObject
*seconds_per_day
= NULL
; /* 3600*24 as Python int */
1478 /* ---------------------------------------------------------------------------
1479 * Class implementations.
1483 * PyDateTime_Delta implementation.
1486 /* Convert a timedelta to a number of us,
1487 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1488 * as a Python int or long.
1489 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1490 * due to ubiquitous overflow possibilities.
1493 delta_to_microseconds(PyDateTime_Delta
*self
)
1495 PyObject
*x1
= NULL
;
1496 PyObject
*x2
= NULL
;
1497 PyObject
*x3
= NULL
;
1498 PyObject
*result
= NULL
;
1500 x1
= PyLong_FromLong(GET_TD_DAYS(self
));
1503 x2
= PyNumber_Multiply(x1
, seconds_per_day
); /* days in seconds */
1509 /* x2 has days in seconds */
1510 x1
= PyLong_FromLong(GET_TD_SECONDS(self
)); /* seconds */
1513 x3
= PyNumber_Add(x1
, x2
); /* days and seconds in seconds */
1520 /* x3 has days+seconds in seconds */
1521 x1
= PyNumber_Multiply(x3
, us_per_second
); /* us */
1527 /* x1 has days+seconds in us */
1528 x2
= PyLong_FromLong(GET_TD_MICROSECONDS(self
));
1531 result
= PyNumber_Add(x1
, x2
);
1540 /* Convert a number of us (as a Python int or long) to a timedelta.
1543 microseconds_to_delta_ex(PyObject
*pyus
, PyTypeObject
*type
)
1550 PyObject
*tuple
= NULL
;
1551 PyObject
*num
= NULL
;
1552 PyObject
*result
= NULL
;
1554 tuple
= PyNumber_Divmod(pyus
, us_per_second
);
1558 num
= PyTuple_GetItem(tuple
, 1); /* us */
1561 temp
= PyLong_AsLong(num
);
1563 if (temp
== -1 && PyErr_Occurred())
1565 assert(0 <= temp
&& temp
< 1000000);
1568 /* The divisor was positive, so this must be an error. */
1569 assert(PyErr_Occurred());
1573 num
= PyTuple_GetItem(tuple
, 0); /* leftover seconds */
1579 tuple
= PyNumber_Divmod(num
, seconds_per_day
);
1584 num
= PyTuple_GetItem(tuple
, 1); /* seconds */
1587 temp
= PyLong_AsLong(num
);
1589 if (temp
== -1 && PyErr_Occurred())
1591 assert(0 <= temp
&& temp
< 24*3600);
1595 /* The divisor was positive, so this must be an error. */
1596 assert(PyErr_Occurred());
1600 num
= PyTuple_GetItem(tuple
, 0); /* leftover days */
1604 temp
= PyLong_AsLong(num
);
1605 if (temp
== -1 && PyErr_Occurred())
1608 if ((long)d
!= temp
) {
1609 PyErr_SetString(PyExc_OverflowError
, "normalized days too "
1610 "large to fit in a C int");
1613 result
= new_delta_ex(d
, s
, us
, 0, type
);
1621 #define microseconds_to_delta(pymicros) \
1622 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1625 multiply_int_timedelta(PyObject
*intobj
, PyDateTime_Delta
*delta
)
1631 pyus_in
= delta_to_microseconds(delta
);
1632 if (pyus_in
== NULL
)
1635 pyus_out
= PyNumber_Multiply(pyus_in
, intobj
);
1637 if (pyus_out
== NULL
)
1640 result
= microseconds_to_delta(pyus_out
);
1641 Py_DECREF(pyus_out
);
1646 divide_timedelta_int(PyDateTime_Delta
*delta
, PyObject
*intobj
)
1652 pyus_in
= delta_to_microseconds(delta
);
1653 if (pyus_in
== NULL
)
1656 pyus_out
= PyNumber_FloorDivide(pyus_in
, intobj
);
1658 if (pyus_out
== NULL
)
1661 result
= microseconds_to_delta(pyus_out
);
1662 Py_DECREF(pyus_out
);
1667 delta_add(PyObject
*left
, PyObject
*right
)
1669 PyObject
*result
= Py_NotImplemented
;
1671 if (PyDelta_Check(left
) && PyDelta_Check(right
)) {
1673 /* The C-level additions can't overflow because of the
1676 int days
= GET_TD_DAYS(left
) + GET_TD_DAYS(right
);
1677 int seconds
= GET_TD_SECONDS(left
) + GET_TD_SECONDS(right
);
1678 int microseconds
= GET_TD_MICROSECONDS(left
) +
1679 GET_TD_MICROSECONDS(right
);
1680 result
= new_delta(days
, seconds
, microseconds
, 1);
1683 if (result
== Py_NotImplemented
)
1689 delta_negative(PyDateTime_Delta
*self
)
1691 return new_delta(-GET_TD_DAYS(self
),
1692 -GET_TD_SECONDS(self
),
1693 -GET_TD_MICROSECONDS(self
),
1698 delta_positive(PyDateTime_Delta
*self
)
1700 /* Could optimize this (by returning self) if this isn't a
1701 * subclass -- but who uses unary + ? Approximately nobody.
1703 return new_delta(GET_TD_DAYS(self
),
1704 GET_TD_SECONDS(self
),
1705 GET_TD_MICROSECONDS(self
),
1710 delta_abs(PyDateTime_Delta
*self
)
1714 assert(GET_TD_MICROSECONDS(self
) >= 0);
1715 assert(GET_TD_SECONDS(self
) >= 0);
1717 if (GET_TD_DAYS(self
) < 0)
1718 result
= delta_negative(self
);
1720 result
= delta_positive(self
);
1726 delta_subtract(PyObject
*left
, PyObject
*right
)
1728 PyObject
*result
= Py_NotImplemented
;
1730 if (PyDelta_Check(left
) && PyDelta_Check(right
)) {
1732 PyObject
*minus_right
= PyNumber_Negative(right
);
1734 result
= delta_add(left
, minus_right
);
1735 Py_DECREF(minus_right
);
1741 if (result
== Py_NotImplemented
)
1747 delta_richcompare(PyObject
*self
, PyObject
*other
, int op
)
1749 if (PyDelta_Check(other
)) {
1750 int diff
= GET_TD_DAYS(self
) - GET_TD_DAYS(other
);
1752 diff
= GET_TD_SECONDS(self
) - GET_TD_SECONDS(other
);
1754 diff
= GET_TD_MICROSECONDS(self
) -
1755 GET_TD_MICROSECONDS(other
);
1757 return diff_to_bool(diff
, op
);
1760 Py_INCREF(Py_NotImplemented
);
1761 return Py_NotImplemented
;
1765 static PyObject
*delta_getstate(PyDateTime_Delta
*self
);
1768 delta_hash(PyDateTime_Delta
*self
)
1770 if (self
->hashcode
== -1) {
1771 PyObject
*temp
= delta_getstate(self
);
1773 self
->hashcode
= PyObject_Hash(temp
);
1777 return self
->hashcode
;
1781 delta_multiply(PyObject
*left
, PyObject
*right
)
1783 PyObject
*result
= Py_NotImplemented
;
1785 if (PyDelta_Check(left
)) {
1787 if (PyLong_Check(right
))
1788 result
= multiply_int_timedelta(right
,
1789 (PyDateTime_Delta
*) left
);
1791 else if (PyLong_Check(left
))
1792 result
= multiply_int_timedelta(left
,
1793 (PyDateTime_Delta
*) right
);
1795 if (result
== Py_NotImplemented
)
1801 delta_divide(PyObject
*left
, PyObject
*right
)
1803 PyObject
*result
= Py_NotImplemented
;
1805 if (PyDelta_Check(left
)) {
1807 if (PyLong_Check(right
))
1808 result
= divide_timedelta_int(
1809 (PyDateTime_Delta
*)left
,
1813 if (result
== Py_NotImplemented
)
1818 /* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1819 * timedelta constructor. sofar is the # of microseconds accounted for
1820 * so far, and there are factor microseconds per current unit, the number
1821 * of which is given by num. num * factor is added to sofar in a
1822 * numerically careful way, and that's the result. Any fractional
1823 * microseconds left over (this can happen if num is a float type) are
1824 * added into *leftover.
1825 * Note that there are many ways this can give an error (NULL) return.
1828 accum(const char* tag
, PyObject
*sofar
, PyObject
*num
, PyObject
*factor
,
1834 assert(num
!= NULL
);
1836 if (PyLong_Check(num
)) {
1837 prod
= PyNumber_Multiply(num
, factor
);
1840 sum
= PyNumber_Add(sofar
, prod
);
1845 if (PyFloat_Check(num
)) {
1852 /* The Plan: decompose num into an integer part and a
1853 * fractional part, num = intpart + fracpart.
1854 * Then num * factor ==
1855 * intpart * factor + fracpart * factor
1856 * and the LHS can be computed exactly in long arithmetic.
1857 * The RHS is again broken into an int part and frac part.
1858 * and the frac part is added into *leftover.
1860 dnum
= PyFloat_AsDouble(num
);
1861 if (dnum
== -1.0 && PyErr_Occurred())
1863 fracpart
= modf(dnum
, &intpart
);
1864 x
= PyLong_FromDouble(intpart
);
1868 prod
= PyNumber_Multiply(x
, factor
);
1873 sum
= PyNumber_Add(sofar
, prod
);
1878 if (fracpart
== 0.0)
1880 /* So far we've lost no information. Dealing with the
1881 * fractional part requires float arithmetic, and may
1882 * lose a little info.
1884 assert(PyLong_Check(factor
));
1885 dnum
= PyLong_AsDouble(factor
);
1888 fracpart
= modf(dnum
, &intpart
);
1889 x
= PyLong_FromDouble(intpart
);
1895 y
= PyNumber_Add(sum
, x
);
1898 *leftover
+= fracpart
;
1902 PyErr_Format(PyExc_TypeError
,
1903 "unsupported type for timedelta %s component: %s",
1904 tag
, Py_TYPE(num
)->tp_name
);
1909 delta_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
1911 PyObject
*self
= NULL
;
1913 /* Argument objects. */
1914 PyObject
*day
= NULL
;
1915 PyObject
*second
= NULL
;
1916 PyObject
*us
= NULL
;
1917 PyObject
*ms
= NULL
;
1918 PyObject
*minute
= NULL
;
1919 PyObject
*hour
= NULL
;
1920 PyObject
*week
= NULL
;
1922 PyObject
*x
= NULL
; /* running sum of microseconds */
1923 PyObject
*y
= NULL
; /* temp sum of microseconds */
1924 double leftover_us
= 0.0;
1926 static char *keywords
[] = {
1927 "days", "seconds", "microseconds", "milliseconds",
1928 "minutes", "hours", "weeks", NULL
1931 if (PyArg_ParseTupleAndKeywords(args
, kw
, "|OOOOOOO:__new__",
1934 &ms
, &minute
, &hour
, &week
) == 0)
1937 x
= PyLong_FromLong(0);
1948 y
= accum("microseconds", x
, us
, us_per_us
, &leftover_us
);
1952 y
= accum("milliseconds", x
, ms
, us_per_ms
, &leftover_us
);
1956 y
= accum("seconds", x
, second
, us_per_second
, &leftover_us
);
1960 y
= accum("minutes", x
, minute
, us_per_minute
, &leftover_us
);
1964 y
= accum("hours", x
, hour
, us_per_hour
, &leftover_us
);
1968 y
= accum("days", x
, day
, us_per_day
, &leftover_us
);
1972 y
= accum("weeks", x
, week
, us_per_week
, &leftover_us
);
1976 /* Round to nearest whole # of us, and add into x. */
1977 PyObject
*temp
= PyLong_FromLong(round_to_long(leftover_us
));
1982 y
= PyNumber_Add(x
, temp
);
1987 self
= microseconds_to_delta_ex(x
, type
);
1996 delta_bool(PyDateTime_Delta
*self
)
1998 return (GET_TD_DAYS(self
) != 0
1999 || GET_TD_SECONDS(self
) != 0
2000 || GET_TD_MICROSECONDS(self
) != 0);
2004 delta_repr(PyDateTime_Delta
*self
)
2006 if (GET_TD_MICROSECONDS(self
) != 0)
2007 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2008 Py_TYPE(self
)->tp_name
,
2010 GET_TD_SECONDS(self
),
2011 GET_TD_MICROSECONDS(self
));
2012 if (GET_TD_SECONDS(self
) != 0)
2013 return PyUnicode_FromFormat("%s(%d, %d)",
2014 Py_TYPE(self
)->tp_name
,
2016 GET_TD_SECONDS(self
));
2018 return PyUnicode_FromFormat("%s(%d)",
2019 Py_TYPE(self
)->tp_name
,
2024 delta_str(PyDateTime_Delta
*self
)
2026 int us
= GET_TD_MICROSECONDS(self
);
2027 int seconds
= GET_TD_SECONDS(self
);
2028 int minutes
= divmod(seconds
, 60, &seconds
);
2029 int hours
= divmod(minutes
, 60, &minutes
);
2030 int days
= GET_TD_DAYS(self
);
2034 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2035 days
, (days
== 1 || days
== -1) ? "" : "s",
2036 hours
, minutes
, seconds
, us
);
2038 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2039 days
, (days
== 1 || days
== -1) ? "" : "s",
2040 hours
, minutes
, seconds
);
2043 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2044 hours
, minutes
, seconds
, us
);
2046 return PyUnicode_FromFormat("%d:%02d:%02d",
2047 hours
, minutes
, seconds
);
2052 /* Pickle support, a simple use of __reduce__. */
2054 /* __getstate__ isn't exposed */
2056 delta_getstate(PyDateTime_Delta
*self
)
2058 return Py_BuildValue("iii", GET_TD_DAYS(self
),
2059 GET_TD_SECONDS(self
),
2060 GET_TD_MICROSECONDS(self
));
2064 delta_reduce(PyDateTime_Delta
* self
)
2066 return Py_BuildValue("ON", Py_TYPE(self
), delta_getstate(self
));
2069 #define OFFSET(field) offsetof(PyDateTime_Delta, field)
2071 static PyMemberDef delta_members
[] = {
2073 {"days", T_INT
, OFFSET(days
), READONLY
,
2074 PyDoc_STR("Number of days.")},
2076 {"seconds", T_INT
, OFFSET(seconds
), READONLY
,
2077 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2079 {"microseconds", T_INT
, OFFSET(microseconds
), READONLY
,
2080 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2084 static PyMethodDef delta_methods
[] = {
2085 {"__reduce__", (PyCFunction
)delta_reduce
, METH_NOARGS
,
2086 PyDoc_STR("__reduce__() -> (cls, state)")},
2091 static char delta_doc
[] =
2092 PyDoc_STR("Difference between two datetime values.");
2094 static PyNumberMethods delta_as_number
= {
2095 delta_add
, /* nb_add */
2096 delta_subtract
, /* nb_subtract */
2097 delta_multiply
, /* nb_multiply */
2098 0, /* nb_remainder */
2101 (unaryfunc
)delta_negative
, /* nb_negative */
2102 (unaryfunc
)delta_positive
, /* nb_positive */
2103 (unaryfunc
)delta_abs
, /* nb_absolute */
2104 (inquiry
)delta_bool
, /* nb_bool */
2114 0, /*nb_inplace_add*/
2115 0, /*nb_inplace_subtract*/
2116 0, /*nb_inplace_multiply*/
2117 0, /*nb_inplace_remainder*/
2118 0, /*nb_inplace_power*/
2119 0, /*nb_inplace_lshift*/
2120 0, /*nb_inplace_rshift*/
2121 0, /*nb_inplace_and*/
2122 0, /*nb_inplace_xor*/
2123 0, /*nb_inplace_or*/
2124 delta_divide
, /* nb_floor_divide */
2125 0, /* nb_true_divide */
2126 0, /* nb_inplace_floor_divide */
2127 0, /* nb_inplace_true_divide */
2130 static PyTypeObject PyDateTime_DeltaType
= {
2131 PyVarObject_HEAD_INIT(NULL
, 0)
2132 "datetime.timedelta", /* tp_name */
2133 sizeof(PyDateTime_Delta
), /* tp_basicsize */
2134 0, /* tp_itemsize */
2139 0, /* tp_reserved */
2140 (reprfunc
)delta_repr
, /* tp_repr */
2141 &delta_as_number
, /* tp_as_number */
2142 0, /* tp_as_sequence */
2143 0, /* tp_as_mapping */
2144 (hashfunc
)delta_hash
, /* tp_hash */
2146 (reprfunc
)delta_str
, /* tp_str */
2147 PyObject_GenericGetAttr
, /* tp_getattro */
2148 0, /* tp_setattro */
2149 0, /* tp_as_buffer */
2150 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2151 delta_doc
, /* tp_doc */
2152 0, /* tp_traverse */
2154 delta_richcompare
, /* tp_richcompare */
2155 0, /* tp_weaklistoffset */
2157 0, /* tp_iternext */
2158 delta_methods
, /* tp_methods */
2159 delta_members
, /* tp_members */
2163 0, /* tp_descr_get */
2164 0, /* tp_descr_set */
2165 0, /* tp_dictoffset */
2168 delta_new
, /* tp_new */
2173 * PyDateTime_Date implementation.
2176 /* Accessor properties. */
2179 date_year(PyDateTime_Date
*self
, void *unused
)
2181 return PyLong_FromLong(GET_YEAR(self
));
2185 date_month(PyDateTime_Date
*self
, void *unused
)
2187 return PyLong_FromLong(GET_MONTH(self
));
2191 date_day(PyDateTime_Date
*self
, void *unused
)
2193 return PyLong_FromLong(GET_DAY(self
));
2196 static PyGetSetDef date_getset
[] = {
2197 {"year", (getter
)date_year
},
2198 {"month", (getter
)date_month
},
2199 {"day", (getter
)date_day
},
2205 static char *date_kws
[] = {"year", "month", "day", NULL
};
2208 date_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
2210 PyObject
*self
= NULL
;
2216 /* Check for invocation from pickle with __getstate__ state */
2217 if (PyTuple_GET_SIZE(args
) == 1 &&
2218 PyBytes_Check(state
= PyTuple_GET_ITEM(args
, 0)) &&
2219 PyBytes_GET_SIZE(state
) == _PyDateTime_DATE_DATASIZE
&&
2220 MONTH_IS_SANE(PyBytes_AS_STRING(state
)[2]))
2222 PyDateTime_Date
*me
;
2224 me
= (PyDateTime_Date
*) (type
->tp_alloc(type
, 0));
2226 char *pdata
= PyBytes_AS_STRING(state
);
2227 memcpy(me
->data
, pdata
, _PyDateTime_DATE_DATASIZE
);
2230 return (PyObject
*)me
;
2233 if (PyArg_ParseTupleAndKeywords(args
, kw
, "iii", date_kws
,
2234 &year
, &month
, &day
)) {
2235 if (check_date_args(year
, month
, day
) < 0)
2237 self
= new_date_ex(year
, month
, day
, type
);
2242 /* Return new date from localtime(t). */
2244 date_local_from_time_t(PyObject
*cls
, double ts
)
2248 PyObject
*result
= NULL
;
2250 t
= _PyTime_DoubleToTimet(ts
);
2251 if (t
== (time_t)-1 && PyErr_Occurred())
2255 result
= PyObject_CallFunction(cls
, "iii",
2260 PyErr_SetString(PyExc_ValueError
,
2261 "timestamp out of range for "
2262 "platform localtime() function");
2266 /* Return new date from current time.
2267 * We say this is equivalent to fromtimestamp(time.time()), and the
2268 * only way to be sure of that is to *call* time.time(). That's not
2269 * generally the same as calling C's time.
2272 date_today(PyObject
*cls
, PyObject
*dummy
)
2281 /* Note well: today() is a class method, so this may not call
2282 * date.fromtimestamp. For example, it may call
2283 * datetime.fromtimestamp. That's why we need all the accuracy
2284 * time.time() delivers; if someone were gonzo about optimization,
2285 * date.today() could get away with plain C time().
2287 result
= PyObject_CallMethod(cls
, "fromtimestamp", "O", time
);
2292 /* Return new date from given timestamp (Python timestamp -- a double). */
2294 date_fromtimestamp(PyObject
*cls
, PyObject
*args
)
2297 PyObject
*result
= NULL
;
2299 if (PyArg_ParseTuple(args
, "d:fromtimestamp", ×tamp
))
2300 result
= date_local_from_time_t(cls
, timestamp
);
2304 /* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2305 * the ordinal is out of range.
2308 date_fromordinal(PyObject
*cls
, PyObject
*args
)
2310 PyObject
*result
= NULL
;
2313 if (PyArg_ParseTuple(args
, "i:fromordinal", &ordinal
)) {
2319 PyErr_SetString(PyExc_ValueError
, "ordinal must be "
2322 ord_to_ymd(ordinal
, &year
, &month
, &day
);
2323 result
= PyObject_CallFunction(cls
, "iii",
2334 /* date + timedelta -> date. If arg negate is true, subtract the timedelta
2338 add_date_timedelta(PyDateTime_Date
*date
, PyDateTime_Delta
*delta
, int negate
)
2340 PyObject
*result
= NULL
;
2341 int year
= GET_YEAR(date
);
2342 int month
= GET_MONTH(date
);
2343 int deltadays
= GET_TD_DAYS(delta
);
2344 /* C-level overflow is impossible because |deltadays| < 1e9. */
2345 int day
= GET_DAY(date
) + (negate
? -deltadays
: deltadays
);
2347 if (normalize_date(&year
, &month
, &day
) >= 0)
2348 result
= new_date(year
, month
, day
);
2353 date_add(PyObject
*left
, PyObject
*right
)
2355 if (PyDateTime_Check(left
) || PyDateTime_Check(right
)) {
2356 Py_INCREF(Py_NotImplemented
);
2357 return Py_NotImplemented
;
2359 if (PyDate_Check(left
)) {
2361 if (PyDelta_Check(right
))
2363 return add_date_timedelta((PyDateTime_Date
*) left
,
2364 (PyDateTime_Delta
*) right
,
2369 * 'right' must be one of us, or we wouldn't have been called
2371 if (PyDelta_Check(left
))
2373 return add_date_timedelta((PyDateTime_Date
*) right
,
2374 (PyDateTime_Delta
*) left
,
2377 Py_INCREF(Py_NotImplemented
);
2378 return Py_NotImplemented
;
2382 date_subtract(PyObject
*left
, PyObject
*right
)
2384 if (PyDateTime_Check(left
) || PyDateTime_Check(right
)) {
2385 Py_INCREF(Py_NotImplemented
);
2386 return Py_NotImplemented
;
2388 if (PyDate_Check(left
)) {
2389 if (PyDate_Check(right
)) {
2391 int left_ord
= ymd_to_ord(GET_YEAR(left
),
2394 int right_ord
= ymd_to_ord(GET_YEAR(right
),
2397 return new_delta(left_ord
- right_ord
, 0, 0, 0);
2399 if (PyDelta_Check(right
)) {
2401 return add_date_timedelta((PyDateTime_Date
*) left
,
2402 (PyDateTime_Delta
*) right
,
2406 Py_INCREF(Py_NotImplemented
);
2407 return Py_NotImplemented
;
2411 /* Various ways to turn a date into a string. */
2414 date_repr(PyDateTime_Date
*self
)
2416 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2417 Py_TYPE(self
)->tp_name
,
2418 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
));
2422 date_isoformat(PyDateTime_Date
*self
)
2424 return PyUnicode_FromFormat("%04d-%02d-%02d",
2425 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
));
2428 /* str() calls the appropriate isoformat() method. */
2430 date_str(PyDateTime_Date
*self
)
2432 return PyObject_CallMethod((PyObject
*)self
, "isoformat", "()");
2437 date_ctime(PyDateTime_Date
*self
)
2439 return format_ctime(self
, 0, 0, 0);
2443 date_strftime(PyDateTime_Date
*self
, PyObject
*args
, PyObject
*kw
)
2445 /* This method can be inherited, and needs to call the
2446 * timetuple() method appropriate to self's class.
2451 static char *keywords
[] = {"format", NULL
};
2453 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "U:strftime", keywords
,
2457 tuple
= PyObject_CallMethod((PyObject
*)self
, "timetuple", "()");
2460 result
= wrap_strftime((PyObject
*)self
, format
, tuple
,
2467 date_format(PyDateTime_Date
*self
, PyObject
*args
)
2471 if (!PyArg_ParseTuple(args
, "U:__format__", &format
))
2474 /* if the format is zero length, return str(self) */
2475 if (PyUnicode_GetSize(format
) == 0)
2476 return PyObject_Str((PyObject
*)self
);
2478 return PyObject_CallMethod((PyObject
*)self
, "strftime", "O", format
);
2484 date_isoweekday(PyDateTime_Date
*self
)
2486 int dow
= weekday(GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
));
2488 return PyLong_FromLong(dow
+ 1);
2492 date_isocalendar(PyDateTime_Date
*self
)
2494 int year
= GET_YEAR(self
);
2495 int week1_monday
= iso_week1_monday(year
);
2496 int today
= ymd_to_ord(year
, GET_MONTH(self
), GET_DAY(self
));
2500 week
= divmod(today
- week1_monday
, 7, &day
);
2503 week1_monday
= iso_week1_monday(year
);
2504 week
= divmod(today
- week1_monday
, 7, &day
);
2506 else if (week
>= 52 && today
>= iso_week1_monday(year
+ 1)) {
2510 return Py_BuildValue("iii", year
, week
+ 1, day
+ 1);
2513 /* Miscellaneous methods. */
2516 date_richcompare(PyObject
*self
, PyObject
*other
, int op
)
2518 if (PyDate_Check(other
)) {
2519 int diff
= memcmp(((PyDateTime_Date
*)self
)->data
,
2520 ((PyDateTime_Date
*)other
)->data
,
2521 _PyDateTime_DATE_DATASIZE
);
2522 return diff_to_bool(diff
, op
);
2525 Py_INCREF(Py_NotImplemented
);
2526 return Py_NotImplemented
;
2531 date_timetuple(PyDateTime_Date
*self
)
2533 return build_struct_time(GET_YEAR(self
),
2540 date_replace(PyDateTime_Date
*self
, PyObject
*args
, PyObject
*kw
)
2544 int year
= GET_YEAR(self
);
2545 int month
= GET_MONTH(self
);
2546 int day
= GET_DAY(self
);
2548 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "|iii:replace", date_kws
,
2549 &year
, &month
, &day
))
2551 tuple
= Py_BuildValue("iii", year
, month
, day
);
2554 clone
= date_new(Py_TYPE(self
), tuple
, NULL
);
2560 Borrowed from stringobject.c, originally it was string_hash()
2563 generic_hash(unsigned char *data
, int len
)
2565 register unsigned char *p
;
2568 p
= (unsigned char *) data
;
2571 x
= (1000003*x
) ^ *p
++;
2580 static PyObject
*date_getstate(PyDateTime_Date
*self
);
2583 date_hash(PyDateTime_Date
*self
)
2585 if (self
->hashcode
== -1)
2586 self
->hashcode
= generic_hash(
2587 (unsigned char *)self
->data
, _PyDateTime_DATE_DATASIZE
);
2589 return self
->hashcode
;
2593 date_toordinal(PyDateTime_Date
*self
)
2595 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self
), GET_MONTH(self
),
2600 date_weekday(PyDateTime_Date
*self
)
2602 int dow
= weekday(GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
));
2604 return PyLong_FromLong(dow
);
2607 /* Pickle support, a simple use of __reduce__. */
2609 /* __getstate__ isn't exposed */
2611 date_getstate(PyDateTime_Date
*self
)
2614 field
= PyBytes_FromStringAndSize((char*)self
->data
,
2615 _PyDateTime_DATE_DATASIZE
);
2616 return Py_BuildValue("(N)", field
);
2620 date_reduce(PyDateTime_Date
*self
, PyObject
*arg
)
2622 return Py_BuildValue("(ON)", Py_TYPE(self
), date_getstate(self
));
2625 static PyMethodDef date_methods
[] = {
2627 /* Class methods: */
2629 {"fromtimestamp", (PyCFunction
)date_fromtimestamp
, METH_VARARGS
|
2631 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2634 {"fromordinal", (PyCFunction
)date_fromordinal
, METH_VARARGS
|
2636 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2639 {"today", (PyCFunction
)date_today
, METH_NOARGS
| METH_CLASS
,
2640 PyDoc_STR("Current date or datetime: same as "
2641 "self.__class__.fromtimestamp(time.time()).")},
2643 /* Instance methods: */
2645 {"ctime", (PyCFunction
)date_ctime
, METH_NOARGS
,
2646 PyDoc_STR("Return ctime() style string.")},
2648 {"strftime", (PyCFunction
)date_strftime
, METH_VARARGS
| METH_KEYWORDS
,
2649 PyDoc_STR("format -> strftime() style string.")},
2651 {"__format__", (PyCFunction
)date_format
, METH_VARARGS
,
2652 PyDoc_STR("Formats self with strftime.")},
2654 {"timetuple", (PyCFunction
)date_timetuple
, METH_NOARGS
,
2655 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2657 {"isocalendar", (PyCFunction
)date_isocalendar
, METH_NOARGS
,
2658 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2661 {"isoformat", (PyCFunction
)date_isoformat
, METH_NOARGS
,
2662 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2664 {"isoweekday", (PyCFunction
)date_isoweekday
, METH_NOARGS
,
2665 PyDoc_STR("Return the day of the week represented by the date.\n"
2666 "Monday == 1 ... Sunday == 7")},
2668 {"toordinal", (PyCFunction
)date_toordinal
, METH_NOARGS
,
2669 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2672 {"weekday", (PyCFunction
)date_weekday
, METH_NOARGS
,
2673 PyDoc_STR("Return the day of the week represented by the date.\n"
2674 "Monday == 0 ... Sunday == 6")},
2676 {"replace", (PyCFunction
)date_replace
, METH_VARARGS
| METH_KEYWORDS
,
2677 PyDoc_STR("Return date with new specified fields.")},
2679 {"__reduce__", (PyCFunction
)date_reduce
, METH_NOARGS
,
2680 PyDoc_STR("__reduce__() -> (cls, state)")},
2685 static char date_doc
[] =
2686 PyDoc_STR("date(year, month, day) --> date object");
2688 static PyNumberMethods date_as_number
= {
2689 date_add
, /* nb_add */
2690 date_subtract
, /* nb_subtract */
2691 0, /* nb_multiply */
2692 0, /* nb_remainder */
2695 0, /* nb_negative */
2696 0, /* nb_positive */
2697 0, /* nb_absolute */
2701 static PyTypeObject PyDateTime_DateType
= {
2702 PyVarObject_HEAD_INIT(NULL
, 0)
2703 "datetime.date", /* tp_name */
2704 sizeof(PyDateTime_Date
), /* tp_basicsize */
2705 0, /* tp_itemsize */
2710 0, /* tp_reserved */
2711 (reprfunc
)date_repr
, /* tp_repr */
2712 &date_as_number
, /* tp_as_number */
2713 0, /* tp_as_sequence */
2714 0, /* tp_as_mapping */
2715 (hashfunc
)date_hash
, /* tp_hash */
2717 (reprfunc
)date_str
, /* tp_str */
2718 PyObject_GenericGetAttr
, /* tp_getattro */
2719 0, /* tp_setattro */
2720 0, /* tp_as_buffer */
2721 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2722 date_doc
, /* tp_doc */
2723 0, /* tp_traverse */
2725 date_richcompare
, /* tp_richcompare */
2726 0, /* tp_weaklistoffset */
2728 0, /* tp_iternext */
2729 date_methods
, /* tp_methods */
2731 date_getset
, /* tp_getset */
2734 0, /* tp_descr_get */
2735 0, /* tp_descr_set */
2736 0, /* tp_dictoffset */
2739 date_new
, /* tp_new */
2744 * PyDateTime_TZInfo implementation.
2747 /* This is a pure abstract base class, so doesn't do anything beyond
2748 * raising NotImplemented exceptions. Real tzinfo classes need
2749 * to derive from this. This is mostly for clarity, and for efficiency in
2750 * datetime and time constructors (their tzinfo arguments need to
2751 * be subclasses of this tzinfo class, which is easy and quick to check).
2753 * Note: For reasons having to do with pickling of subclasses, we have
2754 * to allow tzinfo objects to be instantiated. This wasn't an issue
2755 * in the Python implementation (__init__() could raise NotImplementedError
2756 * there without ill effect), but doing so in the C implementation hit a
2761 tzinfo_nogo(const char* methodname
)
2763 PyErr_Format(PyExc_NotImplementedError
,
2764 "a tzinfo subclass must implement %s()",
2769 /* Methods. A subclass must implement these. */
2772 tzinfo_tzname(PyDateTime_TZInfo
*self
, PyObject
*dt
)
2774 return tzinfo_nogo("tzname");
2778 tzinfo_utcoffset(PyDateTime_TZInfo
*self
, PyObject
*dt
)
2780 return tzinfo_nogo("utcoffset");
2784 tzinfo_dst(PyDateTime_TZInfo
*self
, PyObject
*dt
)
2786 return tzinfo_nogo("dst");
2790 tzinfo_fromutc(PyDateTime_TZInfo
*self
, PyDateTime_DateTime
*dt
)
2792 int y
, m
, d
, hh
, mm
, ss
, us
;
2799 if (! PyDateTime_Check(dt
)) {
2800 PyErr_SetString(PyExc_TypeError
,
2801 "fromutc: argument must be a datetime");
2804 if (! HASTZINFO(dt
) || dt
->tzinfo
!= (PyObject
*)self
) {
2805 PyErr_SetString(PyExc_ValueError
, "fromutc: dt.tzinfo "
2810 off
= call_utcoffset(dt
->tzinfo
, (PyObject
*)dt
, &none
);
2811 if (off
== -1 && PyErr_Occurred())
2814 PyErr_SetString(PyExc_ValueError
, "fromutc: non-None "
2815 "utcoffset() result required");
2819 dst
= call_dst(dt
->tzinfo
, (PyObject
*)dt
, &none
);
2820 if (dst
== -1 && PyErr_Occurred())
2823 PyErr_SetString(PyExc_ValueError
, "fromutc: non-None "
2824 "dst() result required");
2831 hh
= DATE_GET_HOUR(dt
);
2832 mm
= DATE_GET_MINUTE(dt
);
2833 ss
= DATE_GET_SECOND(dt
);
2834 us
= DATE_GET_MICROSECOND(dt
);
2838 if ((mm
< 0 || mm
>= 60) &&
2839 normalize_datetime(&y
, &m
, &d
, &hh
, &mm
, &ss
, &us
) < 0)
2841 result
= new_datetime(y
, m
, d
, hh
, mm
, ss
, us
, dt
->tzinfo
);
2845 dst
= call_dst(dt
->tzinfo
, result
, &none
);
2846 if (dst
== -1 && PyErr_Occurred())
2854 if ((mm
< 0 || mm
>= 60) &&
2855 normalize_datetime(&y
, &m
, &d
, &hh
, &mm
, &ss
, &us
) < 0)
2858 result
= new_datetime(y
, m
, d
, hh
, mm
, ss
, us
, dt
->tzinfo
);
2862 PyErr_SetString(PyExc_ValueError
, "fromutc: tz.dst() gave"
2863 "inconsistent results; cannot convert");
2865 /* fall thru to failure */
2872 * Pickle support. This is solely so that tzinfo subclasses can use
2873 * pickling -- tzinfo itself is supposed to be uninstantiable.
2877 tzinfo_reduce(PyObject
*self
)
2879 PyObject
*args
, *state
, *tmp
;
2880 PyObject
*getinitargs
, *getstate
;
2882 tmp
= PyTuple_New(0);
2886 getinitargs
= PyObject_GetAttrString(self
, "__getinitargs__");
2887 if (getinitargs
!= NULL
) {
2888 args
= PyObject_CallObject(getinitargs
, tmp
);
2889 Py_DECREF(getinitargs
);
2901 getstate
= PyObject_GetAttrString(self
, "__getstate__");
2902 if (getstate
!= NULL
) {
2903 state
= PyObject_CallObject(getstate
, tmp
);
2904 Py_DECREF(getstate
);
2905 if (state
== NULL
) {
2915 dictptr
= _PyObject_GetDictPtr(self
);
2916 if (dictptr
&& *dictptr
&& PyDict_Size(*dictptr
))
2923 if (state
== Py_None
) {
2925 return Py_BuildValue("(ON)", Py_TYPE(self
), args
);
2928 return Py_BuildValue("(ONN)", Py_TYPE(self
), args
, state
);
2931 static PyMethodDef tzinfo_methods
[] = {
2933 {"tzname", (PyCFunction
)tzinfo_tzname
, METH_O
,
2934 PyDoc_STR("datetime -> string name of time zone.")},
2936 {"utcoffset", (PyCFunction
)tzinfo_utcoffset
, METH_O
,
2937 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2940 {"dst", (PyCFunction
)tzinfo_dst
, METH_O
,
2941 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2943 {"fromutc", (PyCFunction
)tzinfo_fromutc
, METH_O
,
2944 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
2945 "values indicating West of UTC")},
2947 {"__reduce__", (PyCFunction
)tzinfo_reduce
, METH_NOARGS
,
2948 PyDoc_STR("-> (cls, state)")},
2953 static char tzinfo_doc
[] =
2954 PyDoc_STR("Abstract base class for time zone info objects.");
2956 static PyTypeObject PyDateTime_TZInfoType
= {
2957 PyVarObject_HEAD_INIT(NULL
, 0)
2958 "datetime.tzinfo", /* tp_name */
2959 sizeof(PyDateTime_TZInfo
), /* tp_basicsize */
2960 0, /* tp_itemsize */
2965 0, /* tp_reserved */
2967 0, /* tp_as_number */
2968 0, /* tp_as_sequence */
2969 0, /* tp_as_mapping */
2973 PyObject_GenericGetAttr
, /* tp_getattro */
2974 0, /* tp_setattro */
2975 0, /* tp_as_buffer */
2976 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
2977 tzinfo_doc
, /* tp_doc */
2978 0, /* tp_traverse */
2980 0, /* tp_richcompare */
2981 0, /* tp_weaklistoffset */
2983 0, /* tp_iternext */
2984 tzinfo_methods
, /* tp_methods */
2989 0, /* tp_descr_get */
2990 0, /* tp_descr_set */
2991 0, /* tp_dictoffset */
2994 PyType_GenericNew
, /* tp_new */
2999 * PyDateTime_Time implementation.
3002 /* Accessor properties.
3006 time_hour(PyDateTime_Time
*self
, void *unused
)
3008 return PyLong_FromLong(TIME_GET_HOUR(self
));
3012 time_minute(PyDateTime_Time
*self
, void *unused
)
3014 return PyLong_FromLong(TIME_GET_MINUTE(self
));
3017 /* The name time_second conflicted with some platform header file. */
3019 py_time_second(PyDateTime_Time
*self
, void *unused
)
3021 return PyLong_FromLong(TIME_GET_SECOND(self
));
3025 time_microsecond(PyDateTime_Time
*self
, void *unused
)
3027 return PyLong_FromLong(TIME_GET_MICROSECOND(self
));
3031 time_tzinfo(PyDateTime_Time
*self
, void *unused
)
3033 PyObject
*result
= HASTZINFO(self
) ? self
->tzinfo
: Py_None
;
3038 static PyGetSetDef time_getset
[] = {
3039 {"hour", (getter
)time_hour
},
3040 {"minute", (getter
)time_minute
},
3041 {"second", (getter
)py_time_second
},
3042 {"microsecond", (getter
)time_microsecond
},
3043 {"tzinfo", (getter
)time_tzinfo
},
3051 static char *time_kws
[] = {"hour", "minute", "second", "microsecond",
3055 time_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
3057 PyObject
*self
= NULL
;
3063 PyObject
*tzinfo
= Py_None
;
3065 /* Check for invocation from pickle with __getstate__ state */
3066 if (PyTuple_GET_SIZE(args
) >= 1 &&
3067 PyTuple_GET_SIZE(args
) <= 2 &&
3068 PyBytes_Check(state
= PyTuple_GET_ITEM(args
, 0)) &&
3069 PyBytes_GET_SIZE(state
) == _PyDateTime_TIME_DATASIZE
&&
3070 ((unsigned char) (PyBytes_AS_STRING(state
)[0])) < 24)
3072 PyDateTime_Time
*me
;
3075 if (PyTuple_GET_SIZE(args
) == 2) {
3076 tzinfo
= PyTuple_GET_ITEM(args
, 1);
3077 if (check_tzinfo_subclass(tzinfo
) < 0) {
3078 PyErr_SetString(PyExc_TypeError
, "bad "
3079 "tzinfo state arg");
3083 aware
= (char)(tzinfo
!= Py_None
);
3084 me
= (PyDateTime_Time
*) (type
->tp_alloc(type
, aware
));
3086 char *pdata
= PyBytes_AS_STRING(state
);
3088 memcpy(me
->data
, pdata
, _PyDateTime_TIME_DATASIZE
);
3090 me
->hastzinfo
= aware
;
3093 me
->tzinfo
= tzinfo
;
3096 return (PyObject
*)me
;
3099 if (PyArg_ParseTupleAndKeywords(args
, kw
, "|iiiiO", time_kws
,
3100 &hour
, &minute
, &second
, &usecond
,
3102 if (check_time_args(hour
, minute
, second
, usecond
) < 0)
3104 if (check_tzinfo_subclass(tzinfo
) < 0)
3106 self
= new_time_ex(hour
, minute
, second
, usecond
, tzinfo
,
3117 time_dealloc(PyDateTime_Time
*self
)
3119 if (HASTZINFO(self
)) {
3120 Py_XDECREF(self
->tzinfo
);
3122 Py_TYPE(self
)->tp_free((PyObject
*)self
);
3126 * Indirect access to tzinfo methods.
3129 /* These are all METH_NOARGS, so don't need to check the arglist. */
3131 time_utcoffset(PyDateTime_Time
*self
, PyObject
*unused
) {
3132 return offset_as_timedelta(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3133 "utcoffset", Py_None
);
3137 time_dst(PyDateTime_Time
*self
, PyObject
*unused
) {
3138 return offset_as_timedelta(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3143 time_tzname(PyDateTime_Time
*self
, PyObject
*unused
) {
3144 return call_tzname(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3149 * Various ways to turn a time into a string.
3153 time_repr(PyDateTime_Time
*self
)
3155 const char *type_name
= Py_TYPE(self
)->tp_name
;
3156 int h
= TIME_GET_HOUR(self
);
3157 int m
= TIME_GET_MINUTE(self
);
3158 int s
= TIME_GET_SECOND(self
);
3159 int us
= TIME_GET_MICROSECOND(self
);
3160 PyObject
*result
= NULL
;
3163 result
= PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3164 type_name
, h
, m
, s
, us
);
3166 result
= PyUnicode_FromFormat("%s(%d, %d, %d)",
3167 type_name
, h
, m
, s
);
3169 result
= PyUnicode_FromFormat("%s(%d, %d)", type_name
, h
, m
);
3170 if (result
!= NULL
&& HASTZINFO(self
))
3171 result
= append_keyword_tzinfo(result
, self
->tzinfo
);
3176 time_str(PyDateTime_Time
*self
)
3178 return PyObject_CallMethod((PyObject
*)self
, "isoformat", "()");
3182 time_isoformat(PyDateTime_Time
*self
, PyObject
*unused
)
3186 int us
= TIME_GET_MICROSECOND(self
);;
3189 result
= PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3190 TIME_GET_HOUR(self
),
3191 TIME_GET_MINUTE(self
),
3192 TIME_GET_SECOND(self
),
3195 result
= PyUnicode_FromFormat("%02d:%02d:%02d",
3196 TIME_GET_HOUR(self
),
3197 TIME_GET_MINUTE(self
),
3198 TIME_GET_SECOND(self
));
3200 if (result
== NULL
|| ! HASTZINFO(self
) || self
->tzinfo
== Py_None
)
3203 /* We need to append the UTC offset. */
3204 if (format_utcoffset(buf
, sizeof(buf
), ":", self
->tzinfo
,
3209 PyUnicode_AppendAndDel(&result
, PyUnicode_FromString(buf
));
3214 time_strftime(PyDateTime_Time
*self
, PyObject
*args
, PyObject
*kw
)
3219 static char *keywords
[] = {"format", NULL
};
3221 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "U:strftime", keywords
,
3225 /* Python's strftime does insane things with the year part of the
3226 * timetuple. The year is forced to (the otherwise nonsensical)
3227 * 1900 to worm around that.
3229 tuple
= Py_BuildValue("iiiiiiiii",
3230 1900, 1, 1, /* year, month, day */
3231 TIME_GET_HOUR(self
),
3232 TIME_GET_MINUTE(self
),
3233 TIME_GET_SECOND(self
),
3234 0, 1, -1); /* weekday, daynum, dst */
3237 assert(PyTuple_Size(tuple
) == 9);
3238 result
= wrap_strftime((PyObject
*)self
, format
, tuple
,
3245 * Miscellaneous methods.
3249 time_richcompare(PyObject
*self
, PyObject
*other
, int op
)
3253 int offset1
, offset2
;
3255 if (! PyTime_Check(other
)) {
3256 Py_INCREF(Py_NotImplemented
);
3257 return Py_NotImplemented
;
3259 if (classify_two_utcoffsets(self
, &offset1
, &n1
, Py_None
,
3260 other
, &offset2
, &n2
, Py_None
) < 0)
3262 assert(n1
!= OFFSET_UNKNOWN
&& n2
!= OFFSET_UNKNOWN
);
3263 /* If they're both naive, or both aware and have the same offsets,
3264 * we get off cheap. Note that if they're both naive, offset1 ==
3265 * offset2 == 0 at this point.
3267 if (n1
== n2
&& offset1
== offset2
) {
3268 diff
= memcmp(((PyDateTime_Time
*)self
)->data
,
3269 ((PyDateTime_Time
*)other
)->data
,
3270 _PyDateTime_TIME_DATASIZE
);
3271 return diff_to_bool(diff
, op
);
3274 if (n1
== OFFSET_AWARE
&& n2
== OFFSET_AWARE
) {
3275 assert(offset1
!= offset2
); /* else last "if" handled it */
3276 /* Convert everything except microseconds to seconds. These
3277 * can't overflow (no more than the # of seconds in 2 days).
3279 offset1
= TIME_GET_HOUR(self
) * 3600 +
3280 (TIME_GET_MINUTE(self
) - offset1
) * 60 +
3281 TIME_GET_SECOND(self
);
3282 offset2
= TIME_GET_HOUR(other
) * 3600 +
3283 (TIME_GET_MINUTE(other
) - offset2
) * 60 +
3284 TIME_GET_SECOND(other
);
3285 diff
= offset1
- offset2
;
3287 diff
= TIME_GET_MICROSECOND(self
) -
3288 TIME_GET_MICROSECOND(other
);
3289 return diff_to_bool(diff
, op
);
3293 PyErr_SetString(PyExc_TypeError
,
3294 "can't compare offset-naive and "
3295 "offset-aware times");
3300 time_hash(PyDateTime_Time
*self
)
3302 if (self
->hashcode
== -1) {
3307 n
= classify_utcoffset((PyObject
*)self
, Py_None
, &offset
);
3308 assert(n
!= OFFSET_UNKNOWN
);
3309 if (n
== OFFSET_ERROR
)
3312 /* Reduce this to a hash of another object. */
3314 self
->hashcode
= generic_hash(
3315 (unsigned char *)self
->data
, _PyDateTime_TIME_DATASIZE
);
3316 return self
->hashcode
;
3322 assert(n
== OFFSET_AWARE
);
3323 assert(HASTZINFO(self
));
3324 hour
= divmod(TIME_GET_HOUR(self
) * 60 +
3325 TIME_GET_MINUTE(self
) - offset
,
3328 if (0 <= hour
&& hour
< 24)
3329 temp
= new_time(hour
, minute
,
3330 TIME_GET_SECOND(self
),
3331 TIME_GET_MICROSECOND(self
),
3334 temp
= Py_BuildValue("iiii",
3336 TIME_GET_SECOND(self
),
3337 TIME_GET_MICROSECOND(self
));
3340 self
->hashcode
= PyObject_Hash(temp
);
3344 return self
->hashcode
;
3348 time_replace(PyDateTime_Time
*self
, PyObject
*args
, PyObject
*kw
)
3352 int hh
= TIME_GET_HOUR(self
);
3353 int mm
= TIME_GET_MINUTE(self
);
3354 int ss
= TIME_GET_SECOND(self
);
3355 int us
= TIME_GET_MICROSECOND(self
);
3356 PyObject
*tzinfo
= HASTZINFO(self
) ? self
->tzinfo
: Py_None
;
3358 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "|iiiiO:replace",
3360 &hh
, &mm
, &ss
, &us
, &tzinfo
))
3362 tuple
= Py_BuildValue("iiiiO", hh
, mm
, ss
, us
, tzinfo
);
3365 clone
= time_new(Py_TYPE(self
), tuple
, NULL
);
3371 time_bool(PyDateTime_Time
*self
)
3376 if (TIME_GET_SECOND(self
) || TIME_GET_MICROSECOND(self
)) {
3377 /* Since utcoffset is in whole minutes, nothing can
3378 * alter the conclusion that this is nonzero.
3383 if (HASTZINFO(self
) && self
->tzinfo
!= Py_None
) {
3384 offset
= call_utcoffset(self
->tzinfo
, Py_None
, &none
);
3385 if (offset
== -1 && PyErr_Occurred())
3388 return (TIME_GET_MINUTE(self
) - offset
+ TIME_GET_HOUR(self
)*60) != 0;
3391 /* Pickle support, a simple use of __reduce__. */
3393 /* Let basestate be the non-tzinfo data string.
3394 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3395 * So it's a tuple in any (non-error) case.
3396 * __getstate__ isn't exposed.
3399 time_getstate(PyDateTime_Time
*self
)
3401 PyObject
*basestate
;
3402 PyObject
*result
= NULL
;
3404 basestate
= PyBytes_FromStringAndSize((char *)self
->data
,
3405 _PyDateTime_TIME_DATASIZE
);
3406 if (basestate
!= NULL
) {
3407 if (! HASTZINFO(self
) || self
->tzinfo
== Py_None
)
3408 result
= PyTuple_Pack(1, basestate
);
3410 result
= PyTuple_Pack(2, basestate
, self
->tzinfo
);
3411 Py_DECREF(basestate
);
3417 time_reduce(PyDateTime_Time
*self
, PyObject
*arg
)
3419 return Py_BuildValue("(ON)", Py_TYPE(self
), time_getstate(self
));
3422 static PyMethodDef time_methods
[] = {
3424 {"isoformat", (PyCFunction
)time_isoformat
, METH_NOARGS
,
3425 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3428 {"strftime", (PyCFunction
)time_strftime
, METH_VARARGS
| METH_KEYWORDS
,
3429 PyDoc_STR("format -> strftime() style string.")},
3431 {"__format__", (PyCFunction
)date_format
, METH_VARARGS
,
3432 PyDoc_STR("Formats self with strftime.")},
3434 {"utcoffset", (PyCFunction
)time_utcoffset
, METH_NOARGS
,
3435 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3437 {"tzname", (PyCFunction
)time_tzname
, METH_NOARGS
,
3438 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3440 {"dst", (PyCFunction
)time_dst
, METH_NOARGS
,
3441 PyDoc_STR("Return self.tzinfo.dst(self).")},
3443 {"replace", (PyCFunction
)time_replace
, METH_VARARGS
| METH_KEYWORDS
,
3444 PyDoc_STR("Return time with new specified fields.")},
3446 {"__reduce__", (PyCFunction
)time_reduce
, METH_NOARGS
,
3447 PyDoc_STR("__reduce__() -> (cls, state)")},
3452 static char time_doc
[] =
3453 PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3455 All arguments are optional. tzinfo may be None, or an instance of\n\
3456 a tzinfo subclass. The remaining arguments may be ints or longs.\n");
3458 static PyNumberMethods time_as_number
= {
3460 0, /* nb_subtract */
3461 0, /* nb_multiply */
3462 0, /* nb_remainder */
3465 0, /* nb_negative */
3466 0, /* nb_positive */
3467 0, /* nb_absolute */
3468 (inquiry
)time_bool
, /* nb_bool */
3471 static PyTypeObject PyDateTime_TimeType
= {
3472 PyVarObject_HEAD_INIT(NULL
, 0)
3473 "datetime.time", /* tp_name */
3474 sizeof(PyDateTime_Time
), /* tp_basicsize */
3475 0, /* tp_itemsize */
3476 (destructor
)time_dealloc
, /* tp_dealloc */
3480 0, /* tp_reserved */
3481 (reprfunc
)time_repr
, /* tp_repr */
3482 &time_as_number
, /* tp_as_number */
3483 0, /* tp_as_sequence */
3484 0, /* tp_as_mapping */
3485 (hashfunc
)time_hash
, /* tp_hash */
3487 (reprfunc
)time_str
, /* tp_str */
3488 PyObject_GenericGetAttr
, /* tp_getattro */
3489 0, /* tp_setattro */
3490 0, /* tp_as_buffer */
3491 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3492 time_doc
, /* tp_doc */
3493 0, /* tp_traverse */
3495 time_richcompare
, /* tp_richcompare */
3496 0, /* tp_weaklistoffset */
3498 0, /* tp_iternext */
3499 time_methods
, /* tp_methods */
3501 time_getset
, /* tp_getset */
3504 0, /* tp_descr_get */
3505 0, /* tp_descr_set */
3506 0, /* tp_dictoffset */
3508 time_alloc
, /* tp_alloc */
3509 time_new
, /* tp_new */
3514 * PyDateTime_DateTime implementation.
3517 /* Accessor properties. Properties for day, month, and year are inherited
3522 datetime_hour(PyDateTime_DateTime
*self
, void *unused
)
3524 return PyLong_FromLong(DATE_GET_HOUR(self
));
3528 datetime_minute(PyDateTime_DateTime
*self
, void *unused
)
3530 return PyLong_FromLong(DATE_GET_MINUTE(self
));
3534 datetime_second(PyDateTime_DateTime
*self
, void *unused
)
3536 return PyLong_FromLong(DATE_GET_SECOND(self
));
3540 datetime_microsecond(PyDateTime_DateTime
*self
, void *unused
)
3542 return PyLong_FromLong(DATE_GET_MICROSECOND(self
));
3546 datetime_tzinfo(PyDateTime_DateTime
*self
, void *unused
)
3548 PyObject
*result
= HASTZINFO(self
) ? self
->tzinfo
: Py_None
;
3553 static PyGetSetDef datetime_getset
[] = {
3554 {"hour", (getter
)datetime_hour
},
3555 {"minute", (getter
)datetime_minute
},
3556 {"second", (getter
)datetime_second
},
3557 {"microsecond", (getter
)datetime_microsecond
},
3558 {"tzinfo", (getter
)datetime_tzinfo
},
3566 static char *datetime_kws
[] = {
3567 "year", "month", "day", "hour", "minute", "second",
3568 "microsecond", "tzinfo", NULL
3572 datetime_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
3574 PyObject
*self
= NULL
;
3583 PyObject
*tzinfo
= Py_None
;
3585 /* Check for invocation from pickle with __getstate__ state */
3586 if (PyTuple_GET_SIZE(args
) >= 1 &&
3587 PyTuple_GET_SIZE(args
) <= 2 &&
3588 PyBytes_Check(state
= PyTuple_GET_ITEM(args
, 0)) &&
3589 PyBytes_GET_SIZE(state
) == _PyDateTime_DATETIME_DATASIZE
&&
3590 MONTH_IS_SANE(PyBytes_AS_STRING(state
)[2]))
3592 PyDateTime_DateTime
*me
;
3595 if (PyTuple_GET_SIZE(args
) == 2) {
3596 tzinfo
= PyTuple_GET_ITEM(args
, 1);
3597 if (check_tzinfo_subclass(tzinfo
) < 0) {
3598 PyErr_SetString(PyExc_TypeError
, "bad "
3599 "tzinfo state arg");
3603 aware
= (char)(tzinfo
!= Py_None
);
3604 me
= (PyDateTime_DateTime
*) (type
->tp_alloc(type
, aware
));
3606 char *pdata
= PyBytes_AS_STRING(state
);
3608 memcpy(me
->data
, pdata
, _PyDateTime_DATETIME_DATASIZE
);
3610 me
->hastzinfo
= aware
;
3613 me
->tzinfo
= tzinfo
;
3616 return (PyObject
*)me
;
3619 if (PyArg_ParseTupleAndKeywords(args
, kw
, "iii|iiiiO", datetime_kws
,
3620 &year
, &month
, &day
, &hour
, &minute
,
3621 &second
, &usecond
, &tzinfo
)) {
3622 if (check_date_args(year
, month
, day
) < 0)
3624 if (check_time_args(hour
, minute
, second
, usecond
) < 0)
3626 if (check_tzinfo_subclass(tzinfo
) < 0)
3628 self
= new_datetime_ex(year
, month
, day
,
3629 hour
, minute
, second
, usecond
,
3635 /* TM_FUNC is the shared type of localtime() and gmtime(). */
3636 typedef struct tm
*(*TM_FUNC
)(const time_t *timer
);
3639 * Build datetime from a time_t and a distinct count of microseconds.
3640 * Pass localtime or gmtime for f, to control the interpretation of timet.
3643 datetime_from_timet_and_us(PyObject
*cls
, TM_FUNC f
, time_t timet
, int us
,
3647 PyObject
*result
= NULL
;
3651 /* The platform localtime/gmtime may insert leap seconds,
3652 * indicated by tm->tm_sec > 59. We don't care about them,
3653 * except to the extent that passing them on to the datetime
3654 * constructor would raise ValueError for a reason that
3655 * made no sense to the user.
3657 if (tm
->tm_sec
> 59)
3659 result
= PyObject_CallFunction(cls
, "iiiiiiiO",
3670 PyErr_SetString(PyExc_ValueError
,
3671 "timestamp out of range for "
3672 "platform localtime()/gmtime() function");
3677 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3678 * to control the interpretation of the timestamp. Since a double doesn't
3679 * have enough bits to cover a datetime's full range of precision, it's
3680 * better to call datetime_from_timet_and_us provided you have a way
3681 * to get that much precision (e.g., C time() isn't good enough).
3684 datetime_from_timestamp(PyObject
*cls
, TM_FUNC f
, double timestamp
,
3691 timet
= _PyTime_DoubleToTimet(timestamp
);
3692 if (timet
== (time_t)-1 && PyErr_Occurred())
3694 fraction
= timestamp
- (double)timet
;
3695 us
= (int)round_to_long(fraction
* 1e6
);
3697 /* Truncation towards zero is not what we wanted
3698 for negative numbers (Python's mod semantics) */
3702 /* If timestamp is less than one microsecond smaller than a
3703 * full second, round up. Otherwise, ValueErrors are raised
3704 * for some floats. */
3705 if (us
== 1000000) {
3709 return datetime_from_timet_and_us(cls
, f
, timet
, us
, tzinfo
);
3713 * Build most accurate possible datetime for current time. Pass localtime or
3714 * gmtime for f as appropriate.
3717 datetime_best_possible(PyObject
*cls
, TM_FUNC f
, PyObject
*tzinfo
)
3719 #ifdef HAVE_GETTIMEOFDAY
3722 #ifdef GETTIMEOFDAY_NO_TZ
3725 gettimeofday(&t
, (struct timezone
*)NULL
);
3727 return datetime_from_timet_and_us(cls
, f
, t
.tv_sec
, (int)t
.tv_usec
,
3730 #else /* ! HAVE_GETTIMEOFDAY */
3731 /* No flavor of gettimeofday exists on this platform. Python's
3732 * time.time() does a lot of other platform tricks to get the
3733 * best time it can on the platform, and we're not going to do
3734 * better than that (if we could, the better code would belong
3735 * in time.time()!) We're limited by the precision of a double,
3744 dtime
= PyFloat_AsDouble(time
);
3746 if (dtime
== -1.0 && PyErr_Occurred())
3748 return datetime_from_timestamp(cls
, f
, dtime
, tzinfo
);
3749 #endif /* ! HAVE_GETTIMEOFDAY */
3752 /* Return best possible local time -- this isn't constrained by the
3753 * precision of a timestamp.
3756 datetime_now(PyObject
*cls
, PyObject
*args
, PyObject
*kw
)
3759 PyObject
*tzinfo
= Py_None
;
3760 static char *keywords
[] = {"tz", NULL
};
3762 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "|O:now", keywords
,
3765 if (check_tzinfo_subclass(tzinfo
) < 0)
3768 self
= datetime_best_possible(cls
,
3769 tzinfo
== Py_None
? localtime
: gmtime
,
3771 if (self
!= NULL
&& tzinfo
!= Py_None
) {
3772 /* Convert UTC to tzinfo's zone. */
3773 PyObject
*temp
= self
;
3774 self
= PyObject_CallMethod(tzinfo
, "fromutc", "O", self
);
3780 /* Return best possible UTC time -- this isn't constrained by the
3781 * precision of a timestamp.
3784 datetime_utcnow(PyObject
*cls
, PyObject
*dummy
)
3786 return datetime_best_possible(cls
, gmtime
, Py_None
);
3789 /* Return new local datetime from timestamp (Python timestamp -- a double). */
3791 datetime_fromtimestamp(PyObject
*cls
, PyObject
*args
, PyObject
*kw
)
3795 PyObject
*tzinfo
= Py_None
;
3796 static char *keywords
[] = {"timestamp", "tz", NULL
};
3798 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "d|O:fromtimestamp",
3799 keywords
, ×tamp
, &tzinfo
))
3801 if (check_tzinfo_subclass(tzinfo
) < 0)
3804 self
= datetime_from_timestamp(cls
,
3805 tzinfo
== Py_None
? localtime
: gmtime
,
3808 if (self
!= NULL
&& tzinfo
!= Py_None
) {
3809 /* Convert UTC to tzinfo's zone. */
3810 PyObject
*temp
= self
;
3811 self
= PyObject_CallMethod(tzinfo
, "fromutc", "O", self
);
3817 /* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3819 datetime_utcfromtimestamp(PyObject
*cls
, PyObject
*args
)
3822 PyObject
*result
= NULL
;
3824 if (PyArg_ParseTuple(args
, "d:utcfromtimestamp", ×tamp
))
3825 result
= datetime_from_timestamp(cls
, gmtime
, timestamp
,
3830 /* Return new datetime from time.strptime(). */
3832 datetime_strptime(PyObject
*cls
, PyObject
*args
)
3834 static PyObject
*module
= NULL
;
3835 PyObject
*result
= NULL
, *obj
, *st
= NULL
, *frac
= NULL
;
3836 const Py_UNICODE
*string
, *format
;
3838 if (!PyArg_ParseTuple(args
, "uu:strptime", &string
, &format
))
3841 if (module
== NULL
&&
3842 (module
= PyImport_ImportModuleNoBlock("_strptime")) == NULL
)
3845 /* _strptime._strptime returns a two-element tuple. The first
3846 element is a time.struct_time object. The second is the
3847 microseconds (which are not defined for time.struct_time). */
3848 obj
= PyObject_CallMethod(module
, "_strptime", "uu", string
, format
);
3850 int i
, good_timetuple
= 1;
3852 if (PySequence_Check(obj
) && PySequence_Size(obj
) == 2) {
3853 st
= PySequence_GetItem(obj
, 0);
3854 frac
= PySequence_GetItem(obj
, 1);
3855 if (st
== NULL
|| frac
== NULL
)
3857 /* copy y/m/d/h/m/s values out of the
3859 if (good_timetuple
&&
3860 PySequence_Check(st
) &&
3861 PySequence_Size(st
) >= 6) {
3862 for (i
=0; i
< 6; i
++) {
3863 PyObject
*p
= PySequence_GetItem(st
, i
);
3868 if (PyLong_Check(p
))
3869 ia
[i
] = PyLong_AsLong(p
);
3874 /* if (PyLong_CheckExact(p)) {
3875 ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
3885 /* follow that up with a little dose of microseconds */
3886 if (PyLong_Check(frac
))
3887 ia
[6] = PyLong_AsLong(frac
);
3894 result
= PyObject_CallFunction(cls
, "iiiiiii",
3895 ia
[0], ia
[1], ia
[2],
3896 ia
[3], ia
[4], ia
[5],
3899 PyErr_SetString(PyExc_ValueError
,
3900 "unexpected value from _strptime._strptime");
3908 /* Return new datetime from date/datetime and time arguments. */
3910 datetime_combine(PyObject
*cls
, PyObject
*args
, PyObject
*kw
)
3912 static char *keywords
[] = {"date", "time", NULL
};
3915 PyObject
*result
= NULL
;
3917 if (PyArg_ParseTupleAndKeywords(args
, kw
, "O!O!:combine", keywords
,
3918 &PyDateTime_DateType
, &date
,
3919 &PyDateTime_TimeType
, &time
)) {
3920 PyObject
*tzinfo
= Py_None
;
3922 if (HASTZINFO(time
))
3923 tzinfo
= ((PyDateTime_Time
*)time
)->tzinfo
;
3924 result
= PyObject_CallFunction(cls
, "iiiiiiiO",
3928 TIME_GET_HOUR(time
),
3929 TIME_GET_MINUTE(time
),
3930 TIME_GET_SECOND(time
),
3931 TIME_GET_MICROSECOND(time
),
3942 datetime_dealloc(PyDateTime_DateTime
*self
)
3944 if (HASTZINFO(self
)) {
3945 Py_XDECREF(self
->tzinfo
);
3947 Py_TYPE(self
)->tp_free((PyObject
*)self
);
3951 * Indirect access to tzinfo methods.
3954 /* These are all METH_NOARGS, so don't need to check the arglist. */
3956 datetime_utcoffset(PyDateTime_DateTime
*self
, PyObject
*unused
) {
3957 return offset_as_timedelta(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3958 "utcoffset", (PyObject
*)self
);
3962 datetime_dst(PyDateTime_DateTime
*self
, PyObject
*unused
) {
3963 return offset_as_timedelta(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3964 "dst", (PyObject
*)self
);
3968 datetime_tzname(PyDateTime_DateTime
*self
, PyObject
*unused
) {
3969 return call_tzname(HASTZINFO(self
) ? self
->tzinfo
: Py_None
,
3974 * datetime arithmetic.
3977 /* factor must be 1 (to add) or -1 (to subtract). The result inherits
3978 * the tzinfo state of date.
3981 add_datetime_timedelta(PyDateTime_DateTime
*date
, PyDateTime_Delta
*delta
,
3984 /* Note that the C-level additions can't overflow, because of
3985 * invariant bounds on the member values.
3987 int year
= GET_YEAR(date
);
3988 int month
= GET_MONTH(date
);
3989 int day
= GET_DAY(date
) + GET_TD_DAYS(delta
) * factor
;
3990 int hour
= DATE_GET_HOUR(date
);
3991 int minute
= DATE_GET_MINUTE(date
);
3992 int second
= DATE_GET_SECOND(date
) + GET_TD_SECONDS(delta
) * factor
;
3993 int microsecond
= DATE_GET_MICROSECOND(date
) +
3994 GET_TD_MICROSECONDS(delta
) * factor
;
3996 assert(factor
== 1 || factor
== -1);
3997 if (normalize_datetime(&year
, &month
, &day
,
3998 &hour
, &minute
, &second
, µsecond
) < 0)
4001 return new_datetime(year
, month
, day
,
4002 hour
, minute
, second
, microsecond
,
4003 HASTZINFO(date
) ? date
->tzinfo
: Py_None
);
4007 datetime_add(PyObject
*left
, PyObject
*right
)
4009 if (PyDateTime_Check(left
)) {
4010 /* datetime + ??? */
4011 if (PyDelta_Check(right
))
4012 /* datetime + delta */
4013 return add_datetime_timedelta(
4014 (PyDateTime_DateTime
*)left
,
4015 (PyDateTime_Delta
*)right
,
4018 else if (PyDelta_Check(left
)) {
4019 /* delta + datetime */
4020 return add_datetime_timedelta((PyDateTime_DateTime
*) right
,
4021 (PyDateTime_Delta
*) left
,
4024 Py_INCREF(Py_NotImplemented
);
4025 return Py_NotImplemented
;
4029 datetime_subtract(PyObject
*left
, PyObject
*right
)
4031 PyObject
*result
= Py_NotImplemented
;
4033 if (PyDateTime_Check(left
)) {
4034 /* datetime - ??? */
4035 if (PyDateTime_Check(right
)) {
4036 /* datetime - datetime */
4038 int offset1
, offset2
;
4039 int delta_d
, delta_s
, delta_us
;
4041 if (classify_two_utcoffsets(left
, &offset1
, &n1
, left
,
4042 right
, &offset2
, &n2
,
4045 assert(n1
!= OFFSET_UNKNOWN
&& n2
!= OFFSET_UNKNOWN
);
4047 PyErr_SetString(PyExc_TypeError
,
4048 "can't subtract offset-naive and "
4049 "offset-aware datetimes");
4052 delta_d
= ymd_to_ord(GET_YEAR(left
),
4055 ymd_to_ord(GET_YEAR(right
),
4058 /* These can't overflow, since the values are
4059 * normalized. At most this gives the number of
4060 * seconds in one day.
4062 delta_s
= (DATE_GET_HOUR(left
) -
4063 DATE_GET_HOUR(right
)) * 3600 +
4064 (DATE_GET_MINUTE(left
) -
4065 DATE_GET_MINUTE(right
)) * 60 +
4066 (DATE_GET_SECOND(left
) -
4067 DATE_GET_SECOND(right
));
4068 delta_us
= DATE_GET_MICROSECOND(left
) -
4069 DATE_GET_MICROSECOND(right
);
4070 /* (left - offset1) - (right - offset2) =
4071 * (left - right) + (offset2 - offset1)
4073 delta_s
+= (offset2
- offset1
) * 60;
4074 result
= new_delta(delta_d
, delta_s
, delta_us
, 1);
4076 else if (PyDelta_Check(right
)) {
4077 /* datetime - delta */
4078 result
= add_datetime_timedelta(
4079 (PyDateTime_DateTime
*)left
,
4080 (PyDateTime_Delta
*)right
,
4085 if (result
== Py_NotImplemented
)
4090 /* Various ways to turn a datetime into a string. */
4093 datetime_repr(PyDateTime_DateTime
*self
)
4095 const char *type_name
= Py_TYPE(self
)->tp_name
;
4098 if (DATE_GET_MICROSECOND(self
)) {
4099 baserepr
= PyUnicode_FromFormat(
4100 "%s(%d, %d, %d, %d, %d, %d, %d)",
4102 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
),
4103 DATE_GET_HOUR(self
), DATE_GET_MINUTE(self
),
4104 DATE_GET_SECOND(self
),
4105 DATE_GET_MICROSECOND(self
));
4107 else if (DATE_GET_SECOND(self
)) {
4108 baserepr
= PyUnicode_FromFormat(
4109 "%s(%d, %d, %d, %d, %d, %d)",
4111 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
),
4112 DATE_GET_HOUR(self
), DATE_GET_MINUTE(self
),
4113 DATE_GET_SECOND(self
));
4116 baserepr
= PyUnicode_FromFormat(
4117 "%s(%d, %d, %d, %d, %d)",
4119 GET_YEAR(self
), GET_MONTH(self
), GET_DAY(self
),
4120 DATE_GET_HOUR(self
), DATE_GET_MINUTE(self
));
4122 if (baserepr
== NULL
|| ! HASTZINFO(self
))
4124 return append_keyword_tzinfo(baserepr
, self
->tzinfo
);
4128 datetime_str(PyDateTime_DateTime
*self
)
4130 return PyObject_CallMethod((PyObject
*)self
, "isoformat", "(s)", " ");
4134 datetime_isoformat(PyDateTime_DateTime
*self
, PyObject
*args
, PyObject
*kw
)
4137 static char *keywords
[] = {"sep", NULL
};
4140 int us
= DATE_GET_MICROSECOND(self
);
4142 if (!PyArg_ParseTupleAndKeywords(args
, kw
, "|C:isoformat", keywords
, &sep
))
4145 result
= PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4146 GET_YEAR(self
), GET_MONTH(self
),
4147 GET_DAY(self
), (int)sep
,
4148 DATE_GET_HOUR(self
), DATE_GET_MINUTE(self
),
4149 DATE_GET_SECOND(self
), us
);
4151 result
= PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4152 GET_YEAR(self
), GET_MONTH(self
),
4153 GET_DAY(self
), (int)sep
,
4154 DATE_GET_HOUR(self
), DATE_GET_MINUTE(self
),
4155 DATE_GET_SECOND(self
));
4157 if (!result
|| !HASTZINFO(self
))
4160 /* We need to append the UTC offset. */
4161 if (format_utcoffset(buffer
, sizeof(buffer
), ":", self
->tzinfo
,
4162 (PyObject
*)self
) < 0) {
4166 PyUnicode_AppendAndDel(&result
, PyUnicode_FromString(buffer
));
4171 datetime_ctime(PyDateTime_DateTime
*self
)
4173 return format_ctime((PyDateTime_Date
*)self
,
4174 DATE_GET_HOUR(self
),
4175 DATE_GET_MINUTE(self
),
4176 DATE_GET_SECOND(self
));
4179 /* Miscellaneous methods. */
4182 datetime_richcompare(PyObject
*self
, PyObject
*other
, int op
)
4186 int offset1
, offset2
;
4188 if (! PyDateTime_Check(other
)) {
4189 if (PyDate_Check(other
)) {
4190 /* Prevent invocation of date_richcompare. We want to
4191 return NotImplemented here to give the other object
4192 a chance. But since DateTime is a subclass of
4193 Date, if the other object is a Date, it would
4194 compute an ordering based on the date part alone,
4195 and we don't want that. So force unequal or
4196 uncomparable here in that case. */
4201 return cmperror(self
, other
);
4203 Py_INCREF(Py_NotImplemented
);
4204 return Py_NotImplemented
;
4207 if (classify_two_utcoffsets(self
, &offset1
, &n1
, self
,
4208 other
, &offset2
, &n2
, other
) < 0)
4210 assert(n1
!= OFFSET_UNKNOWN
&& n2
!= OFFSET_UNKNOWN
);
4211 /* If they're both naive, or both aware and have the same offsets,
4212 * we get off cheap. Note that if they're both naive, offset1 ==
4213 * offset2 == 0 at this point.
4215 if (n1
== n2
&& offset1
== offset2
) {
4216 diff
= memcmp(((PyDateTime_DateTime
*)self
)->data
,
4217 ((PyDateTime_DateTime
*)other
)->data
,
4218 _PyDateTime_DATETIME_DATASIZE
);
4219 return diff_to_bool(diff
, op
);
4222 if (n1
== OFFSET_AWARE
&& n2
== OFFSET_AWARE
) {
4223 PyDateTime_Delta
*delta
;
4225 assert(offset1
!= offset2
); /* else last "if" handled it */
4226 delta
= (PyDateTime_Delta
*)datetime_subtract((PyObject
*)self
,
4230 diff
= GET_TD_DAYS(delta
);
4232 diff
= GET_TD_SECONDS(delta
) |
4233 GET_TD_MICROSECONDS(delta
);
4235 return diff_to_bool(diff
, op
);
4239 PyErr_SetString(PyExc_TypeError
,
4240 "can't compare offset-naive and "
4241 "offset-aware datetimes");
4246 datetime_hash(PyDateTime_DateTime
*self
)
4248 if (self
->hashcode
== -1) {
4253 n
= classify_utcoffset((PyObject
*)self
, (PyObject
*)self
,
4255 assert(n
!= OFFSET_UNKNOWN
);
4256 if (n
== OFFSET_ERROR
)
4259 /* Reduce this to a hash of another object. */
4260 if (n
== OFFSET_NAIVE
) {
4261 self
->hashcode
= generic_hash(
4262 (unsigned char *)self
->data
, _PyDateTime_DATETIME_DATASIZE
);
4263 return self
->hashcode
;
4269 assert(n
== OFFSET_AWARE
);
4270 assert(HASTZINFO(self
));
4271 days
= ymd_to_ord(GET_YEAR(self
),
4274 seconds
= DATE_GET_HOUR(self
) * 3600 +
4275 (DATE_GET_MINUTE(self
) - offset
) * 60 +
4276 DATE_GET_SECOND(self
);
4277 temp
= new_delta(days
,
4279 DATE_GET_MICROSECOND(self
),
4283 self
->hashcode
= PyObject_Hash(temp
);
4287 return self
->hashcode
;
4291 datetime_replace(PyDateTime_DateTime
*self
, PyObject
*args
, PyObject
*kw
)
4295 int y
= GET_YEAR(self
);
4296 int m
= GET_MONTH(self
);
4297 int d
= GET_DAY(self
);
4298 int hh
= DATE_GET_HOUR(self
);
4299 int mm
= DATE_GET_MINUTE(self
);
4300 int ss
= DATE_GET_SECOND(self
);
4301 int us
= DATE_GET_MICROSECOND(self
);
4302 PyObject
*tzinfo
= HASTZINFO(self
) ? self
->tzinfo
: Py_None
;
4304 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "|iiiiiiiO:replace",
4306 &y
, &m
, &d
, &hh
, &mm
, &ss
, &us
,
4309 tuple
= Py_BuildValue("iiiiiiiO", y
, m
, d
, hh
, mm
, ss
, us
, tzinfo
);
4312 clone
= datetime_new(Py_TYPE(self
), tuple
, NULL
);
4318 datetime_astimezone(PyDateTime_DateTime
*self
, PyObject
*args
, PyObject
*kw
)
4320 int y
, m
, d
, hh
, mm
, ss
, us
;
4325 static char *keywords
[] = {"tz", NULL
};
4327 if (! PyArg_ParseTupleAndKeywords(args
, kw
, "O!:astimezone", keywords
,
4328 &PyDateTime_TZInfoType
, &tzinfo
))
4331 if (!HASTZINFO(self
) || self
->tzinfo
== Py_None
)
4334 /* Conversion to self's own time zone is a NOP. */
4335 if (self
->tzinfo
== tzinfo
) {
4337 return (PyObject
*)self
;
4340 /* Convert self to UTC. */
4341 offset
= call_utcoffset(self
->tzinfo
, (PyObject
*)self
, &none
);
4342 if (offset
== -1 && PyErr_Occurred())
4348 m
= GET_MONTH(self
);
4350 hh
= DATE_GET_HOUR(self
);
4351 mm
= DATE_GET_MINUTE(self
);
4352 ss
= DATE_GET_SECOND(self
);
4353 us
= DATE_GET_MICROSECOND(self
);
4356 if ((mm
< 0 || mm
>= 60) &&
4357 normalize_datetime(&y
, &m
, &d
, &hh
, &mm
, &ss
, &us
) < 0)
4360 /* Attach new tzinfo and let fromutc() do the rest. */
4361 result
= new_datetime(y
, m
, d
, hh
, mm
, ss
, us
, tzinfo
);
4362 if (result
!= NULL
) {
4363 PyObject
*temp
= result
;
4365 result
= PyObject_CallMethod(tzinfo
, "fromutc", "O", temp
);
4371 PyErr_SetString(PyExc_ValueError
, "astimezone() cannot be applied to "
4372 "a naive datetime");
4377 datetime_timetuple(PyDateTime_DateTime
*self
)
4381 if (HASTZINFO(self
) && self
->tzinfo
!= Py_None
) {
4384 dstflag
= call_dst(self
->tzinfo
, (PyObject
*)self
, &none
);
4385 if (dstflag
== -1 && PyErr_Occurred())
4390 else if (dstflag
!= 0)
4394 return build_struct_time(GET_YEAR(self
),
4397 DATE_GET_HOUR(self
),
4398 DATE_GET_MINUTE(self
),
4399 DATE_GET_SECOND(self
),
4404 datetime_getdate(PyDateTime_DateTime
*self
)
4406 return new_date(GET_YEAR(self
),
4412 datetime_gettime(PyDateTime_DateTime
*self
)
4414 return new_time(DATE_GET_HOUR(self
),
4415 DATE_GET_MINUTE(self
),
4416 DATE_GET_SECOND(self
),
4417 DATE_GET_MICROSECOND(self
),
4422 datetime_gettimetz(PyDateTime_DateTime
*self
)
4424 return new_time(DATE_GET_HOUR(self
),
4425 DATE_GET_MINUTE(self
),
4426 DATE_GET_SECOND(self
),
4427 DATE_GET_MICROSECOND(self
),
4428 HASTZINFO(self
) ? self
->tzinfo
: Py_None
);
4432 datetime_utctimetuple(PyDateTime_DateTime
*self
)
4434 int y
= GET_YEAR(self
);
4435 int m
= GET_MONTH(self
);
4436 int d
= GET_DAY(self
);
4437 int hh
= DATE_GET_HOUR(self
);
4438 int mm
= DATE_GET_MINUTE(self
);
4439 int ss
= DATE_GET_SECOND(self
);
4440 int us
= 0; /* microseconds are ignored in a timetuple */
4443 if (HASTZINFO(self
) && self
->tzinfo
!= Py_None
) {
4446 offset
= call_utcoffset(self
->tzinfo
, (PyObject
*)self
, &none
);
4447 if (offset
== -1 && PyErr_Occurred())
4450 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4451 * 0 in a UTC timetuple regardless of what dst() says.
4454 /* Subtract offset minutes & normalize. */
4458 stat
= normalize_datetime(&y
, &m
, &d
, &hh
, &mm
, &ss
, &us
);
4460 /* At the edges, it's possible we overflowed
4461 * beyond MINYEAR or MAXYEAR.
4463 if (PyErr_ExceptionMatches(PyExc_OverflowError
))
4469 return build_struct_time(y
, m
, d
, hh
, mm
, ss
, 0);
4472 /* Pickle support, a simple use of __reduce__. */
4474 /* Let basestate be the non-tzinfo data string.
4475 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4476 * So it's a tuple in any (non-error) case.
4477 * __getstate__ isn't exposed.
4480 datetime_getstate(PyDateTime_DateTime
*self
)
4482 PyObject
*basestate
;
4483 PyObject
*result
= NULL
;
4485 basestate
= PyBytes_FromStringAndSize((char *)self
->data
,
4486 _PyDateTime_DATETIME_DATASIZE
);
4487 if (basestate
!= NULL
) {
4488 if (! HASTZINFO(self
) || self
->tzinfo
== Py_None
)
4489 result
= PyTuple_Pack(1, basestate
);
4491 result
= PyTuple_Pack(2, basestate
, self
->tzinfo
);
4492 Py_DECREF(basestate
);
4498 datetime_reduce(PyDateTime_DateTime
*self
, PyObject
*arg
)
4500 return Py_BuildValue("(ON)", Py_TYPE(self
), datetime_getstate(self
));
4503 static PyMethodDef datetime_methods
[] = {
4505 /* Class methods: */
4507 {"now", (PyCFunction
)datetime_now
,
4508 METH_VARARGS
| METH_KEYWORDS
| METH_CLASS
,
4509 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
4511 {"utcnow", (PyCFunction
)datetime_utcnow
,
4512 METH_NOARGS
| METH_CLASS
,
4513 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4515 {"fromtimestamp", (PyCFunction
)datetime_fromtimestamp
,
4516 METH_VARARGS
| METH_KEYWORDS
| METH_CLASS
,
4517 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
4519 {"utcfromtimestamp", (PyCFunction
)datetime_utcfromtimestamp
,
4520 METH_VARARGS
| METH_CLASS
,
4521 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4522 "(like time.time()).")},
4524 {"strptime", (PyCFunction
)datetime_strptime
,
4525 METH_VARARGS
| METH_CLASS
,
4526 PyDoc_STR("string, format -> new datetime parsed from a string "
4527 "(like time.strptime()).")},
4529 {"combine", (PyCFunction
)datetime_combine
,
4530 METH_VARARGS
| METH_KEYWORDS
| METH_CLASS
,
4531 PyDoc_STR("date, time -> datetime with same date and time fields")},
4533 /* Instance methods: */
4535 {"date", (PyCFunction
)datetime_getdate
, METH_NOARGS
,
4536 PyDoc_STR("Return date object with same year, month and day.")},
4538 {"time", (PyCFunction
)datetime_gettime
, METH_NOARGS
,
4539 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4541 {"timetz", (PyCFunction
)datetime_gettimetz
, METH_NOARGS
,
4542 PyDoc_STR("Return time object with same time and tzinfo.")},
4544 {"ctime", (PyCFunction
)datetime_ctime
, METH_NOARGS
,
4545 PyDoc_STR("Return ctime() style string.")},
4547 {"timetuple", (PyCFunction
)datetime_timetuple
, METH_NOARGS
,
4548 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4550 {"utctimetuple", (PyCFunction
)datetime_utctimetuple
, METH_NOARGS
,
4551 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4553 {"isoformat", (PyCFunction
)datetime_isoformat
, METH_VARARGS
| METH_KEYWORDS
,
4554 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4555 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4556 "sep is used to separate the year from the time, and "
4557 "defaults to 'T'.")},
4559 {"utcoffset", (PyCFunction
)datetime_utcoffset
, METH_NOARGS
,
4560 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4562 {"tzname", (PyCFunction
)datetime_tzname
, METH_NOARGS
,
4563 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4565 {"dst", (PyCFunction
)datetime_dst
, METH_NOARGS
,
4566 PyDoc_STR("Return self.tzinfo.dst(self).")},
4568 {"replace", (PyCFunction
)datetime_replace
, METH_VARARGS
| METH_KEYWORDS
,
4569 PyDoc_STR("Return datetime with new specified fields.")},
4571 {"astimezone", (PyCFunction
)datetime_astimezone
, METH_VARARGS
| METH_KEYWORDS
,
4572 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4574 {"__reduce__", (PyCFunction
)datetime_reduce
, METH_NOARGS
,
4575 PyDoc_STR("__reduce__() -> (cls, state)")},
4580 static char datetime_doc
[] =
4581 PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4583 The year, month and day arguments are required. tzinfo may be None, or an\n\
4584 instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
4586 static PyNumberMethods datetime_as_number
= {
4587 datetime_add
, /* nb_add */
4588 datetime_subtract
, /* nb_subtract */
4589 0, /* nb_multiply */
4590 0, /* nb_remainder */
4593 0, /* nb_negative */
4594 0, /* nb_positive */
4595 0, /* nb_absolute */
4599 static PyTypeObject PyDateTime_DateTimeType
= {
4600 PyVarObject_HEAD_INIT(NULL
, 0)
4601 "datetime.datetime", /* tp_name */
4602 sizeof(PyDateTime_DateTime
), /* tp_basicsize */
4603 0, /* tp_itemsize */
4604 (destructor
)datetime_dealloc
, /* tp_dealloc */
4608 0, /* tp_reserved */
4609 (reprfunc
)datetime_repr
, /* tp_repr */
4610 &datetime_as_number
, /* tp_as_number */
4611 0, /* tp_as_sequence */
4612 0, /* tp_as_mapping */
4613 (hashfunc
)datetime_hash
, /* tp_hash */
4615 (reprfunc
)datetime_str
, /* tp_str */
4616 PyObject_GenericGetAttr
, /* tp_getattro */
4617 0, /* tp_setattro */
4618 0, /* tp_as_buffer */
4619 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
4620 datetime_doc
, /* tp_doc */
4621 0, /* tp_traverse */
4623 datetime_richcompare
, /* tp_richcompare */
4624 0, /* tp_weaklistoffset */
4626 0, /* tp_iternext */
4627 datetime_methods
, /* tp_methods */
4629 datetime_getset
, /* tp_getset */
4630 &PyDateTime_DateType
, /* tp_base */
4632 0, /* tp_descr_get */
4633 0, /* tp_descr_set */
4634 0, /* tp_dictoffset */
4636 datetime_alloc
, /* tp_alloc */
4637 datetime_new
, /* tp_new */
4641 /* ---------------------------------------------------------------------------
4642 * Module methods and initialization.
4645 static PyMethodDef module_methods
[] = {
4649 /* C API. Clients get at this via PyDateTime_IMPORT, defined in
4652 static PyDateTime_CAPI CAPI
= {
4653 &PyDateTime_DateType
,
4654 &PyDateTime_DateTimeType
,
4655 &PyDateTime_TimeType
,
4656 &PyDateTime_DeltaType
,
4657 &PyDateTime_TZInfoType
,
4662 datetime_fromtimestamp
,
4668 static struct PyModuleDef datetimemodule
= {
4669 PyModuleDef_HEAD_INIT
,
4671 "Fast implementation of the datetime type.",
4681 PyInit_datetime(void)
4683 PyObject
*m
; /* a module object */
4684 PyObject
*d
; /* its dict */
4687 m
= PyModule_Create(&datetimemodule
);
4691 if (PyType_Ready(&PyDateTime_DateType
) < 0)
4693 if (PyType_Ready(&PyDateTime_DateTimeType
) < 0)
4695 if (PyType_Ready(&PyDateTime_DeltaType
) < 0)
4697 if (PyType_Ready(&PyDateTime_TimeType
) < 0)
4699 if (PyType_Ready(&PyDateTime_TZInfoType
) < 0)
4702 /* timedelta values */
4703 d
= PyDateTime_DeltaType
.tp_dict
;
4705 x
= new_delta(0, 0, 1, 0);
4706 if (x
== NULL
|| PyDict_SetItemString(d
, "resolution", x
) < 0)
4710 x
= new_delta(-MAX_DELTA_DAYS
, 0, 0, 0);
4711 if (x
== NULL
|| PyDict_SetItemString(d
, "min", x
) < 0)
4715 x
= new_delta(MAX_DELTA_DAYS
, 24*3600-1, 1000000-1, 0);
4716 if (x
== NULL
|| PyDict_SetItemString(d
, "max", x
) < 0)
4721 d
= PyDateTime_DateType
.tp_dict
;
4723 x
= new_date(1, 1, 1);
4724 if (x
== NULL
|| PyDict_SetItemString(d
, "min", x
) < 0)
4728 x
= new_date(MAXYEAR
, 12, 31);
4729 if (x
== NULL
|| PyDict_SetItemString(d
, "max", x
) < 0)
4733 x
= new_delta(1, 0, 0, 0);
4734 if (x
== NULL
|| PyDict_SetItemString(d
, "resolution", x
) < 0)
4739 d
= PyDateTime_TimeType
.tp_dict
;
4741 x
= new_time(0, 0, 0, 0, Py_None
);
4742 if (x
== NULL
|| PyDict_SetItemString(d
, "min", x
) < 0)
4746 x
= new_time(23, 59, 59, 999999, Py_None
);
4747 if (x
== NULL
|| PyDict_SetItemString(d
, "max", x
) < 0)
4751 x
= new_delta(0, 0, 1, 0);
4752 if (x
== NULL
|| PyDict_SetItemString(d
, "resolution", x
) < 0)
4756 /* datetime values */
4757 d
= PyDateTime_DateTimeType
.tp_dict
;
4759 x
= new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None
);
4760 if (x
== NULL
|| PyDict_SetItemString(d
, "min", x
) < 0)
4764 x
= new_datetime(MAXYEAR
, 12, 31, 23, 59, 59, 999999, Py_None
);
4765 if (x
== NULL
|| PyDict_SetItemString(d
, "max", x
) < 0)
4769 x
= new_delta(0, 0, 1, 0);
4770 if (x
== NULL
|| PyDict_SetItemString(d
, "resolution", x
) < 0)
4774 /* module initialization */
4775 PyModule_AddIntConstant(m
, "MINYEAR", MINYEAR
);
4776 PyModule_AddIntConstant(m
, "MAXYEAR", MAXYEAR
);
4778 Py_INCREF(&PyDateTime_DateType
);
4779 PyModule_AddObject(m
, "date", (PyObject
*) &PyDateTime_DateType
);
4781 Py_INCREF(&PyDateTime_DateTimeType
);
4782 PyModule_AddObject(m
, "datetime",
4783 (PyObject
*)&PyDateTime_DateTimeType
);
4785 Py_INCREF(&PyDateTime_TimeType
);
4786 PyModule_AddObject(m
, "time", (PyObject
*) &PyDateTime_TimeType
);
4788 Py_INCREF(&PyDateTime_DeltaType
);
4789 PyModule_AddObject(m
, "timedelta", (PyObject
*) &PyDateTime_DeltaType
);
4791 Py_INCREF(&PyDateTime_TZInfoType
);
4792 PyModule_AddObject(m
, "tzinfo", (PyObject
*) &PyDateTime_TZInfoType
);
4794 x
= PyCapsule_New(&CAPI
, PyDateTime_CAPSULE_NAME
, NULL
);
4797 PyModule_AddObject(m
, "datetime_CAPI", x
);
4799 /* A 4-year cycle has an extra leap day over what we'd get from
4800 * pasting together 4 single years.
4802 assert(DI4Y
== 4 * 365 + 1);
4803 assert(DI4Y
== days_before_year(4+1));
4805 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4806 * get from pasting together 4 100-year cycles.
4808 assert(DI400Y
== 4 * DI100Y
+ 1);
4809 assert(DI400Y
== days_before_year(400+1));
4811 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4812 * pasting together 25 4-year cycles.
4814 assert(DI100Y
== 25 * DI4Y
- 1);
4815 assert(DI100Y
== days_before_year(100+1));
4817 us_per_us
= PyLong_FromLong(1);
4818 us_per_ms
= PyLong_FromLong(1000);
4819 us_per_second
= PyLong_FromLong(1000000);
4820 us_per_minute
= PyLong_FromLong(60000000);
4821 seconds_per_day
= PyLong_FromLong(24 * 3600);
4822 if (us_per_us
== NULL
|| us_per_ms
== NULL
|| us_per_second
== NULL
||
4823 us_per_minute
== NULL
|| seconds_per_day
== NULL
)
4826 /* The rest are too big for 32-bit ints, but even
4827 * us_per_week fits in 40 bits, so doubles should be exact.
4829 us_per_hour
= PyLong_FromDouble(3600000000.0);
4830 us_per_day
= PyLong_FromDouble(86400000000.0);
4831 us_per_week
= PyLong_FromDouble(604800000000.0);
4832 if (us_per_hour
== NULL
|| us_per_day
== NULL
|| us_per_week
== NULL
)
4837 /* ---------------------------------------------------------------------------
4838 Some time zone algebra. For a datetime x, let
4839 x.n = x stripped of its timezone -- its naive time.
4840 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4842 x.d = x.dst(), and assuming that doesn't raise an exception or
4844 x.s = x's standard offset, x.o - x.d
4846 Now some derived rules, where k is a duration (timedelta).
4849 This follows from the definition of x.s.
4851 2. If x and y have the same tzinfo member, x.s = y.s.
4852 This is actually a requirement, an assumption we need to make about
4853 sane tzinfo classes.
4855 3. The naive UTC time corresponding to x is x.n - x.o.
4856 This is again a requirement for a sane tzinfo class.
4859 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
4861 5. (x+k).n = x.n + k
4862 Again follows from how arithmetic is defined.
4864 Now we can explain tz.fromutc(x). Let's assume it's an interesting case
4865 (meaning that the various tzinfo methods exist, and don't blow up or return
4868 The function wants to return a datetime y with timezone tz, equivalent to x.
4869 x is already in UTC.
4875 The algorithm starts by attaching tz to x.n, and calling that y. So
4876 x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4877 becomes true; in effect, we want to solve [2] for k:
4879 (y+k).n - (y+k).o = x.n [2]
4881 By #1, this is the same as
4883 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
4885 By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4886 Substituting that into [3],
4888 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4889 k - (y+k).s - (y+k).d = 0; rearranging,
4890 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4893 On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4894 approximate k by ignoring the (y+k).d term at first. Note that k can't be
4895 very large, since all offset-returning methods return a duration of magnitude
4896 less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4897 be 0, so ignoring it has no consequence then.
4899 In any case, the new value is
4903 It's helpful to step back at look at [4] from a higher level: it's simply
4904 mapping from UTC to tz's standard time.
4910 we have an equivalent time, and are almost done. The insecurity here is
4911 at the start of daylight time. Picture US Eastern for concreteness. The wall
4912 time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
4913 sense then. The docs ask that an Eastern tzinfo class consider such a time to
4914 be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4915 on the day DST starts. We want to return the 1:MM EST spelling because that's
4916 the only spelling that makes sense on the local wall clock.
4918 In fact, if [5] holds at this point, we do have the standard-time spelling,
4919 but that takes a bit of proof. We first prove a stronger result. What's the
4920 difference between the LHS and RHS of [5]? Let
4922 diff = x.n - (z.n - z.o) [6]
4927 y.n + y.s = since y.n = x.n
4928 x.n + y.s = since z and y are have the same tzinfo member,
4932 Plugging that back into [6] gives
4935 x.n - ((x.n + z.s) - z.o) = expanding
4936 x.n - x.n - z.s + z.o = cancelling
4942 If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
4943 spelling we wanted in the endcase described above. We're done. Contrarily,
4944 if z.d = 0, then we have a UTC equivalent, and are also done.
4946 If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4947 add to z (in effect, z is in tz's standard time, and we need to shift the
4948 local clock into tz's daylight time).
4952 z' = z + z.d = z + diff [7]
4954 and we can again ask whether
4956 z'.n - z'.o = x.n [8]
4958 If so, we're done. If not, the tzinfo class is insane, according to the
4959 assumptions we've made. This also requires a bit of proof. As before, let's
4960 compute the difference between the LHS and RHS of [8] (and skipping some of
4961 the justifications for the kinds of substitutions we've done several times
4964 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4965 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4966 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4967 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4968 - z.n + z.n - z.o + z'.o = cancel z.n
4969 - z.o + z'.o = #1 twice
4970 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4973 So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
4974 we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4975 return z', not bothering to compute z'.d.
4977 How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4978 a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4979 would have to change the result dst() returns: we start in DST, and moving
4980 a little further into it takes us out of DST.
4982 There isn't a sane case where this can happen. The closest it gets is at
4983 the end of DST, where there's an hour in UTC with no spelling in a hybrid
4984 tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4985 that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4986 UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4987 time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4988 clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4989 standard time. Since that's what the local clock *does*, we want to map both
4990 UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
4991 in local time, but so it goes -- it's the way the local clock works.
4993 When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4994 so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4995 z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
4996 (correctly) concludes that z' is not UTC-equivalent to x.
4998 Because we know z.d said z was in daylight time (else [5] would have held and
4999 we would have stopped then), and we know z.d != z'.d (else [8] would have held
5000 and we would have stopped then), and there are only 2 possible values dst() can
5001 return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5002 but the reasoning doesn't depend on the example -- it depends on there being
5003 two possible dst() outcomes, one zero and the other non-zero). Therefore
5004 z' must be in standard time, and is the spelling we want in this case.
5006 Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5007 concerned (because it takes z' as being in standard time rather than the
5008 daylight time we intend here), but returning it gives the real-life "local
5009 clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5012 When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5013 the 1:MM standard time spelling we want.
5015 So how can this break? One of the assumptions must be violated. Two
5018 1) [2] effectively says that y.s is invariant across all y belong to a given
5019 time zone. This isn't true if, for political reasons or continental drift,
5020 a region decides to change its base offset from UTC.
5022 2) There may be versions of "double daylight" time where the tail end of
5023 the analysis gives up a step too early. I haven't thought about that
5026 In any case, it's clear that the default fromutc() is strong enough to handle
5027 "almost all" time zones: so long as the standard offset is invariant, it
5028 doesn't matter if daylight time transition points change from year to year, or
5029 if daylight time is skipped in some years; it doesn't matter how large or
5030 small dst() may get within its bounds; and it doesn't even matter if some
5031 perverse time zone returns a negative dst()). So a breaking case must be
5032 pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
5033 --------------------------------------------------------------------------- */