Coverage Report

Created: 2026-11-30 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Modules/_datetimemodule.c
Line
Count
Source
1
/*  C implementation of the datetime module */
2
3
/* bpo-35081: Defining this prevents including the C API capsule;
4
 * internal versions of the  Py*_Check macros which do not require
5
 * the capsule are defined below */
6
#define _PY_DATETIME_IMPL
7
8
#ifndef Py_BUILD_CORE_BUILTIN
9
#  define Py_BUILD_CORE_MODULE 1
10
#endif
11
12
#include "Python.h"
13
#include "pycore_long.h"          // _PyLong_GetOne()
14
#include "pycore_object.h"        // _PyObject_Init()
15
#include "pycore_time.h"          // _PyTime_ObjectToTime_t()
16
#include "pycore_tuple.h"         // _PyTuple_FromPair
17
#include "pycore_unicodeobject.h" // _PyUnicode_Copy()
18
#include "pycore_initconfig.h"    // _PyStatus_OK()
19
#include "pycore_pyatomic_ft_wrappers.h"
20
21
#include "datetime.h"
22
23
24
#include <time.h>
25
26
#ifdef MS_WINDOWS
27
#  include <winsock2.h>         /* struct timeval */
28
#endif
29
30
31
/* forward declarations */
32
static PyTypeObject PyDateTime_DateType;
33
static PyTypeObject PyDateTime_DateTimeType;
34
static PyTypeObject PyDateTime_TimeType;
35
static PyTypeObject PyDateTime_DeltaType;
36
static PyTypeObject PyDateTime_TZInfoType;
37
static PyTypeObject PyDateTime_TimeZoneType;
38
39
40
typedef struct {
41
    /* Module heap types. */
42
    PyTypeObject *isocalendar_date_type;
43
44
    /* Conversion factors. */
45
    PyObject *us_per_ms;       // 1_000
46
    PyObject *us_per_second;   // 1_000_000
47
    PyObject *us_per_minute;   // 1e6 * 60 as Python int
48
    PyObject *us_per_hour;     // 1e6 * 3600 as Python int
49
    PyObject *us_per_day;      // 1e6 * 3600 * 24 as Python int
50
    PyObject *us_per_week;     // 1e6 * 3600 * 24 * 7 as Python int
51
    PyObject *seconds_per_day; // 3600 * 24 as Python int
52
53
    /* The interned Unix epoch datetime instance */
54
    PyObject *epoch;
55
56
    PyObject *time_struct_time;
57
    PyObject *time_strftime;
58
} datetime_state;
59
60
/* The module has a fixed number of static objects, due to being exposed
61
 * through the datetime C-API.  There are five types exposed directly,
62
 * one type exposed indirectly, and one singleton constant (UTC).
63
 *
64
 * Each of these objects is hidden behind a macro in the same way as
65
 * the per-module objects stored in module state.  The macros for the
66
 * static objects don't need to be passed a state, but the consistency
67
 * of doing so is more clear.  We use a dedicated noop macro, NO_STATE,
68
 * to make the special case obvious.
69
 *
70
 * The casting macros perform a simple fast pointer cast without
71
 * checking the runtime type. In the future, we may decide whether
72
 * to include that check and whether to provide a fast pointer cast
73
 * macro for pointers known to be of correct time.
74
 */
75
76
#define NO_STATE NULL
77
78
0
#define DATE_TYPE(st) &PyDateTime_DateType
79
0
#define DATETIME_TYPE(st) &PyDateTime_DateTimeType
80
0
#define TIME_TYPE(st) &PyDateTime_TimeType
81
44
#define DELTA_TYPE(st) &PyDateTime_DeltaType
82
#define TZINFO_TYPE(st) &PyDateTime_TZInfoType
83
44
#define TIMEZONE_TYPE(st) &PyDateTime_TimeZoneType
84
0
#define ISOCALENDAR_DATE_TYPE(st) st->isocalendar_date_type
85
86
0
#define PyDate_CAST(op) ((PyDateTime_Date *)(op))
87
0
#define PyDate_Check(op) PyObject_TypeCheck(op, DATE_TYPE(NO_STATE))
88
#define PyDate_CheckExact(op) Py_IS_TYPE(op, DATE_TYPE(NO_STATE))
89
90
0
#define PyDateTime_CAST(op) ((PyDateTime_DateTime *)(op))
91
0
#define PyDateTime_Check(op) PyObject_TypeCheck(op, DATETIME_TYPE(NO_STATE))
92
#define PyDateTime_CheckExact(op) Py_IS_TYPE(op, DATETIME_TYPE(NO_STATE))
93
94
0
#define PyTime_CAST(op) ((PyDateTime_Time *)(op))
95
0
#define PyTime_Check(op) PyObject_TypeCheck(op, TIME_TYPE(NO_STATE))
96
#define PyTime_CheckExact(op) Py_IS_TYPE(op, TIME_TYPE(NO_STATE))
97
98
0
#define PyDelta_CAST(op) ((PyDateTime_Delta *)(op))
99
0
#define PyDelta_Check(op) PyObject_TypeCheck(op, DELTA_TYPE(NO_STATE))
100
#define PyDelta_CheckExact(op) Py_IS_TYPE(op, DELTA_TYPE(NO_STATE))
101
102
#define PyTZInfo_CAST(op) ((PyDateTime_TZInfo *)(op))
103
0
#define PyTZInfo_Check(op) PyObject_TypeCheck(op, TZINFO_TYPE(NO_STATE))
104
#define PyTZInfo_CheckExact(op) Py_IS_TYPE(op, TZINFO_TYPE(NO_STATE))
105
106
0
#define PyTimeZone_CAST(op) ((PyDateTime_TimeZone *)(op))
107
0
#define PyTimezone_Check(op) PyObject_TypeCheck(op, TIMEZONE_TYPE(NO_STATE))
108
109
#define PyIsoCalendarDate_CAST(op) ((PyDateTime_IsoCalendarDate *)(op))
110
111
0
#define CONST_US_PER_MS(st) st->us_per_ms
112
0
#define CONST_US_PER_SECOND(st) st->us_per_second
113
0
#define CONST_US_PER_MINUTE(st) st->us_per_minute
114
0
#define CONST_US_PER_HOUR(st) st->us_per_hour
115
0
#define CONST_US_PER_DAY(st) st->us_per_day
116
0
#define CONST_US_PER_WEEK(st) st->us_per_week
117
0
#define CONST_SEC_PER_DAY(st) st->seconds_per_day
118
0
#define CONST_EPOCH(st) st->epoch
119
0
#define CONST_UTC(st) ((PyObject *)&utc_timezone)
120
121
static datetime_state *
122
get_module_state(PyObject *module)
123
0
{
124
0
    void *state = _PyModule_GetState(module);
125
0
    assert(state != NULL);
126
0
    return (datetime_state *)state;
127
0
}
128
129
130
0
#define INTERP_KEY ((PyObject *)&_Py_ID(cached_datetime_module))
131
132
static int
133
get_current_module(PyInterpreterState *interp, PyObject **p_mod)
134
0
{
135
0
    PyObject *mod = NULL;
136
137
0
    PyObject *dict = PyInterpreterState_GetDict(interp);
138
0
    if (dict == NULL) {
139
0
        goto error;
140
0
    }
141
0
    PyObject *ref = NULL;
142
0
    if (PyDict_GetItemRef(dict, INTERP_KEY, &ref) < 0) {
143
0
        goto error;
144
0
    }
145
0
    if (ref != NULL && ref != Py_None) {
146
0
        if (PyWeakref_GetRef(ref, &mod) < 0) {
147
0
            Py_DECREF(ref);
148
0
            goto error;
149
0
        }
150
0
        if (mod == Py_None) {
151
0
            Py_CLEAR(mod);
152
0
        }
153
0
        Py_DECREF(ref);
154
0
    }
155
0
    assert(!PyErr_Occurred());
156
0
    *p_mod = mod;
157
0
    return mod != NULL;
158
159
0
error:
160
0
    assert(PyErr_Occurred());
161
0
    *p_mod = NULL;
162
0
    return -1;
163
0
}
164
165
static PyModuleDef datetimemodule;
166
167
static datetime_state *
168
_get_current_state(PyObject **p_mod)
169
0
{
170
0
    PyInterpreterState *interp = PyInterpreterState_Get();
171
0
    PyObject *mod;
172
0
    if (get_current_module(interp, &mod) < 0) {
173
0
        goto error;
174
0
    }
175
0
    if (mod == NULL) {
176
        /* The static types can outlive the module,
177
         * so we must re-import the module. */
178
0
        mod = PyImport_ImportModule("_datetime");
179
0
        if (mod == NULL) {
180
0
            goto error;
181
0
        }
182
0
    }
183
0
    datetime_state *st = get_module_state(mod);
184
0
    *p_mod = mod;
185
0
    return st;
186
187
0
error:
188
0
    assert(PyErr_Occurred());
189
0
    *p_mod = NULL;
190
0
    return NULL;
191
0
}
192
193
#define GET_CURRENT_STATE(MOD_VAR)  \
194
0
    _get_current_state(&MOD_VAR)
195
#define RELEASE_CURRENT_STATE(ST_VAR, MOD_VAR)  \
196
0
    Py_DECREF(MOD_VAR)
197
198
static int
199
set_current_module(PyInterpreterState *interp, PyObject *mod)
200
0
{
201
0
    assert(mod != NULL);
202
0
    PyObject *dict = PyInterpreterState_GetDict(interp);
203
0
    if (dict == NULL) {
204
0
        return -1;
205
0
    }
206
0
    PyObject *ref = PyWeakref_NewRef(mod, NULL);
207
0
    if (ref == NULL) {
208
0
        return -1;
209
0
    }
210
0
    int rc = PyDict_SetItem(dict, INTERP_KEY, ref);
211
0
    Py_DECREF(ref);
212
0
    return rc;
213
0
}
214
215
static void
216
clear_current_module(PyInterpreterState *interp, PyObject *expected)
217
0
{
218
0
    PyObject *exc = PyErr_GetRaisedException();
219
220
0
    PyObject *dict = PyInterpreterState_GetDict(interp);
221
0
    if (dict == NULL) {
222
0
        goto error;
223
0
    }
224
225
0
    if (expected != NULL) {
226
0
        PyObject *ref = NULL;
227
0
        if (PyDict_GetItemRef(dict, INTERP_KEY, &ref) < 0) {
228
0
            goto error;
229
0
        }
230
0
        if (ref != NULL && ref != Py_None) {
231
0
            PyObject *current = NULL;
232
0
            int rc = PyWeakref_GetRef(ref, &current);
233
            /* We only need "current" for pointer comparison. */
234
0
            Py_XDECREF(current);
235
0
            Py_DECREF(ref);
236
0
            if (rc < 0) {
237
0
                goto error;
238
0
            }
239
0
            if (current != expected) {
240
0
                goto finally;
241
0
            }
242
0
        }
243
0
    }
244
245
    /* We use None to identify that the module was previously loaded. */
246
0
    if (PyDict_SetItem(dict, INTERP_KEY, Py_None) < 0) {
247
0
        goto error;
248
0
    }
249
250
0
    goto finally;
251
252
0
error:
253
0
    PyErr_FormatUnraisable("Exception ignored while clearing _datetime module");
254
255
0
finally:
256
0
    PyErr_SetRaisedException(exc);
257
0
}
258
259
260
/* We require that C int be at least 32 bits, and use int virtually
261
 * everywhere.  In just a few cases we use a temp long, where a Python
262
 * API returns a C long.  In such cases, we have to ensure that the
263
 * final result fits in a C int (this can be an issue on 64-bit boxes).
264
 */
265
#if SIZEOF_INT < 4
266
#       error "_datetime.c requires that C int have at least 32 bits"
267
#endif
268
269
176
#define MINYEAR 1
270
88
#define MAXYEAR 9999
271
0
#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
272
273
/* Nine decimal digits is easy to communicate, and leaves enough room
274
 * so that two delta days can be added w/o fear of overflowing a signed
275
 * 32-bit int, and with plenty of room left over to absorb any possible
276
 * carries from adding seconds.
277
 */
278
352
#define MAX_DELTA_DAYS 999999999
279
280
/* Rename the long macros in datetime.h to more reasonable short names. */
281
0
#define GET_YEAR                PyDateTime_GET_YEAR
282
0
#define GET_MONTH               PyDateTime_GET_MONTH
283
0
#define GET_DAY                 PyDateTime_GET_DAY
284
0
#define DATE_GET_HOUR           PyDateTime_DATE_GET_HOUR
285
0
#define DATE_GET_MINUTE         PyDateTime_DATE_GET_MINUTE
286
0
#define DATE_GET_SECOND         PyDateTime_DATE_GET_SECOND
287
0
#define DATE_GET_MICROSECOND    PyDateTime_DATE_GET_MICROSECOND
288
0
#define DATE_GET_FOLD           PyDateTime_DATE_GET_FOLD
289
290
/* Date accessors for date and datetime. */
291
88
#define SET_YEAR(o, v)          (((o)->data[0] = ((v) & 0xff00) >> 8), \
292
88
                 ((o)->data[1] = ((v) & 0x00ff)))
293
88
#define SET_MONTH(o, v)         (PyDateTime_GET_MONTH(o) = (v))
294
88
#define SET_DAY(o, v)           (PyDateTime_GET_DAY(o) = (v))
295
296
/* Date/Time accessors for datetime. */
297
44
#define DATE_SET_HOUR(o, v)     (PyDateTime_DATE_GET_HOUR(o) = (v))
298
44
#define DATE_SET_MINUTE(o, v)   (PyDateTime_DATE_GET_MINUTE(o) = (v))
299
44
#define DATE_SET_SECOND(o, v)   (PyDateTime_DATE_GET_SECOND(o) = (v))
300
#define DATE_SET_MICROSECOND(o, v)      \
301
44
    (((o)->data[7] = ((v) & 0xff0000) >> 16), \
302
44
     ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
303
44
     ((o)->data[9] = ((v) & 0x0000ff)))
304
44
#define DATE_SET_FOLD(o, v)   (PyDateTime_DATE_GET_FOLD(o) = (v))
305
306
/* Time accessors for time. */
307
0
#define TIME_GET_HOUR           PyDateTime_TIME_GET_HOUR
308
0
#define TIME_GET_MINUTE         PyDateTime_TIME_GET_MINUTE
309
0
#define TIME_GET_SECOND         PyDateTime_TIME_GET_SECOND
310
0
#define TIME_GET_MICROSECOND    PyDateTime_TIME_GET_MICROSECOND
311
0
#define TIME_GET_FOLD           PyDateTime_TIME_GET_FOLD
312
44
#define TIME_SET_HOUR(o, v)     (PyDateTime_TIME_GET_HOUR(o) = (v))
313
44
#define TIME_SET_MINUTE(o, v)   (PyDateTime_TIME_GET_MINUTE(o) = (v))
314
44
#define TIME_SET_SECOND(o, v)   (PyDateTime_TIME_GET_SECOND(o) = (v))
315
#define TIME_SET_MICROSECOND(o, v)      \
316
44
    (((o)->data[3] = ((v) & 0xff0000) >> 16), \
317
44
     ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
318
44
     ((o)->data[5] = ((v) & 0x0000ff)))
319
44
#define TIME_SET_FOLD(o, v)   (PyDateTime_TIME_GET_FOLD(o) = (v))
320
321
/* Delta accessors for timedelta. */
322
0
#define GET_TD_DAYS(o)          (PyDelta_CAST(o)->days)
323
0
#define GET_TD_SECONDS(o)       (PyDelta_CAST(o)->seconds)
324
0
#define GET_TD_MICROSECONDS(o)  (PyDelta_CAST(o)->microseconds)
325
326
176
#define SET_TD_DAYS(o, v)       ((o)->days = (v))
327
176
#define SET_TD_SECONDS(o, v)    ((o)->seconds = (v))
328
176
#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
329
330
0
#define HASTZINFO               _PyDateTime_HAS_TZINFO
331
0
#define GET_TIME_TZINFO         PyDateTime_TIME_GET_TZINFO
332
0
#define GET_DT_TZINFO           PyDateTime_DATE_GET_TZINFO
333
/* M is a char or int claiming to be a valid month.  The macro is equivalent
334
 * to the two-sided Python test
335
 *      1 <= M <= 12
336
 */
337
0
#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
338
339
static int check_tzinfo_subclass(PyObject *p);
340
341
/*[clinic input]
342
module datetime
343
class datetime.datetime "PyDateTime_DateTime *" "get_datetime_state()->datetime_type"
344
class datetime.date "PyDateTime_Date *" "get_datetime_state()->date_type"
345
class datetime.time "PyDateTime_Time *" "get_datetime_state()->time_type"
346
class datetime.IsoCalendarDate "PyDateTime_IsoCalendarDate *" "get_datetime_state()->isocalendar_date_type"
347
class datetime.timedelta "PyDateTime_Delta *" "&PyDateTime_DeltaType"
348
class datetime.timezone "PyDateTime_TimeZone *" "&PyDateTime_TimeZoneType"
349
[clinic start generated code]*/
350
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c54b9adf60082f0d]*/
351
352
#include "clinic/_datetimemodule.c.h"
353
354
355
/* ---------------------------------------------------------------------------
356
 * Math utilities.
357
 */
358
359
/* k = i+j overflows iff k differs in sign from both inputs,
360
 * iff k^i has sign bit set and k^j has sign bit set,
361
 * iff (k^i)&(k^j) has sign bit set.
362
 */
363
#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
364
    ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
365
366
/* Compute Python divmod(x, y), returning the quotient and storing the
367
 * remainder into *r.  The quotient is the floor of x/y, and that's
368
 * the real point of this.  C will probably truncate instead (C99
369
 * requires truncation; C89 left it implementation-defined).
370
 * Simplification:  we *require* that y > 0 here.  That's appropriate
371
 * for all the uses made of it.  This simplifies the code and makes
372
 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
373
 * overflow case).
374
 */
375
static int
376
divmod(int x, int y, int *r)
377
0
{
378
0
    int quo;
379
380
0
    assert(y > 0);
381
0
    quo = x / y;
382
0
    *r = x - quo * y;
383
0
    if (*r < 0) {
384
0
        --quo;
385
0
        *r += y;
386
0
    }
387
0
    assert(0 <= *r && *r < y);
388
0
    return quo;
389
0
}
390
391
/* Nearest integer to m / n for integers m and n. Half-integer results
392
 * are rounded to even.
393
 */
394
static PyObject *
395
divide_nearest(PyObject *m, PyObject *n)
396
0
{
397
0
    PyObject *result;
398
0
    PyObject *temp;
399
400
0
    temp = _PyLong_DivmodNear(m, n);
401
0
    if (temp == NULL)
402
0
        return NULL;
403
0
    result = Py_NewRef(PyTuple_GET_ITEM(temp, 0));
404
0
    Py_DECREF(temp);
405
406
0
    return result;
407
0
}
408
409
/* ---------------------------------------------------------------------------
410
 * General calendrical helper functions
411
 */
412
413
/* For each month ordinal in 1..12, the number of days in that month,
414
 * and the number of days before that month in the same year.  These
415
 * are correct for non-leap years only.
416
 */
417
static const int _days_in_month[] = {
418
    0, /* unused; this vector uses 1-based indexing */
419
    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
420
};
421
422
static const int _days_before_month[] = {
423
    0, /* unused; this vector uses 1-based indexing */
424
    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
425
};
426
427
/* year -> 1 if leap year, else 0. */
428
static int
429
is_leap(int year)
430
0
{
431
    /* Cast year to unsigned.  The result is the same either way, but
432
     * C can generate faster code for unsigned mod than for signed
433
     * mod (especially for % 4 -- a good compiler should just grab
434
     * the last 2 bits when the LHS is unsigned).
435
     */
436
0
    const unsigned int ayear = (unsigned int)year;
437
0
    return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
438
0
}
439
440
/* year, month -> number of days in that month in that year */
441
static int
442
days_in_month(int year, int month)
443
88
{
444
88
    assert(month >= 1);
445
88
    assert(month <= 12);
446
88
    if (month == 2 && is_leap(year))
447
0
        return 29;
448
88
    else
449
88
        return _days_in_month[month];
450
88
}
451
452
/* year, month -> number of days in year preceding first day of month */
453
static int
454
days_before_month(int year, int month)
455
0
{
456
0
    int days;
457
458
0
    assert(month >= 1);
459
0
    assert(month <= 12);
460
0
    days = _days_before_month[month];
461
0
    if (month > 2 && is_leap(year))
462
0
        ++days;
463
0
    return days;
464
0
}
465
466
467
/* Number of days in 4, 100, and 400 year cycles.  That these have
468
 * the correct values is asserted in the module init function.
469
 */
470
0
#define DI4Y    1461    /* _PyTime_DaysBeforeYear(5); days in 4 years */
471
#define DI100Y  36524   /* _PyTime_DaysBeforeYear(101); days in 100 years */
472
0
#define DI400Y  146097  /* _PyTime_DaysBeforeYear(401); days in 400 years  */
473
474
/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1.
475
 *
476
 * Neri and Schneider's algorithm, https://doi.org/10.1002/spe.3172; see
477
 * _ord2ymd() in Lib/_pydatetime.py for an explanation of the steps.
478
 *
479
 * The intermediate values only fit in 32 bits for small ordinals;
480
 * iso_to_ymd() passes the largest, MAXORDINAL + 2 (10000-01-02).
481
 */
482
static void
483
ord_to_ymd(int ordinal, int *year, int *month, int *day)
484
0
{
485
0
    assert(1 <= ordinal && ordinal <= MAXORDINAL + 2);
486
0
    const uint32_t days = (uint32_t)ordinal + 305;
487
0
    const uint32_t century = (4 * days + 3) / DI400Y;
488
0
    const uint32_t day_of_century = (4 * days + 3) % DI400Y / 4;
489
0
    const uint32_t year_of_century = (4 * day_of_century + 3) / DI4Y;
490
0
    const uint32_t day_of_year = (4 * day_of_century + 3) % DI4Y / 4;
491
0
    const uint32_t m = (5 * day_of_year + 461) / 153;
492
0
    const uint32_t d = (5 * day_of_year + 461) % 153 / 5 + 1;
493
0
    const uint32_t y = 100 * century + year_of_century;
494
0
    if (m > 12) {  /* January or February */
495
0
        *year = (int)(y + 1);
496
0
        *month = (int)(m - 12);
497
0
    }
498
0
    else {
499
0
        *year = (int)y;
500
0
        *month = (int)m;
501
0
    }
502
0
    *day = (int)d;
503
0
}
504
505
/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
506
static int
507
ymd_to_ord(int year, int month, int day)
508
0
{
509
0
    return _PyTime_DaysBeforeYear(year) + days_before_month(year, month) + day;
510
0
}
511
512
/* Day of week, where Monday==0, ..., Sunday==6.  1/1/1 was a Monday. */
513
static int
514
weekday(int year, int month, int day)
515
0
{
516
0
    return _PyTime_Weekday(year, days_before_month(year, month) + day);
517
0
}
518
519
/* Ordinal of the Monday starting week 1 of the ISO year.  Week 1 is the
520
 * first calendar week containing a Thursday.
521
 */
522
static int
523
iso_week1_monday(int year)
524
0
{
525
0
    int first_day = ymd_to_ord(year, 1, 1);     /* ord of 1/1 */
526
    /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
527
0
    int first_weekday = (first_day + 6) % 7;
528
    /* ordinal of closest Monday at or before 1/1 */
529
0
    int week1_monday  = first_day - first_weekday;
530
531
0
    if (first_weekday > 3)      /* if 1/1 was Fri, Sat, Sun */
532
0
        week1_monday += 7;
533
0
    return week1_monday;
534
0
}
535
536
static int
537
iso_to_ymd(const int iso_year, const int iso_week, const int iso_day,
538
0
           int *year, int *month, int *day) {
539
    // Year is bounded to 0 < year < 10000 because 9999-12-31 is (9999, 52, 5)
540
0
    if (iso_year < MINYEAR || iso_year > MAXYEAR) {
541
0
        return -4;
542
0
    }
543
0
    if (iso_week <= 0 || iso_week >= 53) {
544
0
        int out_of_range = 1;
545
0
        if (iso_week == 53) {
546
            // ISO years have 53 weeks in it on years starting with a Thursday
547
            // and on leap years starting on Wednesday
548
0
            int first_weekday = weekday(iso_year, 1, 1);
549
0
            if (first_weekday == 3 || (first_weekday == 2 && is_leap(iso_year))) {
550
0
                out_of_range = 0;
551
0
            }
552
0
        }
553
554
0
        if (out_of_range) {
555
0
            return -2;
556
0
        }
557
0
    }
558
559
0
    if (iso_day <= 0 || iso_day >= 8) {
560
0
        return -3;
561
0
    }
562
563
    // Convert (Y, W, D) to (Y, M, D) in-place
564
0
    int day_1 = iso_week1_monday(iso_year);
565
566
0
    int day_offset = (iso_week - 1)*7 + iso_day - 1;
567
568
0
    ord_to_ymd(day_1 + day_offset, year, month, day);
569
0
    return 0;
570
0
}
571
572
573
/* ---------------------------------------------------------------------------
574
 * Range checkers.
575
 */
576
577
/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS.  If so, return 0.
578
 * If not, raise OverflowError and return -1.
579
 */
580
static int
581
check_delta_day_range(int days)
582
176
{
583
176
    if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
584
176
        return 0;
585
0
    PyErr_Format(PyExc_OverflowError,
586
0
                 "days=%d; must have magnitude <= %d",
587
0
                 days, MAX_DELTA_DAYS);
588
0
    return -1;
589
176
}
590
591
/* Check that date arguments are in range.  Return 0 if they are.  If they
592
 * aren't, raise ValueError and return -1.
593
 */
594
static int
595
check_date_args(int year, int month, int day)
596
88
{
597
598
88
    if (year < MINYEAR || year > MAXYEAR) {
599
0
        PyErr_Format(PyExc_ValueError,
600
0
                     "year must be in %d..%d, not %d", MINYEAR, MAXYEAR, year);
601
0
        return -1;
602
0
    }
603
88
    if (month < 1 || month > 12) {
604
0
        PyErr_Format(PyExc_ValueError,
605
0
                     "month must be in 1..12, not %d", month);
606
0
        return -1;
607
0
    }
608
88
    int dim = days_in_month(year, month);
609
88
    if (day < 1 || day > dim) {
610
0
        PyErr_Format(PyExc_ValueError,
611
0
                     "day %i must be in range 1..%d for month %i in year %i",
612
0
                     day, dim, month, year);
613
0
        return -1;
614
0
    }
615
88
    return 0;
616
88
}
617
618
static int
619
year_from_tm(const struct tm *tm, int *year)
620
0
{
621
0
    if (tm->tm_year > INT_MAX - 1900) {
622
0
        PyErr_Format(PyExc_ValueError, "year must be in %d..%d, not %lld",
623
0
                     MINYEAR, MAXYEAR, (long long)tm->tm_year + 1900);
624
0
        return -1;
625
0
    }
626
0
    *year = tm->tm_year + 1900;
627
0
    return 0;
628
0
}
629
630
/* Check that time arguments are in range.  Return 0 if they are.  If they
631
 * aren't, raise ValueError and return -1.
632
 */
633
static int
634
check_time_args(int h, int m, int s, int us, int fold)
635
88
{
636
88
    if (h < 0 || h > 23) {
637
0
        PyErr_Format(PyExc_ValueError, "hour must be in 0..23, not %i", h);
638
0
        return -1;
639
0
    }
640
88
    if (m < 0 || m > 59) {
641
0
        PyErr_Format(PyExc_ValueError, "minute must be in 0..59, not %i", m);
642
0
        return -1;
643
0
    }
644
88
    if (s < 0 || s > 59) {
645
0
        PyErr_Format(PyExc_ValueError, "second must be in 0..59, not %i", s);
646
0
        return -1;
647
0
    }
648
88
    if (us < 0 || us > 999999) {
649
0
        PyErr_Format(PyExc_ValueError,
650
0
                     "microsecond must be in 0..999999, not %i", us);
651
0
        return -1;
652
0
    }
653
88
    if (fold != 0 && fold != 1) {
654
0
        PyErr_Format(PyExc_ValueError,
655
0
                     "fold must be either 0 or 1, not %i", fold);
656
0
        return -1;
657
0
    }
658
88
    return 0;
659
88
}
660
661
/* ---------------------------------------------------------------------------
662
 * Normalization utilities.
663
 */
664
665
/* One step of a mixed-radix conversion.  A "hi" unit is equivalent to
666
 * factor "lo" units.  factor must be > 0.  If *lo is less than 0, or
667
 * at least factor, enough of *lo is converted into "hi" units so that
668
 * 0 <= *lo < factor.  The input values must be such that int overflow
669
 * is impossible.
670
 */
671
static void
672
normalize_pair(int *hi, int *lo, int factor)
673
0
{
674
0
    assert(factor > 0);
675
0
    assert(lo != hi);
676
0
    if (*lo < 0 || *lo >= factor) {
677
0
        const int num_hi = divmod(*lo, factor, lo);
678
0
        const int new_hi = *hi + num_hi;
679
0
        assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
680
0
        *hi = new_hi;
681
0
    }
682
0
    assert(0 <= *lo && *lo < factor);
683
0
}
684
685
/* Fiddle days (d), seconds (s), and microseconds (us) so that
686
 *      0 <= *s < 24*3600
687
 *      0 <= *us < 1000000
688
 * The input values must be such that the internals don't overflow.
689
 * The way this routine is used, we don't get close.
690
 */
691
static void
692
normalize_d_s_us(int *d, int *s, int *us)
693
22
{
694
22
    if (*us < 0 || *us >= 1000000) {
695
0
        normalize_pair(s, us, 1000000);
696
        /* |s| can't be bigger than about
697
         * |original s| + |original us|/1000000 now.
698
         */
699
700
0
    }
701
22
    if (*s < 0 || *s >= 24*3600) {
702
0
        normalize_pair(d, s, 24*3600);
703
        /* |d| can't be bigger than about
704
         * |original d| +
705
         * (|original s| + |original us|/1000000) / (24*3600) now.
706
         */
707
0
    }
708
22
    assert(0 <= *s && *s < 24*3600);
709
22
    assert(0 <= *us && *us < 1000000);
710
22
}
711
712
/* Fiddle years (y), months (m), and days (d) so that
713
 *      1 <= *m <= 12
714
 *      1 <= *d <= days_in_month(*y, *m)
715
 * The input values must be such that the internals don't overflow.
716
 * The way this routine is used, we don't get close.
717
 */
718
static int
719
normalize_y_m_d(int *y, int *m, int *d)
720
0
{
721
0
    int dim;            /* # of days in month */
722
723
    /* In actual use, m is always the month component extracted from a
724
     * date/datetime object.  Therefore it is always in [1, 12] range.
725
     */
726
727
0
    assert(1 <= *m && *m <= 12);
728
729
    /* Now only day can be out of bounds (year may also be out of bounds
730
     * for a datetime object, but we don't care about that here).
731
     * If day is out of bounds, what to do is arguable, but at least the
732
     * method here is principled and explainable.
733
     */
734
0
    dim = days_in_month(*y, *m);
735
0
    if (*d < 1 || *d > dim) {
736
        /* Move day-1 days from the first of the month.  First try to
737
         * get off cheap if we're only one day out of range
738
         * (adjustments for timezone alone can't be worse than that).
739
         */
740
0
        if (*d == 0) {
741
0
            --*m;
742
0
            if (*m > 0)
743
0
                *d = days_in_month(*y, *m);
744
0
            else {
745
0
                --*y;
746
0
                *m = 12;
747
0
                *d = 31;
748
0
            }
749
0
        }
750
0
        else if (*d == dim + 1) {
751
            /* move forward a day */
752
0
            ++*m;
753
0
            *d = 1;
754
0
            if (*m > 12) {
755
0
                *m = 1;
756
0
                ++*y;
757
0
            }
758
0
        }
759
0
        else {
760
0
            int ordinal = ymd_to_ord(*y, *m, 1) +
761
0
                                      *d - 1;
762
0
            if (ordinal < 1 || ordinal > MAXORDINAL) {
763
0
                goto error;
764
0
            } else {
765
0
                ord_to_ymd(ordinal, y, m, d);
766
0
                return 0;
767
0
            }
768
0
        }
769
0
    }
770
0
    assert(*m > 0);
771
0
    assert(*d > 0);
772
0
    if (MINYEAR <= *y && *y <= MAXYEAR)
773
0
        return 0;
774
0
 error:
775
0
    PyErr_SetString(PyExc_OverflowError,
776
0
            "date value out of range");
777
0
    return -1;
778
779
0
}
780
781
/* Fiddle out-of-bounds months and days so that the result makes some kind
782
 * of sense.  The parameters are both inputs and outputs.  Returns < 0 on
783
 * failure, where failure means the adjusted year is out of bounds.
784
 */
785
static int
786
normalize_date(int *year, int *month, int *day)
787
0
{
788
0
    return normalize_y_m_d(year, month, day);
789
0
}
790
791
/* Force all the datetime fields into range.  The parameters are both
792
 * inputs and outputs.  Returns < 0 on error.
793
 */
794
static int
795
normalize_datetime(int *year, int *month, int *day,
796
                   int *hour, int *minute, int *second,
797
                   int *microsecond)
798
0
{
799
0
    normalize_pair(second, microsecond, 1000000);
800
0
    normalize_pair(minute, second, 60);
801
0
    normalize_pair(hour, minute, 60);
802
0
    normalize_pair(day, hour, 24);
803
0
    return normalize_date(year, month, day);
804
0
}
805
806
/* ---------------------------------------------------------------------------
807
 * Basic object allocation:  tp_alloc implementations.  These allocate
808
 * Python objects of the right size and type, and do the Python object-
809
 * initialization bit.  If there's not enough memory, they return NULL after
810
 * setting MemoryError.  All data members remain uninitialized trash.
811
 *
812
 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
813
 * member is needed.  This is ugly, imprecise, and possibly insecure.
814
 * tp_basicsize for the time and datetime types is set to the size of the
815
 * struct that has room for the tzinfo member, so subclasses in Python will
816
 * allocate enough space for a tzinfo member whether or not one is actually
817
 * needed.  That's the "ugly and imprecise" parts.  The "possibly insecure"
818
 * part is that PyType_GenericAlloc() (which subclasses in Python end up
819
 * using) just happens today to effectively ignore the nitems argument
820
 * when tp_itemsize is 0, which it is for these type objects.  If that
821
 * changes, perhaps the callers of tp_alloc slots in this file should
822
 * be changed to force a 0 nitems argument unless the type being allocated
823
 * is a base type implemented in this file (so that tp_alloc is time_alloc
824
 * or datetime_alloc below, which know about the nitems abuse).
825
 */
826
827
static PyObject *
828
time_alloc(PyTypeObject *type, Py_ssize_t aware)
829
44
{
830
44
    size_t size = aware ? sizeof(PyDateTime_Time) : sizeof(_PyDateTime_BaseTime);
831
44
    PyObject *self = (PyObject *)PyObject_Malloc(size);
832
44
    if (self == NULL) {
833
0
        return PyErr_NoMemory();
834
0
    }
835
44
    _PyObject_Init(self, type);
836
44
    return self;
837
44
}
838
839
static PyObject *
840
datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
841
44
{
842
44
    size_t size = aware ? sizeof(PyDateTime_DateTime) : sizeof(_PyDateTime_BaseDateTime);
843
44
    PyObject *self = (PyObject *)PyObject_Malloc(size);
844
44
    if (self == NULL) {
845
0
        return PyErr_NoMemory();
846
0
    }
847
44
    _PyObject_Init(self, type);
848
44
    return self;
849
44
}
850
851
/* ---------------------------------------------------------------------------
852
 * Helpers for setting object fields.  These work on pointers to the
853
 * appropriate base class.
854
 */
855
856
/* For date and datetime. */
857
static void
858
set_date_fields(PyDateTime_Date *self, int y, int m, int d)
859
88
{
860
88
    self->hashcode = -1;
861
88
    SET_YEAR(self, y);
862
88
    SET_MONTH(self, m);
863
88
    SET_DAY(self, d);
864
88
}
865
866
/* ---------------------------------------------------------------------------
867
 * String parsing utilities and helper functions
868
 */
869
870
static unsigned char
871
0
is_digit(const char c) {
872
0
    return ((unsigned int)(c - '0')) < 10;
873
0
}
874
875
static const char *
876
parse_digits(const char *ptr, int *var, size_t num_digits)
877
0
{
878
0
    for (size_t i = 0; i < num_digits; ++i) {
879
0
        unsigned int tmp = (unsigned int)(*(ptr++) - '0');
880
0
        if (tmp > 9) {
881
0
            return NULL;
882
0
        }
883
0
        *var *= 10;
884
0
        *var += (signed int)tmp;
885
0
    }
886
887
0
    return ptr;
888
0
}
889
890
static int
891
parse_isoformat_date(const char *dtstr, const size_t len, int *year, int *month, int *day)
892
0
{
893
    /* Parse the date components of the result of date.isoformat()
894
     *
895
     *  Return codes:
896
     *       0:  Success
897
     *      -1:  Failed to parse date component
898
     *      -2:  Inconsistent date separator usage
899
     *      -3:  Failed to parse ISO week.
900
     *      -4:  Failed to parse ISO day.
901
     *      -5, -6, -7: Failure in iso_to_ymd
902
     */
903
0
    const char *p = dtstr;
904
0
    p = parse_digits(p, year, 4);
905
0
    if (NULL == p) {
906
0
        return -1;
907
0
    }
908
909
0
    const unsigned char uses_separator = (*p == '-');
910
0
    if (uses_separator) {
911
0
        ++p;
912
0
    }
913
914
0
    if(*p == 'W') {
915
        // This is an isocalendar-style date string
916
0
        p++;
917
0
        int iso_week = 0;
918
0
        int iso_day = 0;
919
920
0
        p = parse_digits(p, &iso_week, 2);
921
0
        if (NULL == p) {
922
0
            return -3;
923
0
        }
924
925
0
        assert(p > dtstr);
926
0
        if ((size_t)(p - dtstr) < len) {
927
0
            if (uses_separator && *(p++) != '-') {
928
0
                return -2;
929
0
            }
930
931
0
            p = parse_digits(p, &iso_day, 1);
932
0
            if (NULL == p) {
933
0
                return -4;
934
0
            }
935
0
        } else {
936
0
            iso_day = 1;
937
0
        }
938
939
0
        if ((size_t)(p - dtstr) != len) {
940
0
            return -1;
941
0
        }
942
943
0
        int rv = iso_to_ymd(*year, iso_week, iso_day, year, month, day);
944
0
        if (rv) {
945
0
            return -3 + rv;
946
0
        } else {
947
0
            return 0;
948
0
        }
949
0
    }
950
951
0
    p = parse_digits(p, month, 2);
952
0
    if (NULL == p) {
953
0
        return -1;
954
0
    }
955
956
0
    if (uses_separator && *(p++) != '-') {
957
0
        return -2;
958
0
    }
959
0
    p = parse_digits(p, day, 2);
960
0
    if (p == NULL) {
961
0
        return -1;
962
0
    }
963
0
    if ((size_t)(p - dtstr) != len) {
964
0
        return -1;
965
0
    }
966
0
    return 0;
967
0
}
968
969
static int
970
parse_hh_mm_ss_ff(const char *tstr, const char *tstr_end, int *hour,
971
                  int *minute, int *second, int *microsecond)
972
0
{
973
0
    *hour = *minute = *second = *microsecond = 0;
974
0
    const char *p = tstr;
975
0
    const char *p_end = tstr_end;
976
0
    int *vals[3] = {hour, minute, second};
977
    // This is initialized to satisfy an erroneous compiler warning.
978
0
    unsigned char has_separator = 1;
979
980
    // Parse [HH[:?MM[:?SS]]]
981
0
    for (size_t i = 0; i < 3; ++i) {
982
0
        p = parse_digits(p, vals[i], 2);
983
0
        if (NULL == p) {
984
0
            return -3;
985
0
        }
986
987
0
        char c = *(p++);
988
0
        if (i == 0) {
989
0
            has_separator = (c == ':');
990
0
        }
991
992
0
        if (c == '.' || c == ',') {
993
0
            if (i < 2) {
994
0
                return -3;  // Decimal mark on hour or minute
995
0
            }
996
0
            if (p >= p_end) {
997
0
                return -3;  // Decimal mark not followed by any digit
998
0
            }
999
0
            break;
1000
0
        }
1001
0
        else if (p > p_end) {
1002
0
            return 0;  // Stopped at p_end: an offset designator or NUL
1003
0
        }
1004
0
        else if (p == p_end) {
1005
0
            return 1;  // Stray character just before p_end
1006
0
        }
1007
0
        else if (has_separator && (c == ':')) {
1008
0
            if (i == 2) {
1009
0
                return -4;  // Malformed microsecond separator
1010
0
            }
1011
0
            continue;
1012
0
        }
1013
0
        else if (!has_separator) {
1014
0
            --p;
1015
0
        }
1016
0
        else {
1017
0
            return -4;  // Malformed time separator
1018
0
        }
1019
0
    }
1020
1021
    // Parse fractional components
1022
0
    size_t len_remains = p_end - p;
1023
0
    size_t to_parse = len_remains;
1024
0
    if (len_remains >= 6) {
1025
0
        to_parse = 6;
1026
0
    }
1027
1028
0
    p = parse_digits(p, microsecond, to_parse);
1029
0
    if (NULL == p) {
1030
0
        return -3;
1031
0
    }
1032
1033
0
    static int correction[] = {
1034
0
        100000, 10000, 1000, 100, 10
1035
0
    };
1036
1037
0
    if (to_parse < 6) {
1038
0
        *microsecond *= correction[to_parse-1];
1039
0
    }
1040
1041
0
    while (is_digit(*p)){
1042
0
        ++p; // skip truncated digits
1043
0
    }
1044
1045
    // Return 1 if there is unparsed text before p_end
1046
0
    return p != p_end;
1047
0
}
1048
1049
static int
1050
parse_isoformat_time(const char *dtstr, size_t dtlen, int *hour, int *minute,
1051
                     int *second, int *microsecond, int *tzoffset,
1052
                     int *tzmicrosecond)
1053
0
{
1054
    // Parse the time portion of a datetime.isoformat() string
1055
    //
1056
    // Return codes:
1057
    //      0:  Success (no tzoffset)
1058
    //      1:  Success (with tzoffset)
1059
    //     -3:  Failed to parse time component
1060
    //     -4:  Failed to parse time separator
1061
    //     -5:  Malformed timezone string
1062
    //     -6:  Timezone fields are not in range
1063
1064
0
    const char *p = dtstr;
1065
0
    const char *p_end = dtstr + dtlen;
1066
1067
0
    const char *tzinfo_pos = p;
1068
0
    do {
1069
0
        if (*tzinfo_pos == 'Z' || *tzinfo_pos == '+' || *tzinfo_pos == '-') {
1070
0
            break;
1071
0
        }
1072
0
    } while (++tzinfo_pos < p_end);
1073
1074
0
    int rv = parse_hh_mm_ss_ff(dtstr, tzinfo_pos, hour, minute, second,
1075
0
                               microsecond);
1076
1077
0
    if (rv < 0) {
1078
0
        return rv;
1079
0
    }
1080
0
    else if (rv == 1) {
1081
0
        return -5;  // Unparsed text after the time
1082
0
    }
1083
0
    else if (tzinfo_pos == p_end) {
1084
0
        return 0;
1085
0
    }
1086
1087
    // Special case UTC / Zulu time.
1088
0
    if (*tzinfo_pos == 'Z') {
1089
0
        *tzoffset = 0;
1090
0
        *tzmicrosecond = 0;
1091
1092
0
        if (*(tzinfo_pos + 1) != '\0') {
1093
0
            return -5;
1094
0
        } else {
1095
0
            return 1;
1096
0
        }
1097
0
    }
1098
1099
0
    int tzsign = (*tzinfo_pos == '-') ? -1 : 1;
1100
0
    tzinfo_pos++;
1101
0
    int tzhour = 0, tzminute = 0, tzsecond = 0;
1102
0
    rv = parse_hh_mm_ss_ff(tzinfo_pos, p_end, &tzhour, &tzminute, &tzsecond,
1103
0
                           tzmicrosecond);
1104
1105
    // Check if timezone fields are in range
1106
0
    if (check_time_args(tzhour, tzminute, tzsecond, *tzmicrosecond, 0) < 0) {
1107
0
        return -6;
1108
0
    }
1109
1110
0
    *tzoffset = tzsign * ((tzhour * 3600) + (tzminute * 60) + tzsecond);
1111
0
    *tzmicrosecond *= tzsign;
1112
1113
0
    return rv ? -5 : 1;
1114
0
}
1115
1116
/* ---------------------------------------------------------------------------
1117
 * Create various objects, mostly without range checking.
1118
 */
1119
1120
/* Create a date instance with no range checking. */
1121
static PyObject *
1122
new_date_ex(int year, int month, int day, PyTypeObject *type)
1123
44
{
1124
44
    PyDateTime_Date *self;
1125
1126
44
    if (check_date_args(year, month, day) < 0) {
1127
0
        return NULL;
1128
0
    }
1129
1130
44
    self = (PyDateTime_Date *)(type->tp_alloc(type, 0));
1131
44
    if (self != NULL)
1132
44
        set_date_fields(self, year, month, day);
1133
44
    return (PyObject *)self;
1134
44
}
1135
1136
#define new_date(year, month, day) \
1137
0
    new_date_ex(year, month, day, DATE_TYPE(NO_STATE))
1138
1139
// Forward declaration
1140
static PyObject *
1141
new_datetime_ex(int, int, int, int, int, int, int, PyObject *, PyTypeObject *);
1142
1143
/* Create date instance with no range checking, or call subclass constructor */
1144
static PyObject *
1145
new_date_subclass_ex(int year, int month, int day, PyTypeObject *cls)
1146
0
{
1147
0
    PyObject *result;
1148
    // We have "fast path" constructors for two subclasses: date and datetime
1149
0
    if (cls == DATE_TYPE(NO_STATE)) {
1150
0
        result = new_date_ex(year, month, day, cls);
1151
0
    }
1152
0
    else if (cls == DATETIME_TYPE(NO_STATE)) {
1153
0
        result = new_datetime_ex(year, month, day, 0, 0, 0, 0, Py_None, cls);
1154
0
    }
1155
0
    else {
1156
0
        result = PyObject_CallFunction((PyObject *)cls, "iii", year, month, day);
1157
0
    }
1158
1159
0
    return result;
1160
0
}
1161
1162
/* Create a datetime instance with no range checking. */
1163
static PyObject *
1164
new_datetime_ex2(int year, int month, int day, int hour, int minute,
1165
                 int second, int usecond, PyObject *tzinfo, int fold, PyTypeObject *type)
1166
44
{
1167
44
    PyDateTime_DateTime *self;
1168
44
    char aware = tzinfo != Py_None;
1169
1170
44
    if (check_date_args(year, month, day) < 0) {
1171
0
        return NULL;
1172
0
    }
1173
44
    if (check_time_args(hour, minute, second, usecond, fold) < 0) {
1174
0
        return NULL;
1175
0
    }
1176
44
    if (check_tzinfo_subclass(tzinfo) < 0) {
1177
0
        return NULL;
1178
0
    }
1179
1180
44
    self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
1181
44
    if (self != NULL) {
1182
44
        self->hastzinfo = aware;
1183
44
        set_date_fields((PyDateTime_Date *)self, year, month, day);
1184
44
        DATE_SET_HOUR(self, hour);
1185
44
        DATE_SET_MINUTE(self, minute);
1186
44
        DATE_SET_SECOND(self, second);
1187
44
        DATE_SET_MICROSECOND(self, usecond);
1188
44
        if (aware) {
1189
0
            self->tzinfo = Py_NewRef(tzinfo);
1190
0
        }
1191
44
        DATE_SET_FOLD(self, fold);
1192
44
    }
1193
44
    return (PyObject *)self;
1194
44
}
1195
1196
static PyObject *
1197
new_datetime_ex(int year, int month, int day, int hour, int minute,
1198
                int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
1199
0
{
1200
0
    return new_datetime_ex2(year, month, day, hour, minute, second, usecond,
1201
0
                            tzinfo, 0, type);
1202
0
}
1203
1204
#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo, fold) \
1205
0
    new_datetime_ex2(y, m, d, hh, mm, ss, us, tzinfo, fold, DATETIME_TYPE(NO_STATE))
1206
1207
static PyObject *
1208
call_subclass_fold(PyTypeObject *cls, int fold, const char *format, ...)
1209
0
{
1210
0
    PyObject *kwargs = NULL, *res = NULL;
1211
0
    va_list va;
1212
1213
0
    va_start(va, format);
1214
0
    PyObject *args = Py_VaBuildValue(format, va);
1215
0
    va_end(va);
1216
0
    if (args == NULL) {
1217
0
        return NULL;
1218
0
    }
1219
0
    if (fold) {
1220
0
        kwargs = PyDict_New();
1221
0
        if (kwargs == NULL) {
1222
0
            goto Done;
1223
0
        }
1224
0
        PyObject *obj = PyLong_FromLong(fold);
1225
0
        if (obj == NULL) {
1226
0
            goto Done;
1227
0
        }
1228
0
        int err = PyDict_SetItemString(kwargs, "fold", obj);
1229
0
        Py_DECREF(obj);
1230
0
        if (err < 0) {
1231
0
            goto Done;
1232
0
        }
1233
0
    }
1234
0
    res = PyObject_Call((PyObject *)cls, args, kwargs);
1235
0
Done:
1236
0
    Py_DECREF(args);
1237
0
    Py_XDECREF(kwargs);
1238
0
    return res;
1239
0
}
1240
1241
static PyObject *
1242
new_datetime_subclass_fold_ex(int year, int month, int day, int hour, int minute,
1243
                              int second, int usecond, PyObject *tzinfo,
1244
                              int fold, PyTypeObject *cls)
1245
0
{
1246
0
    PyObject* dt;
1247
0
    if (cls == DATETIME_TYPE(NO_STATE)) {
1248
        // Use the fast path constructor
1249
0
        dt = new_datetime(year, month, day, hour, minute, second, usecond,
1250
0
                          tzinfo, fold);
1251
0
    }
1252
0
    else {
1253
        // Subclass
1254
0
        dt = call_subclass_fold(cls, fold, "iiiiiiiO", year, month, day,
1255
0
                                hour, minute, second, usecond, tzinfo);
1256
0
    }
1257
1258
0
    return dt;
1259
0
}
1260
1261
static PyObject *
1262
new_datetime_subclass_ex(int year, int month, int day, int hour, int minute,
1263
                              int second, int usecond, PyObject *tzinfo,
1264
0
                              PyTypeObject *cls) {
1265
0
    return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
1266
0
                                         second, usecond, tzinfo, 0,
1267
0
                                         cls);
1268
0
}
1269
1270
/* Create a time instance with no range checking. */
1271
static PyObject *
1272
new_time_ex2(int hour, int minute, int second, int usecond,
1273
             PyObject *tzinfo, int fold, PyTypeObject *type)
1274
44
{
1275
44
    PyDateTime_Time *self;
1276
44
    char aware = tzinfo != Py_None;
1277
1278
44
    if (check_time_args(hour, minute, second, usecond, fold) < 0) {
1279
0
        return NULL;
1280
0
    }
1281
44
    if (check_tzinfo_subclass(tzinfo) < 0) {
1282
0
        return NULL;
1283
0
    }
1284
1285
44
    self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
1286
44
    if (self != NULL) {
1287
44
        self->hastzinfo = aware;
1288
44
        self->hashcode = -1;
1289
44
        TIME_SET_HOUR(self, hour);
1290
44
        TIME_SET_MINUTE(self, minute);
1291
44
        TIME_SET_SECOND(self, second);
1292
44
        TIME_SET_MICROSECOND(self, usecond);
1293
44
        if (aware) {
1294
0
            self->tzinfo = Py_NewRef(tzinfo);
1295
0
        }
1296
44
        TIME_SET_FOLD(self, fold);
1297
44
    }
1298
44
    return (PyObject *)self;
1299
44
}
1300
1301
static PyObject *
1302
new_time_ex(int hour, int minute, int second, int usecond,
1303
            PyObject *tzinfo, PyTypeObject *type)
1304
0
{
1305
0
    return new_time_ex2(hour, minute, second, usecond, tzinfo, 0, type);
1306
0
}
1307
1308
#define new_time(hh, mm, ss, us, tzinfo, fold)  \
1309
0
    new_time_ex2(hh, mm, ss, us, tzinfo, fold, TIME_TYPE(NO_STATE))
1310
1311
static PyObject *
1312
new_time_subclass_fold_ex(int hour, int minute, int second, int usecond,
1313
                          PyObject *tzinfo, int fold, PyTypeObject *cls)
1314
0
{
1315
0
    PyObject *t;
1316
0
    if (cls == TIME_TYPE(NO_STATE)) {
1317
        // Use the fast path constructor
1318
0
        t = new_time(hour, minute, second, usecond, tzinfo, fold);
1319
0
    }
1320
0
    else {
1321
        // Subclass
1322
0
        t = call_subclass_fold(cls, fold, "iiiiO", hour, minute, second,
1323
0
                               usecond, tzinfo);
1324
0
    }
1325
1326
0
    return t;
1327
0
}
1328
1329
static PyDateTime_Delta * look_up_delta(int, int, int, PyTypeObject *);
1330
1331
/* Create a timedelta instance.  Normalize the members iff normalize is
1332
 * true.  Passing false is a speed optimization, if you know for sure
1333
 * that seconds and microseconds are already in their proper ranges.  In any
1334
 * case, raises OverflowError and returns NULL if the normalized days is out
1335
 * of range.
1336
 */
1337
static PyObject *
1338
new_delta_ex(int days, int seconds, int microseconds, int normalize,
1339
             PyTypeObject *type)
1340
176
{
1341
176
    PyDateTime_Delta *self;
1342
1343
176
    if (normalize)
1344
22
        normalize_d_s_us(&days, &seconds, &microseconds);
1345
176
    assert(0 <= seconds && seconds < 24*3600);
1346
176
    assert(0 <= microseconds && microseconds < 1000000);
1347
1348
176
    if (check_delta_day_range(days) < 0)
1349
0
        return NULL;
1350
1351
176
    self = look_up_delta(days, seconds, microseconds, type);
1352
176
    if (self != NULL) {
1353
0
        return (PyObject *)self;
1354
0
    }
1355
176
    assert(!PyErr_Occurred());
1356
1357
176
    self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
1358
176
    if (self != NULL) {
1359
176
        self->hashcode = -1;
1360
176
        SET_TD_DAYS(self, days);
1361
176
        SET_TD_SECONDS(self, seconds);
1362
176
        SET_TD_MICROSECONDS(self, microseconds);
1363
176
    }
1364
176
    return (PyObject *) self;
1365
176
}
1366
1367
#define new_delta(d, s, us, normalize)  \
1368
44
    new_delta_ex(d, s, us, normalize, DELTA_TYPE(NO_STATE))
1369
1370
1371
typedef struct
1372
{
1373
    PyObject_HEAD
1374
    PyObject *offset;
1375
    PyObject *name;
1376
} PyDateTime_TimeZone;
1377
1378
static PyDateTime_TimeZone * look_up_timezone(PyObject *offset, PyObject *name);
1379
1380
/* Create new timezone instance checking offset range.  This
1381
   function does not check the name argument.  Caller must assure
1382
   that offset is a timedelta instance and name is either NULL
1383
   or a unicode object. */
1384
static PyObject *
1385
create_timezone(PyObject *offset, PyObject *name)
1386
44
{
1387
44
    PyDateTime_TimeZone *self;
1388
44
    PyTypeObject *type = TIMEZONE_TYPE(NO_STATE);
1389
1390
44
    assert(offset != NULL);
1391
44
    assert(PyDelta_Check(offset));
1392
44
    assert(name == NULL || PyUnicode_Check(name));
1393
1394
44
    self = look_up_timezone(offset, name);
1395
44
    if (self != NULL) {
1396
0
        return (PyObject *)self;
1397
0
    }
1398
44
    assert(!PyErr_Occurred());
1399
1400
44
    self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
1401
44
    if (self == NULL) {
1402
0
        return NULL;
1403
0
    }
1404
44
    self->offset = Py_NewRef(offset);
1405
44
    self->name = Py_XNewRef(name);
1406
44
    return (PyObject *)self;
1407
44
}
1408
1409
static int delta_bool(PyObject *op);
1410
static PyDateTime_TimeZone utc_timezone;
1411
1412
static PyObject *
1413
new_timezone(PyObject *offset, PyObject *name)
1414
0
{
1415
0
    assert(offset != NULL);
1416
0
    assert(PyDelta_Check(offset));
1417
0
    assert(name == NULL || PyUnicode_Check(name));
1418
1419
0
    if (name == NULL && delta_bool(offset) == 0) {
1420
0
        return Py_NewRef(CONST_UTC(NO_STATE));
1421
0
    }
1422
0
    if ((GET_TD_DAYS(offset) == -1 &&
1423
0
            GET_TD_SECONDS(offset) == 0 &&
1424
0
            GET_TD_MICROSECONDS(offset) < 1) ||
1425
0
        GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
1426
0
        PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
1427
0
                     " strictly between -timedelta(hours=24) and"
1428
0
                     " timedelta(hours=24), not %R", offset);
1429
0
        return NULL;
1430
0
    }
1431
1432
0
    return create_timezone(offset, name);
1433
0
}
1434
1435
/* ---------------------------------------------------------------------------
1436
 * tzinfo helpers.
1437
 */
1438
1439
/* Ensure that p is None or of a tzinfo subclass.  Return 0 if OK; if not
1440
 * raise TypeError and return -1.
1441
 */
1442
static int
1443
check_tzinfo_subclass(PyObject *p)
1444
88
{
1445
88
    if (p == Py_None || PyTZInfo_Check(p))
1446
88
        return 0;
1447
0
    PyErr_Format(PyExc_TypeError,
1448
0
                 "tzinfo argument must be None or of a tzinfo subclass, "
1449
0
                 "not type '%s'",
1450
0
                 Py_TYPE(p)->tp_name);
1451
0
    return -1;
1452
88
}
1453
1454
/* If self has a tzinfo member, return a BORROWED reference to it.  Else
1455
 * return NULL, which is NOT AN ERROR.  There are no error returns here,
1456
 * and the caller must not decref the result.
1457
 */
1458
static PyObject *
1459
get_tzinfo_member(PyObject *self)
1460
0
{
1461
0
    PyObject *tzinfo = NULL;
1462
1463
0
    if (PyDateTime_Check(self) && HASTZINFO(self))
1464
0
        tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
1465
0
    else if (PyTime_Check(self) && HASTZINFO(self))
1466
0
        tzinfo = ((PyDateTime_Time *)self)->tzinfo;
1467
1468
0
    return tzinfo;
1469
0
}
1470
1471
/* Call getattr(tzinfo, name)(tzinfoarg), and check the result.  tzinfo must
1472
 * be an instance of the tzinfo class.  If the method returns None, this
1473
 * returns None.  If the method doesn't return None or timedelta, TypeError is
1474
 * raised and this returns NULL.  If it returns a timedelta and the value is
1475
 * out of range or isn't a whole number of minutes, ValueError is raised and
1476
 * this returns NULL.  Else result is returned.
1477
 */
1478
static PyObject *
1479
call_tzinfo_method(PyObject *tzinfo, PyObject *name, PyObject *tzinfoarg)
1480
0
{
1481
0
    PyObject *offset;
1482
1483
0
    assert(tzinfo != NULL);
1484
0
    assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
1485
0
    assert(tzinfoarg != NULL);
1486
1487
0
    if (tzinfo == Py_None)
1488
0
        Py_RETURN_NONE;
1489
0
    offset = PyObject_CallMethodOneArg(tzinfo, name, tzinfoarg);
1490
0
    if (offset == Py_None || offset == NULL)
1491
0
        return offset;
1492
0
    if (PyDelta_Check(offset)) {
1493
0
        if ((GET_TD_DAYS(offset) == -1 &&
1494
0
                GET_TD_SECONDS(offset) == 0 &&
1495
0
                GET_TD_MICROSECONDS(offset) < 1) ||
1496
0
            GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
1497
0
            PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
1498
0
                         " strictly between -timedelta(hours=24) and"
1499
0
                         " timedelta(hours=24), not %R", offset);
1500
0
            Py_DECREF(offset);
1501
0
            return NULL;
1502
0
        }
1503
0
    }
1504
0
    else {
1505
0
        PyErr_Format(PyExc_TypeError,
1506
0
                     "tzinfo.%U() must return None or "
1507
0
                     "timedelta, not '%.200s'",
1508
0
                     name, Py_TYPE(offset)->tp_name);
1509
0
        Py_DECREF(offset);
1510
0
        return NULL;
1511
0
    }
1512
1513
0
    return offset;
1514
0
}
1515
1516
/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
1517
 * result.  tzinfo must be an instance of the tzinfo class.  If utcoffset()
1518
 * returns None, call_utcoffset returns 0 and sets *none to 1.  If uctoffset()
1519
 * doesn't return None or timedelta, TypeError is raised and this returns -1.
1520
 * If utcoffset() returns an out of range timedelta,
1521
 * ValueError is raised and this returns -1.  Else *none is
1522
 * set to 0 and the offset is returned (as timedelta, positive east of UTC).
1523
 */
1524
static PyObject *
1525
call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
1526
0
{
1527
0
    return call_tzinfo_method(tzinfo, &_Py_ID(utcoffset), tzinfoarg);
1528
0
}
1529
1530
/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
1531
 * result.  tzinfo must be an instance of the tzinfo class.  If dst()
1532
 * returns None, call_dst returns 0 and sets *none to 1.  If dst()
1533
 * doesn't return None or timedelta, TypeError is raised and this
1534
 * returns -1.  If dst() returns an invalid timedelta for a UTC offset,
1535
 * ValueError is raised and this returns -1.  Else *none is set to 0 and
1536
 * the offset is returned (as timedelta, positive east of UTC).
1537
 */
1538
static PyObject *
1539
call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
1540
0
{
1541
0
    return call_tzinfo_method(tzinfo, &_Py_ID(dst), tzinfoarg);
1542
0
}
1543
1544
/* Call tzinfo.tzname(tzinfoarg), and return the result.  tzinfo must be
1545
 * an instance of the tzinfo class or None.  If tzinfo isn't None, and
1546
 * tzname() doesn't return None or a string, TypeError is raised and this
1547
 * returns NULL.  If the result is a string, we ensure it is a Unicode
1548
 * string.
1549
 */
1550
static PyObject *
1551
call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
1552
0
{
1553
0
    PyObject *result;
1554
0
    assert(tzinfo != NULL);
1555
0
    assert(check_tzinfo_subclass(tzinfo) >= 0);
1556
0
    assert(tzinfoarg != NULL);
1557
1558
0
    if (tzinfo == Py_None)
1559
0
        Py_RETURN_NONE;
1560
1561
0
    result = PyObject_CallMethodOneArg(tzinfo, &_Py_ID(tzname), tzinfoarg);
1562
1563
0
    if (result == NULL || result == Py_None)
1564
0
        return result;
1565
1566
0
    if (!PyUnicode_Check(result)) {
1567
0
        PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
1568
0
                     "return None or a string, not '%s'",
1569
0
                     Py_TYPE(result)->tp_name);
1570
0
        Py_SETREF(result, NULL);
1571
0
    }
1572
1573
0
    return result;
1574
0
}
1575
1576
/* repr is like "someclass(arg1, arg2)".  If tzinfo isn't None,
1577
 * stuff
1578
 *     ", tzinfo=" + repr(tzinfo)
1579
 * before the closing ")".
1580
 */
1581
static PyObject *
1582
append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1583
0
{
1584
0
    PyObject *temp;
1585
1586
0
    assert(PyUnicode_Check(repr));
1587
0
    assert(tzinfo);
1588
0
    if (tzinfo == Py_None)
1589
0
        return repr;
1590
    /* Get rid of the trailing ')'. */
1591
0
    assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1592
0
    temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
1593
0
    Py_DECREF(repr);
1594
0
    if (temp == NULL)
1595
0
        return NULL;
1596
0
    repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1597
0
    Py_DECREF(temp);
1598
0
    return repr;
1599
0
}
1600
1601
/* repr is like "someclass(arg1, arg2)".  If fold isn't 0,
1602
 * stuff
1603
 *     ", fold=" + repr(tzinfo)
1604
 * before the closing ")".
1605
 */
1606
static PyObject *
1607
append_keyword_fold(PyObject *repr, int fold)
1608
0
{
1609
0
    PyObject *temp;
1610
1611
0
    assert(PyUnicode_Check(repr));
1612
0
    if (fold == 0)
1613
0
        return repr;
1614
    /* Get rid of the trailing ')'. */
1615
0
    assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1616
0
    temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
1617
0
    Py_DECREF(repr);
1618
0
    if (temp == NULL)
1619
0
        return NULL;
1620
0
    repr = PyUnicode_FromFormat("%U, fold=%d)", temp, fold);
1621
0
    Py_DECREF(temp);
1622
0
    return repr;
1623
0
}
1624
1625
static inline PyObject *
1626
tzinfo_from_isoformat_results(int rv, int tzoffset, int tz_useconds)
1627
0
{
1628
0
    PyObject *tzinfo;
1629
0
    if (rv == 1) {
1630
        // Create a timezone from the offset (a zero offset returns UTC)
1631
0
        if (tzoffset == 0 && tz_useconds == 0) {
1632
0
            return Py_NewRef(CONST_UTC(NO_STATE));
1633
0
        }
1634
1635
0
        PyObject *delta = new_delta(0, tzoffset, tz_useconds, 1);
1636
0
        if (delta == NULL) {
1637
0
            return NULL;
1638
0
        }
1639
0
        tzinfo = new_timezone(delta, NULL);
1640
0
        Py_DECREF(delta);
1641
0
    }
1642
0
    else {
1643
0
        tzinfo = Py_NewRef(Py_None);
1644
0
    }
1645
1646
0
    return tzinfo;
1647
0
}
1648
1649
/* ---------------------------------------------------------------------------
1650
 * String format helpers.
1651
 */
1652
1653
static PyObject *
1654
format_ctime(PyObject *date, int hours, int minutes, int seconds)
1655
0
{
1656
0
    static const char * const DayNames[] = {
1657
0
        "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1658
0
    };
1659
0
    static const char * const MonthNames[] = {
1660
0
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1661
0
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1662
0
    };
1663
1664
0
    int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1665
1666
0
    return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1667
0
                                DayNames[wday], MonthNames[GET_MONTH(date)-1],
1668
0
                                GET_DAY(date), hours, minutes, seconds,
1669
0
                                GET_YEAR(date));
1670
0
}
1671
1672
static PyObject *delta_negative(PyObject *op);
1673
1674
/* Add formatted UTC offset string to buf.  buf has no more than
1675
 * buflen bytes remaining.  The UTC offset is gotten by calling
1676
 * tzinfo.uctoffset(tzinfoarg).  If that returns None, \0 is stored into
1677
 * *buf, and that's all.  Else the returned value is checked for sanity (an
1678
 * integer in range), and if that's OK it's converted to an hours & minutes
1679
 * string of the form
1680
 *   sign HH sep MM [sep SS [. UUUUUU]]
1681
 * Returns 0 if everything is OK.  If the return value from utcoffset() is
1682
 * bogus, an appropriate exception is set and -1 is returned.
1683
 */
1684
static int
1685
format_utcoffset(char *buf, size_t buflen, const char *sep,
1686
                PyObject *tzinfo, PyObject *tzinfoarg)
1687
0
{
1688
0
    PyObject *offset;
1689
0
    int hours, minutes, seconds, microseconds;
1690
0
    char sign;
1691
1692
0
    assert(buflen >= 1);
1693
1694
0
    offset = call_utcoffset(tzinfo, tzinfoarg);
1695
0
    if (offset == NULL)
1696
0
        return -1;
1697
0
    if (offset == Py_None) {
1698
0
        Py_DECREF(offset);
1699
0
        *buf = '\0';
1700
0
        return 0;
1701
0
    }
1702
    /* Offset is normalized, so it is negative if days < 0 */
1703
0
    if (GET_TD_DAYS(offset) < 0) {
1704
0
        sign = '-';
1705
0
        Py_SETREF(offset, delta_negative(offset));
1706
0
        if (offset == NULL)
1707
0
            return -1;
1708
0
    }
1709
0
    else {
1710
0
        sign = '+';
1711
0
    }
1712
    /* Offset is not negative here. */
1713
0
    microseconds = GET_TD_MICROSECONDS(offset);
1714
0
    seconds = GET_TD_SECONDS(offset);
1715
0
    Py_DECREF(offset);
1716
0
    minutes = divmod(seconds, 60, &seconds);
1717
0
    hours = divmod(minutes, 60, &minutes);
1718
0
    if (microseconds) {
1719
0
        PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d.%06d", sign,
1720
0
                      hours, sep, minutes, sep, seconds, microseconds);
1721
0
        return 0;
1722
0
    }
1723
0
    if (seconds) {
1724
0
        PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d", sign, hours,
1725
0
                      sep, minutes, sep, seconds);
1726
0
        return 0;
1727
0
    }
1728
0
    PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1729
0
    return 0;
1730
0
}
1731
1732
/* Check whether year with century should be normalized for strftime. */
1733
inline static int
1734
normalize_century(void)
1735
0
{
1736
0
    static int cache = -1;
1737
0
    int res = FT_ATOMIC_LOAD_INT_RELAXED(cache);
1738
0
    if (res < 0) {
1739
0
        char year[5];
1740
0
        struct tm date = {
1741
0
            .tm_year = -1801,
1742
0
            .tm_mon = 0,
1743
0
            .tm_mday = 1
1744
0
        };
1745
0
        res = (strftime(year, sizeof(year), "%Y", &date) &&
1746
0
               strcmp(year, "0099") != 0);
1747
0
        FT_ATOMIC_STORE_INT_RELAXED(cache, res);
1748
0
    }
1749
0
    return res;
1750
0
}
1751
1752
static PyObject *
1753
make_somezreplacement(PyObject *object, char *sep, PyObject *tzinfoarg)
1754
0
{
1755
0
    char buf[100];
1756
0
    PyObject *tzinfo = get_tzinfo_member(object);
1757
1758
0
    if (tzinfo == Py_None || tzinfo == NULL) {
1759
0
        return PyUnicode_FromStringAndSize(NULL, 0);
1760
0
    }
1761
1762
0
    assert(tzinfoarg != NULL);
1763
0
    if (format_utcoffset(buf,
1764
0
                         sizeof(buf),
1765
0
                         sep,
1766
0
                         tzinfo,
1767
0
                         tzinfoarg) < 0)
1768
0
        return NULL;
1769
1770
0
    return PyUnicode_FromString(buf);
1771
0
}
1772
1773
static PyObject *
1774
make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1775
0
{
1776
0
    PyObject *temp;
1777
0
    PyObject *tzinfo = get_tzinfo_member(object);
1778
0
    PyObject *Zreplacement = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
1779
1780
0
    if (Zreplacement == NULL)
1781
0
        return NULL;
1782
0
    if (tzinfo == Py_None || tzinfo == NULL)
1783
0
        return Zreplacement;
1784
1785
0
    assert(tzinfoarg != NULL);
1786
0
    temp = call_tzname(tzinfo, tzinfoarg);
1787
0
    if (temp == NULL)
1788
0
        goto Error;
1789
0
    if (temp == Py_None) {
1790
0
        Py_DECREF(temp);
1791
0
        return Zreplacement;
1792
0
    }
1793
1794
0
    assert(PyUnicode_Check(temp));
1795
    /* Since the tzname is getting stuffed into the
1796
     * format, we have to double any % signs so that
1797
     * strftime doesn't treat them as format codes.
1798
     */
1799
0
    Py_DECREF(Zreplacement);
1800
0
    Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1801
0
    Py_DECREF(temp);
1802
0
    if (Zreplacement == NULL)
1803
0
        return NULL;
1804
0
    if (!PyUnicode_Check(Zreplacement)) {
1805
0
        PyErr_SetString(PyExc_TypeError,
1806
0
                        "tzname.replace() did not return a string");
1807
0
        goto Error;
1808
0
    }
1809
0
    return Zreplacement;
1810
1811
0
  Error:
1812
0
    Py_DECREF(Zreplacement);
1813
0
    return NULL;
1814
0
}
1815
1816
static PyObject *
1817
make_freplacement(PyObject *object)
1818
0
{
1819
0
    char freplacement[64];
1820
0
    if (PyTime_Check(object)) {
1821
0
        PyOS_snprintf(freplacement, sizeof(freplacement),
1822
0
                      "%06d", TIME_GET_MICROSECOND(object));
1823
0
    }
1824
0
    else if (PyDateTime_Check(object)) {
1825
0
        PyOS_snprintf(freplacement, sizeof(freplacement),
1826
0
                      "%06d", DATE_GET_MICROSECOND(object));
1827
0
    }
1828
0
    else {
1829
0
        PyOS_snprintf(freplacement, sizeof(freplacement), "%06d", 0);
1830
0
    }
1831
1832
0
    return PyUnicode_FromString(freplacement);
1833
0
}
1834
1835
/* I sure don't want to reproduce the strftime code from the time module,
1836
 * so this imports the module and calls it.  All the hair is due to
1837
 * giving special meanings to the %z, %:z, %Z and %f format codes via a
1838
 * preprocessing step on the format string.
1839
 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1840
 * needed.
1841
 */
1842
static PyObject *
1843
wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1844
              PyObject *tzinfoarg)
1845
0
{
1846
0
    PyObject *result = NULL;            /* guilty until proved innocent */
1847
1848
0
    PyObject *zreplacement = NULL;      /* py string, replacement for %z */
1849
0
    PyObject *colonzreplacement = NULL; /* py string, replacement for %:z */
1850
0
    PyObject *Zreplacement = NULL;      /* py string, replacement for %Z */
1851
0
    PyObject *freplacement = NULL;      /* py string, replacement for %f */
1852
1853
0
    assert(object && format && timetuple);
1854
0
    assert(PyUnicode_Check(format));
1855
1856
0
    PyObject *current_mod = NULL;
1857
0
    datetime_state *st = GET_CURRENT_STATE(current_mod);
1858
0
    if (st == NULL) {
1859
0
        return NULL;
1860
0
    }
1861
0
    PyObject *strftime = st->time_strftime;
1862
1863
    /* Scan the input format, looking for %z/%Z/%f escapes, building
1864
     * a new format.  Since computing the replacements for those codes
1865
     * is expensive, don't unless they're actually used.
1866
     */
1867
1868
0
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1869
0
    if (writer == NULL) {
1870
0
        goto Error;
1871
0
    }
1872
1873
0
    Py_ssize_t flen = PyUnicode_GET_LENGTH(format);
1874
0
    Py_ssize_t i = 0;
1875
0
    Py_ssize_t start = 0;
1876
0
    Py_ssize_t end = 0;
1877
0
    while (i != flen) {
1878
0
        i = PyUnicode_FindChar(format, '%', i, flen, 1);
1879
0
        if (i < 0) {
1880
0
            assert(!PyErr_Occurred());
1881
0
            break;
1882
0
        }
1883
0
        end = i;
1884
0
        i++;
1885
0
        if (i == flen) {
1886
0
            break;
1887
0
        }
1888
0
        Py_UCS4 ch = PyUnicode_READ_CHAR(format, i);
1889
0
        i++;
1890
        /* A % has been seen and ch is the character after it. */
1891
0
        PyObject *replacement = NULL;
1892
0
        if (ch == 'z') {
1893
            /* %z -> +HHMM */
1894
0
            if (zreplacement == NULL) {
1895
0
                zreplacement = make_somezreplacement(object, "", tzinfoarg);
1896
0
                if (zreplacement == NULL)
1897
0
                    goto Error;
1898
0
            }
1899
0
            replacement = zreplacement;
1900
0
        }
1901
0
        else if (ch == ':' && i < flen && PyUnicode_READ_CHAR(format, i) == 'z') {
1902
            /* %:z -> +HH:MM */
1903
0
            i++;
1904
0
            if (colonzreplacement == NULL) {
1905
0
                colonzreplacement = make_somezreplacement(object, ":", tzinfoarg);
1906
0
                if (colonzreplacement == NULL)
1907
0
                    goto Error;
1908
0
            }
1909
0
            replacement = colonzreplacement;
1910
0
        }
1911
0
        else if (ch == 'Z') {
1912
            /* format tzname */
1913
0
            if (Zreplacement == NULL) {
1914
0
                Zreplacement = make_Zreplacement(object,
1915
0
                                                 tzinfoarg);
1916
0
                if (Zreplacement == NULL)
1917
0
                    goto Error;
1918
0
            }
1919
0
            replacement = Zreplacement;
1920
0
        }
1921
0
        else if (ch == 'f') {
1922
            /* format microseconds */
1923
0
            if (freplacement == NULL) {
1924
0
                freplacement = make_freplacement(object);
1925
0
                if (freplacement == NULL)
1926
0
                    goto Error;
1927
0
            }
1928
0
            replacement = freplacement;
1929
0
        }
1930
0
        else if (ch >= '1' && ch <= '6'
1931
0
                 && i < flen && PyUnicode_READ_CHAR(format, i) == 'f')
1932
0
        {
1933
            /* %Nf -> first N digits of microseconds */
1934
0
            i++;
1935
0
            if (freplacement == NULL) {
1936
0
                freplacement = make_freplacement(object);
1937
0
                if (freplacement == NULL) {
1938
0
                    goto Error;
1939
0
                }
1940
0
            }
1941
0
            if (PyUnicodeWriter_WriteSubstring(writer, format, start, end) < 0) {
1942
0
                goto Error;
1943
0
            }
1944
0
            start = i;
1945
0
            Py_ssize_t precision = ch - '0';
1946
0
            if (PyUnicodeWriter_WriteSubstring(writer, freplacement,
1947
0
                                               0, precision) < 0)
1948
0
            {
1949
0
                goto Error;
1950
0
            }
1951
0
            continue;
1952
0
        }
1953
0
        else if (normalize_century()
1954
0
                 && (ch == 'Y' || ch == 'G' || ch == 'F' || ch == 'C'))
1955
0
        {
1956
            /* 0-pad year with century as necessary */
1957
0
            PyObject *item = PySequence_GetItem(timetuple, 0);
1958
0
            if (item == NULL) {
1959
0
                goto Error;
1960
0
            }
1961
0
            long year_long = PyLong_AsLong(item);
1962
0
            Py_DECREF(item);
1963
0
            if (year_long == -1 && PyErr_Occurred()) {
1964
0
                goto Error;
1965
0
            }
1966
            /* Note that datetime(1000, 1, 1).strftime('%G') == '1000' so year
1967
               1000 for %G can go on the fast path. */
1968
0
            if (year_long >= 1000) {
1969
0
                continue;
1970
0
            }
1971
0
            if (ch == 'G') {
1972
0
                PyObject *year_str = PyObject_CallFunction(strftime, "sO",
1973
0
                                                           "%G", timetuple);
1974
0
                if (year_str == NULL) {
1975
0
                    goto Error;
1976
0
                }
1977
0
                PyObject *year = PyNumber_Long(year_str);
1978
0
                Py_DECREF(year_str);
1979
0
                if (year == NULL) {
1980
0
                    goto Error;
1981
0
                }
1982
0
                year_long = PyLong_AsLong(year);
1983
0
                Py_DECREF(year);
1984
0
                if (year_long == -1 && PyErr_Occurred()) {
1985
0
                    goto Error;
1986
0
                }
1987
0
            }
1988
            /* Buffer of maximum size of formatted year permitted by long.
1989
             * +6 to accommodate dashes, 2-digit month and day for %F. */
1990
0
            char buf[SIZEOF_LONG * 5 / 2 + 2 + 6];
1991
0
            Py_ssize_t n = PyOS_snprintf(buf, sizeof(buf),
1992
0
                                      ch == 'F' ? "%04ld-%%m-%%d" :
1993
0
                                      "%04ld", year_long);
1994
0
            if (ch == 'C') {
1995
0
                n -= 2;
1996
0
            }
1997
0
            if (PyUnicodeWriter_WriteSubstring(writer, format, start, end) < 0) {
1998
0
                goto Error;
1999
0
            }
2000
0
            start = i;
2001
0
            if (PyUnicodeWriter_WriteUTF8(writer, buf, n) < 0) {
2002
0
                goto Error;
2003
0
            }
2004
0
            continue;
2005
0
        }
2006
0
        else {
2007
            /* percent followed by something else */
2008
0
            continue;
2009
0
        }
2010
0
        assert(replacement != NULL);
2011
0
        assert(PyUnicode_Check(replacement));
2012
0
        if (PyUnicodeWriter_WriteSubstring(writer, format, start, end) < 0) {
2013
0
            goto Error;
2014
0
        }
2015
0
        start = i;
2016
0
        if (PyUnicodeWriter_WriteStr(writer, replacement) < 0) {
2017
0
            goto Error;
2018
0
        }
2019
0
    }  /* end while() */
2020
2021
0
    PyObject *newformat;
2022
0
    if (start == 0) {
2023
0
        PyUnicodeWriter_Discard(writer);
2024
0
        newformat = Py_NewRef(format);
2025
0
    }
2026
0
    else {
2027
0
        if (PyUnicodeWriter_WriteSubstring(writer, format, start, flen) < 0) {
2028
0
            goto Error;
2029
0
        }
2030
0
        newformat = PyUnicodeWriter_Finish(writer);
2031
0
        if (newformat == NULL) {
2032
0
            goto Done;
2033
0
        }
2034
0
    }
2035
0
    result = PyObject_CallFunctionObjArgs(strftime,
2036
0
                                          newformat, timetuple, NULL);
2037
0
    Py_DECREF(newformat);
2038
2039
0
 Done:
2040
0
    Py_XDECREF(freplacement);
2041
0
    Py_XDECREF(zreplacement);
2042
0
    Py_XDECREF(colonzreplacement);
2043
0
    Py_XDECREF(Zreplacement);
2044
0
    RELEASE_CURRENT_STATE(st, current_mod);
2045
0
    return result;
2046
2047
0
 Error:
2048
0
    PyUnicodeWriter_Discard(writer);
2049
0
    goto Done;
2050
0
}
2051
2052
/* ---------------------------------------------------------------------------
2053
 * Wrap functions from the time module.  These aren't directly available
2054
 * from C.  Perhaps they should be.
2055
 */
2056
2057
/* Build a time.struct_time.  The weekday and day number are automatically
2058
 * computed from the y,m,d args.
2059
 */
2060
static PyObject *
2061
build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
2062
0
{
2063
0
    PyObject *current_mod = NULL;
2064
0
    datetime_state *st = GET_CURRENT_STATE(current_mod);
2065
0
    if (st == NULL) {
2066
0
        return NULL;
2067
0
    }
2068
2069
0
    PyObject *result = PyObject_CallFunction(st->time_struct_time,
2070
0
                         "((iiiiiiiii))",
2071
0
                         y, m, d,
2072
0
                         hh, mm, ss,
2073
0
                         weekday(y, m, d),
2074
0
                         days_before_month(y, m) + d,
2075
0
                         dstflag);
2076
0
    RELEASE_CURRENT_STATE(st, current_mod);
2077
0
    return result;
2078
0
}
2079
2080
/* ---------------------------------------------------------------------------
2081
 * Miscellaneous helpers.
2082
 */
2083
2084
/* The comparisons here all most naturally compute a cmp()-like result.
2085
 * This little helper turns that into a bool result for rich comparisons.
2086
 */
2087
static PyObject *
2088
diff_to_bool(int diff, int op)
2089
0
{
2090
0
    Py_RETURN_RICHCOMPARE(diff, 0, op);
2091
0
}
2092
2093
/* ---------------------------------------------------------------------------
2094
 * Class implementations.
2095
 */
2096
2097
/*
2098
 * PyDateTime_Delta implementation.
2099
 */
2100
2101
/* Convert a timedelta to a number of us,
2102
 *      (24*3600*self.days + self.seconds)*1000000 + self.microseconds
2103
 * as a Python int.
2104
 * The number of whole seconds always fits in int64_t, and so does the
2105
 * number of microseconds unless the delta is very large, so compute it
2106
 * in C when possible and fall back to Python int arithmetic otherwise.
2107
 * One second is reserved at the limit so that adding the microseconds
2108
 * field cannot overflow.
2109
 */
2110
static PyObject *
2111
delta_to_microseconds(PyDateTime_Delta *self)
2112
0
{
2113
0
    const int64_t max_seconds = INT64_MAX / 1000000 - 1;
2114
0
    int64_t seconds = (int64_t)GET_TD_DAYS(self) * (24 * 3600)
2115
0
                      + GET_TD_SECONDS(self);
2116
0
    if (-max_seconds <= seconds && seconds <= max_seconds) {
2117
0
        return PyLong_FromInt64(seconds * 1000000
2118
0
                                + GET_TD_MICROSECONDS(self));
2119
0
    }
2120
2121
0
    PyObject *x1 = NULL;
2122
0
    PyObject *x2 = NULL;
2123
0
    PyObject *result = NULL;
2124
2125
0
    PyObject *current_mod;
2126
0
    datetime_state *st = GET_CURRENT_STATE(current_mod);
2127
0
    if (st == NULL) {
2128
0
        return NULL;
2129
0
    }
2130
2131
0
    x1 = PyLong_FromInt64(seconds);     /* days and seconds in seconds */
2132
0
    if (x1 == NULL)
2133
0
        goto Done;
2134
0
    x2 = PyNumber_Multiply(x1, CONST_US_PER_SECOND(st));          /* us */
2135
0
    if (x2 == NULL)
2136
0
        goto Done;
2137
2138
    /* x2 has days+seconds in us */
2139
0
    Py_SETREF(x1, PyLong_FromLong(GET_TD_MICROSECONDS(self)));
2140
0
    if (x1 == NULL)
2141
0
        goto Done;
2142
0
    result = PyNumber_Add(x2, x1);
2143
0
    assert(result == NULL || PyLong_CheckExact(result));
2144
2145
0
Done:
2146
0
    Py_XDECREF(x1);
2147
0
    Py_XDECREF(x2);
2148
0
    RELEASE_CURRENT_STATE(st, current_mod);
2149
0
    return result;
2150
0
}
2151
2152
static PyObject *
2153
checked_divmod(PyObject *a, PyObject *b)
2154
0
{
2155
0
    PyObject *result = PyNumber_Divmod(a, b);
2156
0
    if (result != NULL) {
2157
0
        if (!PyTuple_Check(result)) {
2158
0
            PyErr_Format(PyExc_TypeError,
2159
0
                         "divmod() returned non-tuple (type %.200s)",
2160
0
                         Py_TYPE(result)->tp_name);
2161
0
            Py_DECREF(result);
2162
0
            return NULL;
2163
0
        }
2164
0
        if (PyTuple_GET_SIZE(result) != 2) {
2165
0
            PyErr_Format(PyExc_TypeError,
2166
0
                         "divmod() returned a tuple of size %zd",
2167
0
                         PyTuple_GET_SIZE(result));
2168
0
            Py_DECREF(result);
2169
0
            return NULL;
2170
0
        }
2171
0
    }
2172
0
    return result;
2173
0
}
2174
2175
/* Convert a number of us (as a Python int) to a timedelta.
2176
 */
2177
static PyObject *
2178
microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
2179
0
{
2180
0
    int us;
2181
0
    int s;
2182
0
    int d;
2183
2184
0
    PyObject *tuple = NULL;
2185
0
    PyObject *num = NULL;
2186
0
    PyObject *result = NULL;
2187
2188
0
    PyObject *current_mod;
2189
0
    datetime_state *st = GET_CURRENT_STATE(current_mod);
2190
0
    if (st == NULL) {
2191
0
        return NULL;
2192
0
    }
2193
2194
0
    tuple = checked_divmod(pyus, CONST_US_PER_SECOND(st));
2195
0
    if (tuple == NULL) {
2196
0
        goto Done;
2197
0
    }
2198
2199
0
    num = PyTuple_GET_ITEM(tuple, 1);           /* us */
2200
0
    us = PyLong_AsInt(num);
2201
0
    num = NULL;
2202
0
    if (us == -1 && PyErr_Occurred()) {
2203
0
        goto Done;
2204
0
    }
2205
0
    if (!(0 <= us && us < 1000000)) {
2206
0
        goto BadDivmod;
2207
0
    }
2208
2209
0
    num = Py_NewRef(PyTuple_GET_ITEM(tuple, 0));        /* leftover seconds */
2210
0
    Py_DECREF(tuple);
2211
2212
0
    tuple = checked_divmod(num, CONST_SEC_PER_DAY(st));
2213
0
    if (tuple == NULL)
2214
0
        goto Done;
2215
0
    Py_DECREF(num);
2216
2217
0
    num = PyTuple_GET_ITEM(tuple, 1);           /* seconds */
2218
0
    s = PyLong_AsInt(num);
2219
0
    num = NULL;
2220
0
    if (s == -1 && PyErr_Occurred()) {
2221
0
        goto Done;
2222
0
    }
2223
0
    if (!(0 <= s && s < 24*3600)) {
2224
0
        goto BadDivmod;
2225
0
    }
2226
2227
0
    num = Py_NewRef(PyTuple_GET_ITEM(tuple, 0));           /* leftover days */
2228
0
    d = PyLong_AsInt(num);
2229
0
    if (d == -1 && PyErr_Occurred()) {
2230
0
        goto Done;
2231
0
    }
2232
0
    result = new_delta_ex(d, s, us, 0, type);
2233
2234
0
Done:
2235
0
    Py_XDECREF(tuple);
2236
0
    Py_XDECREF(num);
2237
0
    RELEASE_CURRENT_STATE(st, current_mod);
2238
0
    return result;
2239
2240
0
BadDivmod:
2241
0
    PyErr_SetString(PyExc_TypeError,
2242
0
                    "divmod() returned a value out of range");
2243
0
    goto Done;
2244
0
}
2245
2246
#define microseconds_to_delta(pymicros) \
2247
0
    microseconds_to_delta_ex(pymicros, DELTA_TYPE(NO_STATE))
2248
2249
static PyObject *
2250
multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
2251
0
{
2252
0
    PyObject *pyus_in;
2253
0
    PyObject *pyus_out;
2254
0
    PyObject *result;
2255
2256
0
    pyus_in = delta_to_microseconds(delta);
2257
0
    if (pyus_in == NULL)
2258
0
        return NULL;
2259
2260
0
    pyus_out = PyNumber_Multiply(intobj, pyus_in);
2261
0
    Py_DECREF(pyus_in);
2262
0
    if (pyus_out == NULL)
2263
0
        return NULL;
2264
2265
0
    result = microseconds_to_delta(pyus_out);
2266
0
    Py_DECREF(pyus_out);
2267
0
    return result;
2268
0
}
2269
2270
static PyObject *
2271
get_float_as_integer_ratio(PyObject *floatobj)
2272
0
{
2273
0
    PyObject *ratio;
2274
2275
0
    assert(floatobj && PyFloat_Check(floatobj));
2276
0
    ratio = PyObject_CallMethodNoArgs(floatobj, &_Py_ID(as_integer_ratio));
2277
0
    if (ratio == NULL) {
2278
0
        return NULL;
2279
0
    }
2280
0
    if (!PyTuple_Check(ratio)) {
2281
0
        PyErr_Format(PyExc_TypeError,
2282
0
                     "unexpected return type from as_integer_ratio(): "
2283
0
                     "expected tuple, not '%.200s'",
2284
0
                     Py_TYPE(ratio)->tp_name);
2285
0
        Py_DECREF(ratio);
2286
0
        return NULL;
2287
0
    }
2288
0
    if (PyTuple_Size(ratio) != 2) {
2289
0
        PyErr_SetString(PyExc_ValueError,
2290
0
                        "as_integer_ratio() must return a 2-tuple");
2291
0
        Py_DECREF(ratio);
2292
0
        return NULL;
2293
0
    }
2294
0
    return ratio;
2295
0
}
2296
2297
/* op is 0 for multiplication, 1 for division */
2298
static PyObject *
2299
multiply_truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *floatobj, int op)
2300
0
{
2301
0
    PyObject *result = NULL;
2302
0
    PyObject *pyus_in = NULL, *temp, *pyus_out;
2303
0
    PyObject *ratio = NULL;
2304
2305
0
    pyus_in = delta_to_microseconds(delta);
2306
0
    if (pyus_in == NULL)
2307
0
        return NULL;
2308
0
    ratio = get_float_as_integer_ratio(floatobj);
2309
0
    if (ratio == NULL) {
2310
0
        goto error;
2311
0
    }
2312
0
    temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, op));
2313
0
    Py_SETREF(pyus_in, NULL);
2314
0
    if (temp == NULL)
2315
0
        goto error;
2316
0
    pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, !op));
2317
0
    Py_DECREF(temp);
2318
0
    if (pyus_out == NULL)
2319
0
        goto error;
2320
0
    result = microseconds_to_delta(pyus_out);
2321
0
    Py_DECREF(pyus_out);
2322
0
 error:
2323
0
    Py_XDECREF(pyus_in);
2324
0
    Py_XDECREF(ratio);
2325
2326
0
    return result;
2327
0
}
2328
2329
static PyObject *
2330
divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
2331
0
{
2332
0
    PyObject *pyus_in;
2333
0
    PyObject *pyus_out;
2334
0
    PyObject *result;
2335
2336
0
    pyus_in = delta_to_microseconds(delta);
2337
0
    if (pyus_in == NULL)
2338
0
        return NULL;
2339
2340
0
    pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
2341
0
    Py_DECREF(pyus_in);
2342
0
    if (pyus_out == NULL)
2343
0
        return NULL;
2344
2345
0
    result = microseconds_to_delta(pyus_out);
2346
0
    Py_DECREF(pyus_out);
2347
0
    return result;
2348
0
}
2349
2350
static PyObject *
2351
divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
2352
0
{
2353
0
    PyObject *pyus_left;
2354
0
    PyObject *pyus_right;
2355
0
    PyObject *result;
2356
2357
0
    pyus_left = delta_to_microseconds(left);
2358
0
    if (pyus_left == NULL)
2359
0
        return NULL;
2360
2361
0
    pyus_right = delta_to_microseconds(right);
2362
0
    if (pyus_right == NULL)     {
2363
0
        Py_DECREF(pyus_left);
2364
0
        return NULL;
2365
0
    }
2366
2367
0
    result = PyNumber_FloorDivide(pyus_left, pyus_right);
2368
0
    Py_DECREF(pyus_left);
2369
0
    Py_DECREF(pyus_right);
2370
0
    return result;
2371
0
}
2372
2373
static PyObject *
2374
truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
2375
0
{
2376
0
    PyObject *pyus_left;
2377
0
    PyObject *pyus_right;
2378
0
    PyObject *result;
2379
2380
0
    pyus_left = delta_to_microseconds(left);
2381
0
    if (pyus_left == NULL)
2382
0
        return NULL;
2383
2384
0
    pyus_right = delta_to_microseconds(right);
2385
0
    if (pyus_right == NULL)     {
2386
0
        Py_DECREF(pyus_left);
2387
0
        return NULL;
2388
0
    }
2389
2390
0
    result = PyNumber_TrueDivide(pyus_left, pyus_right);
2391
0
    Py_DECREF(pyus_left);
2392
0
    Py_DECREF(pyus_right);
2393
0
    return result;
2394
0
}
2395
2396
static PyObject *
2397
truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
2398
0
{
2399
0
    PyObject *result;
2400
0
    PyObject *pyus_in, *pyus_out;
2401
0
    pyus_in = delta_to_microseconds(delta);
2402
0
    if (pyus_in == NULL)
2403
0
        return NULL;
2404
0
    pyus_out = divide_nearest(pyus_in, i);
2405
0
    Py_DECREF(pyus_in);
2406
0
    if (pyus_out == NULL)
2407
0
        return NULL;
2408
0
    result = microseconds_to_delta(pyus_out);
2409
0
    Py_DECREF(pyus_out);
2410
2411
0
    return result;
2412
0
}
2413
2414
static PyObject *
2415
delta_add(PyObject *left, PyObject *right)
2416
0
{
2417
0
    PyObject *result = Py_NotImplemented;
2418
2419
0
    if (PyDelta_Check(left) && PyDelta_Check(right)) {
2420
        /* delta + delta */
2421
        /* The C-level additions can't overflow because of the
2422
         * invariant bounds.
2423
         */
2424
0
        int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
2425
0
        int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
2426
0
        int microseconds = GET_TD_MICROSECONDS(left) +
2427
0
                           GET_TD_MICROSECONDS(right);
2428
0
        result = new_delta(days, seconds, microseconds, 1);
2429
0
    }
2430
2431
0
    if (result == Py_NotImplemented)
2432
0
        Py_INCREF(result);
2433
0
    return result;
2434
0
}
2435
2436
static PyObject *
2437
delta_negative(PyObject *self)
2438
0
{
2439
0
    return new_delta(-GET_TD_DAYS(self),
2440
0
                     -GET_TD_SECONDS(self),
2441
0
                     -GET_TD_MICROSECONDS(self),
2442
0
                     1);
2443
0
}
2444
2445
static PyObject *
2446
delta_positive(PyObject *self)
2447
0
{
2448
    /* Could optimize this (by returning self) if this isn't a
2449
     * subclass -- but who uses unary + ?  Approximately nobody.
2450
     */
2451
0
    return new_delta(GET_TD_DAYS(self),
2452
0
                     GET_TD_SECONDS(self),
2453
0
                     GET_TD_MICROSECONDS(self),
2454
0
                     0);
2455
0
}
2456
2457
static PyObject *
2458
delta_abs(PyObject *self)
2459
0
{
2460
0
    PyObject *result;
2461
2462
0
    assert(GET_TD_MICROSECONDS(self) >= 0);
2463
0
    assert(GET_TD_SECONDS(self) >= 0);
2464
2465
0
    if (GET_TD_DAYS(self) < 0)
2466
0
        result = delta_negative(self);
2467
0
    else
2468
0
        result = delta_positive(self);
2469
2470
0
    return result;
2471
0
}
2472
2473
static PyObject *
2474
delta_subtract(PyObject *left, PyObject *right)
2475
0
{
2476
0
    PyObject *result = Py_NotImplemented;
2477
2478
0
    if (PyDelta_Check(left) && PyDelta_Check(right)) {
2479
        /* delta - delta */
2480
        /* The C-level additions can't overflow because of the
2481
         * invariant bounds.
2482
         */
2483
0
        int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
2484
0
        int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
2485
0
        int microseconds = GET_TD_MICROSECONDS(left) -
2486
0
                           GET_TD_MICROSECONDS(right);
2487
0
        result = new_delta(days, seconds, microseconds, 1);
2488
0
    }
2489
2490
0
    if (result == Py_NotImplemented)
2491
0
        Py_INCREF(result);
2492
0
    return result;
2493
0
}
2494
2495
static int
2496
delta_cmp(PyObject *self, PyObject *other)
2497
0
{
2498
0
    int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
2499
0
    if (diff == 0) {
2500
0
        diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
2501
0
        if (diff == 0)
2502
0
            diff = GET_TD_MICROSECONDS(self) -
2503
0
                GET_TD_MICROSECONDS(other);
2504
0
    }
2505
0
    return diff;
2506
0
}
2507
2508
static PyObject *
2509
delta_richcompare(PyObject *self, PyObject *other, int op)
2510
0
{
2511
0
    if (PyDelta_Check(other)) {
2512
0
        int diff = delta_cmp(self, other);
2513
0
        return diff_to_bool(diff, op);
2514
0
    }
2515
0
    else {
2516
0
        Py_RETURN_NOTIMPLEMENTED;
2517
0
    }
2518
0
}
2519
2520
static PyObject *delta_getstate(PyDateTime_Delta *self);
2521
2522
static Py_hash_t
2523
delta_hash(PyObject *op)
2524
0
{
2525
0
    PyDateTime_Delta *self = PyDelta_CAST(op);
2526
0
    Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->hashcode);
2527
0
    if (hash == -1) {
2528
0
        PyObject *temp = delta_getstate(self);
2529
0
        if (temp != NULL) {
2530
0
            hash = PyObject_Hash(temp);
2531
0
            FT_ATOMIC_STORE_SSIZE_RELAXED(self->hashcode, hash);
2532
0
            Py_DECREF(temp);
2533
0
        }
2534
0
    }
2535
0
    return hash;
2536
0
}
2537
2538
static PyObject *
2539
delta_multiply(PyObject *left, PyObject *right)
2540
0
{
2541
0
    PyObject *result = Py_NotImplemented;
2542
2543
0
    if (PyDelta_Check(left)) {
2544
        /* delta * ??? */
2545
0
        if (PyLong_Check(right))
2546
0
            result = multiply_int_timedelta(right,
2547
0
                            (PyDateTime_Delta *) left);
2548
0
        else if (PyFloat_Check(right))
2549
0
            result = multiply_truedivide_timedelta_float(
2550
0
                            (PyDateTime_Delta *) left, right, 0);
2551
0
    }
2552
0
    else if (PyLong_Check(left))
2553
0
        result = multiply_int_timedelta(left,
2554
0
                        (PyDateTime_Delta *) right);
2555
0
    else if (PyFloat_Check(left))
2556
0
        result = multiply_truedivide_timedelta_float(
2557
0
                        (PyDateTime_Delta *) right, left, 0);
2558
2559
0
    if (result == Py_NotImplemented)
2560
0
        Py_INCREF(result);
2561
0
    return result;
2562
0
}
2563
2564
static PyObject *
2565
delta_divide(PyObject *left, PyObject *right)
2566
0
{
2567
0
    PyObject *result = Py_NotImplemented;
2568
2569
0
    if (PyDelta_Check(left)) {
2570
        /* delta * ??? */
2571
0
        if (PyLong_Check(right))
2572
0
            result = divide_timedelta_int(
2573
0
                            (PyDateTime_Delta *)left,
2574
0
                            right);
2575
0
        else if (PyDelta_Check(right))
2576
0
            result = divide_timedelta_timedelta(
2577
0
                            (PyDateTime_Delta *)left,
2578
0
                            (PyDateTime_Delta *)right);
2579
0
    }
2580
2581
0
    if (result == Py_NotImplemented)
2582
0
        Py_INCREF(result);
2583
0
    return result;
2584
0
}
2585
2586
static PyObject *
2587
delta_truedivide(PyObject *left, PyObject *right)
2588
0
{
2589
0
    PyObject *result = Py_NotImplemented;
2590
2591
0
    if (PyDelta_Check(left)) {
2592
0
        if (PyDelta_Check(right))
2593
0
            result = truedivide_timedelta_timedelta(
2594
0
                            (PyDateTime_Delta *)left,
2595
0
                            (PyDateTime_Delta *)right);
2596
0
        else if (PyFloat_Check(right))
2597
0
            result = multiply_truedivide_timedelta_float(
2598
0
                            (PyDateTime_Delta *)left, right, 1);
2599
0
        else if (PyLong_Check(right))
2600
0
            result = truedivide_timedelta_int(
2601
0
                            (PyDateTime_Delta *)left, right);
2602
0
    }
2603
2604
0
    if (result == Py_NotImplemented)
2605
0
        Py_INCREF(result);
2606
0
    return result;
2607
0
}
2608
2609
static PyObject *
2610
delta_remainder(PyObject *left, PyObject *right)
2611
0
{
2612
0
    PyObject *pyus_left;
2613
0
    PyObject *pyus_right;
2614
0
    PyObject *pyus_remainder;
2615
0
    PyObject *remainder;
2616
2617
0
    if (!PyDelta_Check(left) || !PyDelta_Check(right))
2618
0
        Py_RETURN_NOTIMPLEMENTED;
2619
2620
0
    pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2621
0
    if (pyus_left == NULL)
2622
0
        return NULL;
2623
2624
0
    pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2625
0
    if (pyus_right == NULL) {
2626
0
        Py_DECREF(pyus_left);
2627
0
        return NULL;
2628
0
    }
2629
2630
0
    pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
2631
0
    Py_DECREF(pyus_left);
2632
0
    Py_DECREF(pyus_right);
2633
0
    if (pyus_remainder == NULL)
2634
0
        return NULL;
2635
2636
0
    remainder = microseconds_to_delta(pyus_remainder);
2637
0
    Py_DECREF(pyus_remainder);
2638
0
    if (remainder == NULL)
2639
0
        return NULL;
2640
2641
0
    return remainder;
2642
0
}
2643
2644
static PyObject *
2645
delta_divmod(PyObject *left, PyObject *right)
2646
0
{
2647
0
    PyObject *pyus_left;
2648
0
    PyObject *pyus_right;
2649
0
    PyObject *divmod;
2650
0
    PyObject *delta;
2651
0
    PyObject *result;
2652
2653
0
    if (!PyDelta_Check(left) || !PyDelta_Check(right))
2654
0
        Py_RETURN_NOTIMPLEMENTED;
2655
2656
0
    pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2657
0
    if (pyus_left == NULL)
2658
0
        return NULL;
2659
2660
0
    pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2661
0
    if (pyus_right == NULL) {
2662
0
        Py_DECREF(pyus_left);
2663
0
        return NULL;
2664
0
    }
2665
2666
0
    divmod = checked_divmod(pyus_left, pyus_right);
2667
0
    Py_DECREF(pyus_left);
2668
0
    Py_DECREF(pyus_right);
2669
0
    if (divmod == NULL)
2670
0
        return NULL;
2671
2672
0
    delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
2673
0
    if (delta == NULL) {
2674
0
        Py_DECREF(divmod);
2675
0
        return NULL;
2676
0
    }
2677
0
    result = _PyTuple_FromPair(PyTuple_GET_ITEM(divmod, 0), delta);
2678
0
    Py_DECREF(delta);
2679
0
    Py_DECREF(divmod);
2680
0
    return result;
2681
0
}
2682
2683
/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2684
 * timedelta constructor.  sofar is the # of microseconds accounted for
2685
 * so far, and there are factor microseconds per current unit, the number
2686
 * of which is given by num.  num * factor is added to sofar in a
2687
 * numerically careful way, and that's the result.  Any fractional
2688
 * microseconds left over (this can happen if num is a float type) are
2689
 * added into *leftover.
2690
 * Note that there are many ways this can give an error (NULL) return.
2691
 */
2692
static PyObject *
2693
accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2694
      double *leftover)
2695
0
{
2696
0
    PyObject *prod;
2697
0
    PyObject *sum;
2698
2699
0
    assert(num != NULL);
2700
2701
0
    if (PyLong_Check(num)) {
2702
0
        prod = PyNumber_Multiply(num, factor);
2703
0
        if (prod == NULL)
2704
0
            return NULL;
2705
0
        sum = PyNumber_Add(sofar, prod);
2706
0
        Py_DECREF(prod);
2707
0
        return sum;
2708
0
    }
2709
2710
0
    if (PyFloat_Check(num)) {
2711
0
        double dnum;
2712
0
        double fracpart;
2713
0
        double intpart;
2714
0
        PyObject *x;
2715
0
        PyObject *y;
2716
2717
        /* The Plan:  decompose num into an integer part and a
2718
         * fractional part, num = intpart + fracpart.
2719
         * Then num * factor ==
2720
         *      intpart * factor + fracpart * factor
2721
         * and the LHS can be computed exactly in long arithmetic.
2722
         * The RHS is again broken into an int part and frac part.
2723
         * and the frac part is added into *leftover.
2724
         */
2725
0
        dnum = PyFloat_AsDouble(num);
2726
0
        if (dnum == -1.0 && PyErr_Occurred())
2727
0
            return NULL;
2728
0
        fracpart = modf(dnum, &intpart);
2729
0
        x = PyLong_FromDouble(intpart);
2730
0
        if (x == NULL)
2731
0
            return NULL;
2732
2733
0
        prod = PyNumber_Multiply(x, factor);
2734
0
        Py_DECREF(x);
2735
0
        if (prod == NULL)
2736
0
            return NULL;
2737
2738
0
        sum = PyNumber_Add(sofar, prod);
2739
0
        Py_DECREF(prod);
2740
0
        if (sum == NULL)
2741
0
            return NULL;
2742
2743
0
        if (fracpart == 0.0)
2744
0
            return sum;
2745
        /* So far we've lost no information.  Dealing with the
2746
         * fractional part requires float arithmetic, and may
2747
         * lose a little info.
2748
         */
2749
0
        assert(PyLong_CheckExact(factor));
2750
0
        dnum = PyLong_AsDouble(factor);
2751
2752
0
        dnum *= fracpart;
2753
0
        fracpart = modf(dnum, &intpart);
2754
0
        x = PyLong_FromDouble(intpart);
2755
0
        if (x == NULL) {
2756
0
            Py_DECREF(sum);
2757
0
            return NULL;
2758
0
        }
2759
2760
0
        y = PyNumber_Add(sum, x);
2761
0
        Py_DECREF(sum);
2762
0
        Py_DECREF(x);
2763
0
        *leftover += fracpart;
2764
0
        return y;
2765
0
    }
2766
2767
0
    PyErr_Format(PyExc_TypeError,
2768
0
                 "unsupported type for timedelta %s component: %s",
2769
0
                 tag, Py_TYPE(num)->tp_name);
2770
0
    return NULL;
2771
0
}
2772
2773
/*[clinic input]
2774
@vectorcall
2775
@classmethod
2776
datetime.timedelta.__new__ as delta_new
2777
2778
    days: object(c_default="NULL") = 0
2779
    seconds: object(c_default="NULL") = 0
2780
    microseconds: object(c_default="NULL") = 0
2781
    milliseconds: object(c_default="NULL") = 0
2782
    minutes: object(c_default="NULL") = 0
2783
    hours: object(c_default="NULL") = 0
2784
    weeks: object(c_default="NULL") = 0
2785
2786
Difference between two datetime values.
2787
2788
All arguments are optional and default to 0.
2789
Arguments may be integers or floats, and may be positive or negative.
2790
[clinic start generated code]*/
2791
2792
static PyObject *
2793
delta_new_impl(PyTypeObject *type, PyObject *days, PyObject *seconds,
2794
               PyObject *microseconds, PyObject *milliseconds,
2795
               PyObject *minutes, PyObject *hours, PyObject *weeks)
2796
/*[clinic end generated code: output=61d7e02a92a97700 input=8aebc4cdef360d1f]*/
2797
0
{
2798
    /* vectorcall passes borrowed references; hold strong references before
2799
       any conversion can execute arbitrary Python code. */
2800
0
    Py_XINCREF(days);
2801
0
    Py_XINCREF(seconds);
2802
0
    Py_XINCREF(microseconds);
2803
0
    Py_XINCREF(milliseconds);
2804
0
    Py_XINCREF(minutes);
2805
0
    Py_XINCREF(hours);
2806
0
    Py_XINCREF(weeks);
2807
2808
0
    PyObject *self = NULL;
2809
2810
0
    PyObject *current_mod;
2811
0
    datetime_state *st = GET_CURRENT_STATE(current_mod);
2812
0
    if (st == NULL) {
2813
0
        goto Done;
2814
0
    }
2815
2816
0
    PyObject *x = NULL;         /* running sum of microseconds */
2817
0
    PyObject *y = NULL;         /* temp sum of microseconds */
2818
0
    double leftover_us = 0.0;
2819
2820
0
    x = PyLong_FromLong(0);
2821
0
    if (x == NULL)
2822
0
        goto Done;
2823
2824
0
#define CLEANUP         \
2825
0
    Py_DECREF(x);       \
2826
0
    x = y;              \
2827
0
    if (x == NULL)      \
2828
0
        goto Done
2829
2830
0
    if (microseconds) {
2831
0
        y = accum("microseconds", x, microseconds, _PyLong_GetOne(), &leftover_us);
2832
0
        CLEANUP;
2833
0
    }
2834
0
    if (milliseconds) {
2835
0
        y = accum("milliseconds", x, milliseconds, CONST_US_PER_MS(st), &leftover_us);
2836
0
        CLEANUP;
2837
0
    }
2838
0
    if (seconds) {
2839
0
        y = accum("seconds", x, seconds, CONST_US_PER_SECOND(st), &leftover_us);
2840
0
        CLEANUP;
2841
0
    }
2842
0
    if (minutes) {
2843
0
        y = accum("minutes", x, minutes, CONST_US_PER_MINUTE(st), &leftover_us);
2844
0
        CLEANUP;
2845
0
    }
2846
0
    if (hours) {
2847
0
        y = accum("hours", x, hours, CONST_US_PER_HOUR(st), &leftover_us);
2848
0
        CLEANUP;
2849
0
    }
2850
0
    if (days) {
2851
0
        y = accum("days", x, days, CONST_US_PER_DAY(st), &leftover_us);
2852
0
        CLEANUP;
2853
0
    }
2854
0
    if (weeks) {
2855
0
        y = accum("weeks", x, weeks, CONST_US_PER_WEEK(st), &leftover_us);
2856
0
        CLEANUP;
2857
0
    }
2858
0
    if (leftover_us) {
2859
        /* Round to nearest whole # of us, and add into x. */
2860
0
        double whole_us = round(leftover_us);
2861
0
        int x_is_odd;
2862
0
        PyObject *temp;
2863
2864
0
        if (fabs(whole_us - leftover_us) == 0.5) {
2865
            /* We're exactly halfway between two integers.  In order
2866
             * to do round-half-to-even, we must determine whether x
2867
             * is odd. Note that x is odd when it's last bit is 1. The
2868
             * code below uses bitwise and operation to check the last
2869
             * bit. */
2870
0
            temp = PyNumber_And(x, _PyLong_GetOne());  /* temp <- x & 1 */
2871
0
            if (temp == NULL) {
2872
0
                Py_DECREF(x);
2873
0
                goto Done;
2874
0
            }
2875
0
            x_is_odd = PyObject_IsTrue(temp);
2876
0
            Py_DECREF(temp);
2877
0
            if (x_is_odd == -1) {
2878
0
                Py_DECREF(x);
2879
0
                goto Done;
2880
0
            }
2881
0
            whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2882
0
        }
2883
2884
0
        temp = PyLong_FromLong((long)whole_us);
2885
2886
0
        if (temp == NULL) {
2887
0
            Py_DECREF(x);
2888
0
            goto Done;
2889
0
        }
2890
0
        y = PyNumber_Add(x, temp);
2891
0
        Py_DECREF(temp);
2892
0
        CLEANUP;
2893
0
    }
2894
2895
0
    self = microseconds_to_delta_ex(x, type);
2896
0
    Py_DECREF(x);
2897
2898
0
Done:
2899
0
    Py_XDECREF(days);
2900
0
    Py_XDECREF(seconds);
2901
0
    Py_XDECREF(microseconds);
2902
0
    Py_XDECREF(milliseconds);
2903
0
    Py_XDECREF(minutes);
2904
0
    Py_XDECREF(hours);
2905
0
    Py_XDECREF(weeks);
2906
0
    if (st != NULL) {
2907
0
        RELEASE_CURRENT_STATE(st, current_mod);
2908
0
    }
2909
0
    return self;
2910
2911
0
#undef CLEANUP
2912
0
}
2913
2914
static int
2915
delta_bool(PyObject *self)
2916
0
{
2917
0
    return (GET_TD_DAYS(self) != 0
2918
0
        || GET_TD_SECONDS(self) != 0
2919
0
        || GET_TD_MICROSECONDS(self) != 0);
2920
0
}
2921
2922
static PyObject *
2923
delta_repr(PyObject *self)
2924
0
{
2925
0
    PyObject *args = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
2926
2927
0
    if (args == NULL) {
2928
0
        return NULL;
2929
0
    }
2930
2931
0
    const char *sep = "";
2932
2933
0
    if (GET_TD_DAYS(self) != 0) {
2934
0
        Py_SETREF(args, PyUnicode_FromFormat("days=%d", GET_TD_DAYS(self)));
2935
0
        if (args == NULL) {
2936
0
            return NULL;
2937
0
        }
2938
0
        sep = ", ";
2939
0
    }
2940
2941
0
    if (GET_TD_SECONDS(self) != 0) {
2942
0
        Py_SETREF(args, PyUnicode_FromFormat("%U%sseconds=%d", args, sep,
2943
0
                                             GET_TD_SECONDS(self)));
2944
0
        if (args == NULL) {
2945
0
            return NULL;
2946
0
        }
2947
0
        sep = ", ";
2948
0
    }
2949
2950
0
    if (GET_TD_MICROSECONDS(self) != 0) {
2951
0
        Py_SETREF(args, PyUnicode_FromFormat("%U%smicroseconds=%d", args, sep,
2952
0
                                             GET_TD_MICROSECONDS(self)));
2953
0
        if (args == NULL) {
2954
0
            return NULL;
2955
0
        }
2956
0
    }
2957
2958
0
    if (PyUnicode_GET_LENGTH(args) == 0) {
2959
0
        Py_SETREF(args, PyUnicode_FromString("0"));
2960
0
        if (args == NULL) {
2961
0
            return NULL;
2962
0
        }
2963
0
    }
2964
2965
0
    PyObject *repr = PyUnicode_FromFormat("%s(%S)", Py_TYPE(self)->tp_name,
2966
0
                                          args);
2967
0
    Py_DECREF(args);
2968
0
    return repr;
2969
0
}
2970
2971
static PyObject *
2972
delta_str(PyObject *self)
2973
0
{
2974
0
    int us = GET_TD_MICROSECONDS(self);
2975
0
    int seconds = GET_TD_SECONDS(self);
2976
0
    int minutes = divmod(seconds, 60, &seconds);
2977
0
    int hours = divmod(minutes, 60, &minutes);
2978
0
    int days = GET_TD_DAYS(self);
2979
2980
0
    if (days) {
2981
0
        if (us)
2982
0
            return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2983
0
                                        days, (days == 1 || days == -1) ? "" : "s",
2984
0
                                        hours, minutes, seconds, us);
2985
0
        else
2986
0
            return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2987
0
                                        days, (days == 1 || days == -1) ? "" : "s",
2988
0
                                        hours, minutes, seconds);
2989
0
    } else {
2990
0
        if (us)
2991
0
            return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2992
0
                                        hours, minutes, seconds, us);
2993
0
        else
2994
0
            return PyUnicode_FromFormat("%d:%02d:%02d",
2995
0
                                        hours, minutes, seconds);
2996
0
    }
2997
2998
0
}
2999
3000
/* Pickle support, a simple use of __reduce__. */
3001
3002
/* __getstate__ isn't exposed */
3003
static PyObject *
3004
delta_getstate(PyDateTime_Delta *self)
3005
0
{
3006
0
    return Py_BuildValue("iii", GET_TD_DAYS(self),
3007
0
                                GET_TD_SECONDS(self),
3008
0
                                GET_TD_MICROSECONDS(self));
3009
0
}
3010
3011
static PyObject *
3012
delta_total_seconds(PyObject *op, PyObject *Py_UNUSED(dummy))
3013
0
{
3014
0
    PyObject *total_seconds;
3015
0
    PyObject *total_microseconds;
3016
3017
0
    total_microseconds = delta_to_microseconds(PyDelta_CAST(op));
3018
0
    if (total_microseconds == NULL)
3019
0
        return NULL;
3020
3021
0
    PyObject *current_mod;
3022
0
    datetime_state *st = GET_CURRENT_STATE(current_mod);
3023
0
    if (st == NULL) {
3024
0
        Py_DECREF(total_microseconds);
3025
0
        return NULL;
3026
0
    }
3027
3028
0
    total_seconds = PyNumber_TrueDivide(total_microseconds, CONST_US_PER_SECOND(st));
3029
3030
0
    RELEASE_CURRENT_STATE(st, current_mod);
3031
0
    Py_DECREF(total_microseconds);
3032
0
    return total_seconds;
3033
0
}
3034
3035
static PyObject *
3036
delta_reduce(PyObject *op, PyObject *Py_UNUSED(dummy))
3037
0
{
3038
0
    PyDateTime_Delta *self = PyDelta_CAST(op);
3039
0
    return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
3040
0
}
3041
3042
#define OFFSET(field)  offsetof(PyDateTime_Delta, field)
3043
3044
static PyMemberDef delta_members[] = {
3045
3046
    {"days",         Py_T_INT, OFFSET(days),         Py_READONLY,
3047
     PyDoc_STR("Number of days.")},
3048
3049
    {"seconds",      Py_T_INT, OFFSET(seconds),      Py_READONLY,
3050
     PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
3051
3052
    {"microseconds", Py_T_INT, OFFSET(microseconds), Py_READONLY,
3053
     PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
3054
    {NULL}
3055
};
3056
3057
static PyMethodDef delta_methods[] = {
3058
    {"total_seconds", delta_total_seconds, METH_NOARGS,
3059
     PyDoc_STR("Total seconds in the duration.")},
3060
3061
    {"__reduce__", delta_reduce, METH_NOARGS,
3062
     PyDoc_STR("__reduce__() -> (cls, state)")},
3063
3064
    {NULL,      NULL},
3065
};
3066
3067
static PyNumberMethods delta_as_number = {
3068
    delta_add,                                  /* nb_add */
3069
    delta_subtract,                             /* nb_subtract */
3070
    delta_multiply,                             /* nb_multiply */
3071
    delta_remainder,                            /* nb_remainder */
3072
    delta_divmod,                               /* nb_divmod */
3073
    0,                                          /* nb_power */
3074
    delta_negative,                             /* nb_negative */
3075
    delta_positive,                             /* nb_positive */
3076
    delta_abs,                                  /* nb_absolute */
3077
    delta_bool,                                 /* nb_bool */
3078
    0,                                          /*nb_invert*/
3079
    0,                                          /*nb_lshift*/
3080
    0,                                          /*nb_rshift*/
3081
    0,                                          /*nb_and*/
3082
    0,                                          /*nb_xor*/
3083
    0,                                          /*nb_or*/
3084
    0,                                          /*nb_int*/
3085
    0,                                          /*nb_reserved*/
3086
    0,                                          /*nb_float*/
3087
    0,                                          /*nb_inplace_add*/
3088
    0,                                          /*nb_inplace_subtract*/
3089
    0,                                          /*nb_inplace_multiply*/
3090
    0,                                          /*nb_inplace_remainder*/
3091
    0,                                          /*nb_inplace_power*/
3092
    0,                                          /*nb_inplace_lshift*/
3093
    0,                                          /*nb_inplace_rshift*/
3094
    0,                                          /*nb_inplace_and*/
3095
    0,                                          /*nb_inplace_xor*/
3096
    0,                                          /*nb_inplace_or*/
3097
    delta_divide,                               /* nb_floor_divide */
3098
    delta_truedivide,                           /* nb_true_divide */
3099
    0,                                          /* nb_inplace_floor_divide */
3100
    0,                                          /* nb_inplace_true_divide */
3101
};
3102
3103
static PyTypeObject PyDateTime_DeltaType = {
3104
    PyVarObject_HEAD_INIT(NULL, 0)
3105
    "datetime.timedelta",                               /* tp_name */
3106
    sizeof(PyDateTime_Delta),                           /* tp_basicsize */
3107
    0,                                                  /* tp_itemsize */
3108
    0,                                                  /* tp_dealloc */
3109
    0,                                                  /* tp_vectorcall_offset */
3110
    0,                                                  /* tp_getattr */
3111
    0,                                                  /* tp_setattr */
3112
    0,                                                  /* tp_as_async */
3113
    delta_repr,                                         /* tp_repr */
3114
    &delta_as_number,                                   /* tp_as_number */
3115
    0,                                                  /* tp_as_sequence */
3116
    0,                                                  /* tp_as_mapping */
3117
    delta_hash,                                         /* tp_hash */
3118
    0,                                                  /* tp_call */
3119
    delta_str,                                          /* tp_str */
3120
    PyObject_GenericGetAttr,                            /* tp_getattro */
3121
    0,                                                  /* tp_setattro */
3122
    0,                                                  /* tp_as_buffer */
3123
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,           /* tp_flags */
3124
    delta_new__doc__,                                   /* tp_doc */
3125
    0,                                                  /* tp_traverse */
3126
    0,                                                  /* tp_clear */
3127
    delta_richcompare,                                  /* tp_richcompare */
3128
    0,                                                  /* tp_weaklistoffset */
3129
    0,                                                  /* tp_iter */
3130
    0,                                                  /* tp_iternext */
3131
    delta_methods,                                      /* tp_methods */
3132
    delta_members,                                      /* tp_members */
3133
    0,                                                  /* tp_getset */
3134
    0,                                                  /* tp_base */
3135
    0,                                                  /* tp_dict */
3136
    0,                                                  /* tp_descr_get */
3137
    0,                                                  /* tp_descr_set */
3138
    0,                                                  /* tp_dictoffset */
3139
    0,                                                  /* tp_init */
3140
    0,                                                  /* tp_alloc */
3141
    delta_new,                                          /* tp_new */
3142
    0,                                                  /* tp_free */
3143
    .tp_vectorcall = delta_vectorcall,
3144
};
3145
3146
// XXX Can we make this const?
3147
static PyDateTime_Delta zero_delta = {
3148
    PyObject_HEAD_INIT(&PyDateTime_DeltaType)
3149
    /* Letting this be set lazily is a benign race. */
3150
    .hashcode = -1,
3151
};
3152
3153
static PyDateTime_Delta *
3154
look_up_delta(int days, int seconds, int microseconds, PyTypeObject *type)
3155
176
{
3156
176
    if (days == 0 && seconds == 0 && microseconds == 0
3157
0
            && type == Py_TYPE(&zero_delta))
3158
0
    {
3159
0
        return &zero_delta;
3160
0
    }
3161
176
    return NULL;
3162
176
}
3163
3164
3165
/*
3166
 * PyDateTime_Date implementation.
3167
 */
3168
3169
/* Accessor properties. */
3170
3171
static PyObject *
3172
date_year(PyObject *op, void *Py_UNUSED(closure))
3173
0
{
3174
0
    PyDateTime_Date *self = PyDate_CAST(op);
3175
0
    return PyLong_FromLong(GET_YEAR(self));
3176
0
}
3177
3178
static PyObject *
3179
date_month(PyObject *op, void *Py_UNUSED(closure))
3180
0
{
3181
0
    PyDateTime_Date *self = PyDate_CAST(op);
3182
0
    return PyLong_FromLong(GET_MONTH(self));
3183
0
}
3184
3185
static PyObject *
3186
date_day(PyObject *op, void *Py_UNUSED(closure))
3187
0
{
3188
0
    PyDateTime_Date *self = PyDate_CAST(op);
3189
0
    return PyLong_FromLong(GET_DAY(self));
3190
0
}
3191
3192
static PyGetSetDef date_getset[] = {
3193
    {"year", date_year},
3194
    {"month", date_month},
3195
    {"day", date_day},
3196
    {NULL}
3197
};
3198
3199
/* Constructors. */
3200
3201
static PyObject *
3202
date_from_pickle(PyTypeObject *type, PyObject *state)
3203
0
{
3204
0
    PyDateTime_Date *me;
3205
3206
0
    me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
3207
0
    if (me != NULL) {
3208
0
        const char *pdata = PyBytes_AS_STRING(state);
3209
0
        memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
3210
0
        me->hashcode = -1;
3211
0
    }
3212
0
    return (PyObject *)me;
3213
0
}
3214
3215
static PyObject *
3216
date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3217
0
{
3218
    /* Check for invocation from pickle with __getstate__ state */
3219
0
    if (PyTuple_GET_SIZE(args) == 1) {
3220
0
        PyObject *state = PyTuple_GET_ITEM(args, 0);
3221
0
        if (PyBytes_Check(state)) {
3222
0
            if (PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
3223
0
                MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
3224
0
            {
3225
0
                return date_from_pickle(type, state);
3226
0
            }
3227
0
        }
3228
0
        else if (PyUnicode_Check(state)) {
3229
0
            if (PyUnicode_GET_LENGTH(state) == _PyDateTime_DATE_DATASIZE &&
3230
0
                MONTH_IS_SANE(PyUnicode_READ_CHAR(state, 2)))
3231
0
            {
3232
0
                state = PyUnicode_AsLatin1String(state);
3233
0
                if (state == NULL) {
3234
0
                    if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
3235
                        /* More informative error message. */
3236
0
                        PyErr_SetString(PyExc_ValueError,
3237
0
                            "Failed to encode latin1 string when unpickling "
3238
0
                            "a date object. "
3239
0
                            "pickle.load(data, encoding='latin1') is assumed.");
3240
0
                    }
3241
0
                    return NULL;
3242
0
                }
3243
0
                PyObject *self = date_from_pickle(type, state);
3244
0
                Py_DECREF(state);
3245
0
                return self;
3246
0
            }
3247
0
        }
3248
0
    }
3249
3250
0
    return datetime_date(type, args, kw);
3251
0
}
3252
3253
/*[clinic input]
3254
@classmethod
3255
datetime.date.__new__
3256
3257
    year: int
3258
    month: int
3259
    day: int
3260
3261
Concrete date type.
3262
[clinic start generated code]*/
3263
3264
static PyObject *
3265
datetime_date_impl(PyTypeObject *type, int year, int month, int day)
3266
/*[clinic end generated code: output=6654caa3dea7d518 input=fd1bac0658690455]*/
3267
0
{
3268
0
    return new_date_ex(year, month, day, type);
3269
0
}
3270
3271
static PyObject *
3272
date_fromtimestamp(PyTypeObject *cls, PyObject *obj)
3273
0
{
3274
0
    struct tm tm;
3275
0
    time_t t;
3276
0
    int year;
3277
3278
0
    if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
3279
0
        return NULL;
3280
3281
0
    if (_PyTime_localtime(t, &tm) != 0)
3282
0
        return NULL;
3283
0
    if (year_from_tm(&tm, &year) < 0) {
3284
0
        return NULL;
3285
0
    }
3286
3287
0
    return new_date_subclass_ex(year,
3288
0
                                tm.tm_mon + 1,
3289
0
                                tm.tm_mday,
3290
0
                                cls);
3291
0
}
3292
3293
/* Return new date from current time.
3294
 * We say this is equivalent to fromtimestamp(time.time()), and the
3295
 * only way to be sure of that is to *call* time.time().  That's not
3296
 * generally the same as calling C's time.
3297
 */
3298
/*[clinic input]
3299
@classmethod
3300
datetime.date.today
3301
3302
Current date or datetime.
3303
3304
Equivalent to fromtimestamp(time.time()).
3305
[clinic start generated code]*/
3306
3307
static PyObject *
3308
datetime_date_today_impl(PyTypeObject *type)
3309
/*[clinic end generated code: output=d5474697df6b251c input=21688afa289c0a06]*/
3310
0
{
3311
    /* Use C implementation to boost performance for date type */
3312
0
    if (type == &PyDateTime_DateType) {
3313
0
        struct tm tm;
3314
0
        time_t t;
3315
0
        time(&t);
3316
3317
0
        if (_PyTime_localtime(t, &tm) != 0) {
3318
0
            return NULL;
3319
0
        }
3320
3321
0
        return new_date_ex(tm.tm_year + 1900,
3322
0
                           tm.tm_mon + 1,
3323
0
                           tm.tm_mday,
3324
0
                           type);
3325
0
    }
3326
3327
0
    PyTime_t ts;
3328
0
    if (PyTime_Time(&ts) < 0) {
3329
0
        return NULL;
3330
0
    }
3331
0
    PyObject *time = PyFloat_FromDouble(PyTime_AsSecondsDouble(ts));
3332
0
    if (time == NULL) {
3333
0
        return NULL;
3334
0
    }
3335
3336
    /* Note well: since today() is a class method, it may not call
3337
     * date.fromtimestamp, e.g., it may call datetime.fromtimestamp.
3338
     */
3339
0
    PyObject *result = PyObject_CallMethodOneArg((PyObject*)type, &_Py_ID(fromtimestamp), time);
3340
0
    Py_DECREF(time);
3341
0
    return result;
3342
0
}
3343
3344
/*[clinic input]
3345
@classmethod
3346
datetime.date.fromtimestamp
3347
3348
    timestamp: object
3349
    /
3350
3351
Create a date from a POSIX timestamp.
3352
3353
The timestamp is a number, e.g. created via time.time(), that is
3354
interpreted as local time.
3355
[clinic start generated code]*/
3356
3357
static PyObject *
3358
datetime_date_fromtimestamp_impl(PyTypeObject *type, PyObject *timestamp)
3359
/*[clinic end generated code: output=59def4e32c028fb6 input=15720eef43b169a1]*/
3360
0
{
3361
0
    return date_fromtimestamp(type, timestamp);
3362
0
}
3363
3364
/* bpo-36025: This is a wrapper for API compatibility with the public C API,
3365
 * which expects a function that takes an *args tuple, whereas the argument
3366
 * clinic generates code that takes METH_O.
3367
 */
3368
static PyObject *
3369
datetime_date_fromtimestamp_capi(PyObject *cls, PyObject *args)
3370
0
{
3371
0
    PyObject *timestamp;
3372
0
    PyObject *result = NULL;
3373
3374
0
    if (PyArg_UnpackTuple(args, "fromtimestamp", 1, 1, &timestamp)) {
3375
0
        result = date_fromtimestamp((PyTypeObject *)cls, timestamp);
3376
0
    }
3377
3378
0
    return result;
3379
0
}
3380
3381
/*[clinic input]
3382
@classmethod
3383
datetime.date.fromordinal
3384
3385
    ordinal: int
3386
    /
3387
3388
Construct a date from a proleptic Gregorian ordinal.
3389
3390
January 1 of year 1 is day 1.  Only the year, month and day are
3391
non-zero in the result.
3392
[clinic start generated code]*/
3393
3394
static PyObject *
3395
datetime_date_fromordinal_impl(PyTypeObject *type, int ordinal)
3396
/*[clinic end generated code: output=ea5cc69d86614a6b input=a3a4eedf582f145e]*/
3397
0
{
3398
0
    int year;
3399
0
    int month;
3400
0
    int day;
3401
3402
0
    if (ordinal < 1) {
3403
0
        PyErr_SetString(PyExc_ValueError, "ordinal must be >= 1");
3404
0
        return NULL;
3405
0
    }
3406
0
    if (ordinal <= MAXORDINAL) {
3407
0
        ord_to_ymd(ordinal, &year, &month, &day);
3408
0
    }
3409
0
    else {
3410
        /* Out of range, but compute the year for the error message.
3411
         * The calendar repeats every 400 years (DI400Y days). */
3412
0
        int cycles = (ordinal - 1) / DI400Y;
3413
0
        ord_to_ymd(ordinal - cycles * DI400Y, &year, &month, &day);
3414
0
        year += 400 * cycles;
3415
0
    }
3416
0
    return new_date_subclass_ex(year, month, day, type);
3417
0
}
3418
3419
/*[clinic input]
3420
@classmethod
3421
datetime.date.fromisoformat
3422
3423
    string: unicode
3424
    /
3425
3426
Construct a date from a string in ISO 8601 format.
3427
[clinic start generated code]*/
3428
3429
static PyObject *
3430
datetime_date_fromisoformat_impl(PyTypeObject *type, PyObject *string)
3431
/*[clinic end generated code: output=8b9f9324904fca02 input=73c64216c10bcc8e]*/
3432
0
{
3433
0
    Py_ssize_t len;
3434
3435
0
    const char *dt_ptr = PyUnicode_AsUTF8AndSize(string, &len);
3436
0
    if (dt_ptr == NULL) {
3437
0
        goto invalid_string_error;
3438
0
    }
3439
3440
0
    int year = 0, month = 0, day = 0;
3441
3442
0
    int rv;
3443
0
    if (len == 7 || len == 8 || len == 10) {
3444
0
        rv = parse_isoformat_date(dt_ptr, len, &year, &month, &day);
3445
0
    }
3446
0
    else {
3447
0
        rv = -1;
3448
0
    }
3449
3450
0
    if (rv < 0) {
3451
0
        goto invalid_string_error;
3452
0
    }
3453
3454
0
    return new_date_subclass_ex(year, month, day, type);
3455
3456
0
invalid_string_error:
3457
0
    PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", string);
3458
0
    return NULL;
3459
0
}
3460
3461
3462
/*[clinic input]
3463
@classmethod
3464
datetime.date.fromisocalendar
3465
3466
    year: int
3467
    week: int
3468
    day: int
3469
3470
Construct a date from the ISO year, week number and weekday.
3471
3472
This is the inverse of the date.isocalendar() function.
3473
[clinic start generated code]*/
3474
3475
static PyObject *
3476
datetime_date_fromisocalendar_impl(PyTypeObject *type, int year, int week,
3477
                                   int day)
3478
/*[clinic end generated code: output=7b26e15115d24df6 input=fbb05b53d6fb51d8]*/
3479
0
{
3480
0
    int month;
3481
0
    int rv = iso_to_ymd(year, week, day, &year, &month, &day);
3482
3483
0
    if (rv == -4) {
3484
0
        PyErr_Format(PyExc_ValueError,
3485
0
                     "year must be in %d..%d, not %d", MINYEAR, MAXYEAR, year);
3486
0
        return NULL;
3487
0
    }
3488
3489
0
    if (rv == -2) {
3490
0
        PyErr_Format(PyExc_ValueError, "Invalid week: %d", week);
3491
0
        return NULL;
3492
0
    }
3493
3494
0
    if (rv == -3) {
3495
0
        PyErr_Format(PyExc_ValueError, "Invalid weekday: %d (range is [1, 7])",
3496
0
                     day);
3497
0
        return NULL;
3498
0
    }
3499
3500
0
    return new_date_subclass_ex(year, month, day, type);
3501
0
}
3502
3503
/*[clinic input]
3504
@permit_long_summary
3505
@classmethod
3506
datetime.date.strptime
3507
3508
    string: unicode
3509
    format: unicode
3510
    /
3511
3512
Parse string according to the given date format (like time.strptime()).
3513
3514
For a list of supported format codes, see the documentation:
3515
    https://docs.python.org/3/library/datetime.html#format-codes
3516
[clinic start generated code]*/
3517
3518
static PyObject *
3519
datetime_date_strptime_impl(PyTypeObject *type, PyObject *string,
3520
                            PyObject *format)
3521
/*[clinic end generated code: output=454d473bee2d5161 input=2db8f0b2b5242deb]*/
3522
0
{
3523
0
    _PyTime_StrptimeFields fields;
3524
0
    if (type == DATE_TYPE(NO_STATE) &&
3525
0
        _PyTime_Strptime(string, format, &fields)) {
3526
0
        return new_date_ex(fields.year, fields.month, fields.day, type);
3527
0
    }
3528
0
    PyObject *result;
3529
3530
0
    PyObject *module = PyImport_Import(&_Py_ID(_strptime));
3531
0
    if (module == NULL) {
3532
0
        return NULL;
3533
0
    }
3534
0
    result = PyObject_CallMethodObjArgs(module,
3535
0
                                        &_Py_ID(_strptime_datetime_date),
3536
0
                                        (PyObject *)type, string, format, NULL);
3537
0
    Py_DECREF(module);
3538
0
    return result;
3539
0
}
3540
3541
3542
/*
3543
 * Date arithmetic.
3544
 */
3545
3546
/* date + timedelta -> date.  If arg negate is true, subtract the timedelta
3547
 * instead.
3548
 */
3549
static PyObject *
3550
add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
3551
0
{
3552
0
    PyObject *result = NULL;
3553
0
    int year = GET_YEAR(date);
3554
0
    int month = GET_MONTH(date);
3555
0
    int deltadays = GET_TD_DAYS(delta);
3556
    /* C-level overflow is impossible because |deltadays| < 1e9. */
3557
0
    int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
3558
3559
0
    if (normalize_date(&year, &month, &day) >= 0)
3560
0
        result = new_date_subclass_ex(year, month, day, Py_TYPE(date));
3561
0
    return result;
3562
0
}
3563
3564
static PyObject *
3565
date_add(PyObject *left, PyObject *right)
3566
0
{
3567
0
    if (PyDateTime_Check(left) || PyDateTime_Check(right))
3568
0
        Py_RETURN_NOTIMPLEMENTED;
3569
3570
0
    if (PyDate_Check(left)) {
3571
        /* date + ??? */
3572
0
        if (PyDelta_Check(right))
3573
            /* date + delta */
3574
0
            return add_date_timedelta((PyDateTime_Date *) left,
3575
0
                                      (PyDateTime_Delta *) right,
3576
0
                                      0);
3577
0
    }
3578
0
    else {
3579
        /* ??? + date
3580
         * 'right' must be one of us, or we wouldn't have been called
3581
         */
3582
0
        if (PyDelta_Check(left))
3583
            /* delta + date */
3584
0
            return add_date_timedelta((PyDateTime_Date *) right,
3585
0
                                      (PyDateTime_Delta *) left,
3586
0
                                      0);
3587
0
    }
3588
0
    Py_RETURN_NOTIMPLEMENTED;
3589
0
}
3590
3591
static PyObject *
3592
date_subtract(PyObject *left, PyObject *right)
3593
0
{
3594
0
    if (PyDateTime_Check(left) || PyDateTime_Check(right))
3595
0
        Py_RETURN_NOTIMPLEMENTED;
3596
3597
0
    if (PyDate_Check(left)) {
3598
0
        if (PyDate_Check(right)) {
3599
            /* date - date */
3600
0
            int left_ord = ymd_to_ord(GET_YEAR(left),
3601
0
                                      GET_MONTH(left),
3602
0
                                      GET_DAY(left));
3603
0
            int right_ord = ymd_to_ord(GET_YEAR(right),
3604
0
                                       GET_MONTH(right),
3605
0
                                       GET_DAY(right));
3606
0
            return new_delta(left_ord - right_ord, 0, 0, 0);
3607
0
        }
3608
0
        if (PyDelta_Check(right)) {
3609
            /* date - delta */
3610
0
            return add_date_timedelta((PyDateTime_Date *) left,
3611
0
                                      (PyDateTime_Delta *) right,
3612
0
                                      1);
3613
0
        }
3614
0
    }
3615
0
    Py_RETURN_NOTIMPLEMENTED;
3616
0
}
3617
3618
3619
/* Various ways to turn a date into a string. */
3620
3621
static PyObject *
3622
date_repr(PyObject *op)
3623
0
{
3624
0
    PyDateTime_Date *self = PyDate_CAST(op);
3625
0
    return PyUnicode_FromFormat("%s(%d, %d, %d)",
3626
0
                                Py_TYPE(self)->tp_name,
3627
0
                                GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
3628
0
}
3629
3630
static PyObject *
3631
date_isoformat(PyObject *op, PyObject *Py_UNUSED(dummy))
3632
0
{
3633
0
    PyDateTime_Date *self = PyDate_CAST(op);
3634
0
    return PyUnicode_FromFormat("%04d-%02d-%02d",
3635
0
                                GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
3636
0
}
3637
3638
/* str() calls the appropriate isoformat() method. */
3639
static PyObject *
3640
date_str(PyObject *self)
3641
0
{
3642
0
    return PyObject_CallMethodNoArgs(self, &_Py_ID(isoformat));
3643
0
}
3644
3645
3646
static PyObject *
3647
date_ctime(PyObject *self, PyObject *Py_UNUSED(dummy))
3648
0
{
3649
0
    return format_ctime(self, 0, 0, 0);
3650
0
}
3651
3652
/*[clinic input]
3653
datetime.date.strftime
3654
3655
    self: self(type="PyObject *")
3656
    format: unicode
3657
3658
Format using strftime().
3659
3660
Example: "%d/%m/%Y, %H:%M:%S".
3661
3662
For a list of supported format codes, see the documentation:
3663
    https://docs.python.org/3/library/datetime.html#format-codes
3664
[clinic start generated code]*/
3665
3666
static PyObject *
3667
datetime_date_strftime_impl(PyObject *self, PyObject *format)
3668
/*[clinic end generated code: output=6529b70095e16778 input=b6fd4a2ded27b557]*/
3669
0
{
3670
    /* This method can be inherited, and needs to call the
3671
     * timetuple() method appropriate to self's class.
3672
     */
3673
0
    PyObject *result;
3674
0
    PyObject *tuple;
3675
3676
0
    tuple = PyObject_CallMethodNoArgs(self, &_Py_ID(timetuple));
3677
0
    if (tuple == NULL)
3678
0
        return NULL;
3679
0
    result = wrap_strftime(self, format, tuple, self);
3680
0
    Py_DECREF(tuple);
3681
0
    return result;
3682
0
}
3683
3684
/*[clinic input]
3685
datetime.date.__format__
3686
3687
    self: self(type="PyObject *")
3688
    format: unicode
3689
    /
3690
3691
Formats self with strftime.
3692
[clinic start generated code]*/
3693
3694
static PyObject *
3695
datetime_date___format___impl(PyObject *self, PyObject *format)
3696
/*[clinic end generated code: output=efa0223d000a93b7 input=e417a7c84e1abaf9]*/
3697
0
{
3698
    /* if the format is zero length, return str(self) */
3699
0
    if (PyUnicode_GetLength(format) == 0)
3700
0
        return PyObject_Str(self);
3701
3702
0
    return PyObject_CallMethodOneArg(self, &_Py_ID(strftime), format);
3703
0
}
3704
3705
/* ISO methods. */
3706
3707
static PyObject *
3708
date_isoweekday(PyObject *self, PyObject *Py_UNUSED(dummy))
3709
0
{
3710
0
    int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
3711
3712
0
    return PyLong_FromLong(dow + 1);
3713
0
}
3714
3715
PyDoc_STRVAR(iso_calendar_date__doc__,
3716
"The result of date.isocalendar() or datetime.isocalendar()\n\n\
3717
This object may be accessed either as a tuple of\n\
3718
  ((year, week, weekday)\n\
3719
or via the object attributes as named in the above tuple.");
3720
3721
typedef struct {
3722
    PyTupleObject tuple;
3723
} PyDateTime_IsoCalendarDate;
3724
3725
static PyObject *
3726
iso_calendar_date_repr(PyObject *self)
3727
0
{
3728
0
    PyObject *year = PyTuple_GetItem(self, 0);
3729
0
    if (year == NULL) {
3730
0
        return NULL;
3731
0
    }
3732
0
    PyObject *week = PyTuple_GetItem(self, 1);
3733
0
    if (week == NULL) {
3734
0
        return NULL;
3735
0
    }
3736
0
    PyObject *weekday = PyTuple_GetItem(self, 2);
3737
0
    if (weekday == NULL) {
3738
0
        return NULL;
3739
0
    }
3740
3741
0
    return PyUnicode_FromFormat("%.200s(year=%S, week=%S, weekday=%S)",
3742
0
                               Py_TYPE(self)->tp_name, year, week, weekday);
3743
0
}
3744
3745
static PyObject *
3746
iso_calendar_date_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
3747
0
{
3748
    // Construct the tuple that this reduces to
3749
0
    PyObject *reduce_tuple = Py_BuildValue(
3750
0
        "O((OOO))", &PyTuple_Type,
3751
0
        PyTuple_GET_ITEM(self, 0),
3752
0
        PyTuple_GET_ITEM(self, 1),
3753
0
        PyTuple_GET_ITEM(self, 2)
3754
0
    );
3755
3756
0
    return reduce_tuple;
3757
0
}
3758
3759
static PyObject *
3760
iso_calendar_date_year(PyObject *self, void *Py_UNUSED(closure))
3761
0
{
3762
0
    PyObject *year = PyTuple_GetItem(self, 0);
3763
0
    if (year == NULL) {
3764
0
        return NULL;
3765
0
    }
3766
0
    return Py_NewRef(year);
3767
0
}
3768
3769
static PyObject *
3770
iso_calendar_date_week(PyObject *self, void *Py_UNUSED(closure))
3771
0
{
3772
0
    PyObject *week = PyTuple_GetItem(self, 1);
3773
0
    if (week == NULL) {
3774
0
        return NULL;
3775
0
    }
3776
0
    return Py_NewRef(week);
3777
0
}
3778
3779
static PyObject *
3780
iso_calendar_date_weekday(PyObject *self, void *Py_UNUSED(closure))
3781
0
{
3782
0
    PyObject *weekday = PyTuple_GetItem(self, 2);
3783
0
    if (weekday == NULL) {
3784
0
        return NULL;
3785
0
    }
3786
0
    return Py_NewRef(weekday);
3787
0
}
3788
3789
static PyGetSetDef iso_calendar_date_getset[] = {
3790
    {"year", iso_calendar_date_year},
3791
    {"week", iso_calendar_date_week},
3792
    {"weekday", iso_calendar_date_weekday},
3793
    {NULL}
3794
};
3795
3796
static PyMethodDef iso_calendar_date_methods[] = {
3797
    {"__reduce__", iso_calendar_date_reduce, METH_NOARGS,
3798
     PyDoc_STR("__reduce__() -> (cls, state)")},
3799
    {NULL, NULL},
3800
};
3801
3802
static int
3803
iso_calendar_date_traverse(PyObject *self, visitproc visit, void *arg)
3804
0
{
3805
0
    Py_VISIT(Py_TYPE(self));
3806
0
    return PyTuple_Type.tp_traverse(self, visit, arg);
3807
0
}
3808
3809
static void
3810
iso_calendar_date_dealloc(PyObject *self)
3811
0
{
3812
0
    PyTypeObject *tp = Py_TYPE(self);
3813
0
    PyTuple_Type.tp_dealloc(self);  // delegate GC-untrack as well
3814
0
    Py_DECREF(tp);
3815
0
}
3816
3817
static PyType_Slot isocal_slots[] = {
3818
    {Py_tp_repr, iso_calendar_date_repr},
3819
    {Py_tp_doc, (void *)iso_calendar_date__doc__},
3820
    {Py_tp_methods, iso_calendar_date_methods},
3821
    {Py_tp_getset, iso_calendar_date_getset},
3822
    {Py_tp_new, iso_calendar_date_new},
3823
    {Py_tp_dealloc, iso_calendar_date_dealloc},
3824
    {Py_tp_traverse, iso_calendar_date_traverse},
3825
    {0, NULL},
3826
};
3827
3828
static PyType_Spec isocal_spec = {
3829
    .name = "datetime.IsoCalendarDate",
3830
    .basicsize = sizeof(PyDateTime_IsoCalendarDate),
3831
    .flags = (Py_TPFLAGS_DEFAULT |
3832
              Py_TPFLAGS_HAVE_GC |
3833
              Py_TPFLAGS_IMMUTABLETYPE),
3834
    .slots = isocal_slots,
3835
};
3836
3837
/*[clinic input]
3838
@classmethod
3839
datetime.IsoCalendarDate.__new__ as iso_calendar_date_new
3840
    year: int
3841
    week: int
3842
    weekday: int
3843
[clinic start generated code]*/
3844
3845
static PyObject *
3846
iso_calendar_date_new_impl(PyTypeObject *type, int year, int week,
3847
                           int weekday)
3848
/*[clinic end generated code: output=383d33d8dc7183a2 input=4f2c663c9d19c4ee]*/
3849
3850
0
{
3851
0
    PyDateTime_IsoCalendarDate *self;
3852
0
    self = (PyDateTime_IsoCalendarDate *) type->tp_alloc(type, 3);
3853
0
    if (self == NULL) {
3854
0
        return NULL;
3855
0
    }
3856
3857
0
    PyObject *year_object = PyLong_FromLong(year);
3858
0
    if (year_object == NULL) {
3859
0
        Py_DECREF(self);
3860
0
        return NULL;
3861
0
    }
3862
0
    PyTuple_SET_ITEM(self, 0, year_object);
3863
3864
0
    PyObject *week_object = PyLong_FromLong(week);
3865
0
    if (week_object == NULL) {
3866
0
        Py_DECREF(self);
3867
0
        return NULL;
3868
0
    }
3869
0
    PyTuple_SET_ITEM(self, 1, week_object);
3870
3871
0
    PyObject *weekday_object = PyLong_FromLong(weekday);
3872
0
    if (weekday_object == NULL) {
3873
0
        Py_DECREF(self);
3874
0
        return NULL;
3875
0
    }
3876
0
    PyTuple_SET_ITEM(self, 2, weekday_object);
3877
3878
0
    return (PyObject *)self;
3879
0
}
3880
3881
static PyObject *
3882
date_isocalendar(PyObject *self, PyObject *Py_UNUSED(dummy))
3883
0
{
3884
0
    int  year         = GET_YEAR(self);
3885
0
    int  week1_monday = iso_week1_monday(year);
3886
0
    int today         = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
3887
0
    int  week;
3888
0
    int  day;
3889
3890
0
    week = divmod(today - week1_monday, 7, &day);
3891
0
    if (week < 0) {
3892
0
        --year;
3893
0
        week1_monday = iso_week1_monday(year);
3894
0
        week = divmod(today - week1_monday, 7, &day);
3895
0
    }
3896
0
    else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
3897
0
        ++year;
3898
0
        week = 0;
3899
0
    }
3900
3901
0
    PyObject *current_mod;
3902
0
    datetime_state *st = GET_CURRENT_STATE(current_mod);
3903
0
    if (st == NULL) {
3904
0
        return NULL;
3905
0
    }
3906
3907
0
    PyObject *v = iso_calendar_date_new_impl(ISOCALENDAR_DATE_TYPE(st),
3908
0
                                             year, week + 1, day + 1);
3909
0
    RELEASE_CURRENT_STATE(st, current_mod);
3910
0
    if (v == NULL) {
3911
0
        return NULL;
3912
0
    }
3913
0
    return v;
3914
0
}
3915
3916
/* Miscellaneous methods. */
3917
3918
static PyObject *
3919
date_richcompare(PyObject *self, PyObject *other, int op)
3920
0
{
3921
    /* Since DateTime is a subclass of Date, if the other object is
3922
     * a DateTime, it would compute an equality testing or an ordering
3923
     * based on the date part alone, and we don't want that.
3924
     * So return NotImplemented here in that case.
3925
     * If a subclass wants to change this, it's up to the subclass to do so.
3926
     * The behavior is the same as if Date and DateTime were independent
3927
     * classes.
3928
     */
3929
0
    if (PyDate_Check(other) && !PyDateTime_Check(other)) {
3930
0
        int diff = memcmp(((PyDateTime_Date *)self)->data,
3931
0
                          ((PyDateTime_Date *)other)->data,
3932
0
                          _PyDateTime_DATE_DATASIZE);
3933
0
        return diff_to_bool(diff, op);
3934
0
    }
3935
0
    else
3936
0
        Py_RETURN_NOTIMPLEMENTED;
3937
0
}
3938
3939
static PyObject *
3940
date_timetuple(PyObject *self, PyObject *Py_UNUSED(dummy))
3941
0
{
3942
0
    return build_struct_time(GET_YEAR(self),
3943
0
                             GET_MONTH(self),
3944
0
                             GET_DAY(self),
3945
0
                             0, 0, 0, -1);
3946
0
}
3947
3948
/*[clinic input]
3949
datetime.date.replace
3950
3951
    year: int(c_default="GET_YEAR(self)") = unchanged
3952
    month: int(c_default="GET_MONTH(self)") = unchanged
3953
    day: int(c_default="GET_DAY(self)") = unchanged
3954
3955
Return date with new specified fields.
3956
[clinic start generated code]*/
3957
3958
static PyObject *
3959
datetime_date_replace_impl(PyDateTime_Date *self, int year, int month,
3960
                           int day)
3961
/*[clinic end generated code: output=2a9430d1e6318aeb input=0d1f02685b3e90f6]*/
3962
0
{
3963
0
    return new_date_subclass_ex(year, month, day, Py_TYPE(self));
3964
0
}
3965
3966
static Py_hash_t
3967
generic_hash(unsigned char *data, int len)
3968
0
{
3969
0
    return Py_HashBuffer(data, len);
3970
0
}
3971
3972
3973
static PyObject *date_getstate(PyDateTime_Date *self);
3974
3975
static Py_hash_t
3976
date_hash(PyObject *op)
3977
0
{
3978
0
    PyDateTime_Date *self = PyDate_CAST(op);
3979
0
    Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->hashcode);
3980
0
    if (hash == -1) {
3981
0
        hash = generic_hash(
3982
0
            (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
3983
0
        FT_ATOMIC_STORE_SSIZE_RELAXED(self->hashcode, hash);
3984
0
    }
3985
3986
0
    return hash;
3987
0
}
3988
3989
static PyObject *
3990
date_toordinal(PyObject *self, PyObject *Py_UNUSED(dummy))
3991
0
{
3992
0
    return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
3993
0
                                      GET_DAY(self)));
3994
0
}
3995
3996
static PyObject *
3997
date_weekday(PyObject *self, PyObject *Py_UNUSED(dummy))
3998
0
{
3999
0
    int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
4000
0
    return PyLong_FromLong(dow);
4001
0
}
4002
4003
/* Pickle support, a simple use of __reduce__. */
4004
4005
/* __getstate__ isn't exposed */
4006
static PyObject *
4007
date_getstate(PyDateTime_Date *self)
4008
0
{
4009
0
    PyObject* field;
4010
0
    field = PyBytes_FromStringAndSize((char*)self->data,
4011
0
                                       _PyDateTime_DATE_DATASIZE);
4012
0
    return Py_BuildValue("(N)", field);
4013
0
}
4014
4015
static PyObject *
4016
date_reduce(PyObject *op, PyObject *Py_UNUSED(dummy))
4017
0
{
4018
0
    PyDateTime_Date *self = PyDate_CAST(op);
4019
0
    return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
4020
0
}
4021
4022
static PyMethodDef date_methods[] = {
4023
4024
    /* Class methods: */
4025
    DATETIME_DATE_FROMTIMESTAMP_METHODDEF
4026
    DATETIME_DATE_FROMORDINAL_METHODDEF
4027
    DATETIME_DATE_FROMISOFORMAT_METHODDEF
4028
    DATETIME_DATE_FROMISOCALENDAR_METHODDEF
4029
    DATETIME_DATE_STRPTIME_METHODDEF
4030
    DATETIME_DATE_TODAY_METHODDEF
4031
4032
    /* Instance methods: */
4033
4034
    {"ctime", date_ctime, METH_NOARGS,
4035
     PyDoc_STR("Return ctime() style string.")},
4036
4037
    DATETIME_DATE_STRFTIME_METHODDEF
4038
    DATETIME_DATE___FORMAT___METHODDEF
4039
4040
    {"timetuple", date_timetuple, METH_NOARGS,
4041
     PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4042
4043
    {"isocalendar", date_isocalendar,  METH_NOARGS,
4044
     PyDoc_STR("Return a named tuple containing ISO year, week number, and "
4045
               "weekday.")},
4046
4047
    {"isoformat", date_isoformat, METH_NOARGS,
4048
     PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
4049
4050
    {"isoweekday", date_isoweekday, METH_NOARGS,
4051
     PyDoc_STR("Return the day of the week represented by the date.\n"
4052
               "Monday == 1 ... Sunday == 7")},
4053
4054
    {"toordinal", date_toordinal, METH_NOARGS,
4055
     PyDoc_STR("Return proleptic Gregorian ordinal.  January 1 of year "
4056
               "1 is day 1.")},
4057
4058
    {"weekday", date_weekday, METH_NOARGS,
4059
     PyDoc_STR("Return the day of the week represented by the date.\n"
4060
               "Monday == 0 ... Sunday == 6")},
4061
4062
    DATETIME_DATE_REPLACE_METHODDEF
4063
4064
    {"__replace__", _PyCFunction_CAST(datetime_date_replace), METH_FASTCALL | METH_KEYWORDS,
4065
     PyDoc_STR("__replace__($self, /, **changes)\n--\n\nThe same as replace().")},
4066
4067
    {"__reduce__", date_reduce, METH_NOARGS,
4068
     PyDoc_STR("__reduce__() -> (cls, state)")},
4069
4070
    {NULL,      NULL}
4071
};
4072
4073
static PyNumberMethods date_as_number = {
4074
    date_add,                                           /* nb_add */
4075
    date_subtract,                                      /* nb_subtract */
4076
    0,                                                  /* nb_multiply */
4077
    0,                                                  /* nb_remainder */
4078
    0,                                                  /* nb_divmod */
4079
    0,                                                  /* nb_power */
4080
    0,                                                  /* nb_negative */
4081
    0,                                                  /* nb_positive */
4082
    0,                                                  /* nb_absolute */
4083
    0,                                                  /* nb_bool */
4084
};
4085
4086
static PyTypeObject PyDateTime_DateType = {
4087
    PyVarObject_HEAD_INIT(NULL, 0)
4088
    "datetime.date",                                    /* tp_name */
4089
    sizeof(PyDateTime_Date),                            /* tp_basicsize */
4090
    0,                                                  /* tp_itemsize */
4091
    0,                                                  /* tp_dealloc */
4092
    0,                                                  /* tp_vectorcall_offset */
4093
    0,                                                  /* tp_getattr */
4094
    0,                                                  /* tp_setattr */
4095
    0,                                                  /* tp_as_async */
4096
    date_repr,                                          /* tp_repr */
4097
    &date_as_number,                                    /* tp_as_number */
4098
    0,                                                  /* tp_as_sequence */
4099
    0,                                                  /* tp_as_mapping */
4100
    date_hash,                                          /* tp_hash */
4101
    0,                                                  /* tp_call */
4102
    date_str,                                           /* tp_str */
4103
    PyObject_GenericGetAttr,                            /* tp_getattro */
4104
    0,                                                  /* tp_setattro */
4105
    0,                                                  /* tp_as_buffer */
4106
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,           /* tp_flags */
4107
    datetime_date__doc__,                               /* tp_doc */
4108
    0,                                                  /* tp_traverse */
4109
    0,                                                  /* tp_clear */
4110
    date_richcompare,                                   /* tp_richcompare */
4111
    0,                                                  /* tp_weaklistoffset */
4112
    0,                                                  /* tp_iter */
4113
    0,                                                  /* tp_iternext */
4114
    date_methods,                                       /* tp_methods */
4115
    0,                                                  /* tp_members */
4116
    date_getset,                                        /* tp_getset */
4117
    0,                                                  /* tp_base */
4118
    0,                                                  /* tp_dict */
4119
    0,                                                  /* tp_descr_get */
4120
    0,                                                  /* tp_descr_set */
4121
    0,                                                  /* tp_dictoffset */
4122
    0,                                                  /* tp_init */
4123
    0,                                                  /* tp_alloc */
4124
    date_new,                                           /* tp_new */
4125
    0,                                                  /* tp_free */
4126
};
4127
4128
/*
4129
 * PyDateTime_TZInfo implementation.
4130
 */
4131
4132
/* This is a pure abstract base class, so doesn't do anything beyond
4133
 * raising NotImplemented exceptions.  Real tzinfo classes need
4134
 * to derive from this.  This is mostly for clarity, and for efficiency in
4135
 * datetime and time constructors (their tzinfo arguments need to
4136
 * be subclasses of this tzinfo class, which is easy and quick to check).
4137
 *
4138
 * Note:  For reasons having to do with pickling of subclasses, we have
4139
 * to allow tzinfo objects to be instantiated.  This wasn't an issue
4140
 * in the Python implementation (__init__() could raise NotImplementedError
4141
 * there without ill effect), but doing so in the C implementation hit a
4142
 * brick wall.
4143
 */
4144
4145
static PyObject *
4146
tzinfo_nogo(const char* methodname)
4147
0
{
4148
0
    PyErr_Format(PyExc_NotImplementedError,
4149
0
                 "a tzinfo subclass must implement %s()",
4150
0
                 methodname);
4151
0
    return NULL;
4152
0
}
4153
4154
/* Methods.  A subclass must implement these. */
4155
4156
static PyObject *
4157
tzinfo_tzname(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(dt))
4158
0
{
4159
0
    return tzinfo_nogo("tzname");
4160
0
}
4161
4162
static PyObject *
4163
tzinfo_utcoffset(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(dt))
4164
0
{
4165
0
    return tzinfo_nogo("utcoffset");
4166
0
}
4167
4168
static PyObject *
4169
tzinfo_dst(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(dt))
4170
0
{
4171
0
    return tzinfo_nogo("dst");
4172
0
}
4173
4174
4175
static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
4176
                                        PyDateTime_Delta *delta,
4177
                                        int factor);
4178
static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
4179
static PyObject *datetime_dst(PyObject *self, PyObject *);
4180
4181
static PyObject *
4182
tzinfo_fromutc(PyObject *self, PyObject *dt)
4183
0
{
4184
0
    PyObject *result = NULL;
4185
0
    PyObject *off = NULL, *dst = NULL;
4186
0
    PyDateTime_Delta *delta = NULL;
4187
4188
0
    if (!PyDateTime_Check(dt)) {
4189
0
        PyErr_SetString(PyExc_TypeError,
4190
0
                        "fromutc: argument must be a datetime");
4191
0
        return NULL;
4192
0
    }
4193
0
    if (GET_DT_TZINFO(dt) != self) {
4194
0
        PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
4195
0
                        "is not self");
4196
0
        return NULL;
4197
0
    }
4198
4199
0
    off = datetime_utcoffset(dt, NULL);
4200
0
    if (off == NULL)
4201
0
        return NULL;
4202
0
    if (off == Py_None) {
4203
0
        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
4204
0
                        "utcoffset() result required");
4205
0
        goto Fail;
4206
0
    }
4207
4208
0
    dst = datetime_dst(dt, NULL);
4209
0
    if (dst == NULL)
4210
0
        goto Fail;
4211
0
    if (dst == Py_None) {
4212
0
        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
4213
0
                        "dst() result required");
4214
0
        goto Fail;
4215
0
    }
4216
4217
0
    delta = (PyDateTime_Delta *)delta_subtract(off, dst);
4218
0
    if (delta == NULL)
4219
0
        goto Fail;
4220
0
    result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
4221
0
    if (result == NULL)
4222
0
        goto Fail;
4223
4224
0
    Py_DECREF(dst);
4225
0
    dst = call_dst(GET_DT_TZINFO(dt), result);
4226
0
    if (dst == NULL)
4227
0
        goto Fail;
4228
0
    if (dst == Py_None)
4229
0
        goto Inconsistent;
4230
0
    if (delta_bool(dst) != 0) {
4231
0
        Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
4232
0
                                                 (PyDateTime_Delta *)dst, 1));
4233
0
        if (result == NULL)
4234
0
            goto Fail;
4235
0
    }
4236
0
    Py_DECREF(delta);
4237
0
    Py_DECREF(dst);
4238
0
    Py_DECREF(off);
4239
0
    return result;
4240
4241
0
Inconsistent:
4242
0
    PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave "
4243
0
                    "inconsistent results; cannot convert");
4244
4245
    /* fall through to failure */
4246
0
Fail:
4247
0
    Py_XDECREF(off);
4248
0
    Py_XDECREF(dst);
4249
0
    Py_XDECREF(delta);
4250
0
    Py_XDECREF(result);
4251
0
    return NULL;
4252
0
}
4253
4254
/*
4255
 * Pickle support.  This is solely so that tzinfo subclasses can use
4256
 * pickling -- tzinfo itself is supposed to be uninstantiable.
4257
 */
4258
4259
static PyObject *
4260
tzinfo_reduce(PyObject *self, PyObject *Py_UNUSED(dummy))
4261
0
{
4262
0
    PyObject *args, *state;
4263
0
    PyObject *getinitargs;
4264
4265
0
    if (PyObject_GetOptionalAttr(self, &_Py_ID(__getinitargs__), &getinitargs) < 0) {
4266
0
        return NULL;
4267
0
    }
4268
0
    if (getinitargs != NULL) {
4269
0
        args = PyObject_CallNoArgs(getinitargs);
4270
0
        Py_DECREF(getinitargs);
4271
0
    }
4272
0
    else {
4273
0
        args = PyTuple_New(0);
4274
0
    }
4275
0
    if (args == NULL) {
4276
0
        return NULL;
4277
0
    }
4278
4279
0
    state = _PyObject_GetState(self);
4280
0
    if (state == NULL) {
4281
0
        Py_DECREF(args);
4282
0
        return NULL;
4283
0
    }
4284
4285
0
    return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
4286
0
}
4287
4288
static PyMethodDef tzinfo_methods[] = {
4289
4290
    {"tzname", tzinfo_tzname, METH_O,
4291
     PyDoc_STR("datetime -> string name of time zone.")},
4292
4293
    {"utcoffset", tzinfo_utcoffset, METH_O,
4294
     PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
4295
           "values indicating West of UTC")},
4296
4297
    {"dst", tzinfo_dst, METH_O,
4298
     PyDoc_STR("datetime -> DST offset as timedelta positive east of UTC.")},
4299
4300
    {"fromutc", tzinfo_fromutc, METH_O,
4301
     PyDoc_STR("datetime in UTC -> datetime in local time.")},
4302
4303
    {"__reduce__",  tzinfo_reduce, METH_NOARGS,
4304
     PyDoc_STR("-> (cls, state)")},
4305
4306
    {NULL, NULL}
4307
};
4308
4309
static const char tzinfo_doc[] =
4310
PyDoc_STR("Abstract base class for time zone info objects.\n\n"
4311
          "Subclasses must override the tzname(), utcoffset() and dst() methods.");
4312
4313
static PyTypeObject PyDateTime_TZInfoType = {
4314
    PyVarObject_HEAD_INIT(NULL, 0)
4315
    "datetime.tzinfo",                          /* tp_name */
4316
    sizeof(PyDateTime_TZInfo),                  /* tp_basicsize */
4317
    0,                                          /* tp_itemsize */
4318
    0,                                          /* tp_dealloc */
4319
    0,                                          /* tp_vectorcall_offset */
4320
    0,                                          /* tp_getattr */
4321
    0,                                          /* tp_setattr */
4322
    0,                                          /* tp_as_async */
4323
    0,                                          /* tp_repr */
4324
    0,                                          /* tp_as_number */
4325
    0,                                          /* tp_as_sequence */
4326
    0,                                          /* tp_as_mapping */
4327
    0,                                          /* tp_hash */
4328
    0,                                          /* tp_call */
4329
    0,                                          /* tp_str */
4330
    PyObject_GenericGetAttr,                    /* tp_getattro */
4331
    0,                                          /* tp_setattro */
4332
    0,                                          /* tp_as_buffer */
4333
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
4334
    tzinfo_doc,                                 /* tp_doc */
4335
    0,                                          /* tp_traverse */
4336
    0,                                          /* tp_clear */
4337
    0,                                          /* tp_richcompare */
4338
    0,                                          /* tp_weaklistoffset */
4339
    0,                                          /* tp_iter */
4340
    0,                                          /* tp_iternext */
4341
    tzinfo_methods,                             /* tp_methods */
4342
    0,                                          /* tp_members */
4343
    0,                                          /* tp_getset */
4344
    0,                                          /* tp_base */
4345
    0,                                          /* tp_dict */
4346
    0,                                          /* tp_descr_get */
4347
    0,                                          /* tp_descr_set */
4348
    0,                                          /* tp_dictoffset */
4349
    0,                                          /* tp_init */
4350
    0,                                          /* tp_alloc */
4351
    PyType_GenericNew,                          /* tp_new */
4352
    0,                                          /* tp_free */
4353
};
4354
4355
/*[clinic input]
4356
@vectorcall
4357
@classmethod
4358
datetime.timezone.__new__ as timezone_new
4359
4360
    offset: object(subclass_of="DELTA_TYPE(NO_STATE)")
4361
    name: unicode = NULL
4362
4363
Fixed offset from UTC implementation of tzinfo.
4364
[clinic start generated code]*/
4365
4366
static PyObject *
4367
timezone_new_impl(PyTypeObject *type, PyObject *offset, PyObject *name)
4368
/*[clinic end generated code: output=41a2dda500424187 input=8901a8befbc52561]*/
4369
0
{
4370
0
    return new_timezone(offset, name);
4371
0
}
4372
4373
static void
4374
timezone_dealloc(PyObject *op)
4375
0
{
4376
0
    PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
4377
0
    Py_CLEAR(self->offset);
4378
0
    Py_CLEAR(self->name);
4379
0
    Py_TYPE(self)->tp_free(self);
4380
0
}
4381
4382
static PyObject *
4383
timezone_richcompare(PyObject *self, PyObject *other, int op)
4384
0
{
4385
0
    if (op != Py_EQ && op != Py_NE)
4386
0
        Py_RETURN_NOTIMPLEMENTED;
4387
0
    if (!PyTimezone_Check(other)) {
4388
0
        Py_RETURN_NOTIMPLEMENTED;
4389
0
    }
4390
0
    PyDateTime_TimeZone *lhs = PyTimeZone_CAST(self);
4391
0
    PyDateTime_TimeZone *rhs = PyTimeZone_CAST(other);
4392
0
    return delta_richcompare(lhs->offset, rhs->offset, op);
4393
0
}
4394
4395
static Py_hash_t
4396
timezone_hash(PyObject *op)
4397
0
{
4398
0
    PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
4399
0
    return delta_hash(self->offset);
4400
0
}
4401
4402
/* Check argument type passed to tzname, utcoffset, or dst methods.
4403
   Returns 0 for good argument.  Returns -1 and sets exception info
4404
   otherwise.
4405
 */
4406
static int
4407
_timezone_check_argument(PyObject *dt, const char *meth)
4408
0
{
4409
0
    if (dt == Py_None || PyDateTime_Check(dt))
4410
0
        return 0;
4411
0
    PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
4412
0
                 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
4413
0
    return -1;
4414
0
}
4415
4416
static PyObject *
4417
timezone_repr(PyObject *op)
4418
0
{
4419
    /* Note that although timezone is not subclassable, it is convenient
4420
       to use Py_TYPE(self)->tp_name here. */
4421
0
    PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
4422
0
    const char *type_name = Py_TYPE(self)->tp_name;
4423
4424
0
    if (op == CONST_UTC(NO_STATE)) {
4425
0
        return PyUnicode_FromFormat("%s.utc", type_name);
4426
0
    }
4427
4428
0
    if (self->name == NULL)
4429
0
        return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
4430
4431
0
    return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
4432
0
                                self->name);
4433
0
}
4434
4435
static PyObject *
4436
timezone_str(PyObject *op)
4437
0
{
4438
0
    PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
4439
0
    int hours, minutes, seconds, microseconds;
4440
0
    PyObject *offset;
4441
0
    char sign;
4442
4443
0
    if (self->name != NULL) {
4444
0
        return Py_NewRef(self->name);
4445
0
    }
4446
0
    if ((PyObject *)self == CONST_UTC(NO_STATE) ||
4447
0
           (GET_TD_DAYS(self->offset) == 0 &&
4448
0
            GET_TD_SECONDS(self->offset) == 0 &&
4449
0
            GET_TD_MICROSECONDS(self->offset) == 0))
4450
0
    {
4451
0
        return PyUnicode_FromString("UTC");
4452
0
    }
4453
    /* Offset is normalized, so it is negative if days < 0 */
4454
0
    if (GET_TD_DAYS(self->offset) < 0) {
4455
0
        sign = '-';
4456
0
        offset = delta_negative(self->offset);
4457
0
        if (offset == NULL)
4458
0
            return NULL;
4459
0
    }
4460
0
    else {
4461
0
        sign = '+';
4462
0
        offset = Py_NewRef(self->offset);
4463
0
    }
4464
    /* Offset is not negative here. */
4465
0
    microseconds = GET_TD_MICROSECONDS(offset);
4466
0
    seconds = GET_TD_SECONDS(offset);
4467
0
    Py_DECREF(offset);
4468
0
    minutes = divmod(seconds, 60, &seconds);
4469
0
    hours = divmod(minutes, 60, &minutes);
4470
0
    if (microseconds != 0) {
4471
0
        return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d.%06d",
4472
0
                                    sign, hours, minutes,
4473
0
                                    seconds, microseconds);
4474
0
    }
4475
0
    if (seconds != 0) {
4476
0
        return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d",
4477
0
                                    sign, hours, minutes, seconds);
4478
0
    }
4479
0
    return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
4480
0
}
4481
4482
static PyObject *
4483
timezone_tzname(PyObject *op, PyObject *dt)
4484
0
{
4485
0
    if (_timezone_check_argument(dt, "tzname") == -1)
4486
0
        return NULL;
4487
4488
0
    return timezone_str(op);
4489
0
}
4490
4491
static PyObject *
4492
timezone_utcoffset(PyObject *op, PyObject *dt)
4493
0
{
4494
0
    if (_timezone_check_argument(dt, "utcoffset") == -1)
4495
0
        return NULL;
4496
4497
0
    PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
4498
0
    return Py_NewRef(self->offset);
4499
0
}
4500
4501
static PyObject *
4502
timezone_dst(PyObject *op, PyObject *dt)
4503
0
{
4504
0
    if (_timezone_check_argument(dt, "dst") == -1)
4505
0
        return NULL;
4506
4507
0
    Py_RETURN_NONE;
4508
0
}
4509
4510
static PyObject *
4511
timezone_fromutc(PyObject *op, PyObject *arg)
4512
0
{
4513
0
    if (!PyDateTime_Check(arg)) {
4514
0
        PyErr_SetString(PyExc_TypeError,
4515
0
                        "fromutc: argument must be a datetime");
4516
0
        return NULL;
4517
0
    }
4518
4519
0
    PyDateTime_DateTime *dt = (PyDateTime_DateTime *)arg;  // fast safe cast
4520
0
    if (!HASTZINFO(dt) || dt->tzinfo != op) {
4521
0
        PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo is not self");
4522
0
        return NULL;
4523
0
    }
4524
4525
0
    PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
4526
0
    return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
4527
0
}
4528
4529
static PyObject *
4530
timezone_getinitargs(PyObject *op, PyObject *Py_UNUSED(dummy))
4531
0
{
4532
0
    PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
4533
0
    if (self->name == NULL)
4534
0
        return PyTuple_Pack(1, self->offset);
4535
0
    return _PyTuple_FromPair(self->offset, self->name);
4536
0
}
4537
4538
static PyMethodDef timezone_methods[] = {
4539
    {"tzname", timezone_tzname, METH_O,
4540
     PyDoc_STR("If name is specified when timezone is created, returns the name."
4541
               "  Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
4542
4543
    {"utcoffset", timezone_utcoffset, METH_O,
4544
     PyDoc_STR("Return fixed offset.")},
4545
4546
    {"dst", timezone_dst, METH_O,
4547
     PyDoc_STR("Return None.")},
4548
4549
    {"fromutc", timezone_fromutc, METH_O,
4550
     PyDoc_STR("datetime in UTC -> datetime in local time.")},
4551
4552
    {"__getinitargs__", timezone_getinitargs, METH_NOARGS,
4553
     PyDoc_STR("pickle support")},
4554
4555
    {NULL, NULL}
4556
};
4557
4558
static PyObject *
4559
timezone_name(PyObject *op, void *Py_UNUSED(closure))
4560
0
{
4561
0
    PyDateTime_TimeZone *self = PyTimeZone_CAST(op);
4562
0
    if (self->name == NULL) {
4563
0
        Py_RETURN_NONE;
4564
0
    }
4565
0
    return Py_NewRef(self->name);
4566
0
}
4567
4568
static PyGetSetDef timezone_getset[] = {
4569
    {"name", timezone_name, NULL,
4570
     PyDoc_STR("Name given when the timezone was created.")},
4571
    {NULL}
4572
};
4573
4574
static PyTypeObject PyDateTime_TimeZoneType = {
4575
    PyVarObject_HEAD_INIT(NULL, 0)
4576
    "datetime.timezone",              /* tp_name */
4577
    sizeof(PyDateTime_TimeZone),      /* tp_basicsize */
4578
    0,                                /* tp_itemsize */
4579
    timezone_dealloc,                 /* tp_dealloc */
4580
    0,                                /* tp_vectorcall_offset */
4581
    0,                                /* tp_getattr */
4582
    0,                                /* tp_setattr */
4583
    0,                                /* tp_as_async */
4584
    timezone_repr,                    /* tp_repr */
4585
    0,                                /* tp_as_number */
4586
    0,                                /* tp_as_sequence */
4587
    0,                                /* tp_as_mapping */
4588
    timezone_hash,                    /* tp_hash */
4589
    0,                                /* tp_call */
4590
    timezone_str,                     /* tp_str */
4591
    0,                                /* tp_getattro */
4592
    0,                                /* tp_setattro */
4593
    0,                                /* tp_as_buffer */
4594
    Py_TPFLAGS_DEFAULT,               /* tp_flags */
4595
    timezone_new__doc__,              /* tp_doc */
4596
    0,                                /* tp_traverse */
4597
    0,                                /* tp_clear */
4598
    timezone_richcompare,             /* tp_richcompare */
4599
    0,                                /* tp_weaklistoffset */
4600
    0,                                /* tp_iter */
4601
    0,                                /* tp_iternext */
4602
    timezone_methods,                 /* tp_methods */
4603
    0,                                /* tp_members */
4604
    timezone_getset,                  /* tp_getset */
4605
    &PyDateTime_TZInfoType,           /* tp_base */
4606
    0,                                /* tp_dict */
4607
    0,                                /* tp_descr_get */
4608
    0,                                /* tp_descr_set */
4609
    0,                                /* tp_dictoffset */
4610
    0,                                /* tp_init */
4611
    0,                                /* tp_alloc */
4612
    timezone_new,                     /* tp_new */
4613
    .tp_vectorcall = timezone_vectorcall,
4614
};
4615
4616
// XXX Can we make this const?
4617
static PyDateTime_TimeZone utc_timezone = {
4618
    PyObject_HEAD_INIT(&PyDateTime_TimeZoneType)
4619
    .offset = (PyObject *)&zero_delta,
4620
    .name = NULL,
4621
};
4622
4623
static PyDateTime_TimeZone *
4624
look_up_timezone(PyObject *offset, PyObject *name)
4625
44
{
4626
44
    if (offset == utc_timezone.offset && name == NULL) {
4627
0
        return (PyDateTime_TimeZone *)CONST_UTC(NO_STATE);
4628
0
    }
4629
44
    return NULL;
4630
44
}
4631
4632
4633
/*
4634
 * PyDateTime_Time implementation.
4635
 */
4636
4637
/* Accessor properties.
4638
 */
4639
4640
static PyObject *
4641
time_hour(PyObject *op, void *Py_UNUSED(closure))
4642
0
{
4643
0
    PyDateTime_Time *self = PyTime_CAST(op);
4644
0
    return PyLong_FromLong(TIME_GET_HOUR(self));
4645
0
}
4646
4647
static PyObject *
4648
time_minute(PyObject *op, void *Py_UNUSED(closure))
4649
0
{
4650
0
    PyDateTime_Time *self = PyTime_CAST(op);
4651
0
    return PyLong_FromLong(TIME_GET_MINUTE(self));
4652
0
}
4653
4654
/* The name time_second conflicted with some platform header file. */
4655
static PyObject *
4656
py_time_second(PyObject *op, void *Py_UNUSED(closure))
4657
0
{
4658
0
    PyDateTime_Time *self = PyTime_CAST(op);
4659
0
    return PyLong_FromLong(TIME_GET_SECOND(self));
4660
0
}
4661
4662
static PyObject *
4663
time_microsecond(PyObject *op, void *Py_UNUSED(closure))
4664
0
{
4665
0
    PyDateTime_Time *self = PyTime_CAST(op);
4666
0
    return PyLong_FromLong(TIME_GET_MICROSECOND(self));
4667
0
}
4668
4669
static PyObject *
4670
time_tzinfo(PyObject *op, void *Py_UNUSED(closure))
4671
0
{
4672
0
    PyDateTime_Time *self = PyTime_CAST(op);
4673
0
    PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4674
0
    return Py_NewRef(result);
4675
0
}
4676
4677
static PyObject *
4678
time_fold(PyObject *op, void *Py_UNUSED(closure))
4679
0
{
4680
0
    PyDateTime_Time *self = PyTime_CAST(op);
4681
0
    return PyLong_FromLong(TIME_GET_FOLD(self));
4682
0
}
4683
4684
static PyGetSetDef time_getset[] = {
4685
    {"hour", time_hour},
4686
    {"minute", time_minute},
4687
    {"second", py_time_second},
4688
    {"microsecond", time_microsecond},
4689
    {"tzinfo", time_tzinfo},
4690
    {"fold", time_fold},
4691
    {NULL}
4692
};
4693
4694
/*
4695
 * Constructors.
4696
 */
4697
4698
static PyObject *
4699
time_from_pickle(PyTypeObject *type, PyObject *state, PyObject *tzinfo)
4700
0
{
4701
0
    PyDateTime_Time *me;
4702
0
    char aware = (char)(tzinfo != Py_None);
4703
4704
0
    if (aware && check_tzinfo_subclass(tzinfo) < 0) {
4705
0
        PyErr_SetString(PyExc_TypeError, "bad tzinfo state arg");
4706
0
        return NULL;
4707
0
    }
4708
4709
0
    me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
4710
0
    if (me != NULL) {
4711
0
        const char *pdata = PyBytes_AS_STRING(state);
4712
4713
0
        memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
4714
0
        me->hashcode = -1;
4715
0
        me->hastzinfo = aware;
4716
0
        if (aware) {
4717
0
            me->tzinfo = Py_NewRef(tzinfo);
4718
0
        }
4719
0
        if (pdata[0] & (1 << 7)) {
4720
0
            me->data[0] -= 128;
4721
0
            me->fold = 1;
4722
0
        }
4723
0
        else {
4724
0
            me->fold = 0;
4725
0
        }
4726
0
    }
4727
0
    return (PyObject *)me;
4728
0
}
4729
4730
static PyObject *
4731
time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
4732
0
{
4733
    /* Check for invocation from pickle with __getstate__ state */
4734
0
    if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2) {
4735
0
        PyObject *state = PyTuple_GET_ITEM(args, 0);
4736
0
        PyObject *tzinfo = Py_None;
4737
0
        if (PyTuple_GET_SIZE(args) == 2) {
4738
0
            tzinfo = PyTuple_GET_ITEM(args, 1);
4739
0
        }
4740
0
        if (PyBytes_Check(state)) {
4741
0
            if (PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
4742
0
                (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
4743
0
            {
4744
0
                return time_from_pickle(type, state, tzinfo);
4745
0
            }
4746
0
        }
4747
0
        else if (PyUnicode_Check(state)) {
4748
0
            if (PyUnicode_GET_LENGTH(state) == _PyDateTime_TIME_DATASIZE &&
4749
0
                (0x7F & PyUnicode_READ_CHAR(state, 0)) < 24)
4750
0
            {
4751
0
                state = PyUnicode_AsLatin1String(state);
4752
0
                if (state == NULL) {
4753
0
                    if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4754
                        /* More informative error message. */
4755
0
                        PyErr_SetString(PyExc_ValueError,
4756
0
                            "Failed to encode latin1 string when unpickling "
4757
0
                            "a time object. "
4758
0
                            "pickle.load(data, encoding='latin1') is assumed.");
4759
0
                    }
4760
0
                    return NULL;
4761
0
                }
4762
0
                PyObject *self = time_from_pickle(type, state, tzinfo);
4763
0
                Py_DECREF(state);
4764
0
                return self;
4765
0
            }
4766
0
        }
4767
0
    }
4768
4769
0
    return datetime_time(type, args, kw);
4770
0
}
4771
4772
/*[clinic input]
4773
@classmethod
4774
datetime.time.__new__
4775
4776
    hour: int = 0
4777
    minute: int = 0
4778
    second: int = 0
4779
    microsecond: int = 0
4780
    tzinfo: object = None
4781
    *
4782
    fold: int = 0
4783
4784
Time with time zone.
4785
4786
All arguments are optional. tzinfo may be None, or an instance of
4787
a tzinfo subclass. The remaining arguments may be ints.
4788
[clinic start generated code]*/
4789
4790
static PyObject *
4791
datetime_time_impl(PyTypeObject *type, int hour, int minute, int second,
4792
                   int microsecond, PyObject *tzinfo, int fold)
4793
/*[clinic end generated code: output=f06bb4315225e7f6 input=0148df5e8138fe7b]*/
4794
0
{
4795
0
    return new_time_ex2(hour, minute, second, microsecond, tzinfo, fold, type);
4796
0
}
4797
4798
/*[clinic input]
4799
@permit_long_summary
4800
@classmethod
4801
datetime.time.strptime
4802
4803
    string: unicode
4804
    format: unicode
4805
    /
4806
4807
Parse string according to the given time format (like time.strptime()).
4808
4809
For a list of supported format codes, see the documentation:
4810
    https://docs.python.org/3/library/datetime.html#format-codes
4811
[clinic start generated code]*/
4812
4813
static PyObject *
4814
datetime_time_strptime_impl(PyTypeObject *type, PyObject *string,
4815
                            PyObject *format)
4816
/*[clinic end generated code: output=ae05a9bc0241d3bf input=f01d0b9eb5383da5]*/
4817
0
{
4818
0
    _PyTime_StrptimeFields fields;
4819
0
    if (type == TIME_TYPE(NO_STATE) &&
4820
0
        _PyTime_Strptime(string, format, &fields)) {
4821
0
        PyObject *tzinfo = tzinfo_from_isoformat_results(
4822
0
            fields.gmtoff != INT_MIN, fields.gmtoff, 0);
4823
0
        if (tzinfo == NULL) {
4824
0
            return NULL;
4825
0
        }
4826
0
        PyObject *result = new_time_ex(
4827
0
            fields.hour, fields.minute, fields.second, fields.fraction,
4828
0
            tzinfo, type);
4829
0
        Py_DECREF(tzinfo);
4830
0
        return result;
4831
0
    }
4832
0
    PyObject *result;
4833
4834
0
    PyObject *module = PyImport_Import(&_Py_ID(_strptime));
4835
0
    if (module == NULL) {
4836
0
        return NULL;
4837
0
    }
4838
0
    result = PyObject_CallMethodObjArgs(module,
4839
0
                                        &_Py_ID(_strptime_datetime_time),
4840
0
                                        (PyObject *)type, string, format, NULL);
4841
0
    Py_DECREF(module);
4842
0
    return result;
4843
0
}
4844
4845
/*
4846
 * Destructor.
4847
 */
4848
4849
static void
4850
time_dealloc(PyObject *op)
4851
0
{
4852
0
    PyDateTime_Time *self = PyTime_CAST(op);
4853
0
    if (HASTZINFO(self)) {
4854
0
        Py_XDECREF(self->tzinfo);
4855
0
    }
4856
0
    Py_TYPE(self)->tp_free(self);
4857
0
}
4858
4859
/*
4860
 * Indirect access to tzinfo methods.
4861
 */
4862
4863
/* These are all METH_NOARGS, so don't need to check the arglist. */
4864
static PyObject *
4865
0
time_utcoffset(PyObject *op, PyObject *Py_UNUSED(dummy)) {
4866
0
    PyDateTime_Time *self = PyTime_CAST(op);
4867
0
    return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
4868
0
}
4869
4870
static PyObject *
4871
0
time_dst(PyObject *op, PyObject *Py_UNUSED(dummy)) {
4872
0
    PyDateTime_Time *self = PyTime_CAST(op);
4873
0
    return call_dst(GET_TIME_TZINFO(self), Py_None);
4874
0
}
4875
4876
static PyObject *
4877
0
time_tzname(PyObject *op, PyObject *Py_UNUSED(dummy)) {
4878
0
    PyDateTime_Time *self = PyTime_CAST(op);
4879
0
    return call_tzname(GET_TIME_TZINFO(self), Py_None);
4880
0
}
4881
4882
/*
4883
 * Various ways to turn a time into a string.
4884
 */
4885
4886
static PyObject *
4887
time_repr(PyObject *op)
4888
0
{
4889
0
    PyDateTime_Time *self = PyTime_CAST(op);
4890
0
    const char *type_name = Py_TYPE(self)->tp_name;
4891
0
    int h = TIME_GET_HOUR(self);
4892
0
    int m = TIME_GET_MINUTE(self);
4893
0
    int s = TIME_GET_SECOND(self);
4894
0
    int us = TIME_GET_MICROSECOND(self);
4895
0
    int fold = TIME_GET_FOLD(self);
4896
0
    PyObject *result = NULL;
4897
4898
0
    if (us)
4899
0
        result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
4900
0
                                      type_name, h, m, s, us);
4901
0
    else if (s)
4902
0
        result = PyUnicode_FromFormat("%s(%d, %d, %d)",
4903
0
                                      type_name, h, m, s);
4904
0
    else
4905
0
        result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
4906
0
    if (result != NULL && HASTZINFO(self))
4907
0
        result = append_keyword_tzinfo(result, self->tzinfo);
4908
0
    if (result != NULL && fold)
4909
0
        result = append_keyword_fold(result, fold);
4910
0
    return result;
4911
0
}
4912
4913
static PyObject *
4914
time_str(PyObject *op)
4915
0
{
4916
0
    return PyObject_CallMethodNoArgs(op, &_Py_ID(isoformat));
4917
0
}
4918
4919
/*[clinic input]
4920
datetime.time.isoformat
4921
4922
    timespec: str(c_default="NULL") = 'auto'
4923
4924
Return the time formatted according to ISO.
4925
4926
The full format is 'HH:MM:SS.mmmmmm+zz:zz'. By default, the
4927
fractional part is omitted if self.microsecond == 0.
4928
4929
The optional argument timespec specifies the number of additional
4930
terms of the time to include. Valid options are 'auto', 'hours',
4931
'minutes', 'seconds', 'milliseconds' and 'microseconds'.
4932
[clinic start generated code]*/
4933
4934
static PyObject *
4935
datetime_time_isoformat_impl(PyDateTime_Time *self, const char *timespec)
4936
/*[clinic end generated code: output=2bcc7cab65c35545 input=0efae103081060f4]*/
4937
0
{
4938
0
    char buf[100];
4939
4940
0
    PyObject *result;
4941
0
    int us = TIME_GET_MICROSECOND(self);
4942
0
    static const char * const specs[][2] = {
4943
0
        {"hours", "%02d"},
4944
0
        {"minutes", "%02d:%02d"},
4945
0
        {"seconds", "%02d:%02d:%02d"},
4946
0
        {"milliseconds", "%02d:%02d:%02d.%03d"},
4947
0
        {"microseconds", "%02d:%02d:%02d.%06d"},
4948
0
    };
4949
0
    size_t given_spec;
4950
4951
0
    if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4952
0
        if (us == 0) {
4953
            /* seconds */
4954
0
            given_spec = 2;
4955
0
        }
4956
0
        else {
4957
            /* microseconds */
4958
0
            given_spec = 4;
4959
0
        }
4960
0
    }
4961
0
    else {
4962
0
        for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4963
0
            if (strcmp(timespec, specs[given_spec][0]) == 0) {
4964
0
                if (given_spec == 3) {
4965
                    /* milliseconds */
4966
0
                    us = us / 1000;
4967
0
                }
4968
0
                break;
4969
0
            }
4970
0
        }
4971
0
    }
4972
4973
0
    if (given_spec == Py_ARRAY_LENGTH(specs)) {
4974
0
        PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4975
0
        return NULL;
4976
0
    }
4977
0
    else {
4978
0
        result = PyUnicode_FromFormat(specs[given_spec][1],
4979
0
                                      TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
4980
0
                                      TIME_GET_SECOND(self), us);
4981
0
    }
4982
4983
0
    if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
4984
0
        return result;
4985
4986
    /* We need to append the UTC offset. */
4987
0
    if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4988
0
                         Py_None) < 0) {
4989
0
        Py_DECREF(result);
4990
0
        return NULL;
4991
0
    }
4992
0
    PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
4993
0
    return result;
4994
0
}
4995
4996
/*[clinic input]
4997
datetime.time.strftime
4998
4999
    format: unicode
5000
5001
Format using strftime().
5002
5003
The date part of the timestamp passed to underlying strftime should
5004
not be used.
5005
5006
For a list of supported format codes, see the documentation:
5007
    https://docs.python.org/3/library/datetime.html#format-codes
5008
[clinic start generated code]*/
5009
5010
static PyObject *
5011
datetime_time_strftime_impl(PyDateTime_Time *self, PyObject *format)
5012
/*[clinic end generated code: output=10f65af20e2a78c7 input=184e1c0d7d356c5d]*/
5013
0
{
5014
0
    PyObject *result;
5015
0
    PyObject *tuple;
5016
5017
    /* Python's strftime does insane things with the year part of the
5018
     * timetuple.  The year is forced to (the otherwise nonsensical)
5019
     * 1900 to work around that.
5020
     */
5021
0
    tuple = Py_BuildValue("iiiiiiiii",
5022
0
                          1900, 1, 1, /* year, month, day */
5023
0
                  TIME_GET_HOUR(self),
5024
0
                  TIME_GET_MINUTE(self),
5025
0
                  TIME_GET_SECOND(self),
5026
0
                  0, 1, -1); /* weekday, daynum, dst */
5027
0
    if (tuple == NULL)
5028
0
        return NULL;
5029
0
    assert(PyTuple_Size(tuple) == 9);
5030
0
    result = wrap_strftime((PyObject *)self, format, tuple,
5031
0
                           Py_None);
5032
0
    Py_DECREF(tuple);
5033
0
    return result;
5034
0
}
5035
5036
/*[clinic input]
5037
datetime.time.__format__
5038
5039
    self: self(type="PyObject *")
5040
    format: unicode
5041
    /
5042
5043
Formats self with strftime.
5044
[clinic start generated code]*/
5045
5046
static PyObject *
5047
datetime_time___format___impl(PyObject *self, PyObject *format)
5048
/*[clinic end generated code: output=4646451f7a5d2156 input=6a858ae787d20230]*/
5049
0
{
5050
    /* if the format is zero length, return str(self) */
5051
0
    if (PyUnicode_GetLength(format) == 0)
5052
0
        return PyObject_Str(self);
5053
5054
0
    return PyObject_CallMethodOneArg(self, &_Py_ID(strftime), format);
5055
0
}
5056
5057
/*
5058
 * Miscellaneous methods.
5059
 */
5060
5061
static PyObject *
5062
time_richcompare(PyObject *self, PyObject *other, int op)
5063
0
{
5064
0
    PyObject *result = NULL;
5065
0
    PyObject *offset1, *offset2;
5066
0
    int diff;
5067
5068
0
    if (! PyTime_Check(other))
5069
0
        Py_RETURN_NOTIMPLEMENTED;
5070
5071
0
    if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
5072
0
        diff = memcmp(((PyDateTime_Time *)self)->data,
5073
0
                      ((PyDateTime_Time *)other)->data,
5074
0
                      _PyDateTime_TIME_DATASIZE);
5075
0
        return diff_to_bool(diff, op);
5076
0
    }
5077
0
    offset1 = time_utcoffset(self, NULL);
5078
0
    if (offset1 == NULL)
5079
0
        return NULL;
5080
0
    offset2 = time_utcoffset(other, NULL);
5081
0
    if (offset2 == NULL)
5082
0
        goto done;
5083
    /* If they're both naive, or both aware and have the same offsets,
5084
     * we get off cheap.  Note that if they're both naive, offset1 ==
5085
     * offset2 == Py_None at this point.
5086
     */
5087
0
    if ((offset1 == offset2) ||
5088
0
        (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
5089
0
         delta_cmp(offset1, offset2) == 0)) {
5090
0
        diff = memcmp(((PyDateTime_Time *)self)->data,
5091
0
                      ((PyDateTime_Time *)other)->data,
5092
0
                      _PyDateTime_TIME_DATASIZE);
5093
0
        result = diff_to_bool(diff, op);
5094
0
    }
5095
    /* The hard case: both aware with different UTC offsets */
5096
0
    else if (offset1 != Py_None && offset2 != Py_None) {
5097
0
        long long norm_us1, norm_us2;
5098
0
        assert(offset1 != offset2); /* else last "if" handled it */
5099
0
        norm_us1 =
5100
0
            ((TIME_GET_HOUR(self) * 3600 +
5101
0
              TIME_GET_MINUTE(self) * 60 +
5102
0
              TIME_GET_SECOND(self)) * 1000000LL +
5103
0
             TIME_GET_MICROSECOND(self)) -
5104
0
            ((GET_TD_DAYS(offset1) * 86400LL +
5105
0
              GET_TD_SECONDS(offset1)) * 1000000LL +
5106
0
             GET_TD_MICROSECONDS(offset1));
5107
0
        norm_us2 =
5108
0
            ((TIME_GET_HOUR(other) * 3600 +
5109
0
              TIME_GET_MINUTE(other) * 60 +
5110
0
              TIME_GET_SECOND(other)) * 1000000LL +
5111
0
             TIME_GET_MICROSECOND(other)) -
5112
0
            ((GET_TD_DAYS(offset2) * 86400LL +
5113
0
              GET_TD_SECONDS(offset2)) * 1000000LL +
5114
0
             GET_TD_MICROSECONDS(offset2));
5115
0
        if (norm_us1 < norm_us2) {
5116
0
            diff = -1;
5117
0
        }
5118
0
        else if (norm_us1 > norm_us2) {
5119
0
            diff = 1;
5120
0
        }
5121
0
        else {
5122
0
            diff = 0;
5123
0
        }
5124
0
        result = diff_to_bool(diff, op);
5125
0
    }
5126
0
    else if (op == Py_EQ) {
5127
0
        result = Py_NewRef(Py_False);
5128
0
    }
5129
0
    else if (op == Py_NE) {
5130
0
        result = Py_NewRef(Py_True);
5131
0
    }
5132
0
    else {
5133
0
        PyErr_SetString(PyExc_TypeError,
5134
0
                        "can't compare offset-naive and "
5135
0
                        "offset-aware times");
5136
0
    }
5137
0
 done:
5138
0
    Py_DECREF(offset1);
5139
0
    Py_XDECREF(offset2);
5140
0
    return result;
5141
0
}
5142
5143
static Py_hash_t
5144
time_hash(PyObject *op)
5145
0
{
5146
0
    PyDateTime_Time *self = PyTime_CAST(op);
5147
0
    Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->hashcode);
5148
0
    if (hash == -1) {
5149
0
        PyObject *offset, *self0;
5150
0
        if (TIME_GET_FOLD(self)) {
5151
0
            self0 = new_time_ex2(TIME_GET_HOUR(self),
5152
0
                                 TIME_GET_MINUTE(self),
5153
0
                                 TIME_GET_SECOND(self),
5154
0
                                 TIME_GET_MICROSECOND(self),
5155
0
                                 HASTZINFO(self) ? self->tzinfo : Py_None,
5156
0
                                 0, Py_TYPE(self));
5157
0
            if (self0 == NULL)
5158
0
                return -1;
5159
0
        }
5160
0
        else {
5161
0
            self0 = Py_NewRef(self);
5162
0
        }
5163
0
        offset = time_utcoffset(self0, NULL);
5164
0
        Py_DECREF(self0);
5165
5166
0
        if (offset == NULL)
5167
0
            return -1;
5168
5169
        /* Reduce this to a hash of another object. */
5170
0
        if (offset == Py_None) {
5171
0
            hash = generic_hash(
5172
0
                (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
5173
0
            FT_ATOMIC_STORE_SSIZE_RELAXED(self->hashcode, hash);
5174
0
        } else {
5175
0
            PyObject *temp1, *temp2;
5176
0
            int seconds, microseconds;
5177
0
            assert(HASTZINFO(self));
5178
0
            seconds = TIME_GET_HOUR(self) * 3600 +
5179
0
                      TIME_GET_MINUTE(self) * 60 +
5180
0
                      TIME_GET_SECOND(self);
5181
0
            microseconds = TIME_GET_MICROSECOND(self);
5182
0
            temp1 = new_delta(0, seconds, microseconds, 1);
5183
0
            if (temp1 == NULL) {
5184
0
                Py_DECREF(offset);
5185
0
                return -1;
5186
0
            }
5187
0
            temp2 = delta_subtract(temp1, offset);
5188
0
            Py_DECREF(temp1);
5189
0
            if (temp2 == NULL) {
5190
0
                Py_DECREF(offset);
5191
0
                return -1;
5192
0
            }
5193
0
            hash = PyObject_Hash(temp2);
5194
0
            FT_ATOMIC_STORE_SSIZE_RELAXED(self->hashcode, hash);
5195
0
            Py_DECREF(temp2);
5196
0
        }
5197
0
        Py_DECREF(offset);
5198
0
    }
5199
0
    return hash;
5200
0
}
5201
5202
/*[clinic input]
5203
datetime.time.replace
5204
5205
    hour: int(c_default="TIME_GET_HOUR(self)") = unchanged
5206
    minute: int(c_default="TIME_GET_MINUTE(self)") = unchanged
5207
    second: int(c_default="TIME_GET_SECOND(self)") = unchanged
5208
    microsecond: int(c_default="TIME_GET_MICROSECOND(self)") = unchanged
5209
    tzinfo: object(c_default="HASTZINFO(self) ? ((PyDateTime_Time *)self)->tzinfo : Py_None") = unchanged
5210
    *
5211
    fold: int(c_default="TIME_GET_FOLD(self)") = unchanged
5212
5213
Return time with new specified fields.
5214
[clinic start generated code]*/
5215
5216
static PyObject *
5217
datetime_time_replace_impl(PyDateTime_Time *self, int hour, int minute,
5218
                           int second, int microsecond, PyObject *tzinfo,
5219
                           int fold)
5220
/*[clinic end generated code: output=0b89a44c299e4f80 input=abf23656e8df4e97]*/
5221
0
{
5222
0
    return new_time_subclass_fold_ex(hour, minute, second, microsecond, tzinfo,
5223
0
                                     fold, Py_TYPE(self));
5224
0
}
5225
5226
/*[clinic input]
5227
@classmethod
5228
datetime.time.fromisoformat
5229
5230
    string: unicode
5231
    /
5232
5233
Construct a time from a string in ISO 8601 format.
5234
[clinic start generated code]*/
5235
5236
static PyObject *
5237
datetime_time_fromisoformat_impl(PyTypeObject *type, PyObject *string)
5238
/*[clinic end generated code: output=97c57e896e7f2535 input=bdb4b8abea9cd688]*/
5239
0
{
5240
0
    Py_ssize_t len;
5241
0
    const char *p = PyUnicode_AsUTF8AndSize(string, &len);
5242
5243
0
    if (p == NULL) {
5244
0
        goto invalid_string_error;
5245
0
    }
5246
5247
    // The spec actually requires that time-only ISO 8601 strings start with
5248
    // T, but the extended format allows this to be omitted as long as there
5249
    // is no ambiguity with date strings.
5250
0
    if (*p == 'T') {
5251
0
        ++p;
5252
0
        len -= 1;
5253
0
    }
5254
5255
0
    int hour = 0, minute = 0, second = 0, microsecond = 0;
5256
0
    int tzoffset = 0, tzimicrosecond = 0;
5257
0
    int rv = parse_isoformat_time(p, len,
5258
0
                                  &hour, &minute, &second, &microsecond,
5259
0
                                  &tzoffset, &tzimicrosecond);
5260
5261
0
    if (rv < 0) {
5262
0
        if (rv == -6) {
5263
0
            goto error;
5264
0
        }
5265
0
        goto invalid_string_error;
5266
0
    }
5267
5268
0
    if (hour == 24) {
5269
0
        if (minute == 0 && second == 0 && microsecond == 0) {
5270
0
            hour = 0;
5271
0
        } else {
5272
0
            goto invalid_iso_midnight;
5273
0
        }
5274
0
    }
5275
5276
0
    PyObject *tzinfo = tzinfo_from_isoformat_results(rv, tzoffset,
5277
0
                                                     tzimicrosecond);
5278
5279
0
    if (tzinfo == NULL) {
5280
0
        return NULL;
5281
0
    }
5282
5283
0
    PyObject *t;
5284
0
    if (type == TIME_TYPE(NO_STATE)) {
5285
0
        t = new_time(hour, minute, second, microsecond, tzinfo, 0);
5286
0
    } else {
5287
0
        t = PyObject_CallFunction((PyObject *)type, "iiiiO",
5288
0
                                  hour, minute, second, microsecond, tzinfo);
5289
0
    }
5290
5291
0
    Py_DECREF(tzinfo);
5292
0
    return t;
5293
5294
0
invalid_iso_midnight:
5295
0
    PyErr_SetString(PyExc_ValueError, "minute, second, and microsecond must be 0 when hour is 24");
5296
0
    return NULL;
5297
5298
0
invalid_string_error:
5299
0
    PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", string);
5300
0
    return NULL;
5301
5302
0
error:
5303
0
    return NULL;
5304
0
}
5305
5306
5307
/* Pickle support, a simple use of __reduce__. */
5308
5309
/* Let basestate be the non-tzinfo data string.
5310
 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5311
 * So it's a tuple in any (non-error) case.
5312
 * __getstate__ isn't exposed.
5313
 */
5314
static PyObject *
5315
time_getstate(PyDateTime_Time *self, int proto)
5316
0
{
5317
0
    PyObject *basestate;
5318
0
    PyObject *result = NULL;
5319
5320
0
    basestate =  PyBytes_FromStringAndSize((char *)self->data,
5321
0
                                            _PyDateTime_TIME_DATASIZE);
5322
0
    if (basestate != NULL) {
5323
0
        if (proto > 3 && TIME_GET_FOLD(self))
5324
            /* Set the first bit of the first byte */
5325
0
            PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
5326
0
        if (! HASTZINFO(self) || self->tzinfo == Py_None)
5327
0
            result = PyTuple_Pack(1, basestate);
5328
0
        else
5329
0
            result = _PyTuple_FromPair(basestate, self->tzinfo);
5330
0
        Py_DECREF(basestate);
5331
0
    }
5332
0
    return result;
5333
0
}
5334
5335
/*[clinic input]
5336
datetime.time.__reduce_ex__
5337
5338
    proto: int
5339
    /
5340
[clinic start generated code]*/
5341
5342
static PyObject *
5343
datetime_time___reduce_ex___impl(PyDateTime_Time *self, int proto)
5344
/*[clinic end generated code: output=ccfab65f5c320c1b input=4cd06bb3ac3657bb]*/
5345
0
{
5346
0
    return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
5347
0
}
5348
5349
/*[clinic input]
5350
datetime.time.__reduce__
5351
[clinic start generated code]*/
5352
5353
static PyObject *
5354
datetime_time___reduce___impl(PyDateTime_Time *self)
5355
/*[clinic end generated code: output=9a2fcc87e64ce300 input=0fb8dd14d275857f]*/
5356
0
{
5357
0
    return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, 2));
5358
0
}
5359
5360
static PyMethodDef time_methods[] = {
5361
5362
    /* Class method: */
5363
5364
    DATETIME_TIME_FROMISOFORMAT_METHODDEF
5365
    DATETIME_TIME_STRPTIME_METHODDEF
5366
5367
    /* Instance methods: */
5368
5369
    DATETIME_TIME_ISOFORMAT_METHODDEF
5370
    DATETIME_TIME_STRFTIME_METHODDEF
5371
    DATETIME_TIME___FORMAT___METHODDEF
5372
5373
    {"utcoffset", time_utcoffset, METH_NOARGS,
5374
     PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
5375
5376
    {"tzname", time_tzname, METH_NOARGS,
5377
     PyDoc_STR("Return self.tzinfo.tzname(self).")},
5378
5379
    {"dst", time_dst, METH_NOARGS,
5380
     PyDoc_STR("Return self.tzinfo.dst(self).")},
5381
5382
    DATETIME_TIME_REPLACE_METHODDEF
5383
5384
    {"__replace__", _PyCFunction_CAST(datetime_time_replace), METH_FASTCALL | METH_KEYWORDS,
5385
     PyDoc_STR("__replace__($self, /, **changes)\n--\n\nThe same as replace().")},
5386
5387
    DATETIME_TIME___REDUCE_EX___METHODDEF
5388
    DATETIME_TIME___REDUCE___METHODDEF
5389
5390
    {NULL,      NULL}
5391
};
5392
5393
static PyTypeObject PyDateTime_TimeType = {
5394
    PyVarObject_HEAD_INIT(NULL, 0)
5395
    "datetime.time",                            /* tp_name */
5396
    sizeof(PyDateTime_Time),                    /* tp_basicsize */
5397
    0,                                          /* tp_itemsize */
5398
    time_dealloc,                               /* tp_dealloc */
5399
    0,                                          /* tp_vectorcall_offset */
5400
    0,                                          /* tp_getattr */
5401
    0,                                          /* tp_setattr */
5402
    0,                                          /* tp_as_async */
5403
    time_repr,                                  /* tp_repr */
5404
    0,                                          /* tp_as_number */
5405
    0,                                          /* tp_as_sequence */
5406
    0,                                          /* tp_as_mapping */
5407
    time_hash,                                  /* tp_hash */
5408
    0,                                          /* tp_call */
5409
    time_str,                                   /* tp_str */
5410
    PyObject_GenericGetAttr,                    /* tp_getattro */
5411
    0,                                          /* tp_setattro */
5412
    0,                                          /* tp_as_buffer */
5413
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
5414
    datetime_time__doc__,                       /* tp_doc */
5415
    0,                                          /* tp_traverse */
5416
    0,                                          /* tp_clear */
5417
    time_richcompare,                           /* tp_richcompare */
5418
    0,                                          /* tp_weaklistoffset */
5419
    0,                                          /* tp_iter */
5420
    0,                                          /* tp_iternext */
5421
    time_methods,                               /* tp_methods */
5422
    0,                                          /* tp_members */
5423
    time_getset,                                /* tp_getset */
5424
    0,                                          /* tp_base */
5425
    0,                                          /* tp_dict */
5426
    0,                                          /* tp_descr_get */
5427
    0,                                          /* tp_descr_set */
5428
    0,                                          /* tp_dictoffset */
5429
    0,                                          /* tp_init */
5430
    time_alloc,                                 /* tp_alloc */
5431
    time_new,                                   /* tp_new */
5432
    0,                                          /* tp_free */
5433
};
5434
5435
/*
5436
 * PyDateTime_DateTime implementation.
5437
 */
5438
5439
/* Accessor properties.  Properties for day, month, and year are inherited
5440
 * from date.
5441
 */
5442
5443
static PyObject *
5444
datetime_hour(PyObject *op, void *Py_UNUSED(closure))
5445
0
{
5446
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
5447
0
    return PyLong_FromLong(DATE_GET_HOUR(self));
5448
0
}
5449
5450
static PyObject *
5451
datetime_minute(PyObject *op, void *Py_UNUSED(closure))
5452
0
{
5453
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
5454
0
    return PyLong_FromLong(DATE_GET_MINUTE(self));
5455
0
}
5456
5457
static PyObject *
5458
datetime_second(PyObject *op, void *Py_UNUSED(closure))
5459
0
{
5460
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
5461
0
    return PyLong_FromLong(DATE_GET_SECOND(self));
5462
0
}
5463
5464
static PyObject *
5465
datetime_microsecond(PyObject *op, void *Py_UNUSED(closure))
5466
0
{
5467
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
5468
0
    return PyLong_FromLong(DATE_GET_MICROSECOND(self));
5469
0
}
5470
5471
static PyObject *
5472
datetime_tzinfo(PyObject *op, void *Py_UNUSED(closure))
5473
0
{
5474
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
5475
0
    PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
5476
0
    return Py_NewRef(result);
5477
0
}
5478
5479
static PyObject *
5480
datetime_fold(PyObject *op, void *Py_UNUSED(closure))
5481
0
{
5482
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
5483
0
    return PyLong_FromLong(DATE_GET_FOLD(self));
5484
0
}
5485
5486
static PyGetSetDef datetime_getset[] = {
5487
    {"hour", datetime_hour},
5488
    {"minute", datetime_minute},
5489
    {"second", datetime_second},
5490
    {"microsecond", datetime_microsecond},
5491
    {"tzinfo", datetime_tzinfo},
5492
    {"fold", datetime_fold},
5493
    {NULL}
5494
};
5495
5496
/*
5497
 * Constructors.
5498
 */
5499
5500
static PyObject *
5501
datetime_from_pickle(PyTypeObject *type, PyObject *state, PyObject *tzinfo)
5502
0
{
5503
0
    PyDateTime_DateTime *me;
5504
0
    char aware = (char)(tzinfo != Py_None);
5505
5506
0
    if (aware && check_tzinfo_subclass(tzinfo) < 0) {
5507
0
        PyErr_SetString(PyExc_TypeError, "bad tzinfo state arg");
5508
0
        return NULL;
5509
0
    }
5510
5511
0
    me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
5512
0
    if (me != NULL) {
5513
0
        const char *pdata = PyBytes_AS_STRING(state);
5514
5515
0
        memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
5516
0
        me->hashcode = -1;
5517
0
        me->hastzinfo = aware;
5518
0
        if (aware) {
5519
0
            me->tzinfo = Py_NewRef(tzinfo);
5520
0
        }
5521
0
        if (pdata[2] & (1 << 7)) {
5522
0
            me->data[2] -= 128;
5523
0
            me->fold = 1;
5524
0
        }
5525
0
        else {
5526
0
            me->fold = 0;
5527
0
        }
5528
0
    }
5529
0
    return (PyObject *)me;
5530
0
}
5531
5532
static PyObject *
5533
datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
5534
0
{
5535
    /* Check for invocation from pickle with __getstate__ state */
5536
0
    if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2) {
5537
0
        PyObject *state = PyTuple_GET_ITEM(args, 0);
5538
0
        PyObject *tzinfo = Py_None;
5539
0
        if (PyTuple_GET_SIZE(args) == 2) {
5540
0
            tzinfo = PyTuple_GET_ITEM(args, 1);
5541
0
        }
5542
0
        if (PyBytes_Check(state)) {
5543
0
            if (PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
5544
0
                MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
5545
0
            {
5546
0
                return datetime_from_pickle(type, state, tzinfo);
5547
0
            }
5548
0
        }
5549
0
        else if (PyUnicode_Check(state)) {
5550
0
            if (PyUnicode_GET_LENGTH(state) == _PyDateTime_DATETIME_DATASIZE &&
5551
0
                MONTH_IS_SANE(PyUnicode_READ_CHAR(state, 2) & 0x7F))
5552
0
            {
5553
0
                state = PyUnicode_AsLatin1String(state);
5554
0
                if (state == NULL) {
5555
0
                    if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
5556
                        /* More informative error message. */
5557
0
                        PyErr_SetString(PyExc_ValueError,
5558
0
                            "Failed to encode latin1 string when unpickling "
5559
0
                            "a datetime object. "
5560
0
                            "pickle.load(data, encoding='latin1') is assumed.");
5561
0
                    }
5562
0
                    return NULL;
5563
0
                }
5564
0
                PyObject *self = datetime_from_pickle(type, state, tzinfo);
5565
0
                Py_DECREF(state);
5566
0
                return self;
5567
0
            }
5568
0
        }
5569
0
    }
5570
5571
0
    return datetime_datetime(type, args, kw);
5572
0
}
5573
5574
/*[clinic input]
5575
@classmethod
5576
datetime.datetime.__new__
5577
5578
    year: int
5579
    month: int
5580
    day: int
5581
    hour: int = 0
5582
    minute: int = 0
5583
    second: int = 0
5584
    microsecond: int = 0
5585
    tzinfo: object = None
5586
    *
5587
    fold: int = 0
5588
5589
A combination of a date and a time.
5590
5591
The year, month and day arguments are required. tzinfo may be None, or
5592
an instance of a tzinfo subclass. The remaining arguments may be ints.
5593
[clinic start generated code]*/
5594
5595
static PyObject *
5596
datetime_datetime_impl(PyTypeObject *type, int year, int month, int day,
5597
                       int hour, int minute, int second, int microsecond,
5598
                       PyObject *tzinfo, int fold)
5599
/*[clinic end generated code: output=47983ddb47d36037 input=c7fd85dcf6fe9691]*/
5600
0
{
5601
0
    return new_datetime_ex2(year, month, day,
5602
0
                            hour, minute, second, microsecond,
5603
0
                            tzinfo, fold, type);
5604
0
}
5605
5606
/* TM_FUNC is the shared type of _PyTime_localtime() and
5607
 * _PyTime_gmtime(). */
5608
typedef int (*TM_FUNC)(time_t timer, struct tm*);
5609
5610
/* As of version 2015f max fold in IANA database is
5611
 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
5612
static long long max_fold_seconds = 24 * 3600;
5613
/* NB: date(1970,1,1).toordinal() == 719163 */
5614
static long long epoch = 719163LL * 24 * 60 * 60;
5615
5616
static long long
5617
utc_to_seconds(int year, int month, int day,
5618
               int hour, int minute, int second)
5619
0
{
5620
0
    long long ordinal;
5621
5622
    /* ymd_to_ord() doesn't support year <= 0 */
5623
0
    if (year < MINYEAR || year > MAXYEAR) {
5624
0
        PyErr_Format(PyExc_ValueError,
5625
0
                     "year must be in %d..%d, not %d", MINYEAR, MAXYEAR, year);
5626
0
        return -1;
5627
0
    }
5628
5629
0
    ordinal = ymd_to_ord(year, month, day);
5630
0
    return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
5631
0
}
5632
5633
static long long
5634
local(long long u)
5635
0
{
5636
0
    struct tm local_time;
5637
0
    time_t t;
5638
0
    u -= epoch;
5639
0
    t = u;
5640
0
    if (t != u) {
5641
0
        PyErr_SetString(PyExc_OverflowError,
5642
0
        "timestamp out of range for platform time_t");
5643
0
        return -1;
5644
0
    }
5645
0
    if (_PyTime_localtime(t, &local_time) != 0)
5646
0
        return -1;
5647
0
    return utc_to_seconds(local_time.tm_year + 1900,
5648
0
                          local_time.tm_mon + 1,
5649
0
                          local_time.tm_mday,
5650
0
                          local_time.tm_hour,
5651
0
                          local_time.tm_min,
5652
0
                          local_time.tm_sec);
5653
0
}
5654
5655
/* Internal helper.
5656
 * Build datetime from a time_t and a distinct count of microseconds.
5657
 * Pass localtime or gmtime for f, to control the interpretation of timet.
5658
 */
5659
static PyObject *
5660
datetime_from_timet_and_us(PyTypeObject *cls, TM_FUNC f, time_t timet, int us,
5661
                           PyObject *tzinfo)
5662
0
{
5663
0
    struct tm tm;
5664
0
    int year, month, day, hour, minute, second, fold = 0;
5665
5666
0
    if (f(timet, &tm) != 0)
5667
0
        return NULL;
5668
5669
0
    if (year_from_tm(&tm, &year) < 0) {
5670
0
        return NULL;
5671
0
    }
5672
0
    month = tm.tm_mon + 1;
5673
0
    day = tm.tm_mday;
5674
0
    hour = tm.tm_hour;
5675
0
    minute = tm.tm_min;
5676
    /* The platform localtime/gmtime may insert leap seconds,
5677
     * indicated by tm.tm_sec > 59.  We don't care about them,
5678
     * except to the extent that passing them on to the datetime
5679
     * constructor would raise ValueError for a reason that
5680
     * made no sense to the user.
5681
     */
5682
0
    second = Py_MIN(59, tm.tm_sec);
5683
5684
    /* local timezone requires to compute fold */
5685
0
    if (tzinfo == Py_None && f == _PyTime_localtime) {
5686
0
        long long probe_seconds, result_seconds, transition;
5687
5688
0
        result_seconds = utc_to_seconds(year, month, day,
5689
0
                                        hour, minute, second);
5690
0
        if (result_seconds == -1 && PyErr_Occurred()) {
5691
0
            return NULL;
5692
0
        }
5693
5694
        /* Probe max_fold_seconds to detect a fold. */
5695
0
        probe_seconds = local(epoch + timet - max_fold_seconds);
5696
0
        if (probe_seconds == -1)
5697
0
            return NULL;
5698
0
        transition = result_seconds - probe_seconds - max_fold_seconds;
5699
0
        if (transition < 0) {
5700
0
            probe_seconds = local(epoch + timet + transition);
5701
0
            if (probe_seconds == -1)
5702
0
                return NULL;
5703
0
            if (probe_seconds == result_seconds)
5704
0
                fold = 1;
5705
0
        }
5706
0
    }
5707
0
    return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
5708
0
                                         second, us, tzinfo, fold, cls);
5709
0
}
5710
5711
/* Internal helper.
5712
 * Build datetime from a Python timestamp.  Pass localtime or gmtime for f,
5713
 * to control the interpretation of the timestamp.  Since a double doesn't
5714
 * have enough bits to cover a datetime's full range of precision, it's
5715
 * better to call datetime_from_timet_and_us provided you have a way
5716
 * to get that much precision (e.g., C time() isn't good enough).
5717
 */
5718
static PyObject *
5719
datetime_from_timestamp(PyTypeObject *cls, TM_FUNC f, PyObject *timestamp,
5720
                        PyObject *tzinfo)
5721
0
{
5722
0
    time_t timet;
5723
0
    long us;
5724
5725
0
    if (_PyTime_ObjectToTimeval(timestamp,
5726
0
                                &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
5727
0
        return NULL;
5728
5729
0
    return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
5730
0
}
5731
5732
/* Internal helper.
5733
 * Build most accurate possible datetime for current time.  Pass localtime or
5734
 * gmtime for f as appropriate.
5735
 */
5736
static PyObject *
5737
datetime_best_possible(PyTypeObject *cls, TM_FUNC f, PyObject *tzinfo)
5738
0
{
5739
0
    PyTime_t ts;
5740
0
    if (PyTime_Time(&ts) < 0) {
5741
0
        return NULL;
5742
0
    }
5743
5744
0
    time_t secs;
5745
0
    int us;
5746
5747
0
    if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_HALF_EVEN) < 0) {
5748
0
        return NULL;
5749
0
    }
5750
0
    assert(0 <= us && us <= 999999);
5751
5752
0
    return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
5753
0
}
5754
5755
/*[clinic input]
5756
5757
@classmethod
5758
datetime.datetime.now
5759
5760
    tz: object = None
5761
        Timezone object.
5762
5763
Returns new datetime object representing current time local to tz.
5764
5765
If no tz is specified, uses local timezone.
5766
[clinic start generated code]*/
5767
5768
static PyObject *
5769
datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
5770
/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
5771
0
{
5772
0
    PyObject *self;
5773
5774
    /* Return best possible local time -- this isn't constrained by the
5775
     * precision of a timestamp.
5776
     */
5777
0
    if (check_tzinfo_subclass(tz) < 0)
5778
0
        return NULL;
5779
5780
0
    self = datetime_best_possible(type,
5781
0
                                  tz == Py_None ? _PyTime_localtime :
5782
0
                                  _PyTime_gmtime,
5783
0
                                  tz);
5784
0
    if (self != NULL && tz != Py_None) {
5785
        /* Convert UTC to tzinfo's zone. */
5786
0
        PyObject *res = PyObject_CallMethodOneArg(tz, &_Py_ID(fromutc), self);
5787
0
        Py_DECREF(self);
5788
0
        return res;
5789
0
    }
5790
0
    return self;
5791
0
}
5792
5793
/* Return best possible UTC time -- this isn't constrained by the
5794
 * precision of a timestamp.
5795
 */
5796
/*[clinic input]
5797
@classmethod
5798
datetime.datetime.utcnow
5799
5800
Return a new datetime representing UTC day and time.
5801
[clinic start generated code]*/
5802
5803
static PyObject *
5804
datetime_datetime_utcnow_impl(PyTypeObject *type)
5805
/*[clinic end generated code: output=cfcfe71c6c916ba9 input=576eff2b222b80a1]*/
5806
0
{
5807
0
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
5808
0
        "datetime.datetime.utcnow() is deprecated and scheduled for removal in a "
5809
0
        "future version. Use timezone-aware objects to represent datetimes "
5810
0
        "in UTC: datetime.datetime.now(datetime.UTC).", 1))
5811
0
    {
5812
0
        return NULL;
5813
0
    }
5814
0
    return datetime_best_possible(type, _PyTime_gmtime, Py_None);
5815
0
}
5816
5817
/*[clinic input]
5818
@classmethod
5819
datetime.datetime.fromtimestamp
5820
5821
    timestamp: object
5822
    tz as tzinfo: object = None
5823
5824
Create a datetime from a POSIX timestamp.
5825
5826
The timestamp is a number, e.g. created via time.time(), that is
5827
interpreted as local time.
5828
[clinic start generated code]*/
5829
5830
static PyObject *
5831
datetime_datetime_fromtimestamp_impl(PyTypeObject *type, PyObject *timestamp,
5832
                                     PyObject *tzinfo)
5833
/*[clinic end generated code: output=9c47ea2b2ebdaded input=7a2bc81a049ea287]*/
5834
0
{
5835
0
    PyObject *self;
5836
0
    if (check_tzinfo_subclass(tzinfo) < 0)
5837
0
        return NULL;
5838
5839
0
    self = datetime_from_timestamp(type,
5840
0
                                   tzinfo == Py_None ? _PyTime_localtime :
5841
0
                                   _PyTime_gmtime,
5842
0
                                   timestamp,
5843
0
                                   tzinfo);
5844
0
    if (self != NULL && tzinfo != Py_None) {
5845
        /* Convert UTC to tzinfo's zone. */
5846
0
        PyObject *res = PyObject_CallMethodOneArg(tzinfo, &_Py_ID(fromutc), self);
5847
0
        Py_DECREF(self);
5848
0
        return res;
5849
0
    }
5850
0
    return self;
5851
0
}
5852
5853
/* This is a wrapper for API compatibility with the public C API. */
5854
static PyObject *
5855
datetime_datetime_fromtimestamp_capi(PyObject *cls, PyObject *args, PyObject *kw)
5856
0
{
5857
0
    PyObject *timestamp;
5858
0
    PyObject *tzinfo = Py_None;
5859
0
    static char *keywords[] = {"timestamp", "tz", NULL};
5860
5861
0
    if (!PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
5862
0
                                     keywords, &timestamp, &tzinfo))
5863
0
        return NULL;
5864
0
    return datetime_datetime_fromtimestamp_impl((PyTypeObject *)cls,
5865
0
                                                timestamp, tzinfo);
5866
0
}
5867
5868
/*[clinic input]
5869
@classmethod
5870
datetime.datetime.utcfromtimestamp
5871
5872
    timestamp: object
5873
    /
5874
5875
Create a naive UTC datetime from a POSIX timestamp.
5876
[clinic start generated code]*/
5877
5878
static PyObject *
5879
datetime_datetime_utcfromtimestamp_impl(PyTypeObject *type,
5880
                                        PyObject *timestamp)
5881
/*[clinic end generated code: output=66d0b1741d788fd2 input=13fabd4296b1c206]*/
5882
0
{
5883
0
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
5884
0
        "datetime.datetime.utcfromtimestamp() is deprecated and scheduled for removal "
5885
0
        "in a future version. Use timezone-aware objects to represent "
5886
0
        "datetimes in UTC: datetime.datetime.fromtimestamp(timestamp, datetime.UTC).", 1))
5887
0
    {
5888
0
        return NULL;
5889
0
    }
5890
5891
0
    return datetime_from_timestamp(type, _PyTime_gmtime, timestamp, Py_None);
5892
0
}
5893
5894
/*[clinic input]
5895
@permit_long_summary
5896
@classmethod
5897
datetime.datetime.strptime
5898
5899
    string: unicode
5900
    format: unicode
5901
    /
5902
5903
Parse string according to the given date and time format (like time.strptime()).
5904
5905
For a list of supported format codes, see the documentation:
5906
    https://docs.python.org/3/library/datetime.html#format-codes
5907
[clinic start generated code]*/
5908
5909
static PyObject *
5910
datetime_datetime_strptime_impl(PyTypeObject *type, PyObject *string,
5911
                                PyObject *format)
5912
/*[clinic end generated code: output=af2c2d024f3203f5 input=ef7807589f1d50e7]*/
5913
0
{
5914
    /* Subclasses retain the Python parser's constructor arguments. */
5915
0
    _PyTime_StrptimeFields fields;
5916
0
    if (type == DATETIME_TYPE(NO_STATE) &&
5917
0
        _PyTime_Strptime(string, format, &fields)) {
5918
0
        PyObject *tzinfo = tzinfo_from_isoformat_results(
5919
0
            fields.gmtoff != INT_MIN, fields.gmtoff, 0);
5920
0
        if (tzinfo == NULL) {
5921
0
            return NULL;
5922
0
        }
5923
0
        PyObject *result = new_datetime_ex(
5924
0
            fields.year, fields.month, fields.day,
5925
0
            fields.hour, fields.minute, fields.second, fields.fraction,
5926
0
            tzinfo, type);
5927
0
        Py_DECREF(tzinfo);
5928
0
        return result;
5929
0
    }
5930
0
    PyObject *result;
5931
5932
0
    PyObject *module = PyImport_Import(&_Py_ID(_strptime));
5933
0
    if (module == NULL) {
5934
0
        return NULL;
5935
0
    }
5936
0
    result = PyObject_CallMethodObjArgs(module,
5937
0
                                        &_Py_ID(_strptime_datetime_datetime),
5938
0
                                        (PyObject *)type, string, format, NULL);
5939
0
    Py_DECREF(module);
5940
0
    return result;
5941
0
}
5942
5943
/*[clinic input]
5944
@classmethod
5945
datetime.datetime.combine
5946
5947
    date: object(subclass_of="DATE_TYPE(NO_STATE)")
5948
    time: object(subclass_of="TIME_TYPE(NO_STATE)")
5949
    tzinfo: object = NULL
5950
5951
Construct a datetime from a given date and a given time.
5952
[clinic start generated code]*/
5953
5954
static PyObject *
5955
datetime_datetime_combine_impl(PyTypeObject *type, PyObject *date,
5956
                               PyObject *time, PyObject *tzinfo)
5957
/*[clinic end generated code: output=a10f3cbb90f4d0aa input=4fcf0743288d0bab]*/
5958
0
{
5959
0
    if (tzinfo == NULL) {
5960
0
        if (HASTZINFO(time))
5961
0
            tzinfo = ((PyDateTime_Time *)time)->tzinfo;
5962
0
        else
5963
0
            tzinfo = Py_None;
5964
0
    }
5965
0
    return new_datetime_subclass_fold_ex(GET_YEAR(date),
5966
0
                                         GET_MONTH(date),
5967
0
                                         GET_DAY(date),
5968
0
                                         TIME_GET_HOUR(time),
5969
0
                                         TIME_GET_MINUTE(time),
5970
0
                                         TIME_GET_SECOND(time),
5971
0
                                         TIME_GET_MICROSECOND(time),
5972
0
                                         tzinfo,
5973
0
                                         TIME_GET_FOLD(time),
5974
0
                                         type);
5975
0
}
5976
5977
static PyObject *
5978
_sanitize_isoformat_str(PyObject *dtstr)
5979
0
{
5980
0
    Py_ssize_t len = PyUnicode_GetLength(dtstr);
5981
0
    if (len < 7) {  // All valid ISO 8601 strings are at least 7 characters long
5982
0
        return NULL;
5983
0
    }
5984
5985
    // `fromisoformat` allows surrogate characters in exactly one position,
5986
    // the separator; to allow datetime_fromisoformat to make the simplifying
5987
    // assumption that all valid strings can be encoded in UTF-8, this function
5988
    // replaces any surrogate character separators with `T`.
5989
    //
5990
    // The result of this, if not NULL, returns a new reference
5991
0
    const void* const unicode_data = PyUnicode_DATA(dtstr);
5992
0
    const int kind = PyUnicode_KIND(dtstr);
5993
5994
    // Depending on the format of the string, the separator can only ever be
5995
    // in positions 7, 8 or 10. We'll check each of these for a surrogate and
5996
    // if we find one, replace it with `T`. If there is more than one surrogate,
5997
    // we don't have to bother sanitizing it, because the function will later
5998
    // fail when we try to encode the string as ASCII.
5999
0
    static const size_t potential_separators[3] = {7, 8, 10};
6000
0
    size_t surrogate_separator = 0;
6001
0
    for(size_t idx = 0;
6002
0
         idx < sizeof(potential_separators) / sizeof(*potential_separators);
6003
0
         ++idx) {
6004
0
        size_t pos = potential_separators[idx];
6005
0
        if (pos > (size_t)len) {
6006
0
            break;
6007
0
        }
6008
6009
0
        if(Py_UNICODE_IS_SURROGATE(PyUnicode_READ(kind, unicode_data, pos))) {
6010
0
            surrogate_separator = pos;
6011
0
            break;
6012
0
        }
6013
0
    }
6014
6015
0
    if (surrogate_separator == 0) {
6016
0
        return Py_NewRef(dtstr);
6017
0
    }
6018
6019
0
    PyObject *str_out = _PyUnicode_Copy(dtstr);
6020
0
    if (str_out == NULL) {
6021
0
        return NULL;
6022
0
    }
6023
6024
0
    if (PyUnicode_WriteChar(str_out, surrogate_separator, (Py_UCS4)'T')) {
6025
0
        Py_DECREF(str_out);
6026
0
        return NULL;
6027
0
    }
6028
6029
0
    return str_out;
6030
0
}
6031
6032
6033
static Py_ssize_t
6034
0
_find_isoformat_datetime_separator(const char *dtstr, Py_ssize_t len) {
6035
    // The valid date formats can all be distinguished by characters 4 and 5
6036
    // and further narrowed down by character
6037
    // which tells us where to look for the separator character.
6038
    // Format    |  As-rendered |   Position
6039
    // ---------------------------------------
6040
    // %Y-%m-%d  |  YYYY-MM-DD  |    10
6041
    // %Y%m%d    |  YYYYMMDD    |     8
6042
    // %Y-W%V    |  YYYY-Www    |     8
6043
    // %YW%V     |  YYYYWww     |     7
6044
    // %Y-W%V-%u |  YYYY-Www-d  |    10
6045
    // %YW%V%u   |  YYYYWwwd    |     8
6046
    // %Y-%j     |  YYYY-DDD    |     8
6047
    // %Y%j      |  YYYYDDD     |     7
6048
    //
6049
    // Note that because we allow *any* character for the separator, in the
6050
    // case where character 4 is W, it's not straightforward to determine where
6051
    // the separator is — in the case of YYYY-Www-d, you have actual ambiguity,
6052
    // e.g. 2020-W01-0000 could be YYYY-Www-D0HH or YYYY-Www-HHMM, when the
6053
    // separator character is a number in the former case or a hyphen in the
6054
    // latter case.
6055
    //
6056
    // The case of YYYYWww can be distinguished from YYYYWwwd by tracking ahead
6057
    // to either the end of the string or the first non-numeric character —
6058
    // since the time components all come in pairs YYYYWww#HH can be
6059
    // distinguished from YYYYWwwd#HH by the fact that there will always be an
6060
    // odd number of digits before the first non-digit character in the former
6061
    // case.
6062
0
    static const char date_separator = '-';
6063
0
    static const char week_indicator = 'W';
6064
6065
0
    if (len == 7) {
6066
0
        return 7;
6067
0
    }
6068
6069
0
    if (dtstr[4] == date_separator) {
6070
        // YYYY-???
6071
6072
0
        if (dtstr[5] == week_indicator) {
6073
            // YYYY-W??
6074
6075
0
            if (len < 8) {
6076
0
                return -1;
6077
0
            }
6078
6079
0
            if (len > 8 && dtstr[8] == date_separator) {
6080
                // YYYY-Www-D (10) or YYYY-Www-HH (8)
6081
0
                if (len == 9) { return -1; }
6082
0
                if (len > 10 && is_digit(dtstr[10])) {
6083
                    // This is as far as we'll try to go to resolve the
6084
                    // ambiguity for the moment — if we have YYYY-Www-##, the
6085
                    // separator is either a hyphen at 8 or a number at 10.
6086
                    //
6087
                    // We'll assume it's a hyphen at 8 because it's way more
6088
                    // likely that someone will use a hyphen as a separator
6089
                    // than a number, but at this point it's really best effort
6090
                    // because this is an extension of the spec anyway.
6091
0
                    return 8;
6092
0
                }
6093
6094
0
                return 10;
6095
0
            } else {
6096
                // YYYY-Www (8)
6097
0
                return 8;
6098
0
            }
6099
0
        } else {
6100
            // YYYY-MM-DD (10)
6101
0
            return 10;
6102
0
        }
6103
0
    } else {
6104
        // YYYY???
6105
0
        if (dtstr[4] == week_indicator) {
6106
            // YYYYWww (7) or YYYYWwwd (8)
6107
0
            size_t idx = 7;
6108
0
            for (; idx < (size_t)len; ++idx) {
6109
                // Keep going until we run out of digits.
6110
0
                if (!is_digit(dtstr[idx])) {
6111
0
                    break;
6112
0
                }
6113
0
            }
6114
6115
0
            if (idx < 9) {
6116
0
                return idx;
6117
0
            }
6118
6119
0
            if (idx % 2 == 0) {
6120
                // If the index of the last number is even, it's YYYYWww
6121
0
                return 7;
6122
0
            } else {
6123
0
                return 8;
6124
0
            }
6125
0
        } else {
6126
            // YYYYMMDD (8)
6127
0
            return 8;
6128
0
        }
6129
0
    }
6130
0
}
6131
6132
/*[clinic input]
6133
@classmethod
6134
datetime.datetime.fromisoformat
6135
6136
    string: unicode
6137
    /
6138
6139
Construct a date from a string in ISO 8601 format.
6140
[clinic start generated code]*/
6141
6142
static PyObject *
6143
datetime_datetime_fromisoformat_impl(PyTypeObject *type, PyObject *string)
6144
/*[clinic end generated code: output=1800a952fcab79d9 input=d517b158209ded42]*/
6145
0
{
6146
    // We only need to sanitize this string if the separator is a surrogate
6147
    // character. In the situation where the separator location is ambiguous,
6148
    // we don't have to sanitize it anything because that can only happen when
6149
    // the separator is either '-' or a number. This should mostly be a noop
6150
    // but it makes the reference counting easier if we still sanitize.
6151
0
    PyObject *dtstr_clean = _sanitize_isoformat_str(string);
6152
0
    if (dtstr_clean == NULL) {
6153
0
        goto invalid_string_error;
6154
0
    }
6155
6156
0
    Py_ssize_t len;
6157
0
    const char *dt_ptr = PyUnicode_AsUTF8AndSize(dtstr_clean, &len);
6158
6159
0
    if (dt_ptr == NULL) {
6160
0
        if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
6161
            // Encoding errors are invalid string errors at this point
6162
0
            goto invalid_string_error;
6163
0
        }
6164
0
        else {
6165
0
            goto error;
6166
0
        }
6167
0
    }
6168
6169
0
    const Py_ssize_t separator_location = _find_isoformat_datetime_separator(
6170
0
            dt_ptr, len);
6171
6172
6173
0
    const char *p = dt_ptr;
6174
6175
0
    int year = 0, month = 0, day = 0;
6176
0
    int hour = 0, minute = 0, second = 0, microsecond = 0;
6177
0
    int tzoffset = 0, tzusec = 0;
6178
6179
    // date runs up to separator_location
6180
0
    int rv = parse_isoformat_date(p, separator_location, &year, &month, &day);
6181
6182
0
    if (!rv && len > separator_location) {
6183
        // In UTF-8, the length of multi-byte characters is encoded in the MSB
6184
0
        p += separator_location;
6185
0
        if ((p[0] & 0x80) == 0) {
6186
0
            p += 1;
6187
0
        }
6188
0
        else {
6189
0
            switch (p[0] & 0xf0) {
6190
0
                case 0xe0:
6191
0
                    p += 3;
6192
0
                    break;
6193
0
                case 0xf0:
6194
0
                    p += 4;
6195
0
                    break;
6196
0
                default:
6197
0
                    p += 2;
6198
0
                    break;
6199
0
            }
6200
0
        }
6201
6202
0
        len -= (p - dt_ptr);
6203
0
        rv = parse_isoformat_time(p, len, &hour, &minute, &second,
6204
0
                                  &microsecond, &tzoffset, &tzusec);
6205
0
        if (rv == -6) {
6206
0
            goto error;
6207
0
        }
6208
0
    }
6209
0
    if (rv < 0) {
6210
0
        goto invalid_string_error;
6211
0
    }
6212
6213
0
    PyObject *tzinfo = tzinfo_from_isoformat_results(rv, tzoffset, tzusec);
6214
0
    if (tzinfo == NULL) {
6215
0
        goto error;
6216
0
    }
6217
6218
0
    if ((hour == 24) && (month >= 1 && month <= 12))  {
6219
0
        int d_in_month = days_in_month(year, month);
6220
0
        if (day <= d_in_month) {
6221
0
            if (minute == 0 && second == 0 && microsecond == 0) {
6222
                // Calculate midnight of the next day
6223
0
                hour = 0;
6224
0
                day += 1;
6225
0
                if (day > d_in_month) {
6226
0
                    day = 1;
6227
0
                    month += 1;
6228
0
                    if (month > 12) {
6229
0
                        month = 1;
6230
0
                        year += 1;
6231
0
                    }
6232
0
                }
6233
0
            } else {
6234
0
                goto invalid_iso_midnight;
6235
0
            }
6236
0
        }
6237
0
    }
6238
0
    PyObject *dt = new_datetime_subclass_ex(year, month, day, hour, minute,
6239
0
                                            second, microsecond, tzinfo, type);
6240
6241
0
    Py_DECREF(tzinfo);
6242
0
    Py_DECREF(dtstr_clean);
6243
0
    return dt;
6244
6245
0
invalid_iso_midnight:
6246
0
    PyErr_SetString(PyExc_ValueError, "minute, second, and microsecond must be 0 when hour is 24");
6247
0
    Py_DECREF(tzinfo);
6248
0
    Py_DECREF(dtstr_clean);
6249
0
    return NULL;
6250
6251
0
invalid_string_error:
6252
0
    PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", string);
6253
6254
0
error:
6255
0
    Py_XDECREF(dtstr_clean);
6256
6257
0
    return NULL;
6258
0
}
6259
6260
/*
6261
 * Destructor.
6262
 */
6263
6264
static void
6265
datetime_dealloc(PyObject *op)
6266
0
{
6267
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
6268
0
    if (HASTZINFO(self)) {
6269
0
        Py_XDECREF(self->tzinfo);
6270
0
    }
6271
0
    Py_TYPE(self)->tp_free(self);
6272
0
}
6273
6274
/*
6275
 * Indirect access to tzinfo methods.
6276
 */
6277
6278
/* These are all METH_NOARGS, so don't need to check the arglist. */
6279
static PyObject *
6280
0
datetime_utcoffset(PyObject *op, PyObject *Py_UNUSED(dummy)) {
6281
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
6282
0
    return call_utcoffset(GET_DT_TZINFO(self), op);
6283
0
}
6284
6285
static PyObject *
6286
0
datetime_dst(PyObject *op, PyObject *Py_UNUSED(dummy)) {
6287
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
6288
0
    return call_dst(GET_DT_TZINFO(self), op);
6289
0
}
6290
6291
static PyObject *
6292
0
datetime_tzname(PyObject *op, PyObject *Py_UNUSED(dummy)) {
6293
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
6294
0
    return call_tzname(GET_DT_TZINFO(self), op);
6295
0
}
6296
6297
/*
6298
 * datetime arithmetic.
6299
 */
6300
6301
/* factor must be 1 (to add) or -1 (to subtract).  The result inherits
6302
 * the tzinfo state of date.
6303
 */
6304
static PyObject *
6305
add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
6306
                       int factor)
6307
0
{
6308
    /* Note that the C-level additions can't overflow, because of
6309
     * invariant bounds on the member values.
6310
     */
6311
0
    int year = GET_YEAR(date);
6312
0
    int month = GET_MONTH(date);
6313
0
    int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
6314
0
    int hour = DATE_GET_HOUR(date);
6315
0
    int minute = DATE_GET_MINUTE(date);
6316
0
    int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
6317
0
    int microsecond = DATE_GET_MICROSECOND(date) +
6318
0
                      GET_TD_MICROSECONDS(delta) * factor;
6319
6320
0
    assert(factor == 1 || factor == -1);
6321
0
    if (normalize_datetime(&year, &month, &day,
6322
0
                           &hour, &minute, &second, &microsecond) < 0) {
6323
0
        return NULL;
6324
0
    }
6325
6326
0
    return new_datetime_subclass_ex(year, month, day,
6327
0
                                    hour, minute, second, microsecond,
6328
0
                                    HASTZINFO(date) ? date->tzinfo : Py_None,
6329
0
                                    Py_TYPE(date));
6330
0
}
6331
6332
static PyObject *
6333
datetime_add(PyObject *left, PyObject *right)
6334
0
{
6335
0
    if (PyDateTime_Check(left)) {
6336
        /* datetime + ??? */
6337
0
        if (PyDelta_Check(right))
6338
            /* datetime + delta */
6339
0
            return add_datetime_timedelta(
6340
0
                            (PyDateTime_DateTime *)left,
6341
0
                            (PyDateTime_Delta *)right,
6342
0
                            1);
6343
0
    }
6344
0
    else if (PyDelta_Check(left)) {
6345
        /* delta + datetime */
6346
0
        return add_datetime_timedelta((PyDateTime_DateTime *) right,
6347
0
                                      (PyDateTime_Delta *) left,
6348
0
                                      1);
6349
0
    }
6350
0
    Py_RETURN_NOTIMPLEMENTED;
6351
0
}
6352
6353
static PyObject *
6354
datetime_subtract(PyObject *left, PyObject *right)
6355
0
{
6356
0
    PyObject *result = Py_NotImplemented;
6357
6358
0
    if (PyDateTime_Check(left)) {
6359
        /* datetime - ??? */
6360
0
        if (PyDateTime_Check(right)) {
6361
            /* datetime - datetime */
6362
0
            PyObject *offset1, *offset2, *offdiff = NULL;
6363
0
            int delta_d, delta_s, delta_us;
6364
6365
0
            if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
6366
0
                offset1 = Py_NewRef(Py_None);
6367
0
                offset2 = Py_NewRef(Py_None);
6368
0
            }
6369
0
            else {
6370
0
                offset1 = datetime_utcoffset(left, NULL);
6371
0
                if (offset1 == NULL)
6372
0
                    return NULL;
6373
0
                offset2 = datetime_utcoffset(right, NULL);
6374
0
                if (offset2 == NULL) {
6375
0
                    Py_DECREF(offset1);
6376
0
                    return NULL;
6377
0
                }
6378
0
                if ((offset1 != Py_None) != (offset2 != Py_None)) {
6379
0
                    PyErr_SetString(PyExc_TypeError,
6380
0
                                    "can't subtract offset-naive and "
6381
0
                                    "offset-aware datetimes");
6382
0
                    Py_DECREF(offset1);
6383
0
                    Py_DECREF(offset2);
6384
0
                    return NULL;
6385
0
                }
6386
0
            }
6387
0
            if ((offset1 != offset2) &&
6388
0
                delta_cmp(offset1, offset2) != 0) {
6389
0
                offdiff = delta_subtract(offset1, offset2);
6390
0
                if (offdiff == NULL) {
6391
0
                    Py_DECREF(offset1);
6392
0
                    Py_DECREF(offset2);
6393
0
                    return NULL;
6394
0
                }
6395
0
            }
6396
0
            Py_DECREF(offset1);
6397
0
            Py_DECREF(offset2);
6398
0
            delta_d = ymd_to_ord(GET_YEAR(left),
6399
0
                                 GET_MONTH(left),
6400
0
                                 GET_DAY(left)) -
6401
0
                      ymd_to_ord(GET_YEAR(right),
6402
0
                                 GET_MONTH(right),
6403
0
                                 GET_DAY(right));
6404
            /* These can't overflow, since the values are
6405
             * normalized.  At most this gives the number of
6406
             * seconds in one day.
6407
             */
6408
0
            delta_s = (DATE_GET_HOUR(left) -
6409
0
                       DATE_GET_HOUR(right)) * 3600 +
6410
0
                      (DATE_GET_MINUTE(left) -
6411
0
                       DATE_GET_MINUTE(right)) * 60 +
6412
0
                      (DATE_GET_SECOND(left) -
6413
0
                       DATE_GET_SECOND(right));
6414
0
            delta_us = DATE_GET_MICROSECOND(left) -
6415
0
                       DATE_GET_MICROSECOND(right);
6416
0
            result = new_delta(delta_d, delta_s, delta_us, 1);
6417
0
            if (result == NULL)
6418
0
                return NULL;
6419
6420
0
            if (offdiff != NULL) {
6421
0
                Py_SETREF(result, delta_subtract(result, offdiff));
6422
0
                Py_DECREF(offdiff);
6423
0
            }
6424
0
        }
6425
0
        else if (PyDelta_Check(right)) {
6426
            /* datetime - delta */
6427
0
            result = add_datetime_timedelta(
6428
0
                            (PyDateTime_DateTime *)left,
6429
0
                            (PyDateTime_Delta *)right,
6430
0
                            -1);
6431
0
        }
6432
0
    }
6433
6434
0
    if (result == Py_NotImplemented)
6435
0
        Py_INCREF(result);
6436
0
    return result;
6437
0
}
6438
6439
/* Various ways to turn a datetime into a string. */
6440
6441
static PyObject *
6442
datetime_repr(PyObject *op)
6443
0
{
6444
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
6445
0
    const char *type_name = Py_TYPE(self)->tp_name;
6446
0
    PyObject *baserepr;
6447
6448
0
    if (DATE_GET_MICROSECOND(self)) {
6449
0
        baserepr = PyUnicode_FromFormat(
6450
0
                      "%s(%d, %d, %d, %d, %d, %d, %d)",
6451
0
                      type_name,
6452
0
                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
6453
0
                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
6454
0
                      DATE_GET_SECOND(self),
6455
0
                      DATE_GET_MICROSECOND(self));
6456
0
    }
6457
0
    else if (DATE_GET_SECOND(self)) {
6458
0
        baserepr = PyUnicode_FromFormat(
6459
0
                      "%s(%d, %d, %d, %d, %d, %d)",
6460
0
                      type_name,
6461
0
                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
6462
0
                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
6463
0
                      DATE_GET_SECOND(self));
6464
0
    }
6465
0
    else {
6466
0
        baserepr = PyUnicode_FromFormat(
6467
0
                      "%s(%d, %d, %d, %d, %d)",
6468
0
                      type_name,
6469
0
                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
6470
0
                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
6471
0
    }
6472
0
    if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
6473
0
        baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
6474
0
    if (baserepr == NULL || ! HASTZINFO(self))
6475
0
        return baserepr;
6476
0
    return append_keyword_tzinfo(baserepr, self->tzinfo);
6477
0
}
6478
6479
static PyObject *
6480
datetime_str(PyObject *op)
6481
0
{
6482
0
    PyObject *space = PyUnicode_FromString(" ");
6483
0
    if (space == NULL) {
6484
0
        return NULL;
6485
0
    }
6486
0
    PyObject *res = PyObject_CallMethodOneArg(op, &_Py_ID(isoformat), space);
6487
0
    Py_DECREF(space);
6488
0
    return res;
6489
0
}
6490
6491
/*[clinic input]
6492
datetime.datetime.isoformat
6493
6494
    sep: int(accept={str}) = 'T'
6495
    timespec: str(c_default="NULL") = 'auto'
6496
6497
Return the time formatted according to ISO.
6498
6499
The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'.
6500
By default, the fractional part is omitted if self.microsecond == 0.
6501
6502
If self.tzinfo is not None, the UTC offset is also attached, giving
6503
a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'.
6504
6505
Optional argument sep specifies the separator between date and
6506
time, default 'T'.
6507
6508
The optional argument timespec specifies the number of additional
6509
terms of the time to include. Valid options are 'auto', 'hours',
6510
'minutes', 'seconds', 'milliseconds' and 'microseconds'.
6511
[clinic start generated code]*/
6512
6513
static PyObject *
6514
datetime_datetime_isoformat_impl(PyDateTime_DateTime *self, int sep,
6515
                                 const char *timespec)
6516
/*[clinic end generated code: output=9b6ce1383189b0bf input=db935a57fa697c5e]*/
6517
0
{
6518
0
    char buffer[100];
6519
6520
0
    PyObject *result = NULL;
6521
0
    int us = DATE_GET_MICROSECOND(self);
6522
0
    static const char * const specs[][2] = {
6523
0
        {"hours", "%04d-%02d-%02d%c%02d"},
6524
0
        {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
6525
0
        {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
6526
0
        {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
6527
0
        {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
6528
0
    };
6529
0
    size_t given_spec;
6530
6531
0
    if (timespec == NULL || strcmp(timespec, "auto") == 0) {
6532
0
        if (us == 0) {
6533
            /* seconds */
6534
0
            given_spec = 2;
6535
0
        }
6536
0
        else {
6537
            /* microseconds */
6538
0
            given_spec = 4;
6539
0
        }
6540
0
    }
6541
0
    else {
6542
0
        for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
6543
0
            if (strcmp(timespec, specs[given_spec][0]) == 0) {
6544
0
                if (given_spec == 3) {
6545
0
                    us = us / 1000;
6546
0
                }
6547
0
                break;
6548
0
            }
6549
0
        }
6550
0
    }
6551
6552
0
    if (given_spec == Py_ARRAY_LENGTH(specs)) {
6553
0
        PyErr_Format(PyExc_ValueError, "Unknown timespec value");
6554
0
        return NULL;
6555
0
    }
6556
0
    else {
6557
0
        result = PyUnicode_FromFormat(specs[given_spec][1],
6558
0
                                      GET_YEAR(self), GET_MONTH(self),
6559
0
                                      GET_DAY(self), (int)sep,
6560
0
                                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
6561
0
                                      DATE_GET_SECOND(self), us);
6562
0
    }
6563
6564
0
    if (!result || !HASTZINFO(self))
6565
0
        return result;
6566
6567
    /* We need to append the UTC offset. */
6568
0
    if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo, (PyObject *)self) < 0) {
6569
0
        Py_DECREF(result);
6570
0
        return NULL;
6571
0
    }
6572
0
    PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
6573
0
    return result;
6574
0
}
6575
6576
static PyObject *
6577
datetime_ctime(PyObject *op, PyObject *Py_UNUSED(dummy))
6578
0
{
6579
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
6580
0
    return format_ctime(op,
6581
0
                        DATE_GET_HOUR(self),
6582
0
                        DATE_GET_MINUTE(self),
6583
0
                        DATE_GET_SECOND(self));
6584
0
}
6585
6586
/* Miscellaneous methods. */
6587
6588
static PyObject *
6589
flip_fold(PyObject *dt)
6590
0
{
6591
0
    return new_datetime_ex2(GET_YEAR(dt),
6592
0
                            GET_MONTH(dt),
6593
0
                            GET_DAY(dt),
6594
0
                            DATE_GET_HOUR(dt),
6595
0
                            DATE_GET_MINUTE(dt),
6596
0
                            DATE_GET_SECOND(dt),
6597
0
                            DATE_GET_MICROSECOND(dt),
6598
0
                            HASTZINFO(dt) ?
6599
0
                             ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
6600
0
                            !DATE_GET_FOLD(dt),
6601
0
                            Py_TYPE(dt));
6602
0
}
6603
6604
static PyObject *
6605
get_flip_fold_offset(PyObject *dt)
6606
0
{
6607
0
    PyObject *result, *flip_dt;
6608
6609
0
    flip_dt = flip_fold(dt);
6610
0
    if (flip_dt == NULL)
6611
0
        return NULL;
6612
0
    result = datetime_utcoffset(flip_dt, NULL);
6613
0
    Py_DECREF(flip_dt);
6614
0
    return result;
6615
0
}
6616
6617
/* PEP 495 exception: Whenever one or both of the operands in
6618
 * inter-zone comparison is such that its utcoffset() depends
6619
 * on the value of its fold attribute, the result is False.
6620
 *
6621
 * Return 1 if exception applies, 0 if not,  and -1 on error.
6622
 */
6623
static int
6624
pep495_eq_exception(PyObject *self, PyObject *other,
6625
                    PyObject *offset_self, PyObject *offset_other)
6626
0
{
6627
0
    int result = 0;
6628
0
    PyObject *flip_offset;
6629
6630
0
    flip_offset = get_flip_fold_offset(self);
6631
0
    if (flip_offset == NULL)
6632
0
        return -1;
6633
0
    if (flip_offset != offset_self &&
6634
0
        delta_cmp(flip_offset, offset_self))
6635
0
    {
6636
0
        result = 1;
6637
0
        goto done;
6638
0
    }
6639
0
    Py_DECREF(flip_offset);
6640
6641
0
    flip_offset = get_flip_fold_offset(other);
6642
0
    if (flip_offset == NULL)
6643
0
        return -1;
6644
0
    if (flip_offset != offset_other &&
6645
0
        delta_cmp(flip_offset, offset_other))
6646
0
        result = 1;
6647
0
 done:
6648
0
    Py_DECREF(flip_offset);
6649
0
    return result;
6650
0
}
6651
6652
static PyObject *
6653
datetime_richcompare(PyObject *self, PyObject *other, int op)
6654
0
{
6655
0
    PyObject *result = NULL;
6656
0
    PyObject *offset1, *offset2;
6657
0
    int diff;
6658
6659
0
    if (!PyDateTime_Check(other)) {
6660
0
        Py_RETURN_NOTIMPLEMENTED;
6661
0
    }
6662
6663
0
    if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
6664
0
        diff = memcmp(((PyDateTime_DateTime *)self)->data,
6665
0
                      ((PyDateTime_DateTime *)other)->data,
6666
0
                      _PyDateTime_DATETIME_DATASIZE);
6667
0
        return diff_to_bool(diff, op);
6668
0
    }
6669
0
    offset1 = datetime_utcoffset(self, NULL);
6670
0
    if (offset1 == NULL)
6671
0
        return NULL;
6672
0
    offset2 = datetime_utcoffset(other, NULL);
6673
0
    if (offset2 == NULL)
6674
0
        goto done;
6675
    /* If they're both naive, or both aware and have the same offsets,
6676
     * we get off cheap.  Note that if they're both naive, offset1 ==
6677
     * offset2 == Py_None at this point.
6678
     */
6679
0
    if ((offset1 == offset2) ||
6680
0
        (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
6681
0
         delta_cmp(offset1, offset2) == 0)) {
6682
0
        diff = memcmp(((PyDateTime_DateTime *)self)->data,
6683
0
                      ((PyDateTime_DateTime *)other)->data,
6684
0
                      _PyDateTime_DATETIME_DATASIZE);
6685
0
        if ((op == Py_EQ || op == Py_NE) && diff == 0) {
6686
0
            int ex = pep495_eq_exception(self, other, offset1, offset2);
6687
0
            if (ex == -1)
6688
0
                goto done;
6689
0
            if (ex)
6690
0
                diff = 1;
6691
0
        }
6692
0
        result = diff_to_bool(diff, op);
6693
0
    }
6694
0
    else if (offset1 != Py_None && offset2 != Py_None) {
6695
0
        PyDateTime_Delta *delta;
6696
6697
0
        assert(offset1 != offset2); /* else last "if" handled it */
6698
0
        delta = (PyDateTime_Delta *)datetime_subtract(self, other);
6699
0
        if (delta == NULL)
6700
0
            goto done;
6701
0
        diff = GET_TD_DAYS(delta);
6702
0
        if (diff == 0)
6703
0
            diff = GET_TD_SECONDS(delta) |
6704
0
                   GET_TD_MICROSECONDS(delta);
6705
0
        Py_DECREF(delta);
6706
0
        if ((op == Py_EQ || op == Py_NE) && diff == 0) {
6707
0
            int ex = pep495_eq_exception(self, other, offset1, offset2);
6708
0
            if (ex == -1)
6709
0
                goto done;
6710
0
            if (ex)
6711
0
                diff = 1;
6712
0
        }
6713
0
        result = diff_to_bool(diff, op);
6714
0
    }
6715
0
    else if (op == Py_EQ) {
6716
0
        result = Py_NewRef(Py_False);
6717
0
    }
6718
0
    else if (op == Py_NE) {
6719
0
        result = Py_NewRef(Py_True);
6720
0
    }
6721
0
    else {
6722
0
        PyErr_SetString(PyExc_TypeError,
6723
0
                        "can't compare offset-naive and "
6724
0
                        "offset-aware datetimes");
6725
0
    }
6726
0
 done:
6727
0
    Py_DECREF(offset1);
6728
0
    Py_XDECREF(offset2);
6729
0
    return result;
6730
0
}
6731
6732
static Py_hash_t
6733
datetime_hash(PyObject *op)
6734
0
{
6735
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
6736
0
    Py_hash_t hash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->hashcode);
6737
0
    if (hash == -1) {
6738
0
        PyObject *offset, *self0;
6739
0
        if (DATE_GET_FOLD(self)) {
6740
0
            self0 = new_datetime_ex2(GET_YEAR(self),
6741
0
                                     GET_MONTH(self),
6742
0
                                     GET_DAY(self),
6743
0
                                     DATE_GET_HOUR(self),
6744
0
                                     DATE_GET_MINUTE(self),
6745
0
                                     DATE_GET_SECOND(self),
6746
0
                                     DATE_GET_MICROSECOND(self),
6747
0
                                     HASTZINFO(self) ? self->tzinfo : Py_None,
6748
0
                                     0, Py_TYPE(self));
6749
0
            if (self0 == NULL)
6750
0
                return -1;
6751
0
        }
6752
0
        else {
6753
0
            self0 = Py_NewRef(self);
6754
0
        }
6755
0
        offset = datetime_utcoffset(self0, NULL);
6756
0
        Py_DECREF(self0);
6757
6758
0
        if (offset == NULL)
6759
0
            return -1;
6760
6761
        /* Reduce this to a hash of another object. */
6762
0
        if (offset == Py_None) {
6763
0
            hash = generic_hash(
6764
0
                (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
6765
0
            FT_ATOMIC_STORE_SSIZE_RELAXED(self->hashcode, hash);
6766
0
        } else {
6767
0
            PyObject *temp1, *temp2;
6768
0
            int days, seconds;
6769
6770
0
            assert(HASTZINFO(self));
6771
0
            days = ymd_to_ord(GET_YEAR(self),
6772
0
                              GET_MONTH(self),
6773
0
                              GET_DAY(self));
6774
0
            seconds = DATE_GET_HOUR(self) * 3600 +
6775
0
                      DATE_GET_MINUTE(self) * 60 +
6776
0
                      DATE_GET_SECOND(self);
6777
0
            temp1 = new_delta(days, seconds,
6778
0
                              DATE_GET_MICROSECOND(self),
6779
0
                              1);
6780
0
            if (temp1 == NULL) {
6781
0
                Py_DECREF(offset);
6782
0
                return -1;
6783
0
            }
6784
0
            temp2 = delta_subtract(temp1, offset);
6785
0
            Py_DECREF(temp1);
6786
0
            if (temp2 == NULL) {
6787
0
                Py_DECREF(offset);
6788
0
                return -1;
6789
0
            }
6790
0
            hash = PyObject_Hash(temp2);
6791
0
            FT_ATOMIC_STORE_SSIZE_RELAXED(self->hashcode, hash);
6792
0
            Py_DECREF(temp2);
6793
0
        }
6794
0
        Py_DECREF(offset);
6795
0
    }
6796
0
    return hash;
6797
0
}
6798
6799
/*[clinic input]
6800
datetime.datetime.replace
6801
6802
    year: int(c_default="GET_YEAR(self)") = unchanged
6803
    month: int(c_default="GET_MONTH(self)") = unchanged
6804
    day: int(c_default="GET_DAY(self)") = unchanged
6805
    hour: int(c_default="DATE_GET_HOUR(self)") = unchanged
6806
    minute: int(c_default="DATE_GET_MINUTE(self)") = unchanged
6807
    second: int(c_default="DATE_GET_SECOND(self)") = unchanged
6808
    microsecond: int(c_default="DATE_GET_MICROSECOND(self)") = unchanged
6809
    tzinfo: object(c_default="HASTZINFO(self) ? ((PyDateTime_DateTime *)self)->tzinfo : Py_None") = unchanged
6810
    *
6811
    fold: int(c_default="DATE_GET_FOLD(self)") = unchanged
6812
6813
Return datetime with new specified fields.
6814
[clinic start generated code]*/
6815
6816
static PyObject *
6817
datetime_datetime_replace_impl(PyDateTime_DateTime *self, int year,
6818
                               int month, int day, int hour, int minute,
6819
                               int second, int microsecond, PyObject *tzinfo,
6820
                               int fold)
6821
/*[clinic end generated code: output=00bc96536833fddb input=fd972762d604d3e7]*/
6822
0
{
6823
0
    return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
6824
0
                                         second, microsecond, tzinfo, fold,
6825
0
                                         Py_TYPE(self));
6826
0
}
6827
6828
static PyObject *
6829
local_timezone_from_timestamp(time_t timestamp)
6830
0
{
6831
0
    PyObject *result = NULL;
6832
0
    PyObject *delta;
6833
0
    struct tm local_time_tm;
6834
0
    PyObject *nameo = NULL;
6835
0
    const char *zone = NULL;
6836
#ifndef HAVE_STRUCT_TM_TM_ZONE
6837
    char buf[100];  // for zone, which is used after the block below
6838
#endif
6839
6840
0
    if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
6841
0
        return NULL;
6842
0
#ifdef HAVE_STRUCT_TM_TM_ZONE
6843
0
    zone = local_time_tm.tm_zone;
6844
0
    delta = new_delta(0, local_time_tm.tm_gmtoff, 0, 1);
6845
#else /* HAVE_STRUCT_TM_TM_ZONE */
6846
    {
6847
        PyObject *local_time, *utc_time;
6848
        struct tm utc_time_tm;
6849
        if (strftime(buf, sizeof(buf), "%Z", &local_time_tm) != 0) {
6850
            zone = buf;
6851
        }
6852
        local_time = new_datetime(local_time_tm.tm_year + 1900,
6853
                                  local_time_tm.tm_mon + 1,
6854
                                  local_time_tm.tm_mday,
6855
                                  local_time_tm.tm_hour,
6856
                                  local_time_tm.tm_min,
6857
                                  local_time_tm.tm_sec, 0, Py_None, 0);
6858
        if (local_time == NULL) {
6859
            return NULL;
6860
        }
6861
        if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0) {
6862
            Py_DECREF(local_time);
6863
            return NULL;
6864
        }
6865
        utc_time = new_datetime(utc_time_tm.tm_year + 1900,
6866
                                utc_time_tm.tm_mon + 1,
6867
                                utc_time_tm.tm_mday,
6868
                                utc_time_tm.tm_hour,
6869
                                utc_time_tm.tm_min,
6870
                                utc_time_tm.tm_sec, 0, Py_None, 0);
6871
        if (utc_time == NULL) {
6872
            Py_DECREF(local_time);
6873
            return NULL;
6874
        }
6875
        delta = datetime_subtract(local_time, utc_time);
6876
        Py_DECREF(local_time);
6877
        Py_DECREF(utc_time);
6878
    }
6879
#endif /* HAVE_STRUCT_TM_TM_ZONE */
6880
0
    if (delta == NULL) {
6881
0
            return NULL;
6882
0
    }
6883
0
    if (zone != NULL) {
6884
0
        nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
6885
0
        if (nameo == NULL)
6886
0
            goto error;
6887
0
    }
6888
0
    result = new_timezone(delta, nameo);
6889
0
    Py_XDECREF(nameo);
6890
0
  error:
6891
0
    Py_DECREF(delta);
6892
0
    return result;
6893
0
}
6894
6895
static PyObject *
6896
local_timezone(PyDateTime_DateTime *utc_time)
6897
0
{
6898
0
    time_t timestamp;
6899
0
    PyObject *delta;
6900
0
    PyObject *one_second;
6901
0
    PyObject *seconds;
6902
6903
0
    PyObject *current_mod;
6904
0
    datetime_state *st = GET_CURRENT_STATE(current_mod);
6905
0
    if (st == NULL) {
6906
0
        return NULL;
6907
0
    }
6908
6909
0
    delta = datetime_subtract((PyObject *)utc_time, CONST_EPOCH(st));
6910
0
    RELEASE_CURRENT_STATE(st, current_mod);
6911
0
    if (delta == NULL)
6912
0
        return NULL;
6913
6914
0
    one_second = new_delta(0, 1, 0, 0);
6915
0
    if (one_second == NULL) {
6916
0
        Py_DECREF(delta);
6917
0
        return NULL;
6918
0
    }
6919
0
    seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
6920
0
                                         (PyDateTime_Delta *)one_second);
6921
0
    Py_DECREF(one_second);
6922
0
    Py_DECREF(delta);
6923
0
    if (seconds == NULL)
6924
0
        return NULL;
6925
0
    timestamp = _PyLong_AsTime_t(seconds);
6926
0
    Py_DECREF(seconds);
6927
0
    if (timestamp == -1 && PyErr_Occurred())
6928
0
        return NULL;
6929
0
    return local_timezone_from_timestamp(timestamp);
6930
0
}
6931
6932
static long long
6933
local_to_seconds(int year, int month, int day,
6934
                 int hour, int minute, int second, int fold);
6935
6936
static PyObject *
6937
local_timezone_from_local(PyDateTime_DateTime *local_dt)
6938
0
{
6939
0
    long long seconds, seconds2;
6940
0
    time_t timestamp;
6941
0
    int fold = DATE_GET_FOLD(local_dt);
6942
0
    seconds = local_to_seconds(GET_YEAR(local_dt),
6943
0
                               GET_MONTH(local_dt),
6944
0
                               GET_DAY(local_dt),
6945
0
                               DATE_GET_HOUR(local_dt),
6946
0
                               DATE_GET_MINUTE(local_dt),
6947
0
                               DATE_GET_SECOND(local_dt),
6948
0
                               fold);
6949
0
    if (seconds == -1)
6950
0
        return NULL;
6951
0
    seconds2 = local_to_seconds(GET_YEAR(local_dt),
6952
0
                                GET_MONTH(local_dt),
6953
0
                                GET_DAY(local_dt),
6954
0
                                DATE_GET_HOUR(local_dt),
6955
0
                                DATE_GET_MINUTE(local_dt),
6956
0
                                DATE_GET_SECOND(local_dt),
6957
0
                                !fold);
6958
0
    if (seconds2 == -1)
6959
0
        return NULL;
6960
    /* Detect gap */
6961
0
    if (seconds2 != seconds && (seconds2 > seconds) == fold)
6962
0
        seconds = seconds2;
6963
6964
    /* XXX: add bounds check */
6965
0
    timestamp = seconds - epoch;
6966
0
    return local_timezone_from_timestamp(timestamp);
6967
0
}
6968
6969
/*[clinic input]
6970
datetime.datetime.astimezone
6971
6972
    tz as tzinfo: object = None
6973
6974
Convert to local time in new timezone tz.
6975
[clinic start generated code]*/
6976
6977
static PyObject *
6978
datetime_datetime_astimezone_impl(PyDateTime_DateTime *self,
6979
                                  PyObject *tzinfo)
6980
/*[clinic end generated code: output=ae2263d04e944537 input=9c675c8595009935]*/
6981
0
{
6982
0
    PyDateTime_DateTime *result;
6983
0
    PyObject *offset;
6984
0
    PyObject *temp;
6985
0
    PyObject *self_tzinfo;
6986
6987
0
    if (check_tzinfo_subclass(tzinfo) == -1)
6988
0
        return NULL;
6989
6990
0
    if (!HASTZINFO(self) || self->tzinfo == Py_None) {
6991
0
  naive:
6992
0
        self_tzinfo = local_timezone_from_local(self);
6993
0
        if (self_tzinfo == NULL)
6994
0
            return NULL;
6995
0
    } else {
6996
0
        self_tzinfo = Py_NewRef(self->tzinfo);
6997
0
    }
6998
6999
    /* Conversion to self's own time zone is a NOP. */
7000
0
    if (self_tzinfo == tzinfo) {
7001
0
        Py_DECREF(self_tzinfo);
7002
0
        return Py_NewRef(self);
7003
0
    }
7004
7005
    /* Convert self to UTC. */
7006
0
    offset = call_utcoffset(self_tzinfo, (PyObject *)self);
7007
0
    Py_DECREF(self_tzinfo);
7008
0
    if (offset == NULL)
7009
0
        return NULL;
7010
0
    else if(offset == Py_None) {
7011
0
        Py_DECREF(offset);
7012
0
        goto naive;
7013
0
    }
7014
0
    else if (!PyDelta_Check(offset)) {
7015
0
        PyErr_Format(PyExc_TypeError, "utcoffset() returned %T,"
7016
0
                     " expected timedelta or None", offset);
7017
0
        Py_DECREF(offset);
7018
0
        return NULL;
7019
0
    }
7020
    /* result = self - offset */
7021
0
    result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
7022
0
                                       (PyDateTime_Delta *)offset, -1);
7023
0
    Py_DECREF(offset);
7024
0
    if (result == NULL)
7025
0
        return NULL;
7026
7027
    /* Make sure result is aware and UTC. */
7028
0
    if (!HASTZINFO(result)) {
7029
0
        temp = (PyObject *)result;
7030
0
        result = (PyDateTime_DateTime *)
7031
0
                   new_datetime_ex2(GET_YEAR(result),
7032
0
                                    GET_MONTH(result),
7033
0
                                    GET_DAY(result),
7034
0
                                    DATE_GET_HOUR(result),
7035
0
                                    DATE_GET_MINUTE(result),
7036
0
                                    DATE_GET_SECOND(result),
7037
0
                                    DATE_GET_MICROSECOND(result),
7038
0
                                    CONST_UTC(NO_STATE),
7039
0
                                    DATE_GET_FOLD(result),
7040
0
                                    Py_TYPE(result));
7041
0
        Py_DECREF(temp);
7042
0
        if (result == NULL)
7043
0
            return NULL;
7044
0
    }
7045
0
    else {
7046
        /* Result is already aware - just replace tzinfo. */
7047
0
        Py_SETREF(result->tzinfo, Py_NewRef(CONST_UTC(NO_STATE)));
7048
0
    }
7049
7050
    /* Attach new tzinfo and let fromutc() do the rest. */
7051
0
    if (tzinfo == Py_None) {
7052
0
        tzinfo = local_timezone(result);
7053
0
        if (tzinfo == NULL) {
7054
0
            Py_DECREF(result);
7055
0
            return NULL;
7056
0
        }
7057
0
    }
7058
0
    else
7059
0
      Py_INCREF(tzinfo);
7060
0
    Py_SETREF(result->tzinfo, tzinfo);
7061
7062
0
    temp = (PyObject *)result;
7063
0
    result = (PyDateTime_DateTime *)
7064
0
        PyObject_CallMethodOneArg(tzinfo, &_Py_ID(fromutc), temp);
7065
0
    Py_DECREF(temp);
7066
7067
0
    return (PyObject *)result;
7068
0
}
7069
7070
static PyObject *
7071
datetime_timetuple(PyObject *op, PyObject *Py_UNUSED(dummy))
7072
0
{
7073
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
7074
0
    int dstflag = -1;
7075
7076
0
    if (HASTZINFO(self) && self->tzinfo != Py_None) {
7077
0
        PyObject * dst;
7078
7079
0
        dst = call_dst(self->tzinfo, op);
7080
0
        if (dst == NULL)
7081
0
            return NULL;
7082
7083
0
        if (dst != Py_None)
7084
0
            dstflag = delta_bool(dst);
7085
0
        Py_DECREF(dst);
7086
0
    }
7087
0
    return build_struct_time(GET_YEAR(self),
7088
0
                             GET_MONTH(self),
7089
0
                             GET_DAY(self),
7090
0
                             DATE_GET_HOUR(self),
7091
0
                             DATE_GET_MINUTE(self),
7092
0
                             DATE_GET_SECOND(self),
7093
0
                             dstflag);
7094
0
}
7095
7096
static long long
7097
local_to_seconds(int year, int month, int day,
7098
                 int hour, int minute, int second, int fold)
7099
0
{
7100
0
    long long t, a, b, u1, u2, t1, t2, lt;
7101
0
    t = utc_to_seconds(year, month, day, hour, minute, second);
7102
    /* Our goal is to solve t = local(u) for u. */
7103
0
    lt = local(t);
7104
0
    if (lt == -1)
7105
0
        return -1;
7106
0
    a = lt - t;
7107
0
    u1 = t - a;
7108
0
    t1 = local(u1);
7109
0
    if (t1 == -1)
7110
0
        return -1;
7111
0
    if (t1 == t) {
7112
        /* We found one solution, but it may not be the one we need.
7113
         * Look for an earlier solution (if `fold` is 0), or a
7114
         * later one (if `fold` is 1). */
7115
0
        if (fold)
7116
0
            u2 = u1 + max_fold_seconds;
7117
0
        else
7118
0
            u2 = u1 - max_fold_seconds;
7119
0
        lt = local(u2);
7120
0
        if (lt == -1)
7121
0
            return -1;
7122
0
        b = lt - u2;
7123
0
        if (a == b)
7124
0
            return u1;
7125
0
    }
7126
0
    else {
7127
0
        b = t1 - u1;
7128
0
        assert(a != b);
7129
0
    }
7130
0
    u2 = t - b;
7131
0
    t2 = local(u2);
7132
0
    if (t2 == -1)
7133
0
        return -1;
7134
0
    if (t2 == t)
7135
0
        return u2;
7136
0
    if (t1 == t)
7137
0
        return u1;
7138
    /* We have found both offsets a and b, but neither t - a nor t - b is
7139
     * a solution.  This means t is in the gap. */
7140
0
    return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
7141
0
}
7142
7143
/* date(1970,1,1).toordinal() == 719163 */
7144
0
#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
7145
7146
static PyObject *
7147
datetime_timestamp(PyObject *op, PyObject *Py_UNUSED(dummy))
7148
0
{
7149
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
7150
0
    PyObject *result;
7151
7152
0
    if (HASTZINFO(self) && self->tzinfo != Py_None) {
7153
0
        PyObject *current_mod;
7154
0
        datetime_state *st = GET_CURRENT_STATE(current_mod);
7155
0
        if (st == NULL) {
7156
0
            return NULL;
7157
0
        }
7158
7159
0
        PyObject *delta;
7160
0
        delta = datetime_subtract(op, CONST_EPOCH(st));
7161
0
        RELEASE_CURRENT_STATE(st, current_mod);
7162
0
        if (delta == NULL)
7163
0
            return NULL;
7164
0
        result = delta_total_seconds(delta, NULL);
7165
0
        Py_DECREF(delta);
7166
0
    }
7167
0
    else {
7168
0
        long long seconds;
7169
0
        seconds = local_to_seconds(GET_YEAR(self),
7170
0
                                   GET_MONTH(self),
7171
0
                                   GET_DAY(self),
7172
0
                                   DATE_GET_HOUR(self),
7173
0
                                   DATE_GET_MINUTE(self),
7174
0
                                   DATE_GET_SECOND(self),
7175
0
                                   DATE_GET_FOLD(self));
7176
0
        if (seconds == -1)
7177
0
            return NULL;
7178
0
        result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
7179
0
                                    DATE_GET_MICROSECOND(self) / 1e6);
7180
0
    }
7181
0
    return result;
7182
0
}
7183
7184
static PyObject *
7185
datetime_getdate(PyObject *op, PyObject *Py_UNUSED(dummy))
7186
0
{
7187
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
7188
0
    return new_date(GET_YEAR(self),
7189
0
                    GET_MONTH(self),
7190
0
                    GET_DAY(self));
7191
0
}
7192
7193
static PyObject *
7194
datetime_gettime(PyObject *op, PyObject *Py_UNUSED(dummy))
7195
0
{
7196
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
7197
0
    return new_time(DATE_GET_HOUR(self),
7198
0
                    DATE_GET_MINUTE(self),
7199
0
                    DATE_GET_SECOND(self),
7200
0
                    DATE_GET_MICROSECOND(self),
7201
0
                    Py_None,
7202
0
                    DATE_GET_FOLD(self));
7203
0
}
7204
7205
static PyObject *
7206
datetime_gettimetz(PyObject *op, PyObject *Py_UNUSED(dummy))
7207
0
{
7208
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
7209
0
    return new_time(DATE_GET_HOUR(self),
7210
0
                    DATE_GET_MINUTE(self),
7211
0
                    DATE_GET_SECOND(self),
7212
0
                    DATE_GET_MICROSECOND(self),
7213
0
                    GET_DT_TZINFO(self),
7214
0
                    DATE_GET_FOLD(self));
7215
0
}
7216
7217
static PyObject *
7218
datetime_utctimetuple(PyObject *op, PyObject *Py_UNUSED(dummy))
7219
0
{
7220
0
    int y, m, d, hh, mm, ss;
7221
0
    PyObject *tzinfo;
7222
0
    PyDateTime_DateTime *utcself;
7223
0
    PyDateTime_DateTime *self = PyDateTime_CAST(op);
7224
7225
0
    tzinfo = GET_DT_TZINFO(self);
7226
0
    if (tzinfo == Py_None) {
7227
0
        utcself = (PyDateTime_DateTime*)Py_NewRef(self);
7228
0
    }
7229
0
    else {
7230
0
        PyObject *offset;
7231
0
        offset = call_utcoffset(tzinfo, (PyObject *)self);
7232
0
        if (offset == NULL)
7233
0
            return NULL;
7234
0
        if (offset == Py_None) {
7235
0
            Py_DECREF(offset);
7236
0
            utcself = (PyDateTime_DateTime*)Py_NewRef(self);
7237
0
        }
7238
0
        else {
7239
0
            utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
7240
0
                                                (PyDateTime_Delta *)offset, -1);
7241
0
            Py_DECREF(offset);
7242
0
            if (utcself == NULL)
7243
0
                return NULL;
7244
0
        }
7245
0
    }
7246
0
    y = GET_YEAR(utcself);
7247
0
    m = GET_MONTH(utcself);
7248
0
    d = GET_DAY(utcself);
7249
0
    hh = DATE_GET_HOUR(utcself);
7250
0
    mm = DATE_GET_MINUTE(utcself);
7251
0
    ss = DATE_GET_SECOND(utcself);
7252
7253
0
    Py_DECREF(utcself);
7254
0
    return build_struct_time(y, m, d, hh, mm, ss, 0);
7255
0
}
7256
7257
/* Pickle support, a simple use of __reduce__. */
7258
7259
/* Let basestate be the non-tzinfo data string.
7260
 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
7261
 * So it's a tuple in any (non-error) case.
7262
 * __getstate__ isn't exposed.
7263
 */
7264
static PyObject *
7265
datetime_getstate(PyDateTime_DateTime *self, int proto)
7266
0
{
7267
0
    PyObject *basestate;
7268
0
    PyObject *result = NULL;
7269
7270
0
    basestate = PyBytes_FromStringAndSize((char *)self->data,
7271
0
                                           _PyDateTime_DATETIME_DATASIZE);
7272
0
    if (basestate != NULL) {
7273
0
        if (proto > 3 && DATE_GET_FOLD(self))
7274
            /* Set the first bit of the third byte */
7275
0
            PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
7276
0
        if (! HASTZINFO(self) || self->tzinfo == Py_None)
7277
0
            result = PyTuple_Pack(1, basestate);
7278
0
        else
7279
0
            result = _PyTuple_FromPair(basestate, self->tzinfo);
7280
0
        Py_DECREF(basestate);
7281
0
    }
7282
0
    return result;
7283
0
}
7284
7285
/*[clinic input]
7286
datetime.datetime.__reduce_ex__
7287
7288
    proto: int
7289
    /
7290
[clinic start generated code]*/
7291
7292
static PyObject *
7293
datetime_datetime___reduce_ex___impl(PyDateTime_DateTime *self, int proto)
7294
/*[clinic end generated code: output=53d712ce3e927735 input=bab748e49ffb30c3]*/
7295
0
{
7296
0
    return Py_BuildValue("(ON)", Py_TYPE(self),
7297
0
                         datetime_getstate(self, proto));
7298
0
}
7299
7300
/*[clinic input]
7301
datetime.datetime.__reduce__
7302
[clinic start generated code]*/
7303
7304
static PyObject *
7305
datetime_datetime___reduce___impl(PyDateTime_DateTime *self)
7306
/*[clinic end generated code: output=6794df9ea75666cf input=cadbbeb3bf3bf94c]*/
7307
0
{
7308
0
    return Py_BuildValue("(ON)", Py_TYPE(self),
7309
0
                         datetime_getstate(self, 2));
7310
0
}
7311
7312
static PyMethodDef datetime_methods[] = {
7313
7314
    /* Class methods: */
7315
7316
    DATETIME_DATETIME_NOW_METHODDEF
7317
    DATETIME_DATETIME_UTCNOW_METHODDEF
7318
    DATETIME_DATETIME_FROMTIMESTAMP_METHODDEF
7319
    DATETIME_DATETIME_UTCFROMTIMESTAMP_METHODDEF
7320
    DATETIME_DATETIME_STRPTIME_METHODDEF
7321
    DATETIME_DATETIME_COMBINE_METHODDEF
7322
    DATETIME_DATETIME_FROMISOFORMAT_METHODDEF
7323
7324
    /* Instance methods: */
7325
7326
    {"date", datetime_getdate, METH_NOARGS,
7327
     PyDoc_STR("Return date object with same year, month and day.")},
7328
7329
    {"time", datetime_gettime, METH_NOARGS,
7330
     PyDoc_STR("Return time object with same time but with tzinfo=None.")},
7331
7332
    {"timetz", datetime_gettimetz, METH_NOARGS,
7333
     PyDoc_STR("Return time object with same time and tzinfo.")},
7334
7335
    {"ctime", datetime_ctime, METH_NOARGS,
7336
     PyDoc_STR("Return ctime() style string.")},
7337
7338
    {"timetuple", datetime_timetuple, METH_NOARGS,
7339
     PyDoc_STR("Return time tuple, compatible with time.localtime().")},
7340
7341
    {"timestamp", datetime_timestamp, METH_NOARGS,
7342
     PyDoc_STR("Return POSIX timestamp as float.")},
7343
7344
    {"utctimetuple", datetime_utctimetuple, METH_NOARGS,
7345
     PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
7346
7347
    DATETIME_DATETIME_ISOFORMAT_METHODDEF
7348
7349
    {"utcoffset", datetime_utcoffset, METH_NOARGS,
7350
     PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
7351
7352
    {"tzname", datetime_tzname,   METH_NOARGS,
7353
     PyDoc_STR("Return self.tzinfo.tzname(self).")},
7354
7355
    {"dst", datetime_dst, METH_NOARGS,
7356
     PyDoc_STR("Return self.tzinfo.dst(self).")},
7357
7358
    DATETIME_DATETIME_REPLACE_METHODDEF
7359
7360
    {"__replace__", _PyCFunction_CAST(datetime_datetime_replace), METH_FASTCALL | METH_KEYWORDS,
7361
     PyDoc_STR("__replace__($self, /, **changes)\n--\n\nThe same as replace().")},
7362
7363
    DATETIME_DATETIME_ASTIMEZONE_METHODDEF
7364
    DATETIME_DATETIME___REDUCE_EX___METHODDEF
7365
    DATETIME_DATETIME___REDUCE___METHODDEF
7366
7367
    {NULL,      NULL}
7368
};
7369
7370
static PyNumberMethods datetime_as_number = {
7371
    datetime_add,                               /* nb_add */
7372
    datetime_subtract,                          /* nb_subtract */
7373
    0,                                          /* nb_multiply */
7374
    0,                                          /* nb_remainder */
7375
    0,                                          /* nb_divmod */
7376
    0,                                          /* nb_power */
7377
    0,                                          /* nb_negative */
7378
    0,                                          /* nb_positive */
7379
    0,                                          /* nb_absolute */
7380
    0,                                          /* nb_bool */
7381
};
7382
7383
static PyTypeObject PyDateTime_DateTimeType = {
7384
    PyVarObject_HEAD_INIT(NULL, 0)
7385
    "datetime.datetime",                        /* tp_name */
7386
    sizeof(PyDateTime_DateTime),                /* tp_basicsize */
7387
    0,                                          /* tp_itemsize */
7388
    datetime_dealloc,                           /* tp_dealloc */
7389
    0,                                          /* tp_vectorcall_offset */
7390
    0,                                          /* tp_getattr */
7391
    0,                                          /* tp_setattr */
7392
    0,                                          /* tp_as_async */
7393
    datetime_repr,                              /* tp_repr */
7394
    &datetime_as_number,                        /* tp_as_number */
7395
    0,                                          /* tp_as_sequence */
7396
    0,                                          /* tp_as_mapping */
7397
    datetime_hash,                              /* tp_hash */
7398
    0,                                          /* tp_call */
7399
    datetime_str,                               /* tp_str */
7400
    PyObject_GenericGetAttr,                    /* tp_getattro */
7401
    0,                                          /* tp_setattro */
7402
    0,                                          /* tp_as_buffer */
7403
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   /* tp_flags */
7404
    datetime_datetime__doc__,                   /* tp_doc */
7405
    0,                                          /* tp_traverse */
7406
    0,                                          /* tp_clear */
7407
    datetime_richcompare,                       /* tp_richcompare */
7408
    0,                                          /* tp_weaklistoffset */
7409
    0,                                          /* tp_iter */
7410
    0,                                          /* tp_iternext */
7411
    datetime_methods,                           /* tp_methods */
7412
    0,                                          /* tp_members */
7413
    datetime_getset,                            /* tp_getset */
7414
    &PyDateTime_DateType,                       /* tp_base */
7415
    0,                                          /* tp_dict */
7416
    0,                                          /* tp_descr_get */
7417
    0,                                          /* tp_descr_set */
7418
    0,                                          /* tp_dictoffset */
7419
    0,                                          /* tp_init */
7420
    datetime_alloc,                             /* tp_alloc */
7421
    datetime_new,                               /* tp_new */
7422
    0,                                          /* tp_free */
7423
};
7424
7425
/* ---------------------------------------------------------------------------
7426
 * datetime C-API.
7427
 */
7428
7429
static PyTypeObject * const capi_types[] = {
7430
    &PyDateTime_DateType,
7431
    &PyDateTime_DateTimeType,
7432
    &PyDateTime_TimeType,
7433
    &PyDateTime_DeltaType,
7434
    &PyDateTime_TZInfoType,
7435
    /* Indirectly, via the utc object. */
7436
    &PyDateTime_TimeZoneType,
7437
};
7438
7439
/* The C-API is process-global.  This violates interpreter isolation
7440
 * due to the objects stored here.  Thus each of those objects must
7441
 * be managed carefully. */
7442
// XXX Can we make this const?
7443
static PyDateTime_CAPI capi = {
7444
    /* The classes must be readied before used here.
7445
     * That will happen the first time the module is loaded.
7446
     * They aren't safe to be shared between interpreters,
7447
     * but that's okay as long as the module is single-phase init. */
7448
    .DateType = &PyDateTime_DateType,
7449
    .DateTimeType = &PyDateTime_DateTimeType,
7450
    .TimeType = &PyDateTime_TimeType,
7451
    .DeltaType = &PyDateTime_DeltaType,
7452
    .TZInfoType = &PyDateTime_TZInfoType,
7453
7454
    .TimeZone_UTC = (PyObject *)&utc_timezone,
7455
7456
    .Date_FromDate = new_date_ex,
7457
    .DateTime_FromDateAndTime = new_datetime_ex,
7458
    .Time_FromTime = new_time_ex,
7459
    .Delta_FromDelta = new_delta_ex,
7460
    .TimeZone_FromTimeZone = new_timezone,
7461
    .DateTime_FromTimestamp = datetime_datetime_fromtimestamp_capi,
7462
    .Date_FromTimestamp = datetime_date_fromtimestamp_capi,
7463
    .DateTime_FromDateAndTimeAndFold = new_datetime_ex2,
7464
    .Time_FromTimeAndFold = new_time_ex2,
7465
};
7466
7467
/* Get a new C API by calling this function.
7468
 * Clients get at C API via PyDateTime_IMPORT, defined in datetime.h.
7469
 */
7470
static inline PyDateTime_CAPI *
7471
get_datetime_capi(void)
7472
0
{
7473
0
    return &capi;
7474
0
}
7475
7476
static PyObject *
7477
create_timezone_from_delta(int days, int sec, int ms, int normalize)
7478
44
{
7479
44
    PyObject *delta = new_delta(days, sec, ms, normalize);
7480
44
    if (delta == NULL) {
7481
0
        return NULL;
7482
0
    }
7483
44
    PyObject *tz = create_timezone(delta, NULL);
7484
44
    Py_DECREF(delta);
7485
44
    return tz;
7486
44
}
7487
7488
7489
/* ---------------------------------------------------------------------------
7490
 * Module state lifecycle.
7491
 */
7492
7493
static int
7494
init_state(datetime_state *st, PyObject *module, PyObject *old_module)
7495
0
{
7496
    /* Each module gets its own heap types. */
7497
0
#define ADD_TYPE(FIELD, SPEC, BASE)                 \
7498
0
    do {                                            \
7499
0
        PyObject *cls = PyType_FromModuleAndSpec(   \
7500
0
                module, SPEC, (PyObject *)BASE);    \
7501
0
        if (cls == NULL) {                          \
7502
0
            return -1;                              \
7503
0
        }                                           \
7504
0
        st->FIELD = (PyTypeObject *)cls;            \
7505
0
    } while (0)
7506
7507
0
    ADD_TYPE(isocalendar_date_type, &isocal_spec, &PyTuple_Type);
7508
0
#undef ADD_TYPE
7509
7510
0
    if (old_module != NULL) {
7511
0
        assert(old_module != module);
7512
0
        datetime_state *st_old = get_module_state(old_module);
7513
0
        *st = (datetime_state){
7514
0
            .isocalendar_date_type = st->isocalendar_date_type,
7515
0
            .us_per_ms = Py_NewRef(st_old->us_per_ms),
7516
0
            .us_per_second = Py_NewRef(st_old->us_per_second),
7517
0
            .us_per_minute = Py_NewRef(st_old->us_per_minute),
7518
0
            .us_per_hour = Py_NewRef(st_old->us_per_hour),
7519
0
            .us_per_day = Py_NewRef(st_old->us_per_day),
7520
0
            .us_per_week = Py_NewRef(st_old->us_per_week),
7521
0
            .seconds_per_day = Py_NewRef(st_old->seconds_per_day),
7522
0
            .epoch = Py_NewRef(st_old->epoch),
7523
0
            .time_struct_time = Py_NewRef(st_old->time_struct_time),
7524
0
            .time_strftime = Py_NewRef(st_old->time_strftime),
7525
0
        };
7526
0
        return 0;
7527
0
    }
7528
7529
0
    st->us_per_ms = PyLong_FromLong(1000);
7530
0
    if (st->us_per_ms == NULL) {
7531
0
        return -1;
7532
0
    }
7533
0
    st->us_per_second = PyLong_FromLong(1000000);
7534
0
    if (st->us_per_second == NULL) {
7535
0
        return -1;
7536
0
    }
7537
0
    st->us_per_minute = PyLong_FromLong(60000000);
7538
0
    if (st->us_per_minute == NULL) {
7539
0
        return -1;
7540
0
    }
7541
0
    st->seconds_per_day = PyLong_FromLong(24 * 3600);
7542
0
    if (st->seconds_per_day == NULL) {
7543
0
        return -1;
7544
0
    }
7545
7546
    /* The rest are too big for 32-bit ints, but even
7547
     * us_per_week fits in 40 bits, so doubles should be exact.
7548
     */
7549
0
    st->us_per_hour = PyLong_FromDouble(3600000000.0);
7550
0
    if (st->us_per_hour == NULL) {
7551
0
        return -1;
7552
0
    }
7553
0
    st->us_per_day = PyLong_FromDouble(86400000000.0);
7554
0
    if (st->us_per_day == NULL) {
7555
0
        return -1;
7556
0
    }
7557
0
    st->us_per_week = PyLong_FromDouble(604800000000.0);
7558
0
    if (st->us_per_week == NULL) {
7559
0
        return -1;
7560
0
    }
7561
7562
    /* Init Unix epoch */
7563
0
    st->epoch = new_datetime(
7564
0
            1970, 1, 1, 0, 0, 0, 0, (PyObject *)&utc_timezone, 0);
7565
0
    if (st->epoch == NULL) {
7566
0
        return -1;
7567
0
    }
7568
7569
0
    st->time_struct_time = PyImport_ImportModuleAttrString("time", "struct_time");
7570
0
    if (st->time_struct_time == NULL) {
7571
0
        return -1;
7572
0
    }
7573
0
    st->time_strftime = PyImport_ImportModuleAttrString("time", "strftime");
7574
0
    if (st->time_strftime == NULL) {
7575
0
        return -1;
7576
0
    }
7577
7578
0
    return 0;
7579
0
}
7580
7581
static int
7582
traverse_state(datetime_state *st, visitproc visit, void *arg)
7583
0
{
7584
    /* heap types */
7585
0
    Py_VISIT(st->isocalendar_date_type);
7586
7587
0
    Py_VISIT(st->time_struct_time);
7588
0
    Py_VISIT(st->time_strftime);
7589
7590
0
    return 0;
7591
0
}
7592
7593
static int
7594
clear_state(datetime_state *st)
7595
0
{
7596
0
    Py_CLEAR(st->isocalendar_date_type);
7597
0
    Py_CLEAR(st->us_per_ms);
7598
0
    Py_CLEAR(st->us_per_second);
7599
0
    Py_CLEAR(st->us_per_minute);
7600
0
    Py_CLEAR(st->us_per_hour);
7601
0
    Py_CLEAR(st->us_per_day);
7602
0
    Py_CLEAR(st->us_per_week);
7603
0
    Py_CLEAR(st->seconds_per_day);
7604
0
    Py_CLEAR(st->epoch);
7605
0
    Py_CLEAR(st->time_struct_time);
7606
0
    Py_CLEAR(st->time_strftime);
7607
0
    return 0;
7608
0
}
7609
7610
7611
PyStatus
7612
_PyDateTime_InitTypes(PyInterpreterState *interp)
7613
22
{
7614
    /* Bases classes must be initialized before subclasses,
7615
     * so capi_types must have the types in the appropriate order. */
7616
154
    for (size_t i = 0; i < Py_ARRAY_LENGTH(capi_types); i++) {
7617
132
        PyTypeObject *type = capi_types[i];
7618
132
        if (_PyStaticType_InitForExtension(interp, type) < 0) {
7619
0
            return _PyStatus_ERR("could not initialize static types");
7620
0
        }
7621
132
    }
7622
7623
22
#define DATETIME_ADD_MACRO(dict, c, value_expr)         \
7624
308
    do {                                                \
7625
308
        assert(!PyErr_Occurred());                      \
7626
308
        PyObject *value = (value_expr);                 \
7627
308
        if (value == NULL) {                            \
7628
0
            goto error;                                 \
7629
0
        }                                               \
7630
308
        if (PyDict_SetItemString(dict, c, value) < 0) { \
7631
0
            Py_DECREF(value);                           \
7632
0
            goto error;                                 \
7633
0
        }                                               \
7634
308
        Py_DECREF(value);                               \
7635
308
    } while(0)
7636
7637
    /* timedelta values */
7638
22
    PyObject *d = _PyType_GetDict(&PyDateTime_DeltaType);
7639
22
    DATETIME_ADD_MACRO(d, "resolution", new_delta(0, 0, 1, 0));
7640
22
    DATETIME_ADD_MACRO(d, "min", new_delta(-MAX_DELTA_DAYS, 0, 0, 0));
7641
22
    DATETIME_ADD_MACRO(d, "max",
7642
22
                        new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0));
7643
7644
    /* date values */
7645
22
    d = _PyType_GetDict(&PyDateTime_DateType);
7646
22
    DATETIME_ADD_MACRO(d, "min", new_date(1, 1, 1));
7647
22
    DATETIME_ADD_MACRO(d, "max", new_date(MAXYEAR, 12, 31));
7648
22
    DATETIME_ADD_MACRO(d, "resolution", new_delta(1, 0, 0, 0));
7649
7650
    /* time values */
7651
22
    d = _PyType_GetDict(&PyDateTime_TimeType);
7652
22
    DATETIME_ADD_MACRO(d, "min", new_time(0, 0, 0, 0, Py_None, 0));
7653
22
    DATETIME_ADD_MACRO(d, "max", new_time(23, 59, 59, 999999, Py_None, 0));
7654
22
    DATETIME_ADD_MACRO(d, "resolution", new_delta(0, 0, 1, 0));
7655
7656
    /* datetime values */
7657
22
    d = _PyType_GetDict(&PyDateTime_DateTimeType);
7658
22
    DATETIME_ADD_MACRO(d, "min",
7659
22
                        new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0));
7660
22
    DATETIME_ADD_MACRO(d, "max", new_datetime(MAXYEAR, 12, 31, 23, 59, 59,
7661
22
                                                999999, Py_None, 0));
7662
22
    DATETIME_ADD_MACRO(d, "resolution", new_delta(0, 0, 1, 0));
7663
7664
    /* timezone values */
7665
22
    d = _PyType_GetDict(&PyDateTime_TimeZoneType);
7666
22
    if (PyDict_SetItemString(d, "utc", (PyObject *)&utc_timezone) < 0) {
7667
0
        goto error;
7668
0
    }
7669
7670
    /* bpo-37642: These attributes are rounded to the nearest minute for backwards
7671
    * compatibility, even though the constructor will accept a wider range of
7672
    * values. This may change in the future.*/
7673
7674
    /* -23:59 */
7675
22
    DATETIME_ADD_MACRO(d, "min", create_timezone_from_delta(-1, 60, 0, 1));
7676
7677
    /* +23:59 */
7678
22
    DATETIME_ADD_MACRO(
7679
22
            d, "max", create_timezone_from_delta(0, (23 * 60 + 59) * 60, 0, 0));
7680
7681
22
#undef DATETIME_ADD_MACRO
7682
7683
22
    return _PyStatus_OK();
7684
7685
0
error:
7686
0
    return _PyStatus_NO_MEMORY();
7687
22
}
7688
7689
7690
/* ---------------------------------------------------------------------------
7691
 * Module methods and initialization.
7692
 */
7693
7694
static PyMethodDef module_methods[] = {
7695
    {NULL, NULL}
7696
};
7697
7698
7699
static int
7700
_datetime_exec(PyObject *module)
7701
0
{
7702
0
    int rc = -1;
7703
0
    datetime_state *st = get_module_state(module);
7704
7705
0
    PyInterpreterState *interp = PyInterpreterState_Get();
7706
0
    PyObject *old_module;
7707
0
    if (get_current_module(interp, &old_module) < 0) {
7708
0
        goto error;
7709
0
    }
7710
    /* We actually set the "current" module right before a successful return. */
7711
7712
0
    for (size_t i = 0; i < Py_ARRAY_LENGTH(capi_types); i++) {
7713
0
        PyTypeObject *type = capi_types[i];
7714
0
        const char *name = _PyType_Name(type);
7715
0
        assert(name != NULL);
7716
0
        if (PyModule_AddObjectRef(module, name, (PyObject *)type) < 0) {
7717
0
            goto error;
7718
0
        }
7719
0
    }
7720
7721
0
    if (init_state(st, module, old_module) < 0) {
7722
0
        goto error;
7723
0
    }
7724
7725
    /* Add module level attributes */
7726
0
    if (PyModule_AddIntMacro(module, MINYEAR) < 0) {
7727
0
        goto error;
7728
0
    }
7729
0
    if (PyModule_AddIntMacro(module, MAXYEAR) < 0) {
7730
0
        goto error;
7731
0
    }
7732
0
    if (PyModule_AddObjectRef(module, "UTC", (PyObject *)&utc_timezone) < 0) {
7733
0
        goto error;
7734
0
    }
7735
7736
    /* At last, set up and add the encapsulated C API */
7737
0
    PyDateTime_CAPI *capi = get_datetime_capi();
7738
0
    if (capi == NULL) {
7739
0
        goto error;
7740
0
    }
7741
0
    PyObject *capsule = PyCapsule_New(capi, PyDateTime_CAPSULE_NAME, NULL);
7742
    // (capsule == NULL) is handled by PyModule_Add
7743
0
    if (PyModule_Add(module, "datetime_CAPI", capsule) < 0) {
7744
0
        goto error;
7745
0
    }
7746
7747
    /* A 4-year cycle has an extra leap day over what we'd get from
7748
     * pasting together 4 single years.
7749
     */
7750
0
    static_assert(DI4Y == 4 * 365 + 1, "DI4Y");
7751
0
    assert(DI4Y == _PyTime_DaysBeforeYear(4+1));
7752
7753
    /* Similarly, a 400-year cycle has an extra leap day over what we'd
7754
     * get from pasting together 4 100-year cycles.
7755
     */
7756
0
    static_assert(DI400Y == 4 * DI100Y + 1, "DI400Y");
7757
0
    assert(DI400Y == _PyTime_DaysBeforeYear(400+1));
7758
7759
    /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
7760
     * pasting together 25 4-year cycles.
7761
     */
7762
0
    static_assert(DI100Y == 25 * DI4Y - 1, "DI100Y");
7763
0
    assert(DI100Y == _PyTime_DaysBeforeYear(100+1));
7764
7765
0
    if (set_current_module(interp, module) < 0) {
7766
0
        goto error;
7767
0
    }
7768
7769
0
    rc = 0;
7770
0
    goto finally;
7771
7772
0
error:
7773
0
    clear_state(st);
7774
7775
0
finally:
7776
0
    Py_XDECREF(old_module);
7777
0
    return rc;
7778
0
}
7779
7780
static PyModuleDef_Slot module_slots[] = {
7781
    _Py_ABI_SLOT,
7782
    {Py_mod_exec, _datetime_exec},
7783
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
7784
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
7785
    {0, NULL},
7786
};
7787
7788
static int
7789
module_traverse(PyObject *mod, visitproc visit, void *arg)
7790
0
{
7791
0
    datetime_state *st = get_module_state(mod);
7792
0
    traverse_state(st, visit, arg);
7793
0
    return 0;
7794
0
}
7795
7796
static int
7797
module_clear(PyObject *mod)
7798
0
{
7799
0
    datetime_state *st = get_module_state(mod);
7800
0
    clear_state(st);
7801
7802
0
    PyInterpreterState *interp = PyInterpreterState_Get();
7803
0
    clear_current_module(interp, mod);
7804
7805
    // The runtime takes care of the static types for us.
7806
    // See _PyTypes_FiniExtTypes()..
7807
7808
0
    return 0;
7809
0
}
7810
7811
static void
7812
module_free(void *mod)
7813
0
{
7814
0
    (void)module_clear((PyObject *)mod);
7815
0
}
7816
7817
static PyModuleDef datetimemodule = {
7818
    .m_base = PyModuleDef_HEAD_INIT,
7819
    .m_name = "_datetime",
7820
    .m_doc = "Fast implementation of the datetime module.",
7821
    .m_size = sizeof(datetime_state),
7822
    .m_methods = module_methods,
7823
    .m_slots = module_slots,
7824
    .m_traverse = module_traverse,
7825
    .m_clear = module_clear,
7826
    .m_free = module_free,
7827
};
7828
7829
PyMODINIT_FUNC
7830
PyInit__datetime(void)
7831
0
{
7832
0
    return PyModuleDef_Init(&datetimemodule);
7833
0
}
7834
7835
/* ---------------------------------------------------------------------------
7836
Some time zone algebra.  For a datetime x, let
7837
    x.n = x stripped of its timezone -- its naive time.
7838
    x.o = x.utcoffset(), and assuming that doesn't raise an exception or
7839
      return None
7840
    x.d = x.dst(), and assuming that doesn't raise an exception or
7841
      return None
7842
    x.s = x's standard offset, x.o - x.d
7843
7844
Now some derived rules, where k is a duration (timedelta).
7845
7846
1. x.o = x.s + x.d
7847
   This follows from the definition of x.s.
7848
7849
2. If x and y have the same tzinfo member, x.s = y.s.
7850
   This is actually a requirement, an assumption we need to make about
7851
   sane tzinfo classes.
7852
7853
3. The naive UTC time corresponding to x is x.n - x.o.
7854
   This is again a requirement for a sane tzinfo class.
7855
7856
4. (x+k).s = x.s
7857
   This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
7858
7859
5. (x+k).n = x.n + k
7860
   Again follows from how arithmetic is defined.
7861
7862
Now we can explain tz.fromutc(x).  Let's assume it's an interesting case
7863
(meaning that the various tzinfo methods exist, and don't blow up or return
7864
None when called).
7865
7866
The function wants to return a datetime y with timezone tz, equivalent to x.
7867
x is already in UTC.
7868
7869
By #3, we want
7870
7871
    y.n - y.o = x.n                             [1]
7872
7873
The algorithm starts by attaching tz to x.n, and calling that y.  So
7874
x.n = y.n at the start.  Then it wants to add a duration k to y, so that [1]
7875
becomes true; in effect, we want to solve [2] for k:
7876
7877
   (y+k).n - (y+k).o = x.n                      [2]
7878
7879
By #1, this is the same as
7880
7881
   (y+k).n - ((y+k).s + (y+k).d) = x.n          [3]
7882
7883
By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
7884
Substituting that into [3],
7885
7886
   x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
7887
   k - (y+k).s - (y+k).d = 0; rearranging,
7888
   k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
7889
   k = y.s - (y+k).d
7890
7891
On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
7892
approximate k by ignoring the (y+k).d term at first.  Note that k can't be
7893
very large, since all offset-returning methods return a duration of magnitude
7894
less than 24 hours.  For that reason, if y is firmly in std time, (y+k).d must
7895
be 0, so ignoring it has no consequence then.
7896
7897
In any case, the new value is
7898
7899
    z = y + y.s                                 [4]
7900
7901
It's helpful to step back at look at [4] from a higher level:  it's simply
7902
mapping from UTC to tz's standard time.
7903
7904
At this point, if
7905
7906
    z.n - z.o = x.n                             [5]
7907
7908
we have an equivalent time, and are almost done.  The insecurity here is
7909
at the start of daylight time.  Picture US Eastern for concreteness.  The wall
7910
time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
7911
sense then.  The docs ask that an Eastern tzinfo class consider such a time to
7912
be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
7913
on the day DST starts.  We want to return the 1:MM EST spelling because that's
7914
the only spelling that makes sense on the local wall clock.
7915
7916
In fact, if [5] holds at this point, we do have the standard-time spelling,
7917
but that takes a bit of proof.  We first prove a stronger result.  What's the
7918
difference between the LHS and RHS of [5]?  Let
7919
7920
    diff = x.n - (z.n - z.o)                    [6]
7921
7922
Now
7923
    z.n =                       by [4]
7924
    (y + y.s).n =               by #5
7925
    y.n + y.s =                 since y.n = x.n
7926
    x.n + y.s =                 since z and y are have the same tzinfo member,
7927
                                    y.s = z.s by #2
7928
    x.n + z.s
7929
7930
Plugging that back into [6] gives
7931
7932
    diff =
7933
    x.n - ((x.n + z.s) - z.o) =     expanding
7934
    x.n - x.n - z.s + z.o =         cancelling
7935
    - z.s + z.o =                   by #2
7936
    z.d
7937
7938
So diff = z.d.
7939
7940
If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
7941
spelling we wanted in the endcase described above.  We're done.  Contrarily,
7942
if z.d = 0, then we have a UTC equivalent, and are also done.
7943
7944
If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
7945
add to z (in effect, z is in tz's standard time, and we need to shift the
7946
local clock into tz's daylight time).
7947
7948
Let
7949
7950
    z' = z + z.d = z + diff                     [7]
7951
7952
and we can again ask whether
7953
7954
    z'.n - z'.o = x.n                           [8]
7955
7956
If so, we're done.  If not, the tzinfo class is insane, according to the
7957
assumptions we've made.  This also requires a bit of proof.  As before, let's
7958
compute the difference between the LHS and RHS of [8] (and skipping some of
7959
the justifications for the kinds of substitutions we've done several times
7960
already):
7961
7962
    diff' = x.n - (z'.n - z'.o) =           replacing z'.n via [7]
7963
        x.n  - (z.n + diff - z'.o) =    replacing diff via [6]
7964
        x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
7965
        x.n - z.n - x.n + z.n - z.o + z'.o =    cancel x.n
7966
        - z.n + z.n - z.o + z'.o =              cancel z.n
7967
        - z.o + z'.o =                      #1 twice
7968
        -z.s - z.d + z'.s + z'.d =          z and z' have same tzinfo
7969
        z'.d - z.d
7970
7971
So z' is UTC-equivalent to x iff z'.d = z.d at this point.  If they are equal,
7972
we've found the UTC-equivalent so are done.  In fact, we stop with [7] and
7973
return z', not bothering to compute z'.d.
7974
7975
How could z.d and z'd differ?  z' = z + z.d [7], so merely moving z' by
7976
a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
7977
would have to change the result dst() returns:  we start in DST, and moving
7978
a little further into it takes us out of DST.
7979
7980
There isn't a sane case where this can happen.  The closest it gets is at
7981
the end of DST, where there's an hour in UTC with no spelling in a hybrid
7982
tzinfo class.  In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT.  During
7983
that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
7984
UTC) because the docs insist on that, but 0:MM is taken as being in daylight
7985
time (4:MM UTC).  There is no local time mapping to 5:MM UTC.  The local
7986
clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
7987
standard time.  Since that's what the local clock *does*, we want to map both
7988
UTC hours 5:MM and 6:MM to 1:MM Eastern.  The result is ambiguous
7989
in local time, but so it goes -- it's the way the local clock works.
7990
7991
When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
7992
so z=0:MM.  z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
7993
z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
7994
(correctly) concludes that z' is not UTC-equivalent to x.
7995
7996
Because we know z.d said z was in daylight time (else [5] would have held and
7997
we would have stopped then), and we know z.d != z'.d (else [8] would have held
7998
and we would have stopped then), and there are only 2 possible values dst() can
7999
return in Eastern, it follows that z'.d must be 0 (which it is in the example,
8000
but the reasoning doesn't depend on the example -- it depends on there being
8001
two possible dst() outcomes, one zero and the other non-zero).  Therefore
8002
z' must be in standard time, and is the spelling we want in this case.
8003
8004
Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
8005
concerned (because it takes z' as being in standard time rather than the
8006
daylight time we intend here), but returning it gives the real-life "local
8007
clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
8008
tz.
8009
8010
When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
8011
the 1:MM standard time spelling we want.
8012
8013
So how can this break?  One of the assumptions must be violated.  Two
8014
possibilities:
8015
8016
1) [2] effectively says that y.s is invariant across all y belong to a given
8017
   time zone.  This isn't true if, for political reasons or continental drift,
8018
   a region decides to change its base offset from UTC.
8019
8020
2) There may be versions of "double daylight" time where the tail end of
8021
   the analysis gives up a step too early.  I haven't thought about that
8022
   enough to say.
8023
8024
In any case, it's clear that the default fromutc() is strong enough to handle
8025
"almost all" time zones:  so long as the standard offset is invariant, it
8026
doesn't matter if daylight time transition points change from year to year, or
8027
if daylight time is skipped in some years; it doesn't matter how large or
8028
small dst() may get within its bounds; and it doesn't even matter if some
8029
perverse time zone returns a negative dst()).  So a breaking case must be
8030
pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
8031
--------------------------------------------------------------------------- */