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