blob: beb1c3cfbca969c96d2b7785b699834ec9c28989 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
Paul Ganssle0d126722018-11-13 03:02:25 -05005/* bpo-35081: Defining this prevents including the C API capsule;
6 * internal versions of the Py*_Check macros which do not require
7 * the capsule are defined below */
8#define _PY_DATETIME_IMPL
9
Tim Peters2a799bf2002-12-16 20:18:38 +000010#include "Python.h"
Paul Ganssle0d126722018-11-13 03:02:25 -050011#include "datetime.h"
Tim Peters2a799bf2002-12-16 20:18:38 +000012#include "structmember.h"
13
14#include <time.h>
15
Victor Stinner09e5cf22015-03-30 00:09:18 +020016#ifdef MS_WINDOWS
17# include <winsock2.h> /* struct timeval */
18#endif
19
Paul Ganssle0d126722018-11-13 03:02:25 -050020#define PyDate_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateType)
21#define PyDate_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DateType)
22
23#define PyDateTime_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateTimeType)
24#define PyDateTime_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DateTimeType)
25
26#define PyTime_Check(op) PyObject_TypeCheck(op, &PyDateTime_TimeType)
27#define PyTime_CheckExact(op) (Py_TYPE(op) == &PyDateTime_TimeType)
28
29#define PyDelta_Check(op) PyObject_TypeCheck(op, &PyDateTime_DeltaType)
30#define PyDelta_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DeltaType)
31
32#define PyTZInfo_Check(op) PyObject_TypeCheck(op, &PyDateTime_TZInfoType)
33#define PyTZInfo_CheckExact(op) (Py_TYPE(op) == &PyDateTime_TZInfoType)
34
Tim Peters2a799bf2002-12-16 20:18:38 +000035
Larry Hastings61272b72014-01-07 12:41:53 -080036/*[clinic input]
Larry Hastings44e2eaa2013-11-23 15:37:55 -080037module datetime
Larry Hastingsc2047262014-01-25 20:43:29 -080038class datetime.datetime "PyDateTime_DateTime *" "&PyDateTime_DateTimeType"
Tim Hoffmanna0fd7f12018-09-24 10:39:02 +020039class datetime.date "PyDateTime_Date *" "&PyDateTime_DateType"
Larry Hastings61272b72014-01-07 12:41:53 -080040[clinic start generated code]*/
Tim Hoffmanna0fd7f12018-09-24 10:39:02 +020041/*[clinic end generated code: output=da39a3ee5e6b4b0d input=25138ad6a696b785]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080042
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030043#include "clinic/_datetimemodule.c.h"
44
Tim Peters2a799bf2002-12-16 20:18:38 +000045/* We require that C int be at least 32 bits, and use int virtually
46 * everywhere. In just a few cases we use a temp long, where a Python
47 * API returns a C long. In such cases, we have to ensure that the
48 * final result fits in a C int (this can be an issue on 64-bit boxes).
49 */
50#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000051# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000052#endif
53
54#define MINYEAR 1
55#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000056#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000057
58/* Nine decimal digits is easy to communicate, and leaves enough room
59 * so that two delta days can be added w/o fear of overflowing a signed
60 * 32-bit int, and with plenty of room left over to absorb any possible
61 * carries from adding seconds.
62 */
63#define MAX_DELTA_DAYS 999999999
64
65/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066#define GET_YEAR PyDateTime_GET_YEAR
67#define GET_MONTH PyDateTime_GET_MONTH
68#define GET_DAY PyDateTime_GET_DAY
69#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
70#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
71#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
72#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040073#define DATE_GET_FOLD PyDateTime_DATE_GET_FOLD
Tim Peters2a799bf2002-12-16 20:18:38 +000074
75/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
77 ((o)->data[1] = ((v) & 0x00ff)))
78#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
79#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000080
81/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
83#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
84#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
85#define DATE_SET_MICROSECOND(o, v) \
86 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
87 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
88 ((o)->data[9] = ((v) & 0x0000ff)))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040089#define DATE_SET_FOLD(o, v) (PyDateTime_DATE_GET_FOLD(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000090
91/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
93#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
94#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
95#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040096#define TIME_GET_FOLD PyDateTime_TIME_GET_FOLD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
98#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
99#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
100#define TIME_SET_MICROSECOND(o, v) \
101 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
102 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
103 ((o)->data[5] = ((v) & 0x0000ff)))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400104#define TIME_SET_FOLD(o, v) (PyDateTime_TIME_GET_FOLD(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +0000105
106/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
108#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
109#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111#define SET_TD_DAYS(o, v) ((o)->days = (v))
112#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +0000113#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
114
Tim Petersa032d2e2003-01-11 00:15:54 +0000115/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
116 * p->hastzinfo.
117 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000118#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
119#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
120 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
121#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
122 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +0000123/* M is a char or int claiming to be a valid month. The macro is equivalent
124 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +0000126 */
127#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
128
Tim Peters2a799bf2002-12-16 20:18:38 +0000129/* Forward declarations. */
130static PyTypeObject PyDateTime_DateType;
131static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000132static PyTypeObject PyDateTime_DeltaType;
133static PyTypeObject PyDateTime_TimeType;
134static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000135static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000136
Victor Stinnerb67f0962017-02-10 10:34:02 +0100137static int check_tzinfo_subclass(PyObject *p);
138
Martin v. Löwise75fc142013-11-07 18:46:53 +0100139_Py_IDENTIFIER(as_integer_ratio);
140_Py_IDENTIFIER(fromutc);
141_Py_IDENTIFIER(isoformat);
142_Py_IDENTIFIER(strftime);
143
Tim Peters2a799bf2002-12-16 20:18:38 +0000144/* ---------------------------------------------------------------------------
145 * Math utilities.
146 */
147
148/* k = i+j overflows iff k differs in sign from both inputs,
149 * iff k^i has sign bit set and k^j has sign bit set,
150 * iff (k^i)&(k^j) has sign bit set.
151 */
152#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000154
155/* Compute Python divmod(x, y), returning the quotient and storing the
156 * remainder into *r. The quotient is the floor of x/y, and that's
157 * the real point of this. C will probably truncate instead (C99
158 * requires truncation; C89 left it implementation-defined).
159 * Simplification: we *require* that y > 0 here. That's appropriate
160 * for all the uses made of it. This simplifies the code and makes
161 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
162 * overflow case).
163 */
164static int
165divmod(int x, int y, int *r)
166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 assert(y > 0);
170 quo = x / y;
171 *r = x - quo * y;
172 if (*r < 0) {
173 --quo;
174 *r += y;
175 }
176 assert(0 <= *r && *r < y);
177 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000178}
179
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000180/* Nearest integer to m / n for integers m and n. Half-integer results
181 * are rounded to even.
182 */
183static PyObject *
184divide_nearest(PyObject *m, PyObject *n)
185{
186 PyObject *result;
187 PyObject *temp;
188
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000189 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000190 if (temp == NULL)
191 return NULL;
192 result = PyTuple_GET_ITEM(temp, 0);
193 Py_INCREF(result);
194 Py_DECREF(temp);
195
196 return result;
197}
198
Tim Peters2a799bf2002-12-16 20:18:38 +0000199/* ---------------------------------------------------------------------------
200 * General calendrical helper functions
201 */
202
203/* For each month ordinal in 1..12, the number of days in that month,
204 * and the number of days before that month in the same year. These
205 * are correct for non-leap years only.
206 */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200207static const int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 0, /* unused; this vector uses 1-based indexing */
209 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000210};
211
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200212static const int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 0, /* unused; this vector uses 1-based indexing */
214 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000215};
216
217/* year -> 1 if leap year, else 0. */
218static int
219is_leap(int year)
220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 /* Cast year to unsigned. The result is the same either way, but
222 * C can generate faster code for unsigned mod than for signed
223 * mod (especially for % 4 -- a good compiler should just grab
224 * the last 2 bits when the LHS is unsigned).
225 */
226 const unsigned int ayear = (unsigned int)year;
227 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000228}
229
230/* year, month -> number of days in that month in that year */
231static int
232days_in_month(int year, int month)
233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 assert(month >= 1);
235 assert(month <= 12);
236 if (month == 2 && is_leap(year))
237 return 29;
238 else
239 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000240}
241
Martin Panter46f50722016-05-26 05:35:26 +0000242/* year, month -> number of days in year preceding first day of month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000243static int
244days_before_month(int year, int month)
245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 assert(month >= 1);
249 assert(month <= 12);
250 days = _days_before_month[month];
251 if (month > 2 && is_leap(year))
252 ++days;
253 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000254}
255
256/* year -> number of days before January 1st of year. Remember that we
257 * start with year 1, so days_before_year(1) == 0.
258 */
259static int
260days_before_year(int year)
261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 int y = year - 1;
263 /* This is incorrect if year <= 0; we really want the floor
264 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000265 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000267 assert (year >= 1);
268 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000269}
270
271/* Number of days in 4, 100, and 400 year cycles. That these have
272 * the correct values is asserted in the module init function.
273 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274#define DI4Y 1461 /* days_before_year(5); days in 4 years */
275#define DI100Y 36524 /* days_before_year(101); days in 100 years */
276#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000277
278/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
279static void
280ord_to_ymd(int ordinal, int *year, int *month, int *day)
281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
285 * leap years repeats exactly every 400 years. The basic strategy is
286 * to find the closest 400-year boundary at or before ordinal, then
287 * work with the offset from that boundary to ordinal. Life is much
288 * clearer if we subtract 1 from ordinal first -- then the values
289 * of ordinal at 400-year boundaries are exactly those divisible
290 * by DI400Y:
291 *
292 * D M Y n n-1
293 * -- --- ---- ---------- ----------------
294 * 31 Dec -400 -DI400Y -DI400Y -1
295 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
296 * ...
297 * 30 Dec 000 -1 -2
298 * 31 Dec 000 0 -1
299 * 1 Jan 001 1 0 400-year boundary
300 * 2 Jan 001 2 1
301 * 3 Jan 001 3 2
302 * ...
303 * 31 Dec 400 DI400Y DI400Y -1
304 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
305 */
306 assert(ordinal >= 1);
307 --ordinal;
308 n400 = ordinal / DI400Y;
309 n = ordinal % DI400Y;
310 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 /* Now n is the (non-negative) offset, in days, from January 1 of
313 * year, to the desired date. Now compute how many 100-year cycles
314 * precede n.
315 * Note that it's possible for n100 to equal 4! In that case 4 full
316 * 100-year cycles precede the desired day, which implies the
317 * desired day is December 31 at the end of a 400-year cycle.
318 */
319 n100 = n / DI100Y;
320 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 /* Now compute how many 4-year cycles precede it. */
323 n4 = n / DI4Y;
324 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 /* And now how many single years. Again n1 can be 4, and again
327 * meaning that the desired day is December 31 at the end of the
328 * 4-year cycle.
329 */
330 n1 = n / 365;
331 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 *year += n100 * 100 + n4 * 4 + n1;
334 if (n1 == 4 || n100 == 4) {
335 assert(n == 0);
336 *year -= 1;
337 *month = 12;
338 *day = 31;
339 return;
340 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 /* Now the year is correct, and n is the offset from January 1. We
343 * find the month via an estimate that's either exact or one too
344 * large.
345 */
346 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
347 assert(leapyear == is_leap(*year));
348 *month = (n + 50) >> 5;
349 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
350 if (preceding > n) {
351 /* estimate is too large */
352 *month -= 1;
353 preceding -= days_in_month(*year, *month);
354 }
355 n -= preceding;
356 assert(0 <= n);
357 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000360}
361
362/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
363static int
364ymd_to_ord(int year, int month, int day)
365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000367}
368
369/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
370static int
371weekday(int year, int month, int day)
372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000374}
375
376/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
377 * first calendar week containing a Thursday.
378 */
379static int
380iso_week1_monday(int year)
381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
383 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
384 int first_weekday = (first_day + 6) % 7;
385 /* ordinal of closest Monday at or before 1/1 */
386 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
389 week1_monday += 7;
390 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000391}
392
393/* ---------------------------------------------------------------------------
394 * Range checkers.
395 */
396
397/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
398 * If not, raise OverflowError and return -1.
399 */
400static int
401check_delta_day_range(int days)
402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
404 return 0;
405 PyErr_Format(PyExc_OverflowError,
406 "days=%d; must have magnitude <= %d",
407 days, MAX_DELTA_DAYS);
408 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000409}
410
411/* Check that date arguments are in range. Return 0 if they are. If they
412 * aren't, raise ValueError and return -1.
413 */
414static int
415check_date_args(int year, int month, int day)
416{
417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (year < MINYEAR || year > MAXYEAR) {
Victor Stinnerb67f0962017-02-10 10:34:02 +0100419 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 return -1;
421 }
422 if (month < 1 || month > 12) {
423 PyErr_SetString(PyExc_ValueError,
424 "month must be in 1..12");
425 return -1;
426 }
427 if (day < 1 || day > days_in_month(year, month)) {
428 PyErr_SetString(PyExc_ValueError,
429 "day is out of range for month");
430 return -1;
431 }
432 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000433}
434
435/* Check that time arguments are in range. Return 0 if they are. If they
436 * aren't, raise ValueError and return -1.
437 */
438static int
Alexander Belopolsky47649ab2016-08-08 17:05:40 -0400439check_time_args(int h, int m, int s, int us, int fold)
Tim Peters2a799bf2002-12-16 20:18:38 +0000440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (h < 0 || h > 23) {
442 PyErr_SetString(PyExc_ValueError,
443 "hour must be in 0..23");
444 return -1;
445 }
446 if (m < 0 || m > 59) {
447 PyErr_SetString(PyExc_ValueError,
448 "minute must be in 0..59");
449 return -1;
450 }
451 if (s < 0 || s > 59) {
452 PyErr_SetString(PyExc_ValueError,
453 "second must be in 0..59");
454 return -1;
455 }
456 if (us < 0 || us > 999999) {
457 PyErr_SetString(PyExc_ValueError,
458 "microsecond must be in 0..999999");
459 return -1;
460 }
Alexander Belopolsky47649ab2016-08-08 17:05:40 -0400461 if (fold != 0 && fold != 1) {
462 PyErr_SetString(PyExc_ValueError,
463 "fold must be either 0 or 1");
464 return -1;
465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000467}
468
469/* ---------------------------------------------------------------------------
470 * Normalization utilities.
471 */
472
473/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
474 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
475 * at least factor, enough of *lo is converted into "hi" units so that
476 * 0 <= *lo < factor. The input values must be such that int overflow
477 * is impossible.
478 */
479static void
480normalize_pair(int *hi, int *lo, int factor)
481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 assert(factor > 0);
483 assert(lo != hi);
484 if (*lo < 0 || *lo >= factor) {
485 const int num_hi = divmod(*lo, factor, lo);
486 const int new_hi = *hi + num_hi;
487 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
488 *hi = new_hi;
489 }
490 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000491}
492
493/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 * 0 <= *s < 24*3600
495 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000496 * The input values must be such that the internals don't overflow.
497 * The way this routine is used, we don't get close.
498 */
499static void
500normalize_d_s_us(int *d, int *s, int *us)
501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (*us < 0 || *us >= 1000000) {
503 normalize_pair(s, us, 1000000);
504 /* |s| can't be bigger than about
505 * |original s| + |original us|/1000000 now.
506 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 }
509 if (*s < 0 || *s >= 24*3600) {
510 normalize_pair(d, s, 24*3600);
511 /* |d| can't be bigger than about
512 * |original d| +
513 * (|original s| + |original us|/1000000) / (24*3600) now.
514 */
515 }
516 assert(0 <= *s && *s < 24*3600);
517 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000518}
519
520/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 * 1 <= *m <= 12
522 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000523 * The input values must be such that the internals don't overflow.
524 * The way this routine is used, we don't get close.
525 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000526static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000527normalize_y_m_d(int *y, int *m, int *d)
528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000530
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000531 /* In actual use, m is always the month component extracted from a
532 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* Now only day can be out of bounds (year may also be out of bounds
538 * for a datetime object, but we don't care about that here).
539 * If day is out of bounds, what to do is arguable, but at least the
540 * method here is principled and explainable.
541 */
542 dim = days_in_month(*y, *m);
543 if (*d < 1 || *d > dim) {
544 /* Move day-1 days from the first of the month. First try to
545 * get off cheap if we're only one day out of range
546 * (adjustments for timezone alone can't be worse than that).
547 */
548 if (*d == 0) {
549 --*m;
550 if (*m > 0)
551 *d = days_in_month(*y, *m);
552 else {
553 --*y;
554 *m = 12;
555 *d = 31;
556 }
557 }
558 else if (*d == dim + 1) {
559 /* move forward a day */
560 ++*m;
561 *d = 1;
562 if (*m > 12) {
563 *m = 1;
564 ++*y;
565 }
566 }
567 else {
568 int ordinal = ymd_to_ord(*y, *m, 1) +
569 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000570 if (ordinal < 1 || ordinal > MAXORDINAL) {
571 goto error;
572 } else {
573 ord_to_ymd(ordinal, y, m, d);
574 return 0;
575 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 }
577 }
578 assert(*m > 0);
579 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000580 if (MINYEAR <= *y && *y <= MAXYEAR)
581 return 0;
582 error:
583 PyErr_SetString(PyExc_OverflowError,
584 "date value out of range");
585 return -1;
586
Tim Peters2a799bf2002-12-16 20:18:38 +0000587}
588
589/* Fiddle out-of-bounds months and days so that the result makes some kind
590 * of sense. The parameters are both inputs and outputs. Returns < 0 on
591 * failure, where failure means the adjusted year is out of bounds.
592 */
593static int
594normalize_date(int *year, int *month, int *day)
595{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000596 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000597}
598
599/* Force all the datetime fields into range. The parameters are both
600 * inputs and outputs. Returns < 0 on error.
601 */
602static int
603normalize_datetime(int *year, int *month, int *day,
604 int *hour, int *minute, int *second,
605 int *microsecond)
606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 normalize_pair(second, microsecond, 1000000);
608 normalize_pair(minute, second, 60);
609 normalize_pair(hour, minute, 60);
610 normalize_pair(day, hour, 24);
611 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000612}
613
614/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000615 * Basic object allocation: tp_alloc implementations. These allocate
616 * Python objects of the right size and type, and do the Python object-
617 * initialization bit. If there's not enough memory, they return NULL after
618 * setting MemoryError. All data members remain uninitialized trash.
619 *
620 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000621 * member is needed. This is ugly, imprecise, and possibly insecure.
622 * tp_basicsize for the time and datetime types is set to the size of the
623 * struct that has room for the tzinfo member, so subclasses in Python will
624 * allocate enough space for a tzinfo member whether or not one is actually
625 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
626 * part is that PyType_GenericAlloc() (which subclasses in Python end up
627 * using) just happens today to effectively ignore the nitems argument
628 * when tp_itemsize is 0, which it is for these type objects. If that
629 * changes, perhaps the callers of tp_alloc slots in this file should
630 * be changed to force a 0 nitems argument unless the type being allocated
631 * is a base type implemented in this file (so that tp_alloc is time_alloc
632 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000633 */
634
635static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000636time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 self = (PyObject *)
641 PyObject_MALLOC(aware ?
642 sizeof(PyDateTime_Time) :
643 sizeof(_PyDateTime_BaseTime));
644 if (self == NULL)
645 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100646 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000648}
649
650static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000651datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 self = (PyObject *)
656 PyObject_MALLOC(aware ?
657 sizeof(PyDateTime_DateTime) :
658 sizeof(_PyDateTime_BaseDateTime));
659 if (self == NULL)
660 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100661 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000663}
664
665/* ---------------------------------------------------------------------------
666 * Helpers for setting object fields. These work on pointers to the
667 * appropriate base class.
668 */
669
670/* For date and datetime. */
671static void
672set_date_fields(PyDateTime_Date *self, int y, int m, int d)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 self->hashcode = -1;
675 SET_YEAR(self, y);
676 SET_MONTH(self, m);
677 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000678}
679
680/* ---------------------------------------------------------------------------
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500681 * String parsing utilities and helper functions
682 */
683
Paul Ganssle3df85402018-10-22 12:32:52 -0400684static const char *
685parse_digits(const char *ptr, int *var, size_t num_digits)
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500686{
687 for (size_t i = 0; i < num_digits; ++i) {
688 unsigned int tmp = (unsigned int)(*(ptr++) - '0');
689 if (tmp > 9) {
690 return NULL;
691 }
692 *var *= 10;
693 *var += (signed int)tmp;
694 }
695
696 return ptr;
697}
698
Paul Ganssle3df85402018-10-22 12:32:52 -0400699static int
700parse_isoformat_date(const char *dtstr, int *year, int *month, int *day)
701{
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500702 /* Parse the date components of the result of date.isoformat()
Paul Ganssle3df85402018-10-22 12:32:52 -0400703 *
704 * Return codes:
705 * 0: Success
706 * -1: Failed to parse date component
707 * -2: Failed to parse dateseparator
708 */
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500709 const char *p = dtstr;
710 p = parse_digits(p, year, 4);
711 if (NULL == p) {
712 return -1;
713 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100714
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500715 if (*(p++) != '-') {
716 return -2;
717 }
718
719 p = parse_digits(p, month, 2);
720 if (NULL == p) {
721 return -1;
722 }
723
724 if (*(p++) != '-') {
725 return -2;
726 }
727
728 p = parse_digits(p, day, 2);
729 if (p == NULL) {
730 return -1;
731 }
732
733 return 0;
734}
735
736static int
Paul Ganssle3df85402018-10-22 12:32:52 -0400737parse_hh_mm_ss_ff(const char *tstr, const char *tstr_end, int *hour,
738 int *minute, int *second, int *microsecond)
739{
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500740 const char *p = tstr;
741 const char *p_end = tstr_end;
742 int *vals[3] = {hour, minute, second};
743
744 // Parse [HH[:MM[:SS]]]
745 for (size_t i = 0; i < 3; ++i) {
746 p = parse_digits(p, vals[i], 2);
747 if (NULL == p) {
748 return -3;
749 }
750
751 char c = *(p++);
752 if (p >= p_end) {
753 return c != '\0';
Paul Ganssle3df85402018-10-22 12:32:52 -0400754 }
755 else if (c == ':') {
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500756 continue;
Paul Ganssle3df85402018-10-22 12:32:52 -0400757 }
758 else if (c == '.') {
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500759 break;
Paul Ganssle3df85402018-10-22 12:32:52 -0400760 }
761 else {
762 return -4; // Malformed time separator
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500763 }
764 }
765
766 // Parse .fff[fff]
767 size_t len_remains = p_end - p;
768 if (!(len_remains == 6 || len_remains == 3)) {
769 return -3;
770 }
771
772 p = parse_digits(p, microsecond, len_remains);
773 if (NULL == p) {
774 return -3;
775 }
776
777 if (len_remains == 3) {
778 *microsecond *= 1000;
779 }
780
781 // Return 1 if it's not the end of the string
782 return *p != '\0';
783}
784
785static int
Paul Ganssle3df85402018-10-22 12:32:52 -0400786parse_isoformat_time(const char *dtstr, size_t dtlen, int *hour, int *minute,
787 int *second, int *microsecond, int *tzoffset,
788 int *tzmicrosecond)
789{
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500790 // Parse the time portion of a datetime.isoformat() string
791 //
792 // Return codes:
793 // 0: Success (no tzoffset)
794 // 1: Success (with tzoffset)
795 // -3: Failed to parse time component
796 // -4: Failed to parse time separator
797 // -5: Malformed timezone string
798
799 const char *p = dtstr;
800 const char *p_end = dtstr + dtlen;
801
802 const char *tzinfo_pos = p;
803 do {
804 if (*tzinfo_pos == '+' || *tzinfo_pos == '-') {
805 break;
806 }
Paul Ganssle3df85402018-10-22 12:32:52 -0400807 } while (++tzinfo_pos < p_end);
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500808
Paul Ganssle3df85402018-10-22 12:32:52 -0400809 int rv = parse_hh_mm_ss_ff(dtstr, tzinfo_pos, hour, minute, second,
810 microsecond);
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500811
812 if (rv < 0) {
813 return rv;
Paul Ganssle3df85402018-10-22 12:32:52 -0400814 }
815 else if (tzinfo_pos == p_end) {
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500816 // We know that there's no time zone, so if there's stuff at the
817 // end of the string it's an error.
818 if (rv == 1) {
819 return -5;
Paul Ganssle3df85402018-10-22 12:32:52 -0400820 }
821 else {
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500822 return 0;
823 }
824 }
825
826 // Parse time zone component
827 // Valid formats are:
828 // - +HH:MM (len 6)
829 // - +HH:MM:SS (len 9)
830 // - +HH:MM:SS.ffffff (len 16)
831 size_t tzlen = p_end - tzinfo_pos;
832 if (!(tzlen == 6 || tzlen == 9 || tzlen == 16)) {
833 return -5;
834 }
835
Paul Ganssle3df85402018-10-22 12:32:52 -0400836 int tzsign = (*tzinfo_pos == '-') ? -1 : 1;
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500837 tzinfo_pos++;
838 int tzhour = 0, tzminute = 0, tzsecond = 0;
Paul Ganssle3df85402018-10-22 12:32:52 -0400839 rv = parse_hh_mm_ss_ff(tzinfo_pos, p_end, &tzhour, &tzminute, &tzsecond,
840 tzmicrosecond);
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500841
842 *tzoffset = tzsign * ((tzhour * 3600) + (tzminute * 60) + tzsecond);
843 *tzmicrosecond *= tzsign;
844
Paul Ganssle3df85402018-10-22 12:32:52 -0400845 return rv ? -5 : 1;
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500846}
847
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500848/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000849 * Create various objects, mostly without range checking.
850 */
851
852/* Create a date instance with no range checking. */
853static PyObject *
854new_date_ex(int year, int month, int day, PyTypeObject *type)
855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000857
Victor Stinnerb67f0962017-02-10 10:34:02 +0100858 if (check_date_args(year, month, day) < 0) {
859 return NULL;
860 }
861
Paul Ganssle3df85402018-10-22 12:32:52 -0400862 self = (PyDateTime_Date *)(type->tp_alloc(type, 0));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (self != NULL)
864 set_date_fields(self, year, month, day);
Paul Ganssle3df85402018-10-22 12:32:52 -0400865 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000866}
867
868#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000870
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500871// Forward declaration
Paul Ganssle3df85402018-10-22 12:32:52 -0400872static PyObject *
873new_datetime_ex(int, int, int, int, int, int, int, PyObject *, PyTypeObject *);
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500874
875/* Create date instance with no range checking, or call subclass constructor */
876static PyObject *
Paul Ganssle3df85402018-10-22 12:32:52 -0400877new_date_subclass_ex(int year, int month, int day, PyObject *cls)
878{
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500879 PyObject *result;
880 // We have "fast path" constructors for two subclasses: date and datetime
881 if ((PyTypeObject *)cls == &PyDateTime_DateType) {
882 result = new_date_ex(year, month, day, (PyTypeObject *)cls);
Paul Ganssle3df85402018-10-22 12:32:52 -0400883 }
884 else if ((PyTypeObject *)cls == &PyDateTime_DateTimeType) {
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500885 result = new_datetime_ex(year, month, day, 0, 0, 0, 0, Py_None,
886 (PyTypeObject *)cls);
Paul Ganssle3df85402018-10-22 12:32:52 -0400887 }
888 else {
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500889 result = PyObject_CallFunction(cls, "iii", year, month, day);
890 }
891
892 return result;
893}
894
Tim Petersb0c854d2003-05-17 15:57:00 +0000895/* Create a datetime instance with no range checking. */
896static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400897new_datetime_ex2(int year, int month, int day, int hour, int minute,
898 int second, int usecond, PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyDateTime_DateTime *self;
901 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000902
Victor Stinnerb67f0962017-02-10 10:34:02 +0100903 if (check_date_args(year, month, day) < 0) {
904 return NULL;
905 }
906 if (check_time_args(hour, minute, second, usecond, fold) < 0) {
907 return NULL;
908 }
909 if (check_tzinfo_subclass(tzinfo) < 0) {
910 return NULL;
911 }
912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
914 if (self != NULL) {
915 self->hastzinfo = aware;
916 set_date_fields((PyDateTime_Date *)self, year, month, day);
917 DATE_SET_HOUR(self, hour);
918 DATE_SET_MINUTE(self, minute);
919 DATE_SET_SECOND(self, second);
920 DATE_SET_MICROSECOND(self, usecond);
921 if (aware) {
922 Py_INCREF(tzinfo);
923 self->tzinfo = tzinfo;
924 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400925 DATE_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 }
927 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000928}
929
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400930static PyObject *
931new_datetime_ex(int year, int month, int day, int hour, int minute,
932 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
933{
934 return new_datetime_ex2(year, month, day, hour, minute, second, usecond,
935 tzinfo, 0, type);
936}
937
938#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo, fold) \
939 new_datetime_ex2(y, m, d, hh, mm, ss, us, tzinfo, fold, \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000941
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500942static PyObject *
943new_datetime_subclass_fold_ex(int year, int month, int day, int hour, int minute,
944 int second, int usecond, PyObject *tzinfo,
945 int fold, PyObject *cls) {
946 PyObject* dt;
947 if ((PyTypeObject*)cls == &PyDateTime_DateTimeType) {
948 // Use the fast path constructor
949 dt = new_datetime(year, month, day, hour, minute, second, usecond,
950 tzinfo, fold);
951 } else {
952 // Subclass
953 dt = PyObject_CallFunction(cls, "iiiiiiiO",
954 year,
955 month,
956 day,
957 hour,
958 minute,
959 second,
960 usecond,
961 tzinfo);
962 }
963
964 return dt;
965}
966
967static PyObject *
968new_datetime_subclass_ex(int year, int month, int day, int hour, int minute,
969 int second, int usecond, PyObject *tzinfo,
970 PyObject *cls) {
971 return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
972 second, usecond, tzinfo, 0,
973 cls);
974}
975
Tim Petersb0c854d2003-05-17 15:57:00 +0000976/* Create a time instance with no range checking. */
977static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400978new_time_ex2(int hour, int minute, int second, int usecond,
979 PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 PyDateTime_Time *self;
982 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000983
Victor Stinnerb67f0962017-02-10 10:34:02 +0100984 if (check_time_args(hour, minute, second, usecond, fold) < 0) {
985 return NULL;
986 }
987 if (check_tzinfo_subclass(tzinfo) < 0) {
988 return NULL;
989 }
990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
992 if (self != NULL) {
993 self->hastzinfo = aware;
994 self->hashcode = -1;
995 TIME_SET_HOUR(self, hour);
996 TIME_SET_MINUTE(self, minute);
997 TIME_SET_SECOND(self, second);
998 TIME_SET_MICROSECOND(self, usecond);
999 if (aware) {
1000 Py_INCREF(tzinfo);
1001 self->tzinfo = tzinfo;
1002 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001003 TIME_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 }
1005 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +00001006}
1007
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001008static PyObject *
1009new_time_ex(int hour, int minute, int second, int usecond,
1010 PyObject *tzinfo, PyTypeObject *type)
1011{
1012 return new_time_ex2(hour, minute, second, usecond, tzinfo, 0, type);
1013}
1014
1015#define new_time(hh, mm, ss, us, tzinfo, fold) \
1016 new_time_ex2(hh, mm, ss, us, tzinfo, fold, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001017
1018/* Create a timedelta instance. Normalize the members iff normalize is
1019 * true. Passing false is a speed optimization, if you know for sure
1020 * that seconds and microseconds are already in their proper ranges. In any
1021 * case, raises OverflowError and returns NULL if the normalized days is out
1022 * of range).
1023 */
1024static PyObject *
1025new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +00001027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (normalize)
1031 normalize_d_s_us(&days, &seconds, &microseconds);
1032 assert(0 <= seconds && seconds < 24*3600);
1033 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 if (check_delta_day_range(days) < 0)
1036 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
1039 if (self != NULL) {
1040 self->hashcode = -1;
1041 SET_TD_DAYS(self, days);
1042 SET_TD_SECONDS(self, seconds);
1043 SET_TD_MICROSECONDS(self, microseconds);
1044 }
1045 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +00001046}
1047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048#define new_delta(d, s, us, normalize) \
1049 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001050
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001051
1052typedef struct
1053{
1054 PyObject_HEAD
1055 PyObject *offset;
1056 PyObject *name;
1057} PyDateTime_TimeZone;
1058
Victor Stinner6ced7c42011-03-21 18:15:42 +01001059/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00001060static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya4415142012-06-08 12:33:09 -04001061/* The interned Epoch datetime instance */
1062static PyObject *PyDateTime_Epoch;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00001063
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001064/* Create new timezone instance checking offset range. This
1065 function does not check the name argument. Caller must assure
1066 that offset is a timedelta instance and name is either NULL
1067 or a unicode object. */
1068static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00001069create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001070{
1071 PyDateTime_TimeZone *self;
1072 PyTypeObject *type = &PyDateTime_TimeZoneType;
1073
1074 assert(offset != NULL);
1075 assert(PyDelta_Check(offset));
1076 assert(name == NULL || PyUnicode_Check(name));
1077
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00001078 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
1079 if (self == NULL) {
1080 return NULL;
1081 }
1082 Py_INCREF(offset);
1083 self->offset = offset;
1084 Py_XINCREF(name);
1085 self->name = name;
1086 return (PyObject *)self;
1087}
1088
1089static int delta_bool(PyDateTime_Delta *self);
1090
1091static PyObject *
1092new_timezone(PyObject *offset, PyObject *name)
1093{
1094 assert(offset != NULL);
1095 assert(PyDelta_Check(offset));
1096 assert(name == NULL || PyUnicode_Check(name));
1097
1098 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
1099 Py_INCREF(PyDateTime_TimeZone_UTC);
1100 return PyDateTime_TimeZone_UTC;
1101 }
Paul Ganssle27b38b92019-08-15 15:08:57 -04001102 if ((GET_TD_DAYS(offset) == -1 &&
1103 GET_TD_SECONDS(offset) == 0 &&
1104 GET_TD_MICROSECONDS(offset) < 1) ||
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001105 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
1106 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
1107 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04001108 " timedelta(hours=24),"
1109 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001110 return NULL;
1111 }
1112
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00001113 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001114}
1115
Tim Petersb0c854d2003-05-17 15:57:00 +00001116/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001117 * tzinfo helpers.
1118 */
1119
Tim Peters855fe882002-12-22 03:43:39 +00001120/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
1121 * raise TypeError and return -1.
1122 */
1123static int
1124check_tzinfo_subclass(PyObject *p)
1125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (p == Py_None || PyTZInfo_Check(p))
1127 return 0;
1128 PyErr_Format(PyExc_TypeError,
1129 "tzinfo argument must be None or of a tzinfo subclass, "
1130 "not type '%s'",
1131 Py_TYPE(p)->tp_name);
1132 return -1;
Tim Peters855fe882002-12-22 03:43:39 +00001133}
1134
Tim Peters2a799bf2002-12-16 20:18:38 +00001135/* If self has a tzinfo member, return a BORROWED reference to it. Else
1136 * return NULL, which is NOT AN ERROR. There are no error returns here,
1137 * and the caller must not decref the result.
1138 */
1139static PyObject *
1140get_tzinfo_member(PyObject *self)
1141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (PyDateTime_Check(self) && HASTZINFO(self))
1145 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
1146 else if (PyTime_Check(self) && HASTZINFO(self))
1147 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +00001150}
1151
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001152/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
1153 * be an instance of the tzinfo class. If the method returns None, this
1154 * returns None. If the method doesn't return None or timedelta, TypeError is
1155 * raised and this returns NULL. If it returns a timedelta and the value is
1156 * out of range or isn't a whole number of minutes, ValueError is raised and
1157 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +00001158 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001159static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001160call_tzinfo_method(PyObject *tzinfo, const char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001161{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001162 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001165 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001167
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001168 if (tzinfo == Py_None)
1169 Py_RETURN_NONE;
1170 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
1171 if (offset == Py_None || offset == NULL)
1172 return offset;
1173 if (PyDelta_Check(offset)) {
Paul Ganssle27b38b92019-08-15 15:08:57 -04001174 if ((GET_TD_DAYS(offset) == -1 &&
1175 GET_TD_SECONDS(offset) == 0 &&
1176 GET_TD_MICROSECONDS(offset) < 1) ||
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001177 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
1178 Py_DECREF(offset);
1179 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
1180 " strictly between -timedelta(hours=24) and"
1181 " timedelta(hours=24).");
1182 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 }
1184 }
1185 else {
1186 PyErr_Format(PyExc_TypeError,
1187 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001188 "timedelta, not '%.200s'",
1189 name, Py_TYPE(offset)->tp_name);
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07001190 Py_DECREF(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001191 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001193
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001194 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +00001195}
1196
1197/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
1198 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
1199 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +00001200 * doesn't return None or timedelta, TypeError is raised and this returns -1.
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001201 * If utcoffset() returns an out of range timedelta,
1202 * ValueError is raised and this returns -1. Else *none is
1203 * set to 0 and the offset is returned (as timedelta, positive east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +00001204 */
Tim Peters855fe882002-12-22 03:43:39 +00001205static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001206call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
1207{
1208 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +00001209}
1210
Tim Peters2a799bf2002-12-16 20:18:38 +00001211/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
1212 * result. tzinfo must be an instance of the tzinfo class. If dst()
1213 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001214 * doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00001215 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +00001216 * ValueError is raised and this returns -1. Else *none is set to 0 and
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001217 * the offset is returned (as timedelta, positive east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +00001218 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001219static PyObject *
1220call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001221{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001222 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001223}
1224
Tim Petersbad8ff02002-12-30 20:52:32 +00001225/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +00001226 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +00001227 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +00001228 * returns NULL. If the result is a string, we ensure it is a Unicode
1229 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +00001230 */
1231static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001232call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001235 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 assert(tzinfo != NULL);
1238 assert(check_tzinfo_subclass(tzinfo) >= 0);
1239 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001242 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001243
Victor Stinner20401de2016-12-09 15:24:31 +01001244 result = _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_tzname,
1245 tzinfoarg, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001246
1247 if (result == NULL || result == Py_None)
1248 return result;
1249
1250 if (!PyUnicode_Check(result)) {
1251 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
1252 "return None or a string, not '%s'",
1253 Py_TYPE(result)->tp_name);
1254 Py_DECREF(result);
1255 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001257
1258 return result;
Tim Peters00237032002-12-27 02:21:51 +00001259}
1260
Tim Peters2a799bf2002-12-16 20:18:38 +00001261/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1262 * stuff
1263 * ", tzinfo=" + repr(tzinfo)
1264 * before the closing ")".
1265 */
1266static PyObject *
1267append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 assert(PyUnicode_Check(repr));
1272 assert(tzinfo);
1273 if (tzinfo == Py_None)
1274 return repr;
1275 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1277 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 Py_DECREF(repr);
1279 if (temp == NULL)
1280 return NULL;
1281 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1282 Py_DECREF(temp);
1283 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001284}
1285
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001286/* repr is like "someclass(arg1, arg2)". If fold isn't 0,
1287 * stuff
1288 * ", fold=" + repr(tzinfo)
1289 * before the closing ")".
1290 */
1291static PyObject *
1292append_keyword_fold(PyObject *repr, int fold)
1293{
1294 PyObject *temp;
1295
1296 assert(PyUnicode_Check(repr));
1297 if (fold == 0)
1298 return repr;
1299 /* Get rid of the trailing ')'. */
1300 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1301 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
1302 Py_DECREF(repr);
1303 if (temp == NULL)
1304 return NULL;
1305 repr = PyUnicode_FromFormat("%U, fold=%d)", temp, fold);
1306 Py_DECREF(temp);
1307 return repr;
1308}
1309
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001310static inline PyObject *
Paul Ganssle3df85402018-10-22 12:32:52 -04001311tzinfo_from_isoformat_results(int rv, int tzoffset, int tz_useconds)
1312{
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001313 PyObject *tzinfo;
1314 if (rv == 1) {
1315 // Create a timezone from offset in seconds (0 returns UTC)
1316 if (tzoffset == 0) {
1317 Py_INCREF(PyDateTime_TimeZone_UTC);
1318 return PyDateTime_TimeZone_UTC;
1319 }
1320
1321 PyObject *delta = new_delta(0, tzoffset, tz_useconds, 1);
Alexey Izbyshev49884532018-08-24 18:53:16 +03001322 if (delta == NULL) {
1323 return NULL;
1324 }
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001325 tzinfo = new_timezone(delta, NULL);
Alexey Izbyshev49884532018-08-24 18:53:16 +03001326 Py_DECREF(delta);
Paul Ganssle3df85402018-10-22 12:32:52 -04001327 }
1328 else {
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001329 tzinfo = Py_None;
1330 Py_INCREF(Py_None);
1331 }
1332
1333 return tzinfo;
1334}
1335
Tim Peters2a799bf2002-12-16 20:18:38 +00001336/* ---------------------------------------------------------------------------
1337 * String format helpers.
1338 */
1339
1340static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001341format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001342{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001343 static const char * const DayNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1345 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001346 static const char * const MonthNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1348 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1349 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1354 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1355 GET_DAY(date), hours, minutes, seconds,
1356 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001357}
1358
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001359static PyObject *delta_negative(PyDateTime_Delta *self);
1360
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001361/* Add formatted UTC offset string to buf. buf has no more than
Tim Peters2a799bf2002-12-16 20:18:38 +00001362 * buflen bytes remaining. The UTC offset is gotten by calling
1363 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1364 * *buf, and that's all. Else the returned value is checked for sanity (an
1365 * integer in range), and if that's OK it's converted to an hours & minutes
1366 * string of the form
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001367 * sign HH sep MM [sep SS [. UUUUUU]]
Tim Peters2a799bf2002-12-16 20:18:38 +00001368 * Returns 0 if everything is OK. If the return value from utcoffset() is
1369 * bogus, an appropriate exception is set and -1 is returned.
1370 */
1371static int
Tim Peters328fff72002-12-20 01:31:27 +00001372format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001374{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001375 PyObject *offset;
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001376 int hours, minutes, seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001380
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001381 offset = call_utcoffset(tzinfo, tzinfoarg);
1382 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001384 if (offset == Py_None) {
1385 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 *buf = '\0';
1387 return 0;
1388 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001389 /* Offset is normalized, so it is negative if days < 0 */
1390 if (GET_TD_DAYS(offset) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 sign = '-';
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03001392 Py_SETREF(offset, delta_negative((PyDateTime_Delta *)offset));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001393 if (offset == NULL)
1394 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001396 else {
1397 sign = '+';
1398 }
1399 /* Offset is not negative here. */
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001400 microseconds = GET_TD_MICROSECONDS(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001401 seconds = GET_TD_SECONDS(offset);
1402 Py_DECREF(offset);
1403 minutes = divmod(seconds, 60, &seconds);
1404 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001405 if (microseconds) {
1406 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d.%06d", sign,
1407 hours, sep, minutes, sep, seconds, microseconds);
1408 return 0;
1409 }
1410 if (seconds) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001411 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d", sign, hours,
1412 sep, minutes, sep, seconds);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001413 return 0;
1414 }
1415 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001417}
1418
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001419static PyObject *
1420make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 PyObject *temp;
1423 PyObject *tzinfo = get_tzinfo_member(object);
1424 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001425 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (Zreplacement == NULL)
1428 return NULL;
1429 if (tzinfo == Py_None || tzinfo == NULL)
1430 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 assert(tzinfoarg != NULL);
1433 temp = call_tzname(tzinfo, tzinfoarg);
1434 if (temp == NULL)
1435 goto Error;
1436 if (temp == Py_None) {
1437 Py_DECREF(temp);
1438 return Zreplacement;
1439 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 assert(PyUnicode_Check(temp));
1442 /* Since the tzname is getting stuffed into the
1443 * format, we have to double any % signs so that
1444 * strftime doesn't treat them as format codes.
1445 */
1446 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001447 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 Py_DECREF(temp);
1449 if (Zreplacement == NULL)
1450 return NULL;
1451 if (!PyUnicode_Check(Zreplacement)) {
1452 PyErr_SetString(PyExc_TypeError,
1453 "tzname.replace() did not return a string");
1454 goto Error;
1455 }
1456 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001457
1458 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 Py_DECREF(Zreplacement);
1460 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001461}
1462
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001463static PyObject *
1464make_freplacement(PyObject *object)
1465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 char freplacement[64];
1467 if (PyTime_Check(object))
1468 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1469 else if (PyDateTime_Check(object))
1470 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1471 else
1472 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001475}
1476
Tim Peters2a799bf2002-12-16 20:18:38 +00001477/* I sure don't want to reproduce the strftime code from the time module,
1478 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001479 * giving special meanings to the %z, %Z and %f format codes via a
1480 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001481 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1482 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001483 */
1484static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001485wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1491 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1492 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 const char *pin; /* pointer to next char in input format */
1495 Py_ssize_t flen; /* length of input format */
1496 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyObject *newfmt = NULL; /* py string, the output format */
1499 char *pnew; /* pointer to available byte in output format */
1500 size_t totalnew; /* number bytes total in output format buffer,
1501 exclusive of trailing \0 */
1502 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 const char *ptoappend; /* ptr to string to append to output buffer */
1505 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 assert(object && format && timetuple);
1508 assert(PyUnicode_Check(format));
1509 /* Convert the input format to a C string and size */
Serhiy Storchaka06515832016-11-20 09:13:07 +02001510 pin = PyUnicode_AsUTF8AndSize(format, &flen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (!pin)
1512 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 /* Scan the input format, looking for %z/%Z/%f escapes, building
1515 * a new format. Since computing the replacements for those codes
1516 * is expensive, don't unless they're actually used.
1517 */
1518 if (flen > INT_MAX - 1) {
1519 PyErr_NoMemory();
1520 goto Done;
1521 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 totalnew = flen + 1; /* realistic if no %z/%Z */
1524 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1525 if (newfmt == NULL) goto Done;
1526 pnew = PyBytes_AsString(newfmt);
1527 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 while ((ch = *pin++) != '\0') {
1530 if (ch != '%') {
1531 ptoappend = pin - 1;
1532 ntoappend = 1;
1533 }
1534 else if ((ch = *pin++) == '\0') {
MichaelSaah454b3d42019-01-14 05:23:39 -05001535 /* Null byte follows %, copy only '%'.
1536 *
1537 * Back the pin up one char so that we catch the null check
1538 * the next time through the loop.*/
1539 pin--;
1540 ptoappend = pin - 1;
1541 ntoappend = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 }
1543 /* A % has been seen and ch is the character after it. */
1544 else if (ch == 'z') {
1545 if (zreplacement == NULL) {
1546 /* format utcoffset */
1547 char buf[100];
1548 PyObject *tzinfo = get_tzinfo_member(object);
1549 zreplacement = PyBytes_FromStringAndSize("", 0);
1550 if (zreplacement == NULL) goto Done;
1551 if (tzinfo != Py_None && tzinfo != NULL) {
1552 assert(tzinfoarg != NULL);
1553 if (format_utcoffset(buf,
1554 sizeof(buf),
1555 "",
1556 tzinfo,
1557 tzinfoarg) < 0)
1558 goto Done;
1559 Py_DECREF(zreplacement);
1560 zreplacement =
1561 PyBytes_FromStringAndSize(buf,
1562 strlen(buf));
1563 if (zreplacement == NULL)
1564 goto Done;
1565 }
1566 }
1567 assert(zreplacement != NULL);
1568 ptoappend = PyBytes_AS_STRING(zreplacement);
1569 ntoappend = PyBytes_GET_SIZE(zreplacement);
1570 }
1571 else if (ch == 'Z') {
1572 /* format tzname */
1573 if (Zreplacement == NULL) {
1574 Zreplacement = make_Zreplacement(object,
1575 tzinfoarg);
1576 if (Zreplacement == NULL)
1577 goto Done;
1578 }
1579 assert(Zreplacement != NULL);
1580 assert(PyUnicode_Check(Zreplacement));
Serhiy Storchaka06515832016-11-20 09:13:07 +02001581 ptoappend = PyUnicode_AsUTF8AndSize(Zreplacement,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001583 if (ptoappend == NULL)
1584 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 }
1586 else if (ch == 'f') {
1587 /* format microseconds */
1588 if (freplacement == NULL) {
1589 freplacement = make_freplacement(object);
1590 if (freplacement == NULL)
1591 goto Done;
1592 }
1593 assert(freplacement != NULL);
1594 assert(PyBytes_Check(freplacement));
1595 ptoappend = PyBytes_AS_STRING(freplacement);
1596 ntoappend = PyBytes_GET_SIZE(freplacement);
1597 }
1598 else {
1599 /* percent followed by neither z nor Z */
1600 ptoappend = pin - 2;
1601 ntoappend = 2;
1602 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 /* Append the ntoappend chars starting at ptoappend to
1605 * the new format.
1606 */
1607 if (ntoappend == 0)
1608 continue;
1609 assert(ptoappend != NULL);
1610 assert(ntoappend > 0);
1611 while (usednew + ntoappend > totalnew) {
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001612 if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 PyErr_NoMemory();
1614 goto Done;
1615 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001616 totalnew <<= 1;
1617 if (_PyBytes_Resize(&newfmt, totalnew) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 pnew = PyBytes_AsString(newfmt) + usednew;
1620 }
1621 memcpy(pnew, ptoappend, ntoappend);
1622 pnew += ntoappend;
1623 usednew += ntoappend;
1624 assert(usednew <= totalnew);
1625 } /* end while() */
MichaelSaah454b3d42019-01-14 05:23:39 -05001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1628 goto Done;
1629 {
1630 PyObject *format;
1631 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 if (time == NULL)
1634 goto Done;
1635 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1636 if (format != NULL) {
Victor Stinner20401de2016-12-09 15:24:31 +01001637 result = _PyObject_CallMethodIdObjArgs(time, &PyId_strftime,
1638 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 Py_DECREF(format);
1640 }
1641 Py_DECREF(time);
1642 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001643 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 Py_XDECREF(freplacement);
1645 Py_XDECREF(zreplacement);
1646 Py_XDECREF(Zreplacement);
1647 Py_XDECREF(newfmt);
1648 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001649}
1650
Tim Peters2a799bf2002-12-16 20:18:38 +00001651/* ---------------------------------------------------------------------------
1652 * Wrap functions from the time module. These aren't directly available
1653 * from C. Perhaps they should be.
1654 */
1655
1656/* Call time.time() and return its result (a Python float). */
1657static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001658time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 PyObject *result = NULL;
1661 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001664 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001665
Victor Stinnerad8c83a2016-09-05 17:53:15 -07001666 result = _PyObject_CallMethodId(time, &PyId_time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 Py_DECREF(time);
1668 }
1669 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001670}
1671
1672/* Build a time.struct_time. The weekday and day number are automatically
1673 * computed from the y,m,d args.
1674 */
1675static PyObject *
1676build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 PyObject *time;
Victor Stinner2b635972016-12-09 00:38:16 +01001679 PyObject *result;
1680 _Py_IDENTIFIER(struct_time);
1681 PyObject *args;
1682
Tim Peters2a799bf2002-12-16 20:18:38 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 time = PyImport_ImportModuleNoBlock("time");
Victor Stinner2b635972016-12-09 00:38:16 +01001685 if (time == NULL) {
1686 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 }
Victor Stinner2b635972016-12-09 00:38:16 +01001688
1689 args = Py_BuildValue("iiiiiiiii",
1690 y, m, d,
1691 hh, mm, ss,
1692 weekday(y, m, d),
1693 days_before_month(y, m) + d,
1694 dstflag);
1695 if (args == NULL) {
1696 Py_DECREF(time);
1697 return NULL;
1698 }
1699
1700 result = _PyObject_CallMethodIdObjArgs(time, &PyId_struct_time,
1701 args, NULL);
1702 Py_DECREF(time);
Victor Stinnerddc120f2016-12-09 15:35:40 +01001703 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001705}
1706
1707/* ---------------------------------------------------------------------------
1708 * Miscellaneous helpers.
1709 */
1710
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001711/* The comparisons here all most naturally compute a cmp()-like result.
Tim Peters2a799bf2002-12-16 20:18:38 +00001712 * This little helper turns that into a bool result for rich comparisons.
1713 */
1714static PyObject *
1715diff_to_bool(int diff, int op)
1716{
stratakise8b19652017-11-02 11:32:54 +01001717 Py_RETURN_RICHCOMPARE(diff, 0, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001718}
1719
Tim Peters07534a62003-02-07 22:50:28 +00001720/* Raises a "can't compare" TypeError and returns NULL. */
1721static PyObject *
1722cmperror(PyObject *a, PyObject *b)
1723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 PyErr_Format(PyExc_TypeError,
1725 "can't compare %s to %s",
1726 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1727 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001728}
1729
Tim Peters2a799bf2002-12-16 20:18:38 +00001730/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001731 * Cached Python objects; these are set by the module init function.
1732 */
1733
1734/* Conversion factors. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735static PyObject *us_per_ms = NULL; /* 1000 */
1736static PyObject *us_per_second = NULL; /* 1000000 */
1737static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001738static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
1739static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
1740static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
Tim Peters2a799bf2002-12-16 20:18:38 +00001741static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1742
Tim Peters2a799bf2002-12-16 20:18:38 +00001743/* ---------------------------------------------------------------------------
1744 * Class implementations.
1745 */
1746
1747/*
1748 * PyDateTime_Delta implementation.
1749 */
1750
1751/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Serhiy Storchaka95949422013-08-27 19:40:23 +03001753 * as a Python int.
Tim Peters2a799bf2002-12-16 20:18:38 +00001754 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1755 * due to ubiquitous overflow possibilities.
1756 */
1757static PyObject *
1758delta_to_microseconds(PyDateTime_Delta *self)
1759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyObject *x1 = NULL;
1761 PyObject *x2 = NULL;
1762 PyObject *x3 = NULL;
1763 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1766 if (x1 == NULL)
1767 goto Done;
1768 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1769 if (x2 == NULL)
1770 goto Done;
1771 Py_DECREF(x1);
1772 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 /* x2 has days in seconds */
1775 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1776 if (x1 == NULL)
1777 goto Done;
1778 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1779 if (x3 == NULL)
1780 goto Done;
1781 Py_DECREF(x1);
1782 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001783 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 /* x3 has days+seconds in seconds */
1786 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1787 if (x1 == NULL)
1788 goto Done;
1789 Py_DECREF(x3);
1790 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /* x1 has days+seconds in us */
1793 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1794 if (x2 == NULL)
1795 goto Done;
1796 result = PyNumber_Add(x1, x2);
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03001797 assert(result == NULL || PyLong_CheckExact(result));
Tim Peters2a799bf2002-12-16 20:18:38 +00001798
1799Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 Py_XDECREF(x1);
1801 Py_XDECREF(x2);
1802 Py_XDECREF(x3);
1803 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001804}
1805
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001806static PyObject *
1807checked_divmod(PyObject *a, PyObject *b)
1808{
1809 PyObject *result = PyNumber_Divmod(a, b);
1810 if (result != NULL) {
1811 if (!PyTuple_Check(result)) {
1812 PyErr_Format(PyExc_TypeError,
1813 "divmod() returned non-tuple (type %.200s)",
1814 result->ob_type->tp_name);
1815 Py_DECREF(result);
1816 return NULL;
1817 }
1818 if (PyTuple_GET_SIZE(result) != 2) {
1819 PyErr_Format(PyExc_TypeError,
1820 "divmod() returned a tuple of size %zd",
1821 PyTuple_GET_SIZE(result));
1822 Py_DECREF(result);
1823 return NULL;
1824 }
1825 }
1826 return result;
1827}
1828
Serhiy Storchaka95949422013-08-27 19:40:23 +03001829/* Convert a number of us (as a Python int) to a timedelta.
Tim Peters2a799bf2002-12-16 20:18:38 +00001830 */
1831static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001832microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 int us;
1835 int s;
1836 int d;
Tim Peters2a799bf2002-12-16 20:18:38 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 PyObject *tuple = NULL;
1839 PyObject *num = NULL;
1840 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001841
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001842 tuple = checked_divmod(pyus, us_per_second);
1843 if (tuple == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 goto Done;
1845 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001846
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001847 num = PyTuple_GET_ITEM(tuple, 1); /* us */
1848 us = _PyLong_AsInt(num);
1849 num = NULL;
1850 if (us == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 goto Done;
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001852 }
1853 if (!(0 <= us && us < 1000000)) {
1854 goto BadDivmod;
1855 }
1856
1857 num = PyTuple_GET_ITEM(tuple, 0); /* leftover seconds */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 Py_INCREF(num);
1859 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001860
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001861 tuple = checked_divmod(num, seconds_per_day);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (tuple == NULL)
1863 goto Done;
1864 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001865
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001866 num = PyTuple_GET_ITEM(tuple, 1); /* seconds */
1867 s = _PyLong_AsInt(num);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 num = NULL;
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001869 if (s == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 goto Done;
1871 }
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001872 if (!(0 <= s && s < 24*3600)) {
1873 goto BadDivmod;
1874 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001875
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001876 num = PyTuple_GET_ITEM(tuple, 0); /* leftover days */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 Py_INCREF(num);
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001878 d = _PyLong_AsInt(num);
1879 if (d == -1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 goto Done;
1881 }
1882 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001883
1884Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 Py_XDECREF(tuple);
1886 Py_XDECREF(num);
1887 return result;
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001888
1889BadDivmod:
1890 PyErr_SetString(PyExc_TypeError,
1891 "divmod() returned a value out of range");
1892 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001893}
1894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895#define microseconds_to_delta(pymicros) \
1896 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001897
Tim Peters2a799bf2002-12-16 20:18:38 +00001898static PyObject *
1899multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyObject *pyus_in;
1902 PyObject *pyus_out;
1903 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 pyus_in = delta_to_microseconds(delta);
1906 if (pyus_in == NULL)
1907 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001908
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02001909 pyus_out = PyNumber_Multiply(intobj, pyus_in);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 Py_DECREF(pyus_in);
1911 if (pyus_out == NULL)
1912 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 result = microseconds_to_delta(pyus_out);
1915 Py_DECREF(pyus_out);
1916 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001917}
1918
1919static PyObject *
Oren Milman865e4b42017-09-19 15:58:11 +03001920get_float_as_integer_ratio(PyObject *floatobj)
1921{
1922 PyObject *ratio;
1923
1924 assert(floatobj && PyFloat_Check(floatobj));
1925 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
1926 if (ratio == NULL) {
1927 return NULL;
1928 }
1929 if (!PyTuple_Check(ratio)) {
1930 PyErr_Format(PyExc_TypeError,
1931 "unexpected return type from as_integer_ratio(): "
1932 "expected tuple, got '%.200s'",
1933 Py_TYPE(ratio)->tp_name);
1934 Py_DECREF(ratio);
1935 return NULL;
1936 }
1937 if (PyTuple_Size(ratio) != 2) {
1938 PyErr_SetString(PyExc_ValueError,
1939 "as_integer_ratio() must return a 2-tuple");
1940 Py_DECREF(ratio);
1941 return NULL;
1942 }
1943 return ratio;
1944}
1945
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03001946/* op is 0 for multiplication, 1 for division */
Oren Milman865e4b42017-09-19 15:58:11 +03001947static PyObject *
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03001948multiply_truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *floatobj, int op)
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001949{
1950 PyObject *result = NULL;
1951 PyObject *pyus_in = NULL, *temp, *pyus_out;
1952 PyObject *ratio = NULL;
1953
1954 pyus_in = delta_to_microseconds(delta);
1955 if (pyus_in == NULL)
1956 return NULL;
Oren Milman865e4b42017-09-19 15:58:11 +03001957 ratio = get_float_as_integer_ratio(floatobj);
1958 if (ratio == NULL) {
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001959 goto error;
Oren Milman865e4b42017-09-19 15:58:11 +03001960 }
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03001961 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, op));
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001962 Py_DECREF(pyus_in);
1963 pyus_in = NULL;
1964 if (temp == NULL)
1965 goto error;
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03001966 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, !op));
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001967 Py_DECREF(temp);
1968 if (pyus_out == NULL)
1969 goto error;
1970 result = microseconds_to_delta(pyus_out);
1971 Py_DECREF(pyus_out);
1972 error:
1973 Py_XDECREF(pyus_in);
1974 Py_XDECREF(ratio);
1975
1976 return result;
1977}
1978
1979static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001980divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 PyObject *pyus_in;
1983 PyObject *pyus_out;
1984 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 pyus_in = delta_to_microseconds(delta);
1987 if (pyus_in == NULL)
1988 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1991 Py_DECREF(pyus_in);
1992 if (pyus_out == NULL)
1993 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 result = microseconds_to_delta(pyus_out);
1996 Py_DECREF(pyus_out);
1997 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001998}
1999
2000static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00002001divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
2002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PyObject *pyus_left;
2004 PyObject *pyus_right;
2005 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 pyus_left = delta_to_microseconds(left);
2008 if (pyus_left == NULL)
2009 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 pyus_right = delta_to_microseconds(right);
2012 if (pyus_right == NULL) {
2013 Py_DECREF(pyus_left);
2014 return NULL;
2015 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 result = PyNumber_FloorDivide(pyus_left, pyus_right);
2018 Py_DECREF(pyus_left);
2019 Py_DECREF(pyus_right);
2020 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002021}
2022
2023static PyObject *
2024truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
2025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyObject *pyus_left;
2027 PyObject *pyus_right;
2028 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 pyus_left = delta_to_microseconds(left);
2031 if (pyus_left == NULL)
2032 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 pyus_right = delta_to_microseconds(right);
2035 if (pyus_right == NULL) {
2036 Py_DECREF(pyus_left);
2037 return NULL;
2038 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 result = PyNumber_TrueDivide(pyus_left, pyus_right);
2041 Py_DECREF(pyus_left);
2042 Py_DECREF(pyus_right);
2043 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002044}
2045
2046static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002047truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
2048{
2049 PyObject *result;
2050 PyObject *pyus_in, *pyus_out;
2051 pyus_in = delta_to_microseconds(delta);
2052 if (pyus_in == NULL)
2053 return NULL;
2054 pyus_out = divide_nearest(pyus_in, i);
2055 Py_DECREF(pyus_in);
2056 if (pyus_out == NULL)
2057 return NULL;
2058 result = microseconds_to_delta(pyus_out);
2059 Py_DECREF(pyus_out);
2060
2061 return result;
2062}
2063
2064static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002065delta_add(PyObject *left, PyObject *right)
2066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (PyDelta_Check(left) && PyDelta_Check(right)) {
2070 /* delta + delta */
2071 /* The C-level additions can't overflow because of the
2072 * invariant bounds.
2073 */
2074 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
2075 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
2076 int microseconds = GET_TD_MICROSECONDS(left) +
2077 GET_TD_MICROSECONDS(right);
2078 result = new_delta(days, seconds, microseconds, 1);
2079 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 if (result == Py_NotImplemented)
2082 Py_INCREF(result);
2083 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002084}
2085
2086static PyObject *
2087delta_negative(PyDateTime_Delta *self)
2088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 return new_delta(-GET_TD_DAYS(self),
2090 -GET_TD_SECONDS(self),
2091 -GET_TD_MICROSECONDS(self),
2092 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002093}
2094
2095static PyObject *
2096delta_positive(PyDateTime_Delta *self)
2097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 /* Could optimize this (by returning self) if this isn't a
2099 * subclass -- but who uses unary + ? Approximately nobody.
2100 */
2101 return new_delta(GET_TD_DAYS(self),
2102 GET_TD_SECONDS(self),
2103 GET_TD_MICROSECONDS(self),
2104 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002105}
2106
2107static PyObject *
2108delta_abs(PyDateTime_Delta *self)
2109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 assert(GET_TD_MICROSECONDS(self) >= 0);
2113 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (GET_TD_DAYS(self) < 0)
2116 result = delta_negative(self);
2117 else
2118 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002121}
2122
2123static PyObject *
2124delta_subtract(PyObject *left, PyObject *right)
2125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (PyDelta_Check(left) && PyDelta_Check(right)) {
2129 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04002130 /* The C-level additions can't overflow because of the
2131 * invariant bounds.
2132 */
2133 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
2134 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
2135 int microseconds = GET_TD_MICROSECONDS(left) -
2136 GET_TD_MICROSECONDS(right);
2137 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (result == Py_NotImplemented)
2141 Py_INCREF(result);
2142 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002143}
2144
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002145static int
2146delta_cmp(PyObject *self, PyObject *other)
2147{
2148 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
2149 if (diff == 0) {
2150 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
2151 if (diff == 0)
2152 diff = GET_TD_MICROSECONDS(self) -
2153 GET_TD_MICROSECONDS(other);
2154 }
2155 return diff;
2156}
2157
Tim Peters2a799bf2002-12-16 20:18:38 +00002158static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002159delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002162 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 return diff_to_bool(diff, op);
2164 }
2165 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05002166 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002168}
2169
2170static PyObject *delta_getstate(PyDateTime_Delta *self);
2171
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002172static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002173delta_hash(PyDateTime_Delta *self)
2174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 if (self->hashcode == -1) {
2176 PyObject *temp = delta_getstate(self);
2177 if (temp != NULL) {
2178 self->hashcode = PyObject_Hash(temp);
2179 Py_DECREF(temp);
2180 }
2181 }
2182 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002183}
2184
2185static PyObject *
2186delta_multiply(PyObject *left, PyObject *right)
2187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (PyDelta_Check(left)) {
2191 /* delta * ??? */
2192 if (PyLong_Check(right))
2193 result = multiply_int_timedelta(right,
2194 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002195 else if (PyFloat_Check(right))
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03002196 result = multiply_truedivide_timedelta_float(
2197 (PyDateTime_Delta *) left, right, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 }
2199 else if (PyLong_Check(left))
2200 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002201 (PyDateTime_Delta *) right);
2202 else if (PyFloat_Check(left))
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03002203 result = multiply_truedivide_timedelta_float(
2204 (PyDateTime_Delta *) right, left, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (result == Py_NotImplemented)
2207 Py_INCREF(result);
2208 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002209}
2210
2211static PyObject *
2212delta_divide(PyObject *left, PyObject *right)
2213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (PyDelta_Check(left)) {
2217 /* delta * ??? */
2218 if (PyLong_Check(right))
2219 result = divide_timedelta_int(
2220 (PyDateTime_Delta *)left,
2221 right);
2222 else if (PyDelta_Check(right))
2223 result = divide_timedelta_timedelta(
2224 (PyDateTime_Delta *)left,
2225 (PyDateTime_Delta *)right);
2226 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 if (result == Py_NotImplemented)
2229 Py_INCREF(result);
2230 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002231}
2232
Mark Dickinson7c186e22010-04-20 22:32:49 +00002233static PyObject *
2234delta_truedivide(PyObject *left, PyObject *right)
2235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (PyDelta_Check(left)) {
2239 if (PyDelta_Check(right))
2240 result = truedivide_timedelta_timedelta(
2241 (PyDateTime_Delta *)left,
2242 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002243 else if (PyFloat_Check(right))
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03002244 result = multiply_truedivide_timedelta_float(
2245 (PyDateTime_Delta *)left, right, 1);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002246 else if (PyLong_Check(right))
2247 result = truedivide_timedelta_int(
2248 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 if (result == Py_NotImplemented)
2252 Py_INCREF(result);
2253 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002254}
2255
2256static PyObject *
2257delta_remainder(PyObject *left, PyObject *right)
2258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 PyObject *pyus_left;
2260 PyObject *pyus_right;
2261 PyObject *pyus_remainder;
2262 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002263
Brian Curtindfc80e32011-08-10 20:28:54 -05002264 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2265 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2268 if (pyus_left == NULL)
2269 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2272 if (pyus_right == NULL) {
2273 Py_DECREF(pyus_left);
2274 return NULL;
2275 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
2278 Py_DECREF(pyus_left);
2279 Py_DECREF(pyus_right);
2280 if (pyus_remainder == NULL)
2281 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 remainder = microseconds_to_delta(pyus_remainder);
2284 Py_DECREF(pyus_remainder);
2285 if (remainder == NULL)
2286 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002289}
2290
2291static PyObject *
2292delta_divmod(PyObject *left, PyObject *right)
2293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 PyObject *pyus_left;
2295 PyObject *pyus_right;
2296 PyObject *divmod;
2297 PyObject *delta;
2298 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002299
Brian Curtindfc80e32011-08-10 20:28:54 -05002300 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2301 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2304 if (pyus_left == NULL)
2305 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2308 if (pyus_right == NULL) {
2309 Py_DECREF(pyus_left);
2310 return NULL;
2311 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002312
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02002313 divmod = checked_divmod(pyus_left, pyus_right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 Py_DECREF(pyus_left);
2315 Py_DECREF(pyus_right);
2316 if (divmod == NULL)
2317 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
2320 if (delta == NULL) {
2321 Py_DECREF(divmod);
2322 return NULL;
2323 }
2324 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
2325 Py_DECREF(delta);
2326 Py_DECREF(divmod);
2327 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002328}
2329
Tim Peters2a799bf2002-12-16 20:18:38 +00002330/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2331 * timedelta constructor. sofar is the # of microseconds accounted for
2332 * so far, and there are factor microseconds per current unit, the number
2333 * of which is given by num. num * factor is added to sofar in a
2334 * numerically careful way, and that's the result. Any fractional
2335 * microseconds left over (this can happen if num is a float type) are
2336 * added into *leftover.
2337 * Note that there are many ways this can give an error (NULL) return.
2338 */
2339static PyObject *
2340accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2341 double *leftover)
2342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 PyObject *prod;
2344 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 if (PyLong_Check(num)) {
Serhiy Storchaka3ec0f492018-11-20 20:41:09 +02002349 prod = PyNumber_Multiply(num, factor);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 if (prod == NULL)
2351 return NULL;
2352 sum = PyNumber_Add(sofar, prod);
2353 Py_DECREF(prod);
2354 return sum;
2355 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (PyFloat_Check(num)) {
2358 double dnum;
2359 double fracpart;
2360 double intpart;
2361 PyObject *x;
2362 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 /* The Plan: decompose num into an integer part and a
2365 * fractional part, num = intpart + fracpart.
2366 * Then num * factor ==
2367 * intpart * factor + fracpart * factor
2368 * and the LHS can be computed exactly in long arithmetic.
2369 * The RHS is again broken into an int part and frac part.
2370 * and the frac part is added into *leftover.
2371 */
2372 dnum = PyFloat_AsDouble(num);
2373 if (dnum == -1.0 && PyErr_Occurred())
2374 return NULL;
2375 fracpart = modf(dnum, &intpart);
2376 x = PyLong_FromDouble(intpart);
2377 if (x == NULL)
2378 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 prod = PyNumber_Multiply(x, factor);
2381 Py_DECREF(x);
2382 if (prod == NULL)
2383 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 sum = PyNumber_Add(sofar, prod);
2386 Py_DECREF(prod);
2387 if (sum == NULL)
2388 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 if (fracpart == 0.0)
2391 return sum;
2392 /* So far we've lost no information. Dealing with the
2393 * fractional part requires float arithmetic, and may
2394 * lose a little info.
2395 */
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03002396 assert(PyLong_CheckExact(factor));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 dnum *= fracpart;
2400 fracpart = modf(dnum, &intpart);
2401 x = PyLong_FromDouble(intpart);
2402 if (x == NULL) {
2403 Py_DECREF(sum);
2404 return NULL;
2405 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 y = PyNumber_Add(sum, x);
2408 Py_DECREF(sum);
2409 Py_DECREF(x);
2410 *leftover += fracpart;
2411 return y;
2412 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 PyErr_Format(PyExc_TypeError,
2415 "unsupported type for timedelta %s component: %s",
2416 tag, Py_TYPE(num)->tp_name);
2417 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002418}
2419
2420static PyObject *
2421delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 /* Argument objects. */
2426 PyObject *day = NULL;
2427 PyObject *second = NULL;
2428 PyObject *us = NULL;
2429 PyObject *ms = NULL;
2430 PyObject *minute = NULL;
2431 PyObject *hour = NULL;
2432 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 PyObject *x = NULL; /* running sum of microseconds */
2435 PyObject *y = NULL; /* temp sum of microseconds */
2436 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 static char *keywords[] = {
2439 "days", "seconds", "microseconds", "milliseconds",
2440 "minutes", "hours", "weeks", NULL
2441 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2444 keywords,
2445 &day, &second, &us,
2446 &ms, &minute, &hour, &week) == 0)
2447 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 x = PyLong_FromLong(0);
2450 if (x == NULL)
2451 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453#define CLEANUP \
2454 Py_DECREF(x); \
2455 x = y; \
2456 if (x == NULL) \
2457 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 if (us) {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002460 y = accum("microseconds", x, us, _PyLong_One, &leftover_us);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 CLEANUP;
2462 }
2463 if (ms) {
2464 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2465 CLEANUP;
2466 }
2467 if (second) {
2468 y = accum("seconds", x, second, us_per_second, &leftover_us);
2469 CLEANUP;
2470 }
2471 if (minute) {
2472 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2473 CLEANUP;
2474 }
2475 if (hour) {
2476 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2477 CLEANUP;
2478 }
2479 if (day) {
2480 y = accum("days", x, day, us_per_day, &leftover_us);
2481 CLEANUP;
2482 }
2483 if (week) {
2484 y = accum("weeks", x, week, us_per_week, &leftover_us);
2485 CLEANUP;
2486 }
2487 if (leftover_us) {
2488 /* Round to nearest whole # of us, and add into x. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002489 double whole_us = round(leftover_us);
Victor Stinner69cc4872015-09-08 23:58:54 +02002490 int x_is_odd;
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002491 PyObject *temp;
2492
Victor Stinner69cc4872015-09-08 23:58:54 +02002493 whole_us = round(leftover_us);
2494 if (fabs(whole_us - leftover_us) == 0.5) {
2495 /* We're exactly halfway between two integers. In order
2496 * to do round-half-to-even, we must determine whether x
2497 * is odd. Note that x is odd when it's last bit is 1. The
2498 * code below uses bitwise and operation to check the last
2499 * bit. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002500 temp = PyNumber_And(x, _PyLong_One); /* temp <- x & 1 */
Victor Stinner69cc4872015-09-08 23:58:54 +02002501 if (temp == NULL) {
2502 Py_DECREF(x);
2503 goto Done;
2504 }
2505 x_is_odd = PyObject_IsTrue(temp);
2506 Py_DECREF(temp);
2507 if (x_is_odd == -1) {
2508 Py_DECREF(x);
2509 goto Done;
2510 }
2511 whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2512 }
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002513
Victor Stinner36a5a062013-08-28 01:53:39 +02002514 temp = PyLong_FromLong((long)whole_us);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 if (temp == NULL) {
2517 Py_DECREF(x);
2518 goto Done;
2519 }
2520 y = PyNumber_Add(x, temp);
2521 Py_DECREF(temp);
2522 CLEANUP;
2523 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 self = microseconds_to_delta_ex(x, type);
2526 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002527Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002529
2530#undef CLEANUP
2531}
2532
2533static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002534delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 return (GET_TD_DAYS(self) != 0
2537 || GET_TD_SECONDS(self) != 0
2538 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002539}
2540
2541static PyObject *
2542delta_repr(PyDateTime_Delta *self)
2543{
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +02002544 PyObject *args = PyUnicode_FromString("");
Tim Peters2a799bf2002-12-16 20:18:38 +00002545
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +02002546 if (args == NULL) {
2547 return NULL;
2548 }
2549
2550 const char *sep = "";
2551
2552 if (GET_TD_DAYS(self) != 0) {
2553 Py_SETREF(args, PyUnicode_FromFormat("days=%d", GET_TD_DAYS(self)));
2554 if (args == NULL) {
2555 return NULL;
2556 }
2557 sep = ", ";
2558 }
2559
2560 if (GET_TD_SECONDS(self) != 0) {
2561 Py_SETREF(args, PyUnicode_FromFormat("%U%sseconds=%d", args, sep,
2562 GET_TD_SECONDS(self)));
2563 if (args == NULL) {
2564 return NULL;
2565 }
2566 sep = ", ";
2567 }
2568
2569 if (GET_TD_MICROSECONDS(self) != 0) {
2570 Py_SETREF(args, PyUnicode_FromFormat("%U%smicroseconds=%d", args, sep,
2571 GET_TD_MICROSECONDS(self)));
2572 if (args == NULL) {
2573 return NULL;
2574 }
2575 }
2576
2577 if (PyUnicode_GET_LENGTH(args) == 0) {
2578 Py_SETREF(args, PyUnicode_FromString("0"));
2579 if (args == NULL) {
2580 return NULL;
2581 }
2582 }
2583
2584 PyObject *repr = PyUnicode_FromFormat("%s(%S)", Py_TYPE(self)->tp_name,
2585 args);
2586 Py_DECREF(args);
2587 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00002588}
2589
2590static PyObject *
2591delta_str(PyDateTime_Delta *self)
2592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 int us = GET_TD_MICROSECONDS(self);
2594 int seconds = GET_TD_SECONDS(self);
2595 int minutes = divmod(seconds, 60, &seconds);
2596 int hours = divmod(minutes, 60, &minutes);
2597 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 if (days) {
2600 if (us)
2601 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2602 days, (days == 1 || days == -1) ? "" : "s",
2603 hours, minutes, seconds, us);
2604 else
2605 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2606 days, (days == 1 || days == -1) ? "" : "s",
2607 hours, minutes, seconds);
2608 } else {
2609 if (us)
2610 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2611 hours, minutes, seconds, us);
2612 else
2613 return PyUnicode_FromFormat("%d:%02d:%02d",
2614 hours, minutes, seconds);
2615 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002616
Tim Peters2a799bf2002-12-16 20:18:38 +00002617}
2618
Tim Peters371935f2003-02-01 01:52:50 +00002619/* Pickle support, a simple use of __reduce__. */
2620
Tim Petersb57f8f02003-02-01 02:54:15 +00002621/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002622static PyObject *
2623delta_getstate(PyDateTime_Delta *self)
2624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 return Py_BuildValue("iii", GET_TD_DAYS(self),
2626 GET_TD_SECONDS(self),
2627 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002628}
2629
Tim Peters2a799bf2002-12-16 20:18:38 +00002630static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302631delta_total_seconds(PyObject *self, PyObject *Py_UNUSED(ignored))
Antoine Pitroube6859d2009-11-25 23:02:32 +00002632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 PyObject *total_seconds;
2634 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2637 if (total_microseconds == NULL)
2638 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002639
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002640 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002644}
2645
2646static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302647delta_reduce(PyDateTime_Delta* self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00002648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002650}
2651
2652#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2653
2654static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 {"days", T_INT, OFFSET(days), READONLY,
2657 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 {"seconds", T_INT, OFFSET(seconds), READONLY,
2660 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2663 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2664 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002665};
2666
2667static PyMethodDef delta_methods[] = {
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05302668 {"total_seconds", delta_total_seconds, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2672 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002675};
2676
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002677static const char delta_doc[] =
Chris Barkerd6a61f22018-10-19 15:43:24 -07002678PyDoc_STR("Difference between two datetime values.\n\n"
2679 "timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, "
2680 "minutes=0, hours=0, weeks=0)\n\n"
2681 "All arguments are optional and default to 0.\n"
2682 "Arguments may be integers or floats, and may be positive or negative.");
Tim Peters2a799bf2002-12-16 20:18:38 +00002683
2684static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 delta_add, /* nb_add */
2686 delta_subtract, /* nb_subtract */
2687 delta_multiply, /* nb_multiply */
2688 delta_remainder, /* nb_remainder */
2689 delta_divmod, /* nb_divmod */
2690 0, /* nb_power */
2691 (unaryfunc)delta_negative, /* nb_negative */
2692 (unaryfunc)delta_positive, /* nb_positive */
2693 (unaryfunc)delta_abs, /* nb_absolute */
2694 (inquiry)delta_bool, /* nb_bool */
2695 0, /*nb_invert*/
2696 0, /*nb_lshift*/
2697 0, /*nb_rshift*/
2698 0, /*nb_and*/
2699 0, /*nb_xor*/
2700 0, /*nb_or*/
2701 0, /*nb_int*/
2702 0, /*nb_reserved*/
2703 0, /*nb_float*/
2704 0, /*nb_inplace_add*/
2705 0, /*nb_inplace_subtract*/
2706 0, /*nb_inplace_multiply*/
2707 0, /*nb_inplace_remainder*/
2708 0, /*nb_inplace_power*/
2709 0, /*nb_inplace_lshift*/
2710 0, /*nb_inplace_rshift*/
2711 0, /*nb_inplace_and*/
2712 0, /*nb_inplace_xor*/
2713 0, /*nb_inplace_or*/
2714 delta_divide, /* nb_floor_divide */
2715 delta_truedivide, /* nb_true_divide */
2716 0, /* nb_inplace_floor_divide */
2717 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002718};
2719
2720static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 PyVarObject_HEAD_INIT(NULL, 0)
2722 "datetime.timedelta", /* tp_name */
2723 sizeof(PyDateTime_Delta), /* tp_basicsize */
2724 0, /* tp_itemsize */
2725 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002726 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 0, /* tp_getattr */
2728 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002729 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 (reprfunc)delta_repr, /* tp_repr */
2731 &delta_as_number, /* tp_as_number */
2732 0, /* tp_as_sequence */
2733 0, /* tp_as_mapping */
2734 (hashfunc)delta_hash, /* tp_hash */
2735 0, /* tp_call */
2736 (reprfunc)delta_str, /* tp_str */
2737 PyObject_GenericGetAttr, /* tp_getattro */
2738 0, /* tp_setattro */
2739 0, /* tp_as_buffer */
2740 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2741 delta_doc, /* tp_doc */
2742 0, /* tp_traverse */
2743 0, /* tp_clear */
2744 delta_richcompare, /* tp_richcompare */
2745 0, /* tp_weaklistoffset */
2746 0, /* tp_iter */
2747 0, /* tp_iternext */
2748 delta_methods, /* tp_methods */
2749 delta_members, /* tp_members */
2750 0, /* tp_getset */
2751 0, /* tp_base */
2752 0, /* tp_dict */
2753 0, /* tp_descr_get */
2754 0, /* tp_descr_set */
2755 0, /* tp_dictoffset */
2756 0, /* tp_init */
2757 0, /* tp_alloc */
2758 delta_new, /* tp_new */
2759 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002760};
2761
2762/*
2763 * PyDateTime_Date implementation.
2764 */
2765
2766/* Accessor properties. */
2767
2768static PyObject *
2769date_year(PyDateTime_Date *self, void *unused)
2770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002772}
2773
2774static PyObject *
2775date_month(PyDateTime_Date *self, void *unused)
2776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002778}
2779
2780static PyObject *
2781date_day(PyDateTime_Date *self, void *unused)
2782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002784}
2785
2786static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 {"year", (getter)date_year},
2788 {"month", (getter)date_month},
2789 {"day", (getter)date_day},
2790 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002791};
2792
2793/* Constructors. */
2794
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002795static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002796
Tim Peters2a799bf2002-12-16 20:18:38 +00002797static PyObject *
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02002798date_from_pickle(PyTypeObject *type, PyObject *state)
2799{
2800 PyDateTime_Date *me;
2801
2802 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2803 if (me != NULL) {
2804 const char *pdata = PyBytes_AS_STRING(state);
2805 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2806 me->hashcode = -1;
2807 }
2808 return (PyObject *)me;
2809}
2810
2811static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002812date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 PyObject *self = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 int year;
2816 int month;
2817 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 /* Check for invocation from pickle with __getstate__ state */
Serhiy Storchaka1133a8c2018-12-07 16:48:21 +02002820 if (PyTuple_GET_SIZE(args) == 1) {
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02002821 PyObject *state = PyTuple_GET_ITEM(args, 0);
2822 if (PyBytes_Check(state)) {
2823 if (PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2824 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2825 {
2826 return date_from_pickle(type, state);
Victor Stinnerb37672d2018-11-22 03:37:50 +01002827 }
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02002828 }
2829 else if (PyUnicode_Check(state)) {
2830 if (PyUnicode_READY(state)) {
2831 return NULL;
2832 }
2833 if (PyUnicode_GET_LENGTH(state) == _PyDateTime_DATE_DATASIZE &&
2834 MONTH_IS_SANE(PyUnicode_READ_CHAR(state, 2)))
2835 {
2836 state = PyUnicode_AsLatin1String(state);
2837 if (state == NULL) {
2838 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
2839 /* More informative error message. */
2840 PyErr_SetString(PyExc_ValueError,
2841 "Failed to encode latin1 string when unpickling "
2842 "a date object. "
2843 "pickle.load(data, encoding='latin1') is assumed.");
2844 }
2845 return NULL;
2846 }
2847 self = date_from_pickle(type, state);
2848 Py_DECREF(state);
2849 return self;
2850 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2855 &year, &month, &day)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 self = new_date_ex(year, month, day, type);
2857 }
2858 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002859}
2860
Tim Peters2a799bf2002-12-16 20:18:38 +00002861static PyObject *
Tim Hoffmanna0fd7f12018-09-24 10:39:02 +02002862date_fromtimestamp(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002863{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002864 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002866
Victor Stinnere4a994d2015-03-30 01:10:14 +02002867 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002869
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04002870 if (_PyTime_localtime(t, &tm) != 0)
Victor Stinner21f58932012-03-14 00:15:40 +01002871 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01002872
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05002873 return new_date_subclass_ex(tm.tm_year + 1900,
2874 tm.tm_mon + 1,
2875 tm.tm_mday,
2876 cls);
Tim Peters2a799bf2002-12-16 20:18:38 +00002877}
2878
2879/* Return new date from current time.
2880 * We say this is equivalent to fromtimestamp(time.time()), and the
2881 * only way to be sure of that is to *call* time.time(). That's not
2882 * generally the same as calling C's time.
2883 */
2884static PyObject *
2885date_today(PyObject *cls, PyObject *dummy)
2886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyObject *time;
2888 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002889 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 time = time_time();
2892 if (time == NULL)
2893 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002895 /* Note well: today() is a class method, so this may not call
2896 * date.fromtimestamp. For example, it may call
2897 * datetime.fromtimestamp. That's why we need all the accuracy
2898 * time.time() delivers; if someone were gonzo about optimization,
2899 * date.today() could get away with plain C time().
2900 */
Victor Stinner20401de2016-12-09 15:24:31 +01002901 result = _PyObject_CallMethodIdObjArgs(cls, &PyId_fromtimestamp,
2902 time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 Py_DECREF(time);
2904 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002905}
2906
Tim Hoffmanna0fd7f12018-09-24 10:39:02 +02002907/*[clinic input]
2908@classmethod
2909datetime.date.fromtimestamp
2910
2911 timestamp: object
2912 /
2913
2914Create a date from a POSIX timestamp.
2915
2916The timestamp is a number, e.g. created via time.time(), that is interpreted
2917as local time.
2918[clinic start generated code]*/
2919
Tim Peters2a799bf2002-12-16 20:18:38 +00002920static PyObject *
Tim Hoffmanna0fd7f12018-09-24 10:39:02 +02002921datetime_date_fromtimestamp(PyTypeObject *type, PyObject *timestamp)
2922/*[clinic end generated code: output=fd045fda58168869 input=eabb3fe7f40491fe]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002923{
Tim Hoffmanna0fd7f12018-09-24 10:39:02 +02002924 return date_fromtimestamp((PyObject *) type, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002925}
2926
Paul Ganssle4d8c8c02019-04-27 15:39:40 -04002927/* bpo-36025: This is a wrapper for API compatibility with the public C API,
2928 * which expects a function that takes an *args tuple, whereas the argument
2929 * clinic generates code that takes METH_O.
2930 */
2931static PyObject *
2932datetime_date_fromtimestamp_capi(PyObject *cls, PyObject *args)
2933{
2934 PyObject *timestamp;
2935 PyObject *result = NULL;
2936
2937 if (PyArg_UnpackTuple(args, "fromtimestamp", 1, 1, &timestamp)) {
2938 result = date_fromtimestamp(cls, timestamp);
2939 }
2940
2941 return result;
2942}
2943
Tim Peters2a799bf2002-12-16 20:18:38 +00002944/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2945 * the ordinal is out of range.
2946 */
2947static PyObject *
2948date_fromordinal(PyObject *cls, PyObject *args)
2949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 PyObject *result = NULL;
2951 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2954 int year;
2955 int month;
2956 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 if (ordinal < 1)
2959 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2960 ">= 1");
2961 else {
2962 ord_to_ymd(ordinal, &year, &month, &day);
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05002963 result = new_date_subclass_ex(year, month, day, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 }
2965 }
2966 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002967}
2968
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002969/* Return the new date from a string as generated by date.isoformat() */
2970static PyObject *
Paul Ganssle3df85402018-10-22 12:32:52 -04002971date_fromisoformat(PyObject *cls, PyObject *dtstr)
2972{
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002973 assert(dtstr != NULL);
2974
2975 if (!PyUnicode_Check(dtstr)) {
Paul Ganssle3df85402018-10-22 12:32:52 -04002976 PyErr_SetString(PyExc_TypeError,
2977 "fromisoformat: argument must be str");
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002978 return NULL;
2979 }
2980
2981 Py_ssize_t len;
2982
Paul Ganssle3df85402018-10-22 12:32:52 -04002983 const char *dt_ptr = PyUnicode_AsUTF8AndSize(dtstr, &len);
Paul Ganssle096329f2018-08-23 11:06:20 -04002984 if (dt_ptr == NULL) {
2985 goto invalid_string_error;
2986 }
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002987
2988 int year = 0, month = 0, day = 0;
2989
2990 int rv;
2991 if (len == 10) {
2992 rv = parse_isoformat_date(dt_ptr, &year, &month, &day);
Paul Ganssle3df85402018-10-22 12:32:52 -04002993 }
2994 else {
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002995 rv = -1;
2996 }
2997
2998 if (rv < 0) {
Paul Ganssle096329f2018-08-23 11:06:20 -04002999 goto invalid_string_error;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05003000 }
3001
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05003002 return new_date_subclass_ex(year, month, day, cls);
Paul Ganssle096329f2018-08-23 11:06:20 -04003003
3004invalid_string_error:
Paul Ganssle3df85402018-10-22 12:32:52 -04003005 PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", dtstr);
Paul Ganssle096329f2018-08-23 11:06:20 -04003006 return NULL;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05003007}
3008
Paul Ganssle88c09372019-04-29 09:22:03 -04003009
3010static PyObject *
3011date_fromisocalendar(PyObject *cls, PyObject *args, PyObject *kw)
3012{
3013 static char *keywords[] = {
3014 "year", "week", "day", NULL
3015 };
3016
3017 int year, week, day;
3018 if (PyArg_ParseTupleAndKeywords(args, kw, "iii:fromisocalendar",
3019 keywords,
3020 &year, &week, &day) == 0) {
3021 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3022 PyErr_Format(PyExc_ValueError,
3023 "ISO calendar component out of range");
3024
3025 }
3026 return NULL;
3027 }
3028
3029 // Year is bounded to 0 < year < 10000 because 9999-12-31 is (9999, 52, 5)
3030 if (year < MINYEAR || year > MAXYEAR) {
3031 PyErr_Format(PyExc_ValueError, "Year is out of range: %d", year);
3032 return NULL;
3033 }
3034
3035 if (week <= 0 || week >= 53) {
3036 int out_of_range = 1;
3037 if (week == 53) {
3038 // ISO years have 53 weeks in it on years starting with a Thursday
3039 // and on leap years starting on Wednesday
3040 int first_weekday = weekday(year, 1, 1);
3041 if (first_weekday == 3 || (first_weekday == 2 && is_leap(year))) {
3042 out_of_range = 0;
3043 }
3044 }
3045
3046 if (out_of_range) {
3047 PyErr_Format(PyExc_ValueError, "Invalid week: %d", week);
3048 return NULL;
3049 }
3050 }
3051
3052 if (day <= 0 || day >= 8) {
3053 PyErr_Format(PyExc_ValueError, "Invalid day: %d (range is [1, 7])",
3054 day);
3055 return NULL;
3056 }
3057
3058 // Convert (Y, W, D) to (Y, M, D) in-place
3059 int day_1 = iso_week1_monday(year);
3060
3061 int month = week;
3062 int day_offset = (month - 1)*7 + day - 1;
3063
3064 ord_to_ymd(day_1 + day_offset, &year, &month, &day);
3065
3066 return new_date_subclass_ex(year, month, day, cls);
3067}
3068
3069
Tim Peters2a799bf2002-12-16 20:18:38 +00003070/*
3071 * Date arithmetic.
3072 */
3073
3074/* date + timedelta -> date. If arg negate is true, subtract the timedelta
3075 * instead.
3076 */
3077static PyObject *
3078add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
3079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 PyObject *result = NULL;
3081 int year = GET_YEAR(date);
3082 int month = GET_MONTH(date);
3083 int deltadays = GET_TD_DAYS(delta);
3084 /* C-level overflow is impossible because |deltadays| < 1e9. */
3085 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00003086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 if (normalize_date(&year, &month, &day) >= 0)
Paul Ganssle89427cd2019-02-04 14:42:04 -05003088 result = new_date_subclass_ex(year, month, day,
3089 (PyObject* )Py_TYPE(date));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003091}
3092
3093static PyObject *
3094date_add(PyObject *left, PyObject *right)
3095{
Brian Curtindfc80e32011-08-10 20:28:54 -05003096 if (PyDateTime_Check(left) || PyDateTime_Check(right))
3097 Py_RETURN_NOTIMPLEMENTED;
3098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 if (PyDate_Check(left)) {
3100 /* date + ??? */
3101 if (PyDelta_Check(right))
3102 /* date + delta */
3103 return add_date_timedelta((PyDateTime_Date *) left,
3104 (PyDateTime_Delta *) right,
3105 0);
3106 }
3107 else {
3108 /* ??? + date
3109 * 'right' must be one of us, or we wouldn't have been called
3110 */
3111 if (PyDelta_Check(left))
3112 /* delta + date */
3113 return add_date_timedelta((PyDateTime_Date *) right,
3114 (PyDateTime_Delta *) left,
3115 0);
3116 }
Brian Curtindfc80e32011-08-10 20:28:54 -05003117 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00003118}
3119
3120static PyObject *
3121date_subtract(PyObject *left, PyObject *right)
3122{
Brian Curtindfc80e32011-08-10 20:28:54 -05003123 if (PyDateTime_Check(left) || PyDateTime_Check(right))
3124 Py_RETURN_NOTIMPLEMENTED;
3125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 if (PyDate_Check(left)) {
3127 if (PyDate_Check(right)) {
3128 /* date - date */
3129 int left_ord = ymd_to_ord(GET_YEAR(left),
3130 GET_MONTH(left),
3131 GET_DAY(left));
3132 int right_ord = ymd_to_ord(GET_YEAR(right),
3133 GET_MONTH(right),
3134 GET_DAY(right));
3135 return new_delta(left_ord - right_ord, 0, 0, 0);
3136 }
3137 if (PyDelta_Check(right)) {
3138 /* date - delta */
3139 return add_date_timedelta((PyDateTime_Date *) left,
3140 (PyDateTime_Delta *) right,
3141 1);
3142 }
3143 }
Brian Curtindfc80e32011-08-10 20:28:54 -05003144 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00003145}
3146
3147
3148/* Various ways to turn a date into a string. */
3149
3150static PyObject *
3151date_repr(PyDateTime_Date *self)
3152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 return PyUnicode_FromFormat("%s(%d, %d, %d)",
3154 Py_TYPE(self)->tp_name,
3155 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003156}
3157
3158static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303159date_isoformat(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00003160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 return PyUnicode_FromFormat("%04d-%02d-%02d",
3162 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003163}
3164
Tim Peterse2df5ff2003-05-02 18:39:55 +00003165/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003166static PyObject *
3167date_str(PyDateTime_Date *self)
3168{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003169 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00003170}
3171
3172
3173static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303174date_ctime(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00003175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00003177}
3178
3179static PyObject *
3180date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
3181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 /* This method can be inherited, and needs to call the
3183 * timetuple() method appropriate to self's class.
3184 */
3185 PyObject *result;
3186 PyObject *tuple;
3187 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003188 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3192 &format))
3193 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003194
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003195 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 if (tuple == NULL)
3197 return NULL;
3198 result = wrap_strftime((PyObject *)self, format, tuple,
3199 (PyObject *)self);
3200 Py_DECREF(tuple);
3201 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003202}
3203
Eric Smith1ba31142007-09-11 18:06:02 +00003204static PyObject *
3205date_format(PyDateTime_Date *self, PyObject *args)
3206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 if (!PyArg_ParseTuple(args, "U:__format__", &format))
3210 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01003213 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00003215
Victor Stinner20401de2016-12-09 15:24:31 +01003216 return _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_strftime,
3217 format, NULL);
Eric Smith1ba31142007-09-11 18:06:02 +00003218}
3219
Tim Peters2a799bf2002-12-16 20:18:38 +00003220/* ISO methods. */
3221
3222static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303223date_isoweekday(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00003224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003228}
3229
3230static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303231date_isocalendar(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00003232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 int year = GET_YEAR(self);
3234 int week1_monday = iso_week1_monday(year);
3235 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
3236 int week;
3237 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00003238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 week = divmod(today - week1_monday, 7, &day);
3240 if (week < 0) {
3241 --year;
3242 week1_monday = iso_week1_monday(year);
3243 week = divmod(today - week1_monday, 7, &day);
3244 }
3245 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
3246 ++year;
3247 week = 0;
3248 }
3249 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003250}
3251
3252/* Miscellaneous methods. */
3253
Tim Peters2a799bf2002-12-16 20:18:38 +00003254static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003255date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00003256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 if (PyDate_Check(other)) {
3258 int diff = memcmp(((PyDateTime_Date *)self)->data,
3259 ((PyDateTime_Date *)other)->data,
3260 _PyDateTime_DATE_DATASIZE);
3261 return diff_to_bool(diff, op);
3262 }
Brian Curtindfc80e32011-08-10 20:28:54 -05003263 else
3264 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00003265}
3266
3267static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303268date_timetuple(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00003269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 return build_struct_time(GET_YEAR(self),
3271 GET_MONTH(self),
3272 GET_DAY(self),
3273 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003274}
3275
Tim Peters12bf3392002-12-24 05:41:27 +00003276static PyObject *
3277date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
3278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 PyObject *clone;
3280 PyObject *tuple;
3281 int year = GET_YEAR(self);
3282 int month = GET_MONTH(self);
3283 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
3286 &year, &month, &day))
3287 return NULL;
3288 tuple = Py_BuildValue("iii", year, month, day);
3289 if (tuple == NULL)
3290 return NULL;
3291 clone = date_new(Py_TYPE(self), tuple, NULL);
3292 Py_DECREF(tuple);
3293 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003294}
3295
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003296static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003297generic_hash(unsigned char *data, int len)
3298{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08003299 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003300}
3301
3302
3303static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003304
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003305static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00003306date_hash(PyDateTime_Date *self)
3307{
Benjamin Petersondec2df32016-09-09 17:46:24 -07003308 if (self->hashcode == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 self->hashcode = generic_hash(
3310 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Benjamin Petersondec2df32016-09-09 17:46:24 -07003311 }
Guido van Rossum254348e2007-11-21 19:29:53 +00003312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00003314}
3315
3316static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303317date_toordinal(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00003318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
3320 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00003321}
3322
3323static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303324date_weekday(PyDateTime_Date *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00003325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00003329}
3330
Tim Peters371935f2003-02-01 01:52:50 +00003331/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003332
Tim Petersb57f8f02003-02-01 02:54:15 +00003333/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00003334static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003335date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 PyObject* field;
3338 field = PyBytes_FromStringAndSize((char*)self->data,
3339 _PyDateTime_DATE_DATASIZE);
3340 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00003341}
3342
3343static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003344date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003347}
3348
3349static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 /* Class methods: */
Tim Hoffmanna0fd7f12018-09-24 10:39:02 +02003352 DATETIME_DATE_FROMTIMESTAMP_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
3355 METH_CLASS,
3356 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
3357 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003358
Paul Ganssle09dc2f52017-12-21 00:33:49 -05003359 {"fromisoformat", (PyCFunction)date_fromisoformat, METH_O |
3360 METH_CLASS,
3361 PyDoc_STR("str -> Construct a date from the output of date.isoformat()")},
3362
Paul Ganssle88c09372019-04-29 09:22:03 -04003363 {"fromisocalendar", (PyCFunction)(void(*)(void))date_fromisocalendar,
3364 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3365 PyDoc_STR("int, int, int -> Construct a date from the ISO year, week "
3366 "number and weekday.\n\n"
3367 "This is the inverse of the date.isocalendar() function")},
3368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
3370 PyDoc_STR("Current date or datetime: same as "
3371 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
3376 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003377
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003378 {"strftime", (PyCFunction)(void(*)(void))date_strftime, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3382 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
3385 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
3388 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
3389 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
3392 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
3395 PyDoc_STR("Return the day of the week represented by the date.\n"
3396 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
3399 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
3400 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
3403 PyDoc_STR("Return the day of the week represented by the date.\n"
3404 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003405
Serhiy Storchaka62be7422018-11-27 13:27:31 +02003406 {"replace", (PyCFunction)(void(*)(void))date_replace, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
3410 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003413};
3414
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003415static const char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003416PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00003417
3418static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 date_add, /* nb_add */
3420 date_subtract, /* nb_subtract */
3421 0, /* nb_multiply */
3422 0, /* nb_remainder */
3423 0, /* nb_divmod */
3424 0, /* nb_power */
3425 0, /* nb_negative */
3426 0, /* nb_positive */
3427 0, /* nb_absolute */
3428 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003429};
3430
3431static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 PyVarObject_HEAD_INIT(NULL, 0)
3433 "datetime.date", /* tp_name */
3434 sizeof(PyDateTime_Date), /* tp_basicsize */
3435 0, /* tp_itemsize */
3436 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003437 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 0, /* tp_getattr */
3439 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003440 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 (reprfunc)date_repr, /* tp_repr */
3442 &date_as_number, /* tp_as_number */
3443 0, /* tp_as_sequence */
3444 0, /* tp_as_mapping */
3445 (hashfunc)date_hash, /* tp_hash */
3446 0, /* tp_call */
3447 (reprfunc)date_str, /* tp_str */
3448 PyObject_GenericGetAttr, /* tp_getattro */
3449 0, /* tp_setattro */
3450 0, /* tp_as_buffer */
3451 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3452 date_doc, /* tp_doc */
3453 0, /* tp_traverse */
3454 0, /* tp_clear */
3455 date_richcompare, /* tp_richcompare */
3456 0, /* tp_weaklistoffset */
3457 0, /* tp_iter */
3458 0, /* tp_iternext */
3459 date_methods, /* tp_methods */
3460 0, /* tp_members */
3461 date_getset, /* tp_getset */
3462 0, /* tp_base */
3463 0, /* tp_dict */
3464 0, /* tp_descr_get */
3465 0, /* tp_descr_set */
3466 0, /* tp_dictoffset */
3467 0, /* tp_init */
3468 0, /* tp_alloc */
3469 date_new, /* tp_new */
3470 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003471};
3472
3473/*
Tim Peters2a799bf2002-12-16 20:18:38 +00003474 * PyDateTime_TZInfo implementation.
3475 */
3476
3477/* This is a pure abstract base class, so doesn't do anything beyond
3478 * raising NotImplemented exceptions. Real tzinfo classes need
3479 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00003480 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00003481 * be subclasses of this tzinfo class, which is easy and quick to check).
3482 *
3483 * Note: For reasons having to do with pickling of subclasses, we have
3484 * to allow tzinfo objects to be instantiated. This wasn't an issue
3485 * in the Python implementation (__init__() could raise NotImplementedError
3486 * there without ill effect), but doing so in the C implementation hit a
3487 * brick wall.
3488 */
3489
3490static PyObject *
3491tzinfo_nogo(const char* methodname)
3492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 PyErr_Format(PyExc_NotImplementedError,
3494 "a tzinfo subclass must implement %s()",
3495 methodname);
3496 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003497}
3498
3499/* Methods. A subclass must implement these. */
3500
Tim Peters52dcce22003-01-23 16:36:11 +00003501static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003502tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00003505}
3506
Tim Peters52dcce22003-01-23 16:36:11 +00003507static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003508tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00003511}
3512
Tim Peters52dcce22003-01-23 16:36:11 +00003513static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003514tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003517}
3518
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003519
3520static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
3521 PyDateTime_Delta *delta,
3522 int factor);
3523static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
3524static PyObject *datetime_dst(PyObject *self, PyObject *);
3525
Tim Peters52dcce22003-01-23 16:36:11 +00003526static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003527tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003528{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003529 PyObject *result = NULL;
3530 PyObject *off = NULL, *dst = NULL;
3531 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003532
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003533 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 PyErr_SetString(PyExc_TypeError,
3535 "fromutc: argument must be a datetime");
3536 return NULL;
3537 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003538 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3540 "is not self");
3541 return NULL;
3542 }
Tim Peters52dcce22003-01-23 16:36:11 +00003543
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003544 off = datetime_utcoffset(dt, NULL);
3545 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003547 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3549 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003550 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 }
Tim Peters52dcce22003-01-23 16:36:11 +00003552
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003553 dst = datetime_dst(dt, NULL);
3554 if (dst == NULL)
3555 goto Fail;
3556 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3558 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003559 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 }
Tim Peters52dcce22003-01-23 16:36:11 +00003561
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003562 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3563 if (delta == NULL)
3564 goto Fail;
3565 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003568
3569 Py_DECREF(dst);
3570 dst = call_dst(GET_DT_TZINFO(dt), result);
3571 if (dst == NULL)
3572 goto Fail;
3573 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 goto Inconsistent;
Alexander Belopolskyc79447b2015-09-27 21:41:55 -04003575 if (delta_bool((PyDateTime_Delta *)dst) != 0) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03003576 Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
Serhiy Storchaka576f1322016-01-05 21:27:54 +02003577 (PyDateTime_Delta *)dst, 1));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003578 if (result == NULL)
3579 goto Fail;
3580 }
3581 Py_DECREF(delta);
3582 Py_DECREF(dst);
3583 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003585
3586Inconsistent:
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02003587 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003589
Leo Ariasc3d95082018-02-03 18:36:10 -06003590 /* fall through to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003591Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003592 Py_XDECREF(off);
3593 Py_XDECREF(dst);
3594 Py_XDECREF(delta);
3595 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003597}
3598
Tim Peters2a799bf2002-12-16 20:18:38 +00003599/*
3600 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003601 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003602 */
3603
Guido van Rossum177e41a2003-01-30 22:06:23 +00003604static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303605tzinfo_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003606{
Victor Stinnerd1584d32016-08-23 00:11:04 +02003607 PyObject *args, *state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003609 _Py_IDENTIFIER(__getinitargs__);
3610 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003611
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003612 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 if (getinitargs != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003614 args = _PyObject_CallNoArg(getinitargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 Py_DECREF(getinitargs);
3616 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 return NULL;
3618 }
3619 }
3620 else {
3621 PyErr_Clear();
Victor Stinnerd1584d32016-08-23 00:11:04 +02003622
3623 args = PyTuple_New(0);
3624 if (args == NULL) {
3625 return NULL;
3626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003628
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003629 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 if (getstate != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003631 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 Py_DECREF(getstate);
3633 if (state == NULL) {
3634 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 return NULL;
3636 }
3637 }
3638 else {
3639 PyObject **dictptr;
3640 PyErr_Clear();
3641 state = Py_None;
3642 dictptr = _PyObject_GetDictPtr(self);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02003643 if (dictptr && *dictptr && PyDict_GET_SIZE(*dictptr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 state = *dictptr;
Victor Stinnerd1584d32016-08-23 00:11:04 +02003645 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 Py_INCREF(state);
3647 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 if (state == Py_None) {
3650 Py_DECREF(state);
3651 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3652 }
3653 else
3654 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003655}
Tim Peters2a799bf2002-12-16 20:18:38 +00003656
3657static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3660 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003663 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3664 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 {"dst", (PyCFunction)tzinfo_dst, METH_O,
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003667 PyDoc_STR("datetime -> DST offset as timedelta positive east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003670 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003671
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303672 {"__reduce__", tzinfo_reduce, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003676};
3677
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003678static const char tzinfo_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00003679PyDoc_STR("Abstract base class for time zone info objects.");
3680
Neal Norwitz227b5332006-03-22 09:28:35 +00003681static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 PyVarObject_HEAD_INIT(NULL, 0)
3683 "datetime.tzinfo", /* tp_name */
3684 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3685 0, /* tp_itemsize */
3686 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003687 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 0, /* tp_getattr */
3689 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003690 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 0, /* tp_repr */
3692 0, /* tp_as_number */
3693 0, /* tp_as_sequence */
3694 0, /* tp_as_mapping */
3695 0, /* tp_hash */
3696 0, /* tp_call */
3697 0, /* tp_str */
3698 PyObject_GenericGetAttr, /* tp_getattro */
3699 0, /* tp_setattro */
3700 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003701 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 tzinfo_doc, /* tp_doc */
3703 0, /* tp_traverse */
3704 0, /* tp_clear */
3705 0, /* tp_richcompare */
3706 0, /* tp_weaklistoffset */
3707 0, /* tp_iter */
3708 0, /* tp_iternext */
3709 tzinfo_methods, /* tp_methods */
3710 0, /* tp_members */
3711 0, /* tp_getset */
3712 0, /* tp_base */
3713 0, /* tp_dict */
3714 0, /* tp_descr_get */
3715 0, /* tp_descr_set */
3716 0, /* tp_dictoffset */
3717 0, /* tp_init */
3718 0, /* tp_alloc */
3719 PyType_GenericNew, /* tp_new */
3720 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003721};
3722
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003723static char *timezone_kws[] = {"offset", "name", NULL};
3724
3725static PyObject *
3726timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3727{
3728 PyObject *offset;
3729 PyObject *name = NULL;
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03003730 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|U:timezone", timezone_kws,
3731 &PyDateTime_DeltaType, &offset, &name))
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003732 return new_timezone(offset, name);
3733
3734 return NULL;
3735}
3736
3737static void
3738timezone_dealloc(PyDateTime_TimeZone *self)
3739{
3740 Py_CLEAR(self->offset);
3741 Py_CLEAR(self->name);
3742 Py_TYPE(self)->tp_free((PyObject *)self);
3743}
3744
3745static PyObject *
3746timezone_richcompare(PyDateTime_TimeZone *self,
3747 PyDateTime_TimeZone *other, int op)
3748{
Brian Curtindfc80e32011-08-10 20:28:54 -05003749 if (op != Py_EQ && op != Py_NE)
3750 Py_RETURN_NOTIMPLEMENTED;
Miss Islington (bot)dde944f2019-08-04 03:01:55 -07003751 if (!PyTZInfo_Check(other)) {
3752 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003753 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003754 return delta_richcompare(self->offset, other->offset, op);
3755}
3756
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003757static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003758timezone_hash(PyDateTime_TimeZone *self)
3759{
3760 return delta_hash((PyDateTime_Delta *)self->offset);
3761}
3762
3763/* Check argument type passed to tzname, utcoffset, or dst methods.
3764 Returns 0 for good argument. Returns -1 and sets exception info
3765 otherwise.
3766 */
3767static int
3768_timezone_check_argument(PyObject *dt, const char *meth)
3769{
3770 if (dt == Py_None || PyDateTime_Check(dt))
3771 return 0;
3772 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3773 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3774 return -1;
3775}
3776
3777static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003778timezone_repr(PyDateTime_TimeZone *self)
3779{
3780 /* Note that although timezone is not subclassable, it is convenient
3781 to use Py_TYPE(self)->tp_name here. */
3782 const char *type_name = Py_TYPE(self)->tp_name;
3783
3784 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3785 return PyUnicode_FromFormat("%s.utc", type_name);
3786
3787 if (self->name == NULL)
3788 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3789
3790 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3791 self->name);
3792}
3793
3794
3795static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003796timezone_str(PyDateTime_TimeZone *self)
3797{
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003798 int hours, minutes, seconds, microseconds;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003799 PyObject *offset;
3800 char sign;
3801
3802 if (self->name != NULL) {
3803 Py_INCREF(self->name);
3804 return self->name;
3805 }
Victor Stinner90fd8952015-09-08 00:12:49 +02003806 if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04003807 (GET_TD_DAYS(self->offset) == 0 &&
3808 GET_TD_SECONDS(self->offset) == 0 &&
3809 GET_TD_MICROSECONDS(self->offset) == 0))
3810 return PyUnicode_FromString("UTC");
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003811 /* Offset is normalized, so it is negative if days < 0 */
3812 if (GET_TD_DAYS(self->offset) < 0) {
3813 sign = '-';
3814 offset = delta_negative((PyDateTime_Delta *)self->offset);
3815 if (offset == NULL)
3816 return NULL;
3817 }
3818 else {
3819 sign = '+';
3820 offset = self->offset;
3821 Py_INCREF(offset);
3822 }
3823 /* Offset is not negative here. */
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003824 microseconds = GET_TD_MICROSECONDS(offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003825 seconds = GET_TD_SECONDS(offset);
3826 Py_DECREF(offset);
3827 minutes = divmod(seconds, 60, &seconds);
3828 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003829 if (microseconds != 0) {
3830 return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d.%06d",
3831 sign, hours, minutes,
3832 seconds, microseconds);
3833 }
3834 if (seconds != 0) {
3835 return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d",
3836 sign, hours, minutes, seconds);
3837 }
Victor Stinner6ced7c42011-03-21 18:15:42 +01003838 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003839}
3840
3841static PyObject *
3842timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3843{
3844 if (_timezone_check_argument(dt, "tzname") == -1)
3845 return NULL;
3846
3847 return timezone_str(self);
3848}
3849
3850static PyObject *
3851timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3852{
3853 if (_timezone_check_argument(dt, "utcoffset") == -1)
3854 return NULL;
3855
3856 Py_INCREF(self->offset);
3857 return self->offset;
3858}
3859
3860static PyObject *
3861timezone_dst(PyObject *self, PyObject *dt)
3862{
3863 if (_timezone_check_argument(dt, "dst") == -1)
3864 return NULL;
3865
3866 Py_RETURN_NONE;
3867}
3868
3869static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003870timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3871{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003872 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003873 PyErr_SetString(PyExc_TypeError,
3874 "fromutc: argument must be a datetime");
3875 return NULL;
3876 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003877 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003878 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3879 "is not self");
3880 return NULL;
3881 }
3882
3883 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3884}
3885
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003886static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05303887timezone_getinitargs(PyDateTime_TimeZone *self, PyObject *Py_UNUSED(ignored))
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003888{
3889 if (self->name == NULL)
3890 return Py_BuildValue("(O)", self->offset);
3891 return Py_BuildValue("(OO)", self->offset, self->name);
3892}
3893
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003894static PyMethodDef timezone_methods[] = {
3895 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3896 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003897 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003898
3899 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003900 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003901
3902 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003903 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003904
3905 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3906 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3907
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003908 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3909 PyDoc_STR("pickle support")},
3910
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003911 {NULL, NULL}
3912};
3913
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003914static const char timezone_doc[] =
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003915PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3916
3917static PyTypeObject PyDateTime_TimeZoneType = {
3918 PyVarObject_HEAD_INIT(NULL, 0)
3919 "datetime.timezone", /* tp_name */
3920 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3921 0, /* tp_itemsize */
3922 (destructor)timezone_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003923 0, /* tp_vectorcall_offset */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003924 0, /* tp_getattr */
3925 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003926 0, /* tp_as_async */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003927 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003928 0, /* tp_as_number */
3929 0, /* tp_as_sequence */
3930 0, /* tp_as_mapping */
3931 (hashfunc)timezone_hash, /* tp_hash */
3932 0, /* tp_call */
3933 (reprfunc)timezone_str, /* tp_str */
3934 0, /* tp_getattro */
3935 0, /* tp_setattro */
3936 0, /* tp_as_buffer */
3937 Py_TPFLAGS_DEFAULT, /* tp_flags */
3938 timezone_doc, /* tp_doc */
3939 0, /* tp_traverse */
3940 0, /* tp_clear */
3941 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3942 0, /* tp_weaklistoffset */
3943 0, /* tp_iter */
3944 0, /* tp_iternext */
3945 timezone_methods, /* tp_methods */
3946 0, /* tp_members */
3947 0, /* tp_getset */
3948 &PyDateTime_TZInfoType, /* tp_base */
3949 0, /* tp_dict */
3950 0, /* tp_descr_get */
3951 0, /* tp_descr_set */
3952 0, /* tp_dictoffset */
3953 0, /* tp_init */
3954 0, /* tp_alloc */
3955 timezone_new, /* tp_new */
3956};
3957
Tim Peters2a799bf2002-12-16 20:18:38 +00003958/*
Tim Peters37f39822003-01-10 03:49:02 +00003959 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003960 */
3961
Tim Peters37f39822003-01-10 03:49:02 +00003962/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003963 */
3964
3965static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003966time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003969}
3970
Tim Peters37f39822003-01-10 03:49:02 +00003971static PyObject *
3972time_minute(PyDateTime_Time *self, void *unused)
3973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003975}
3976
3977/* The name time_second conflicted with some platform header file. */
3978static PyObject *
3979py_time_second(PyDateTime_Time *self, void *unused)
3980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003982}
3983
3984static PyObject *
3985time_microsecond(PyDateTime_Time *self, void *unused)
3986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003988}
3989
3990static PyObject *
3991time_tzinfo(PyDateTime_Time *self, void *unused)
3992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3994 Py_INCREF(result);
3995 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003996}
3997
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003998static PyObject *
3999time_fold(PyDateTime_Time *self, void *unused)
4000{
4001 return PyLong_FromLong(TIME_GET_FOLD(self));
4002}
4003
Tim Peters37f39822003-01-10 03:49:02 +00004004static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 {"hour", (getter)time_hour},
4006 {"minute", (getter)time_minute},
4007 {"second", (getter)py_time_second},
4008 {"microsecond", (getter)time_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004009 {"tzinfo", (getter)time_tzinfo},
4010 {"fold", (getter)time_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004012};
4013
4014/*
4015 * Constructors.
4016 */
4017
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004018static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004019 "tzinfo", "fold", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00004020
Tim Peters2a799bf2002-12-16 20:18:38 +00004021static PyObject *
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02004022time_from_pickle(PyTypeObject *type, PyObject *state, PyObject *tzinfo)
4023{
4024 PyDateTime_Time *me;
4025 char aware = (char)(tzinfo != Py_None);
4026
4027 if (aware && check_tzinfo_subclass(tzinfo) < 0) {
4028 PyErr_SetString(PyExc_TypeError, "bad tzinfo state arg");
4029 return NULL;
4030 }
4031
4032 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
4033 if (me != NULL) {
4034 const char *pdata = PyBytes_AS_STRING(state);
4035
4036 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
4037 me->hashcode = -1;
4038 me->hastzinfo = aware;
4039 if (aware) {
4040 Py_INCREF(tzinfo);
4041 me->tzinfo = tzinfo;
4042 }
4043 if (pdata[0] & (1 << 7)) {
4044 me->data[0] -= 128;
4045 me->fold = 1;
4046 }
4047 else {
4048 me->fold = 0;
4049 }
4050 }
4051 return (PyObject *)me;
4052}
4053
4054static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00004055time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 PyObject *self = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 int hour = 0;
4059 int minute = 0;
4060 int second = 0;
4061 int usecond = 0;
4062 PyObject *tzinfo = Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004063 int fold = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 /* Check for invocation from pickle with __getstate__ state */
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02004066 if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2) {
4067 PyObject *state = PyTuple_GET_ITEM(args, 0);
4068 if (PyTuple_GET_SIZE(args) == 2) {
4069 tzinfo = PyTuple_GET_ITEM(args, 1);
4070 }
4071 if (PyBytes_Check(state)) {
4072 if (PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
4073 (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
4074 {
4075 return time_from_pickle(type, state, tzinfo);
4076 }
4077 }
4078 else if (PyUnicode_Check(state)) {
4079 if (PyUnicode_READY(state)) {
4080 return NULL;
4081 }
4082 if (PyUnicode_GET_LENGTH(state) == _PyDateTime_TIME_DATASIZE &&
4083 (0x7F & PyUnicode_READ_CHAR(state, 2)) < 24)
4084 {
4085 state = PyUnicode_AsLatin1String(state);
4086 if (state == NULL) {
4087 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4088 /* More informative error message. */
4089 PyErr_SetString(PyExc_ValueError,
4090 "Failed to encode latin1 string when unpickling "
4091 "a time object. "
4092 "pickle.load(data, encoding='latin1') is assumed.");
4093 }
Victor Stinnerb37672d2018-11-22 03:37:50 +01004094 return NULL;
4095 }
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02004096 self = time_from_pickle(type, state, tzinfo);
4097 Py_DECREF(state);
4098 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 }
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02004101 tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004103
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004104 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 &hour, &minute, &second, &usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004106 &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004107 self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
4108 type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 }
4110 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004111}
4112
4113/*
4114 * Destructor.
4115 */
4116
4117static void
Tim Peters37f39822003-01-10 03:49:02 +00004118time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 if (HASTZINFO(self)) {
4121 Py_XDECREF(self->tzinfo);
4122 }
4123 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004124}
4125
4126/*
Tim Peters855fe882002-12-22 03:43:39 +00004127 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00004128 */
4129
Tim Peters2a799bf2002-12-16 20:18:38 +00004130/* These are all METH_NOARGS, so don't need to check the arglist. */
4131static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004132time_utcoffset(PyObject *self, PyObject *unused) {
4133 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004134}
4135
4136static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004137time_dst(PyObject *self, PyObject *unused) {
4138 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00004139}
4140
4141static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00004142time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004143 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004144}
4145
4146/*
Tim Peters37f39822003-01-10 03:49:02 +00004147 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004148 */
4149
4150static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00004151time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 const char *type_name = Py_TYPE(self)->tp_name;
4154 int h = TIME_GET_HOUR(self);
4155 int m = TIME_GET_MINUTE(self);
4156 int s = TIME_GET_SECOND(self);
4157 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004158 int fold = TIME_GET_FOLD(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 if (us)
4162 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
4163 type_name, h, m, s, us);
4164 else if (s)
4165 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
4166 type_name, h, m, s);
4167 else
4168 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
4169 if (result != NULL && HASTZINFO(self))
4170 result = append_keyword_tzinfo(result, self->tzinfo);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004171 if (result != NULL && fold)
4172 result = append_keyword_fold(result, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004174}
4175
Tim Peters37f39822003-01-10 03:49:02 +00004176static PyObject *
4177time_str(PyDateTime_Time *self)
4178{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07004179 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters37f39822003-01-10 03:49:02 +00004180}
Tim Peters2a799bf2002-12-16 20:18:38 +00004181
4182static PyObject *
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004183time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 char buf[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004186 char *timespec = NULL;
4187 static char *keywords[] = {"timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02004189 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004190 static char *specs[][2] = {
4191 {"hours", "%02d"},
4192 {"minutes", "%02d:%02d"},
4193 {"seconds", "%02d:%02d:%02d"},
4194 {"milliseconds", "%02d:%02d:%02d.%03d"},
4195 {"microseconds", "%02d:%02d:%02d.%06d"},
4196 };
4197 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00004198
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004199 if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
4200 return NULL;
4201
4202 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4203 if (us == 0) {
4204 /* seconds */
4205 given_spec = 2;
4206 }
4207 else {
4208 /* microseconds */
4209 given_spec = 4;
4210 }
4211 }
4212 else {
4213 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4214 if (strcmp(timespec, specs[given_spec][0]) == 0) {
4215 if (given_spec == 3) {
4216 /* milliseconds */
4217 us = us / 1000;
4218 }
4219 break;
4220 }
4221 }
4222 }
4223
4224 if (given_spec == Py_ARRAY_LENGTH(specs)) {
4225 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4226 return NULL;
4227 }
4228 else {
4229 result = PyUnicode_FromFormat(specs[given_spec][1],
4230 TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
4231 TIME_GET_SECOND(self), us);
4232 }
Tim Peters37f39822003-01-10 03:49:02 +00004233
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004234 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 /* We need to append the UTC offset. */
4238 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4239 Py_None) < 0) {
4240 Py_DECREF(result);
4241 return NULL;
4242 }
4243 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
4244 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004245}
4246
Tim Peters37f39822003-01-10 03:49:02 +00004247static PyObject *
4248time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
4249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 PyObject *result;
4251 PyObject *tuple;
4252 PyObject *format;
4253 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
4256 &format))
4257 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00004258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 /* Python's strftime does insane things with the year part of the
4260 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00004261 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 */
4263 tuple = Py_BuildValue("iiiiiiiii",
4264 1900, 1, 1, /* year, month, day */
4265 TIME_GET_HOUR(self),
4266 TIME_GET_MINUTE(self),
4267 TIME_GET_SECOND(self),
4268 0, 1, -1); /* weekday, daynum, dst */
4269 if (tuple == NULL)
4270 return NULL;
4271 assert(PyTuple_Size(tuple) == 9);
4272 result = wrap_strftime((PyObject *)self, format, tuple,
4273 Py_None);
4274 Py_DECREF(tuple);
4275 return result;
Tim Peters37f39822003-01-10 03:49:02 +00004276}
Tim Peters2a799bf2002-12-16 20:18:38 +00004277
4278/*
4279 * Miscellaneous methods.
4280 */
4281
Tim Peters37f39822003-01-10 03:49:02 +00004282static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004283time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00004284{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004285 PyObject *result = NULL;
4286 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00004288
Brian Curtindfc80e32011-08-10 20:28:54 -05004289 if (! PyTime_Check(other))
4290 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004291
4292 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 diff = memcmp(((PyDateTime_Time *)self)->data,
4294 ((PyDateTime_Time *)other)->data,
4295 _PyDateTime_TIME_DATASIZE);
4296 return diff_to_bool(diff, op);
4297 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004298 offset1 = time_utcoffset(self, NULL);
4299 if (offset1 == NULL)
4300 return NULL;
4301 offset2 = time_utcoffset(other, NULL);
4302 if (offset2 == NULL)
4303 goto done;
4304 /* If they're both naive, or both aware and have the same offsets,
4305 * we get off cheap. Note that if they're both naive, offset1 ==
4306 * offset2 == Py_None at this point.
4307 */
4308 if ((offset1 == offset2) ||
4309 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4310 delta_cmp(offset1, offset2) == 0)) {
4311 diff = memcmp(((PyDateTime_Time *)self)->data,
4312 ((PyDateTime_Time *)other)->data,
4313 _PyDateTime_TIME_DATASIZE);
4314 result = diff_to_bool(diff, op);
4315 }
4316 /* The hard case: both aware with different UTC offsets */
4317 else if (offset1 != Py_None && offset2 != Py_None) {
4318 int offsecs1, offsecs2;
4319 assert(offset1 != offset2); /* else last "if" handled it */
4320 offsecs1 = TIME_GET_HOUR(self) * 3600 +
4321 TIME_GET_MINUTE(self) * 60 +
4322 TIME_GET_SECOND(self) -
4323 GET_TD_DAYS(offset1) * 86400 -
4324 GET_TD_SECONDS(offset1);
4325 offsecs2 = TIME_GET_HOUR(other) * 3600 +
4326 TIME_GET_MINUTE(other) * 60 +
4327 TIME_GET_SECOND(other) -
4328 GET_TD_DAYS(offset2) * 86400 -
4329 GET_TD_SECONDS(offset2);
4330 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 if (diff == 0)
4332 diff = TIME_GET_MICROSECOND(self) -
4333 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004334 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004336 else if (op == Py_EQ) {
4337 result = Py_False;
4338 Py_INCREF(result);
4339 }
4340 else if (op == Py_NE) {
4341 result = Py_True;
4342 Py_INCREF(result);
4343 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004344 else {
4345 PyErr_SetString(PyExc_TypeError,
4346 "can't compare offset-naive and "
4347 "offset-aware times");
4348 }
4349 done:
4350 Py_DECREF(offset1);
4351 Py_XDECREF(offset2);
4352 return result;
Tim Peters37f39822003-01-10 03:49:02 +00004353}
4354
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004355static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00004356time_hash(PyDateTime_Time *self)
4357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004359 PyObject *offset, *self0;
Victor Stinner423c16b2017-01-03 23:47:12 +01004360 if (TIME_GET_FOLD(self)) {
4361 self0 = new_time_ex2(TIME_GET_HOUR(self),
4362 TIME_GET_MINUTE(self),
4363 TIME_GET_SECOND(self),
4364 TIME_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004365 HASTZINFO(self) ? self->tzinfo : Py_None,
4366 0, Py_TYPE(self));
4367 if (self0 == NULL)
4368 return -1;
4369 }
4370 else {
4371 self0 = (PyObject *)self;
4372 Py_INCREF(self0);
4373 }
4374 offset = time_utcoffset(self0, NULL);
4375 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004376
4377 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00004379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004381 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 self->hashcode = generic_hash(
4383 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004385 PyObject *temp1, *temp2;
4386 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004388 seconds = TIME_GET_HOUR(self) * 3600 +
4389 TIME_GET_MINUTE(self) * 60 +
4390 TIME_GET_SECOND(self);
4391 microseconds = TIME_GET_MICROSECOND(self);
4392 temp1 = new_delta(0, seconds, microseconds, 1);
4393 if (temp1 == NULL) {
4394 Py_DECREF(offset);
4395 return -1;
4396 }
4397 temp2 = delta_subtract(temp1, offset);
4398 Py_DECREF(temp1);
4399 if (temp2 == NULL) {
4400 Py_DECREF(offset);
4401 return -1;
4402 }
4403 self->hashcode = PyObject_Hash(temp2);
4404 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004406 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 }
4408 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00004409}
Tim Peters2a799bf2002-12-16 20:18:38 +00004410
Tim Peters12bf3392002-12-24 05:41:27 +00004411static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00004412time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 PyObject *clone;
4415 PyObject *tuple;
4416 int hh = TIME_GET_HOUR(self);
4417 int mm = TIME_GET_MINUTE(self);
4418 int ss = TIME_GET_SECOND(self);
4419 int us = TIME_GET_MICROSECOND(self);
4420 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004421 int fold = TIME_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00004422
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004423 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 time_kws,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004425 &hh, &mm, &ss, &us, &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03004427 if (fold != 0 && fold != 1) {
4428 PyErr_SetString(PyExc_ValueError,
4429 "fold must be either 0 or 1");
4430 return NULL;
4431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
4433 if (tuple == NULL)
4434 return NULL;
4435 clone = time_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04004436 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004437 TIME_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04004438 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 Py_DECREF(tuple);
4440 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004441}
4442
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004443static PyObject *
4444time_fromisoformat(PyObject *cls, PyObject *tstr) {
4445 assert(tstr != NULL);
4446
4447 if (!PyUnicode_Check(tstr)) {
4448 PyErr_SetString(PyExc_TypeError, "fromisoformat: argument must be str");
4449 return NULL;
4450 }
4451
4452 Py_ssize_t len;
4453 const char *p = PyUnicode_AsUTF8AndSize(tstr, &len);
4454
Paul Ganssle096329f2018-08-23 11:06:20 -04004455 if (p == NULL) {
4456 goto invalid_string_error;
4457 }
4458
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004459 int hour = 0, minute = 0, second = 0, microsecond = 0;
4460 int tzoffset, tzimicrosecond = 0;
4461 int rv = parse_isoformat_time(p, len,
4462 &hour, &minute, &second, &microsecond,
4463 &tzoffset, &tzimicrosecond);
4464
4465 if (rv < 0) {
Paul Ganssle096329f2018-08-23 11:06:20 -04004466 goto invalid_string_error;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004467 }
4468
4469 PyObject *tzinfo = tzinfo_from_isoformat_results(rv, tzoffset,
4470 tzimicrosecond);
4471
4472 if (tzinfo == NULL) {
4473 return NULL;
4474 }
4475
4476 PyObject *t;
4477 if ( (PyTypeObject *)cls == &PyDateTime_TimeType ) {
4478 t = new_time(hour, minute, second, microsecond, tzinfo, 0);
4479 } else {
4480 t = PyObject_CallFunction(cls, "iiiiO",
4481 hour, minute, second, microsecond, tzinfo);
4482 }
4483
4484 Py_DECREF(tzinfo);
4485 return t;
Paul Ganssle096329f2018-08-23 11:06:20 -04004486
4487invalid_string_error:
4488 PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", tstr);
4489 return NULL;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004490}
4491
4492
Tim Peters371935f2003-02-01 01:52:50 +00004493/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00004494
Tim Peters33e0f382003-01-10 02:05:14 +00004495/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004496 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4497 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004498 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004499 */
4500static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004501time_getstate(PyDateTime_Time *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00004502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 PyObject *basestate;
4504 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 basestate = PyBytes_FromStringAndSize((char *)self->data,
4507 _PyDateTime_TIME_DATASIZE);
4508 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004509 if (proto > 3 && TIME_GET_FOLD(self))
4510 /* Set the first bit of the first byte */
4511 PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4513 result = PyTuple_Pack(1, basestate);
4514 else
4515 result = PyTuple_Pack(2, basestate, self->tzinfo);
4516 Py_DECREF(basestate);
4517 }
4518 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004519}
4520
4521static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004522time_reduce_ex(PyDateTime_Time *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00004523{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004524 int proto;
4525 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004526 return NULL;
4527
4528 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00004529}
4530
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004531static PyObject *
4532time_reduce(PyDateTime_Time *self, PyObject *arg)
4533{
4534 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, 2));
4535}
4536
Tim Peters37f39822003-01-10 03:49:02 +00004537static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004538
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004539 {"isoformat", (PyCFunction)(void(*)(void))time_isoformat, METH_VARARGS | METH_KEYWORDS,
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004540 PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
4541 "[+HH:MM].\n\n"
4542 "timespec specifies what components of the time to include.\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004543
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004544 {"strftime", (PyCFunction)(void(*)(void))time_strftime, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00004546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 {"__format__", (PyCFunction)date_format, METH_VARARGS,
4548 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00004549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
4551 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
4554 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 {"dst", (PyCFunction)time_dst, METH_NOARGS,
4557 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004558
Serhiy Storchaka62be7422018-11-27 13:27:31 +02004559 {"replace", (PyCFunction)(void(*)(void))time_replace, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004561
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004562 {"fromisoformat", (PyCFunction)time_fromisoformat, METH_O | METH_CLASS,
4563 PyDoc_STR("string -> time from time.isoformat() output")},
4564
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004565 {"__reduce_ex__", (PyCFunction)time_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004566 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004567
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004568 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
4569 PyDoc_STR("__reduce__() -> (cls, state)")},
4570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004572};
4573
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004574static const char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004575PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
4576\n\
4577All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03004578a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004579
Neal Norwitz227b5332006-03-22 09:28:35 +00004580static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 PyVarObject_HEAD_INIT(NULL, 0)
4582 "datetime.time", /* tp_name */
4583 sizeof(PyDateTime_Time), /* tp_basicsize */
4584 0, /* tp_itemsize */
4585 (destructor)time_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004586 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 0, /* tp_getattr */
4588 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004589 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05004591 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 0, /* tp_as_sequence */
4593 0, /* tp_as_mapping */
4594 (hashfunc)time_hash, /* tp_hash */
4595 0, /* tp_call */
4596 (reprfunc)time_str, /* tp_str */
4597 PyObject_GenericGetAttr, /* tp_getattro */
4598 0, /* tp_setattro */
4599 0, /* tp_as_buffer */
4600 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4601 time_doc, /* tp_doc */
4602 0, /* tp_traverse */
4603 0, /* tp_clear */
4604 time_richcompare, /* tp_richcompare */
4605 0, /* tp_weaklistoffset */
4606 0, /* tp_iter */
4607 0, /* tp_iternext */
4608 time_methods, /* tp_methods */
4609 0, /* tp_members */
4610 time_getset, /* tp_getset */
4611 0, /* tp_base */
4612 0, /* tp_dict */
4613 0, /* tp_descr_get */
4614 0, /* tp_descr_set */
4615 0, /* tp_dictoffset */
4616 0, /* tp_init */
4617 time_alloc, /* tp_alloc */
4618 time_new, /* tp_new */
4619 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004620};
4621
4622/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004623 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00004624 */
4625
Tim Petersa9bc1682003-01-11 03:39:11 +00004626/* Accessor properties. Properties for day, month, and year are inherited
4627 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004628 */
4629
4630static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004631datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00004632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004634}
4635
Tim Petersa9bc1682003-01-11 03:39:11 +00004636static PyObject *
4637datetime_minute(PyDateTime_DateTime *self, void *unused)
4638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004640}
4641
4642static PyObject *
4643datetime_second(PyDateTime_DateTime *self, void *unused)
4644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004646}
4647
4648static PyObject *
4649datetime_microsecond(PyDateTime_DateTime *self, void *unused)
4650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004652}
4653
4654static PyObject *
4655datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
4656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4658 Py_INCREF(result);
4659 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004660}
4661
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004662static PyObject *
4663datetime_fold(PyDateTime_DateTime *self, void *unused)
4664{
4665 return PyLong_FromLong(DATE_GET_FOLD(self));
4666}
4667
Tim Petersa9bc1682003-01-11 03:39:11 +00004668static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 {"hour", (getter)datetime_hour},
4670 {"minute", (getter)datetime_minute},
4671 {"second", (getter)datetime_second},
4672 {"microsecond", (getter)datetime_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004673 {"tzinfo", (getter)datetime_tzinfo},
4674 {"fold", (getter)datetime_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004676};
4677
4678/*
4679 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004680 */
4681
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004682static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 "year", "month", "day", "hour", "minute", "second",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004684 "microsecond", "tzinfo", "fold", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004685};
4686
Tim Peters2a799bf2002-12-16 20:18:38 +00004687static PyObject *
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02004688datetime_from_pickle(PyTypeObject *type, PyObject *state, PyObject *tzinfo)
4689{
4690 PyDateTime_DateTime *me;
4691 char aware = (char)(tzinfo != Py_None);
4692
4693 if (aware && check_tzinfo_subclass(tzinfo) < 0) {
4694 PyErr_SetString(PyExc_TypeError, "bad tzinfo state arg");
4695 return NULL;
4696 }
4697
4698 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4699 if (me != NULL) {
4700 const char *pdata = PyBytes_AS_STRING(state);
4701
4702 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4703 me->hashcode = -1;
4704 me->hastzinfo = aware;
4705 if (aware) {
4706 Py_INCREF(tzinfo);
4707 me->tzinfo = tzinfo;
4708 }
4709 if (pdata[2] & (1 << 7)) {
4710 me->data[2] -= 128;
4711 me->fold = 1;
4712 }
4713 else {
4714 me->fold = 0;
4715 }
4716 }
4717 return (PyObject *)me;
4718}
4719
4720static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004721datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 PyObject *self = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 int year;
4725 int month;
4726 int day;
4727 int hour = 0;
4728 int minute = 0;
4729 int second = 0;
4730 int usecond = 0;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004731 int fold = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 /* Check for invocation from pickle with __getstate__ state */
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02004735 if (PyTuple_GET_SIZE(args) >= 1 && PyTuple_GET_SIZE(args) <= 2) {
4736 PyObject *state = PyTuple_GET_ITEM(args, 0);
4737 if (PyTuple_GET_SIZE(args) == 2) {
4738 tzinfo = PyTuple_GET_ITEM(args, 1);
4739 }
4740 if (PyBytes_Check(state)) {
4741 if (PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
4742 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
4743 {
4744 return datetime_from_pickle(type, state, tzinfo);
4745 }
4746 }
4747 else if (PyUnicode_Check(state)) {
4748 if (PyUnicode_READY(state)) {
4749 return NULL;
4750 }
4751 if (PyUnicode_GET_LENGTH(state) == _PyDateTime_DATETIME_DATASIZE &&
4752 MONTH_IS_SANE(PyUnicode_READ_CHAR(state, 2) & 0x7F))
4753 {
4754 state = PyUnicode_AsLatin1String(state);
4755 if (state == NULL) {
4756 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4757 /* More informative error message. */
4758 PyErr_SetString(PyExc_ValueError,
4759 "Failed to encode latin1 string when unpickling "
4760 "a datetime object. "
4761 "pickle.load(data, encoding='latin1') is assumed.");
4762 }
Victor Stinnerb37672d2018-11-22 03:37:50 +01004763 return NULL;
4764 }
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02004765 self = datetime_from_pickle(type, state, tzinfo);
4766 Py_DECREF(state);
4767 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 }
Serhiy Storchaka8452ca12018-12-07 13:42:10 +02004770 tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004772
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004773 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 &year, &month, &day, &hour, &minute,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004775 &second, &usecond, &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004776 self = new_datetime_ex2(year, month, day,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 hour, minute, second, usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004778 tzinfo, fold, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 }
4780 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004781}
4782
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004783/* TM_FUNC is the shared type of _PyTime_localtime() and
4784 * _PyTime_gmtime(). */
4785typedef int (*TM_FUNC)(time_t timer, struct tm*);
Tim Petersa9bc1682003-01-11 03:39:11 +00004786
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004787/* As of version 2015f max fold in IANA database is
4788 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004789static long long max_fold_seconds = 24 * 3600;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004790/* NB: date(1970,1,1).toordinal() == 719163 */
Benjamin Petersonac965ca2016-09-18 18:12:21 -07004791static long long epoch = 719163LL * 24 * 60 * 60;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004792
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004793static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004794utc_to_seconds(int year, int month, int day,
4795 int hour, int minute, int second)
4796{
Victor Stinnerb67f0962017-02-10 10:34:02 +01004797 long long ordinal;
4798
4799 /* ymd_to_ord() doesn't support year <= 0 */
4800 if (year < MINYEAR || year > MAXYEAR) {
4801 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
4802 return -1;
4803 }
4804
4805 ordinal = ymd_to_ord(year, month, day);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004806 return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
4807}
4808
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004809static long long
4810local(long long u)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004811{
4812 struct tm local_time;
Alexander Belopolsky8e1d3a22016-07-25 13:54:51 -04004813 time_t t;
4814 u -= epoch;
4815 t = u;
4816 if (t != u) {
4817 PyErr_SetString(PyExc_OverflowError,
4818 "timestamp out of range for platform time_t");
4819 return -1;
4820 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004821 if (_PyTime_localtime(t, &local_time) != 0)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004822 return -1;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004823 return utc_to_seconds(local_time.tm_year + 1900,
4824 local_time.tm_mon + 1,
4825 local_time.tm_mday,
4826 local_time.tm_hour,
4827 local_time.tm_min,
4828 local_time.tm_sec);
4829}
4830
Tim Petersa9bc1682003-01-11 03:39:11 +00004831/* Internal helper.
4832 * Build datetime from a time_t and a distinct count of microseconds.
4833 * Pass localtime or gmtime for f, to control the interpretation of timet.
4834 */
4835static PyObject *
4836datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004838{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004839 struct tm tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004840 int year, month, day, hour, minute, second, fold = 0;
Tim Petersa9bc1682003-01-11 03:39:11 +00004841
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004842 if (f(timet, &tm) != 0)
4843 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01004844
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004845 year = tm.tm_year + 1900;
4846 month = tm.tm_mon + 1;
4847 day = tm.tm_mday;
4848 hour = tm.tm_hour;
4849 minute = tm.tm_min;
Victor Stinner21f58932012-03-14 00:15:40 +01004850 /* The platform localtime/gmtime may insert leap seconds,
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004851 * indicated by tm.tm_sec > 59. We don't care about them,
Victor Stinner21f58932012-03-14 00:15:40 +01004852 * except to the extent that passing them on to the datetime
4853 * constructor would raise ValueError for a reason that
4854 * made no sense to the user.
4855 */
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004856 second = Py_MIN(59, tm.tm_sec);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004857
Victor Stinnerb67f0962017-02-10 10:34:02 +01004858 /* local timezone requires to compute fold */
Ammar Askar96d1e692018-07-25 09:54:58 -07004859 if (tzinfo == Py_None && f == _PyTime_localtime
4860 /* On Windows, passing a negative value to local results
4861 * in an OSError because localtime_s on Windows does
4862 * not support negative timestamps. Unfortunately this
4863 * means that fold detection for time values between
4864 * 0 and max_fold_seconds will result in an identical
4865 * error since we subtract max_fold_seconds to detect a
4866 * fold. However, since we know there haven't been any
4867 * folds in the interval [0, max_fold_seconds) in any
4868 * timezone, we can hackily just forego fold detection
4869 * for this time range.
4870 */
4871#ifdef MS_WINDOWS
4872 && (timet - max_fold_seconds > 0)
4873#endif
4874 ) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004875 long long probe_seconds, result_seconds, transition;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004876
4877 result_seconds = utc_to_seconds(year, month, day,
4878 hour, minute, second);
4879 /* Probe max_fold_seconds to detect a fold. */
4880 probe_seconds = local(epoch + timet - max_fold_seconds);
4881 if (probe_seconds == -1)
4882 return NULL;
4883 transition = result_seconds - probe_seconds - max_fold_seconds;
4884 if (transition < 0) {
4885 probe_seconds = local(epoch + timet + transition);
4886 if (probe_seconds == -1)
4887 return NULL;
4888 if (probe_seconds == result_seconds)
4889 fold = 1;
4890 }
4891 }
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05004892 return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
4893 second, us, tzinfo, fold, cls);
Tim Petersa9bc1682003-01-11 03:39:11 +00004894}
4895
4896/* Internal helper.
4897 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4898 * to control the interpretation of the timestamp. Since a double doesn't
4899 * have enough bits to cover a datetime's full range of precision, it's
4900 * better to call datetime_from_timet_and_us provided you have a way
4901 * to get that much precision (e.g., C time() isn't good enough).
4902 */
4903static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004904datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004905 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004908 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004909
Victor Stinnere4a994d2015-03-30 01:10:14 +02004910 if (_PyTime_ObjectToTimeval(timestamp,
Victor Stinner7667f582015-09-09 01:02:23 +02004911 &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004913
Victor Stinner21f58932012-03-14 00:15:40 +01004914 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004915}
4916
4917/* Internal helper.
4918 * Build most accurate possible datetime for current time. Pass localtime or
4919 * gmtime for f as appropriate.
4920 */
4921static PyObject *
4922datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4923{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004924 _PyTime_t ts = _PyTime_GetSystemClock();
Victor Stinner1e2b6882015-09-18 13:23:02 +02004925 time_t secs;
4926 int us;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004927
Victor Stinner1e2b6882015-09-18 13:23:02 +02004928 if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner09e5cf22015-03-30 00:09:18 +02004929 return NULL;
Victor Stinner1e2b6882015-09-18 13:23:02 +02004930 assert(0 <= us && us <= 999999);
Victor Stinner09e5cf22015-03-30 00:09:18 +02004931
Victor Stinner1e2b6882015-09-18 13:23:02 +02004932 return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004933}
4934
Larry Hastings61272b72014-01-07 12:41:53 -08004935/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004936
4937@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004938datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004939
4940 tz: object = None
4941 Timezone object.
4942
4943Returns new datetime object representing current time local to tz.
4944
4945If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004946[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004947
Larry Hastings31826802013-10-19 00:09:25 -07004948static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004949datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03004950/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004953
Larry Hastings31826802013-10-19 00:09:25 -07004954 /* Return best possible local time -- this isn't constrained by the
4955 * precision of a timestamp.
4956 */
4957 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004959
Larry Hastings5c661892014-01-24 06:17:25 -08004960 self = datetime_best_possible((PyObject *)type,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004961 tz == Py_None ? _PyTime_localtime :
4962 _PyTime_gmtime,
Larry Hastings31826802013-10-19 00:09:25 -07004963 tz);
4964 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004965 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004966 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 }
4968 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004969}
4970
Tim Petersa9bc1682003-01-11 03:39:11 +00004971/* Return best possible UTC time -- this isn't constrained by the
4972 * precision of a timestamp.
4973 */
4974static PyObject *
4975datetime_utcnow(PyObject *cls, PyObject *dummy)
4976{
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004977 return datetime_best_possible(cls, _PyTime_gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004978}
4979
Tim Peters2a799bf2002-12-16 20:18:38 +00004980/* Return new local datetime from timestamp (Python timestamp -- a double). */
4981static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004982datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004985 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 PyObject *tzinfo = Py_None;
4987 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004988
Victor Stinner5d272cc2012-03-13 13:35:55 +01004989 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 keywords, &timestamp, &tzinfo))
4991 return NULL;
4992 if (check_tzinfo_subclass(tzinfo) < 0)
4993 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 self = datetime_from_timestamp(cls,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004996 tzinfo == Py_None ? _PyTime_localtime :
4997 _PyTime_gmtime,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 timestamp,
4999 tzinfo);
5000 if (self != NULL && tzinfo != Py_None) {
5001 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02005002 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 }
5004 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00005005}
5006
Tim Petersa9bc1682003-01-11 03:39:11 +00005007/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
5008static PyObject *
5009datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
5010{
Victor Stinner5d272cc2012-03-13 13:35:55 +01005011 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005013
Victor Stinner5d272cc2012-03-13 13:35:55 +01005014 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005015 result = datetime_from_timestamp(cls, _PyTime_gmtime, timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 Py_None);
5017 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00005018}
5019
Alexander Belopolskyca94f552010-06-17 18:30:34 +00005020/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005021static PyObject *
5022datetime_strptime(PyObject *cls, PyObject *args)
5023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005025 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02005026 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005027
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005028 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005030
Alexander Belopolskyca94f552010-06-17 18:30:34 +00005031 if (module == NULL) {
5032 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00005033 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00005034 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 }
Victor Stinner20401de2016-12-09 15:24:31 +01005036 return _PyObject_CallMethodIdObjArgs(module, &PyId__strptime_datetime,
5037 cls, string, format, NULL);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005038}
5039
Tim Petersa9bc1682003-01-11 03:39:11 +00005040/* Return new datetime from date/datetime and time arguments. */
5041static PyObject *
5042datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
5043{
Alexander Belopolsky43746c32016-08-02 17:49:30 -04005044 static char *keywords[] = {"date", "time", "tzinfo", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 PyObject *date;
5046 PyObject *time;
Alexander Belopolsky43746c32016-08-02 17:49:30 -04005047 PyObject *tzinfo = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00005049
Alexander Belopolsky43746c32016-08-02 17:49:30 -04005050 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 &PyDateTime_DateType, &date,
Alexander Belopolsky43746c32016-08-02 17:49:30 -04005052 &PyDateTime_TimeType, &time, &tzinfo)) {
5053 if (tzinfo == NULL) {
5054 if (HASTZINFO(time))
5055 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
5056 else
5057 tzinfo = Py_None;
5058 }
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05005059 result = new_datetime_subclass_fold_ex(GET_YEAR(date),
5060 GET_MONTH(date),
5061 GET_DAY(date),
5062 TIME_GET_HOUR(time),
5063 TIME_GET_MINUTE(time),
5064 TIME_GET_SECOND(time),
5065 TIME_GET_MICROSECOND(time),
5066 tzinfo,
5067 TIME_GET_FOLD(time),
5068 cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 }
5070 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00005071}
Tim Peters2a799bf2002-12-16 20:18:38 +00005072
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005073static PyObject *
Paul Ganssle3df85402018-10-22 12:32:52 -04005074_sanitize_isoformat_str(PyObject *dtstr)
5075{
Paul Ganssle096329f2018-08-23 11:06:20 -04005076 // `fromisoformat` allows surrogate characters in exactly one position,
5077 // the separator; to allow datetime_fromisoformat to make the simplifying
5078 // assumption that all valid strings can be encoded in UTF-8, this function
5079 // replaces any surrogate character separators with `T`.
Paul Ganssle3df85402018-10-22 12:32:52 -04005080 //
5081 // The result of this, if not NULL, returns a new reference
Paul Ganssle096329f2018-08-23 11:06:20 -04005082 Py_ssize_t len = PyUnicode_GetLength(dtstr);
Paul Ganssle3df85402018-10-22 12:32:52 -04005083 if (len < 0) {
5084 return NULL;
5085 }
5086
5087 if (len <= 10 ||
5088 !Py_UNICODE_IS_SURROGATE(PyUnicode_READ_CHAR(dtstr, 10))) {
5089 Py_INCREF(dtstr);
Paul Ganssle096329f2018-08-23 11:06:20 -04005090 return dtstr;
5091 }
5092
Paul Ganssle3df85402018-10-22 12:32:52 -04005093 PyObject *str_out = _PyUnicode_Copy(dtstr);
Paul Ganssle096329f2018-08-23 11:06:20 -04005094 if (str_out == NULL) {
5095 return NULL;
5096 }
5097
Paul Ganssle3df85402018-10-22 12:32:52 -04005098 if (PyUnicode_WriteChar(str_out, 10, (Py_UCS4)'T')) {
Paul Ganssle096329f2018-08-23 11:06:20 -04005099 Py_DECREF(str_out);
5100 return NULL;
5101 }
5102
Paul Ganssle096329f2018-08-23 11:06:20 -04005103 return str_out;
5104}
5105
5106static PyObject *
Paul Ganssle3df85402018-10-22 12:32:52 -04005107datetime_fromisoformat(PyObject *cls, PyObject *dtstr)
5108{
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005109 assert(dtstr != NULL);
5110
5111 if (!PyUnicode_Check(dtstr)) {
Paul Ganssle3df85402018-10-22 12:32:52 -04005112 PyErr_SetString(PyExc_TypeError,
5113 "fromisoformat: argument must be str");
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005114 return NULL;
5115 }
5116
Paul Ganssle3df85402018-10-22 12:32:52 -04005117 PyObject *dtstr_clean = _sanitize_isoformat_str(dtstr);
5118 if (dtstr_clean == NULL) {
Paul Ganssle096329f2018-08-23 11:06:20 -04005119 goto error;
5120 }
5121
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005122 Py_ssize_t len;
Paul Ganssle3df85402018-10-22 12:32:52 -04005123 const char *dt_ptr = PyUnicode_AsUTF8AndSize(dtstr_clean, &len);
Paul Ganssle096329f2018-08-23 11:06:20 -04005124
5125 if (dt_ptr == NULL) {
Paul Ganssle3df85402018-10-22 12:32:52 -04005126 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
5127 // Encoding errors are invalid string errors at this point
5128 goto invalid_string_error;
5129 }
5130 else {
5131 goto error;
5132 }
Paul Ganssle096329f2018-08-23 11:06:20 -04005133 }
5134
5135 const char *p = dt_ptr;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005136
5137 int year = 0, month = 0, day = 0;
5138 int hour = 0, minute = 0, second = 0, microsecond = 0;
5139 int tzoffset = 0, tzusec = 0;
5140
5141 // date has a fixed length of 10
5142 int rv = parse_isoformat_date(p, &year, &month, &day);
5143
5144 if (!rv && len > 10) {
5145 // In UTF-8, the length of multi-byte characters is encoded in the MSB
5146 if ((p[10] & 0x80) == 0) {
5147 p += 11;
Paul Ganssle3df85402018-10-22 12:32:52 -04005148 }
5149 else {
5150 switch (p[10] & 0xf0) {
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005151 case 0xe0:
5152 p += 13;
5153 break;
5154 case 0xf0:
5155 p += 14;
5156 break;
5157 default:
5158 p += 12;
5159 break;
5160 }
5161 }
5162
5163 len -= (p - dt_ptr);
Paul Ganssle3df85402018-10-22 12:32:52 -04005164 rv = parse_isoformat_time(p, len, &hour, &minute, &second,
5165 &microsecond, &tzoffset, &tzusec);
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005166 }
5167 if (rv < 0) {
Paul Ganssle096329f2018-08-23 11:06:20 -04005168 goto invalid_string_error;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005169 }
5170
Paul Ganssle3df85402018-10-22 12:32:52 -04005171 PyObject *tzinfo = tzinfo_from_isoformat_results(rv, tzoffset, tzusec);
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005172 if (tzinfo == NULL) {
Paul Ganssle096329f2018-08-23 11:06:20 -04005173 goto error;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005174 }
5175
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05005176 PyObject *dt = new_datetime_subclass_ex(year, month, day, hour, minute,
5177 second, microsecond, tzinfo, cls);
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005178
5179 Py_DECREF(tzinfo);
Paul Ganssle3df85402018-10-22 12:32:52 -04005180 Py_DECREF(dtstr_clean);
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005181 return dt;
Paul Ganssle096329f2018-08-23 11:06:20 -04005182
5183invalid_string_error:
5184 PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", dtstr);
5185
5186error:
Paul Ganssle3df85402018-10-22 12:32:52 -04005187 Py_XDECREF(dtstr_clean);
Paul Ganssle096329f2018-08-23 11:06:20 -04005188
5189 return NULL;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05005190}
5191
Tim Peters2a799bf2002-12-16 20:18:38 +00005192/*
5193 * Destructor.
5194 */
5195
5196static void
Tim Petersa9bc1682003-01-11 03:39:11 +00005197datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005199 if (HASTZINFO(self)) {
5200 Py_XDECREF(self->tzinfo);
5201 }
5202 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00005203}
5204
5205/*
5206 * Indirect access to tzinfo methods.
5207 */
5208
Tim Peters2a799bf2002-12-16 20:18:38 +00005209/* These are all METH_NOARGS, so don't need to check the arglist. */
5210static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005211datetime_utcoffset(PyObject *self, PyObject *unused) {
5212 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00005213}
5214
5215static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005216datetime_dst(PyObject *self, PyObject *unused) {
5217 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00005218}
5219
5220static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005221datetime_tzname(PyObject *self, PyObject *unused) {
5222 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00005223}
5224
5225/*
Tim Petersa9bc1682003-01-11 03:39:11 +00005226 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00005227 */
5228
Tim Petersa9bc1682003-01-11 03:39:11 +00005229/* factor must be 1 (to add) or -1 (to subtract). The result inherits
5230 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00005231 */
5232static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005233add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005234 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00005235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 /* Note that the C-level additions can't overflow, because of
5237 * invariant bounds on the member values.
5238 */
5239 int year = GET_YEAR(date);
5240 int month = GET_MONTH(date);
5241 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
5242 int hour = DATE_GET_HOUR(date);
5243 int minute = DATE_GET_MINUTE(date);
5244 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
5245 int microsecond = DATE_GET_MICROSECOND(date) +
5246 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00005247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 assert(factor == 1 || factor == -1);
5249 if (normalize_datetime(&year, &month, &day,
Victor Stinnerb67f0962017-02-10 10:34:02 +01005250 &hour, &minute, &second, &microsecond) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 return NULL;
Victor Stinnerb67f0962017-02-10 10:34:02 +01005252 }
5253
Paul Ganssle89427cd2019-02-04 14:42:04 -05005254 return new_datetime_subclass_ex(year, month, day,
5255 hour, minute, second, microsecond,
5256 HASTZINFO(date) ? date->tzinfo : Py_None,
5257 (PyObject *)Py_TYPE(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00005258}
5259
5260static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005261datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00005262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 if (PyDateTime_Check(left)) {
5264 /* datetime + ??? */
5265 if (PyDelta_Check(right))
5266 /* datetime + delta */
5267 return add_datetime_timedelta(
5268 (PyDateTime_DateTime *)left,
5269 (PyDateTime_Delta *)right,
5270 1);
5271 }
5272 else if (PyDelta_Check(left)) {
5273 /* delta + datetime */
5274 return add_datetime_timedelta((PyDateTime_DateTime *) right,
5275 (PyDateTime_Delta *) left,
5276 1);
5277 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005278 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00005279}
5280
5281static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005282datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00005283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00005285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 if (PyDateTime_Check(left)) {
5287 /* datetime - ??? */
5288 if (PyDateTime_Check(right)) {
5289 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005290 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00005292
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005293 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
5294 offset2 = offset1 = Py_None;
5295 Py_INCREF(offset1);
5296 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005298 else {
5299 offset1 = datetime_utcoffset(left, NULL);
5300 if (offset1 == NULL)
5301 return NULL;
5302 offset2 = datetime_utcoffset(right, NULL);
5303 if (offset2 == NULL) {
5304 Py_DECREF(offset1);
5305 return NULL;
5306 }
5307 if ((offset1 != Py_None) != (offset2 != Py_None)) {
5308 PyErr_SetString(PyExc_TypeError,
5309 "can't subtract offset-naive and "
5310 "offset-aware datetimes");
5311 Py_DECREF(offset1);
5312 Py_DECREF(offset2);
5313 return NULL;
5314 }
5315 }
5316 if ((offset1 != offset2) &&
5317 delta_cmp(offset1, offset2) != 0) {
5318 offdiff = delta_subtract(offset1, offset2);
5319 if (offdiff == NULL) {
5320 Py_DECREF(offset1);
5321 Py_DECREF(offset2);
5322 return NULL;
5323 }
5324 }
5325 Py_DECREF(offset1);
5326 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 delta_d = ymd_to_ord(GET_YEAR(left),
5328 GET_MONTH(left),
5329 GET_DAY(left)) -
5330 ymd_to_ord(GET_YEAR(right),
5331 GET_MONTH(right),
5332 GET_DAY(right));
5333 /* These can't overflow, since the values are
5334 * normalized. At most this gives the number of
5335 * seconds in one day.
5336 */
5337 delta_s = (DATE_GET_HOUR(left) -
5338 DATE_GET_HOUR(right)) * 3600 +
5339 (DATE_GET_MINUTE(left) -
5340 DATE_GET_MINUTE(right)) * 60 +
5341 (DATE_GET_SECOND(left) -
5342 DATE_GET_SECOND(right));
5343 delta_us = DATE_GET_MICROSECOND(left) -
5344 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01005346 if (result == NULL)
5347 return NULL;
5348
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005349 if (offdiff != NULL) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03005350 Py_SETREF(result, delta_subtract(result, offdiff));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005351 Py_DECREF(offdiff);
5352 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 }
5354 else if (PyDelta_Check(right)) {
5355 /* datetime - delta */
5356 result = add_datetime_timedelta(
5357 (PyDateTime_DateTime *)left,
5358 (PyDateTime_Delta *)right,
5359 -1);
5360 }
5361 }
Tim Peters2a799bf2002-12-16 20:18:38 +00005362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 if (result == Py_NotImplemented)
5364 Py_INCREF(result);
5365 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005366}
5367
5368/* Various ways to turn a datetime into a string. */
5369
5370static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005371datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 const char *type_name = Py_TYPE(self)->tp_name;
5374 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00005375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 if (DATE_GET_MICROSECOND(self)) {
5377 baserepr = PyUnicode_FromFormat(
5378 "%s(%d, %d, %d, %d, %d, %d, %d)",
5379 type_name,
5380 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
5381 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
5382 DATE_GET_SECOND(self),
5383 DATE_GET_MICROSECOND(self));
5384 }
5385 else if (DATE_GET_SECOND(self)) {
5386 baserepr = PyUnicode_FromFormat(
5387 "%s(%d, %d, %d, %d, %d, %d)",
5388 type_name,
5389 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
5390 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
5391 DATE_GET_SECOND(self));
5392 }
5393 else {
5394 baserepr = PyUnicode_FromFormat(
5395 "%s(%d, %d, %d, %d, %d)",
5396 type_name,
5397 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
5398 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
5399 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005400 if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
5401 baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 if (baserepr == NULL || ! HASTZINFO(self))
5403 return baserepr;
5404 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00005405}
5406
Tim Petersa9bc1682003-01-11 03:39:11 +00005407static PyObject *
5408datetime_str(PyDateTime_DateTime *self)
5409{
Victor Stinner4c381542016-12-09 00:33:39 +01005410 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "s", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00005411}
Tim Peters2a799bf2002-12-16 20:18:38 +00005412
5413static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005414datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00005415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 int sep = 'T';
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005417 char *timespec = NULL;
5418 static char *keywords[] = {"sep", "timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 char buffer[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005420 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 int us = DATE_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005422 static char *specs[][2] = {
5423 {"hours", "%04d-%02d-%02d%c%02d"},
5424 {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
5425 {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
5426 {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
5427 {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
5428 };
5429 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00005430
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005431 if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 return NULL;
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005433
5434 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
5435 if (us == 0) {
5436 /* seconds */
5437 given_spec = 2;
5438 }
5439 else {
5440 /* microseconds */
5441 given_spec = 4;
5442 }
5443 }
5444 else {
5445 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
5446 if (strcmp(timespec, specs[given_spec][0]) == 0) {
5447 if (given_spec == 3) {
5448 us = us / 1000;
5449 }
5450 break;
5451 }
5452 }
5453 }
5454
5455 if (given_spec == Py_ARRAY_LENGTH(specs)) {
5456 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
5457 return NULL;
5458 }
5459 else {
5460 result = PyUnicode_FromFormat(specs[given_spec][1],
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 GET_YEAR(self), GET_MONTH(self),
5462 GET_DAY(self), (int)sep,
5463 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
5464 DATE_GET_SECOND(self), us);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005465 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00005466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 if (!result || !HASTZINFO(self))
5468 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 /* We need to append the UTC offset. */
5471 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
5472 (PyObject *)self) < 0) {
5473 Py_DECREF(result);
5474 return NULL;
5475 }
5476 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
5477 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005478}
5479
Tim Petersa9bc1682003-01-11 03:39:11 +00005480static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305481datetime_ctime(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
Tim Petersa9bc1682003-01-11 03:39:11 +00005482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 return format_ctime((PyDateTime_Date *)self,
5484 DATE_GET_HOUR(self),
5485 DATE_GET_MINUTE(self),
5486 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005487}
5488
Tim Peters2a799bf2002-12-16 20:18:38 +00005489/* Miscellaneous methods. */
5490
Tim Petersa9bc1682003-01-11 03:39:11 +00005491static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005492flip_fold(PyObject *dt)
5493{
5494 return new_datetime_ex2(GET_YEAR(dt),
5495 GET_MONTH(dt),
5496 GET_DAY(dt),
5497 DATE_GET_HOUR(dt),
5498 DATE_GET_MINUTE(dt),
5499 DATE_GET_SECOND(dt),
5500 DATE_GET_MICROSECOND(dt),
5501 HASTZINFO(dt) ?
5502 ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
5503 !DATE_GET_FOLD(dt),
5504 Py_TYPE(dt));
5505}
5506
5507static PyObject *
5508get_flip_fold_offset(PyObject *dt)
5509{
5510 PyObject *result, *flip_dt;
5511
5512 flip_dt = flip_fold(dt);
5513 if (flip_dt == NULL)
5514 return NULL;
5515 result = datetime_utcoffset(flip_dt, NULL);
5516 Py_DECREF(flip_dt);
5517 return result;
5518}
5519
5520/* PEP 495 exception: Whenever one or both of the operands in
5521 * inter-zone comparison is such that its utcoffset() depends
Serhiy Storchakabac2d5b2018-03-28 22:14:26 +03005522 * on the value of its fold attribute, the result is False.
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005523 *
5524 * Return 1 if exception applies, 0 if not, and -1 on error.
5525 */
5526static int
5527pep495_eq_exception(PyObject *self, PyObject *other,
5528 PyObject *offset_self, PyObject *offset_other)
5529{
5530 int result = 0;
5531 PyObject *flip_offset;
5532
5533 flip_offset = get_flip_fold_offset(self);
5534 if (flip_offset == NULL)
5535 return -1;
5536 if (flip_offset != offset_self &&
5537 delta_cmp(flip_offset, offset_self))
5538 {
5539 result = 1;
5540 goto done;
5541 }
5542 Py_DECREF(flip_offset);
5543
5544 flip_offset = get_flip_fold_offset(other);
5545 if (flip_offset == NULL)
5546 return -1;
5547 if (flip_offset != offset_other &&
5548 delta_cmp(flip_offset, offset_other))
5549 result = 1;
5550 done:
5551 Py_DECREF(flip_offset);
5552 return result;
5553}
5554
5555static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00005556datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00005557{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005558 PyObject *result = NULL;
5559 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00005561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 if (! PyDateTime_Check(other)) {
5563 if (PyDate_Check(other)) {
5564 /* Prevent invocation of date_richcompare. We want to
5565 return NotImplemented here to give the other object
5566 a chance. But since DateTime is a subclass of
5567 Date, if the other object is a Date, it would
5568 compute an ordering based on the date part alone,
5569 and we don't want that. So force unequal or
5570 uncomparable here in that case. */
5571 if (op == Py_EQ)
5572 Py_RETURN_FALSE;
5573 if (op == Py_NE)
5574 Py_RETURN_TRUE;
5575 return cmperror(self, other);
5576 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005577 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 }
Tim Petersa9bc1682003-01-11 03:39:11 +00005579
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005580 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 diff = memcmp(((PyDateTime_DateTime *)self)->data,
5582 ((PyDateTime_DateTime *)other)->data,
5583 _PyDateTime_DATETIME_DATASIZE);
5584 return diff_to_bool(diff, op);
5585 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005586 offset1 = datetime_utcoffset(self, NULL);
5587 if (offset1 == NULL)
5588 return NULL;
5589 offset2 = datetime_utcoffset(other, NULL);
5590 if (offset2 == NULL)
5591 goto done;
5592 /* If they're both naive, or both aware and have the same offsets,
5593 * we get off cheap. Note that if they're both naive, offset1 ==
5594 * offset2 == Py_None at this point.
5595 */
5596 if ((offset1 == offset2) ||
5597 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
5598 delta_cmp(offset1, offset2) == 0)) {
5599 diff = memcmp(((PyDateTime_DateTime *)self)->data,
5600 ((PyDateTime_DateTime *)other)->data,
5601 _PyDateTime_DATETIME_DATASIZE);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005602 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
5603 int ex = pep495_eq_exception(self, other, offset1, offset2);
5604 if (ex == -1)
5605 goto done;
5606 if (ex)
5607 diff = 1;
5608 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005609 result = diff_to_bool(diff, op);
5610 }
5611 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00005613
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005614 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005615 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
5616 other);
5617 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005618 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 diff = GET_TD_DAYS(delta);
5620 if (diff == 0)
5621 diff = GET_TD_SECONDS(delta) |
5622 GET_TD_MICROSECONDS(delta);
5623 Py_DECREF(delta);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005624 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
5625 int ex = pep495_eq_exception(self, other, offset1, offset2);
5626 if (ex == -1)
5627 goto done;
5628 if (ex)
5629 diff = 1;
5630 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005631 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005632 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04005633 else if (op == Py_EQ) {
5634 result = Py_False;
5635 Py_INCREF(result);
5636 }
5637 else if (op == Py_NE) {
5638 result = Py_True;
5639 Py_INCREF(result);
5640 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005641 else {
5642 PyErr_SetString(PyExc_TypeError,
5643 "can't compare offset-naive and "
5644 "offset-aware datetimes");
5645 }
5646 done:
5647 Py_DECREF(offset1);
5648 Py_XDECREF(offset2);
5649 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00005650}
5651
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005652static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00005653datetime_hash(PyDateTime_DateTime *self)
5654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005656 PyObject *offset, *self0;
5657 if (DATE_GET_FOLD(self)) {
5658 self0 = new_datetime_ex2(GET_YEAR(self),
5659 GET_MONTH(self),
5660 GET_DAY(self),
5661 DATE_GET_HOUR(self),
5662 DATE_GET_MINUTE(self),
5663 DATE_GET_SECOND(self),
5664 DATE_GET_MICROSECOND(self),
5665 HASTZINFO(self) ? self->tzinfo : Py_None,
5666 0, Py_TYPE(self));
5667 if (self0 == NULL)
5668 return -1;
5669 }
5670 else {
5671 self0 = (PyObject *)self;
5672 Py_INCREF(self0);
5673 }
5674 offset = datetime_utcoffset(self0, NULL);
5675 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005676
5677 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00005679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005681 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 self->hashcode = generic_hash(
5683 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005685 PyObject *temp1, *temp2;
5686 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00005687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 assert(HASTZINFO(self));
5689 days = ymd_to_ord(GET_YEAR(self),
5690 GET_MONTH(self),
5691 GET_DAY(self));
5692 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005693 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005695 temp1 = new_delta(days, seconds,
5696 DATE_GET_MICROSECOND(self),
5697 1);
5698 if (temp1 == NULL) {
5699 Py_DECREF(offset);
5700 return -1;
5701 }
5702 temp2 = delta_subtract(temp1, offset);
5703 Py_DECREF(temp1);
5704 if (temp2 == NULL) {
5705 Py_DECREF(offset);
5706 return -1;
5707 }
5708 self->hashcode = PyObject_Hash(temp2);
5709 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005711 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 }
5713 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00005714}
Tim Peters2a799bf2002-12-16 20:18:38 +00005715
5716static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005717datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00005718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005719 PyObject *clone;
5720 PyObject *tuple;
5721 int y = GET_YEAR(self);
5722 int m = GET_MONTH(self);
5723 int d = GET_DAY(self);
5724 int hh = DATE_GET_HOUR(self);
5725 int mm = DATE_GET_MINUTE(self);
5726 int ss = DATE_GET_SECOND(self);
5727 int us = DATE_GET_MICROSECOND(self);
5728 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005729 int fold = DATE_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00005730
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005731 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005732 datetime_kws,
5733 &y, &m, &d, &hh, &mm, &ss, &us,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005734 &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03005736 if (fold != 0 && fold != 1) {
5737 PyErr_SetString(PyExc_ValueError,
5738 "fold must be either 0 or 1");
5739 return NULL;
5740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005741 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
5742 if (tuple == NULL)
5743 return NULL;
5744 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005745 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005746 DATE_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005747 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 Py_DECREF(tuple);
5749 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00005750}
5751
5752static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005753local_timezone_from_timestamp(time_t timestamp)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005754{
5755 PyObject *result = NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005756 PyObject *delta;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005757 struct tm local_time_tm;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005758 PyObject *nameo = NULL;
5759 const char *zone = NULL;
5760
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005761 if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005762 return NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005763#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005764 zone = local_time_tm.tm_zone;
5765 delta = new_delta(0, local_time_tm.tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005766#else /* HAVE_STRUCT_TM_TM_ZONE */
5767 {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005768 PyObject *local_time, *utc_time;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005769 struct tm utc_time_tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005770 char buf[100];
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005771 strftime(buf, sizeof(buf), "%Z", &local_time_tm);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005772 zone = buf;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005773 local_time = new_datetime(local_time_tm.tm_year + 1900,
5774 local_time_tm.tm_mon + 1,
5775 local_time_tm.tm_mday,
5776 local_time_tm.tm_hour,
5777 local_time_tm.tm_min,
5778 local_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005779 if (local_time == NULL) {
5780 return NULL;
5781 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005782 if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005783 return NULL;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005784 utc_time = new_datetime(utc_time_tm.tm_year + 1900,
5785 utc_time_tm.tm_mon + 1,
5786 utc_time_tm.tm_mday,
5787 utc_time_tm.tm_hour,
5788 utc_time_tm.tm_min,
5789 utc_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005790 if (utc_time == NULL) {
5791 Py_DECREF(local_time);
5792 return NULL;
5793 }
5794 delta = datetime_subtract(local_time, utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005795 Py_DECREF(local_time);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005796 Py_DECREF(utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005797 }
5798#endif /* HAVE_STRUCT_TM_TM_ZONE */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005799 if (delta == NULL) {
5800 return NULL;
5801 }
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005802 if (zone != NULL) {
5803 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
5804 if (nameo == NULL)
5805 goto error;
5806 }
5807 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02005808 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005809 error:
5810 Py_DECREF(delta);
5811 return result;
5812}
5813
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005814static PyObject *
5815local_timezone(PyDateTime_DateTime *utc_time)
5816{
5817 time_t timestamp;
5818 PyObject *delta;
5819 PyObject *one_second;
5820 PyObject *seconds;
5821
5822 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
5823 if (delta == NULL)
5824 return NULL;
5825 one_second = new_delta(0, 1, 0, 0);
5826 if (one_second == NULL) {
5827 Py_DECREF(delta);
5828 return NULL;
5829 }
5830 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
5831 (PyDateTime_Delta *)one_second);
5832 Py_DECREF(one_second);
5833 Py_DECREF(delta);
5834 if (seconds == NULL)
5835 return NULL;
5836 timestamp = _PyLong_AsTime_t(seconds);
5837 Py_DECREF(seconds);
5838 if (timestamp == -1 && PyErr_Occurred())
5839 return NULL;
5840 return local_timezone_from_timestamp(timestamp);
5841}
5842
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005843static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005844local_to_seconds(int year, int month, int day,
5845 int hour, int minute, int second, int fold);
5846
5847static PyObject *
5848local_timezone_from_local(PyDateTime_DateTime *local_dt)
5849{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005850 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005851 time_t timestamp;
5852 seconds = local_to_seconds(GET_YEAR(local_dt),
5853 GET_MONTH(local_dt),
5854 GET_DAY(local_dt),
5855 DATE_GET_HOUR(local_dt),
5856 DATE_GET_MINUTE(local_dt),
5857 DATE_GET_SECOND(local_dt),
5858 DATE_GET_FOLD(local_dt));
5859 if (seconds == -1)
5860 return NULL;
5861 /* XXX: add bounds check */
5862 timestamp = seconds - epoch;
5863 return local_timezone_from_timestamp(timestamp);
5864}
5865
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005866static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00005867datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00005868{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005869 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005870 PyObject *offset;
5871 PyObject *temp;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005872 PyObject *self_tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005873 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00005875
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005876 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07005877 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005878 return NULL;
5879
5880 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005881 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00005882
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005883 if (!HASTZINFO(self) || self->tzinfo == Py_None) {
Alexander Belopolsky877b2322018-06-10 17:02:58 -04005884 naive:
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005885 self_tzinfo = local_timezone_from_local(self);
5886 if (self_tzinfo == NULL)
5887 return NULL;
5888 } else {
5889 self_tzinfo = self->tzinfo;
5890 Py_INCREF(self_tzinfo);
5891 }
Tim Peters521fc152002-12-31 17:36:56 +00005892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 /* Conversion to self's own time zone is a NOP. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005894 if (self_tzinfo == tzinfo) {
5895 Py_DECREF(self_tzinfo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005896 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005897 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 }
Tim Peters521fc152002-12-31 17:36:56 +00005899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 /* Convert self to UTC. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005901 offset = call_utcoffset(self_tzinfo, (PyObject *)self);
5902 Py_DECREF(self_tzinfo);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005903 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 return NULL;
Alexander Belopolsky877b2322018-06-10 17:02:58 -04005905 else if(offset == Py_None) {
5906 Py_DECREF(offset);
5907 goto naive;
5908 }
5909 else if (!PyDelta_Check(offset)) {
5910 Py_DECREF(offset);
5911 PyErr_Format(PyExc_TypeError, "utcoffset() returned %.200s,"
5912 " expected timedelta or None", Py_TYPE(offset)->tp_name);
5913 return NULL;
5914 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005915 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005916 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5917 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005918 Py_DECREF(offset);
5919 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005920 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00005921
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005922 /* Make sure result is aware and UTC. */
5923 if (!HASTZINFO(result)) {
5924 temp = (PyObject *)result;
5925 result = (PyDateTime_DateTime *)
5926 new_datetime_ex2(GET_YEAR(result),
5927 GET_MONTH(result),
5928 GET_DAY(result),
5929 DATE_GET_HOUR(result),
5930 DATE_GET_MINUTE(result),
5931 DATE_GET_SECOND(result),
5932 DATE_GET_MICROSECOND(result),
5933 PyDateTime_TimeZone_UTC,
5934 DATE_GET_FOLD(result),
5935 Py_TYPE(result));
5936 Py_DECREF(temp);
5937 if (result == NULL)
5938 return NULL;
5939 }
5940 else {
5941 /* Result is already aware - just replace tzinfo. */
5942 temp = result->tzinfo;
5943 result->tzinfo = PyDateTime_TimeZone_UTC;
5944 Py_INCREF(result->tzinfo);
5945 Py_DECREF(temp);
5946 }
5947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005948 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005949 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005950 if (tzinfo == Py_None) {
5951 tzinfo = local_timezone(result);
5952 if (tzinfo == NULL) {
5953 Py_DECREF(result);
5954 return NULL;
5955 }
5956 }
5957 else
5958 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005959 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005960 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00005961
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005962 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005963 result = (PyDateTime_DateTime *)
Victor Stinner20401de2016-12-09 15:24:31 +01005964 _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_fromutc, temp, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005965 Py_DECREF(temp);
5966
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005967 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00005968}
5969
5970static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05305971datetime_timetuple(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00005972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005973 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00005974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005975 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005976 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00005977
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005978 dst = call_dst(self->tzinfo, (PyObject *)self);
5979 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005980 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005981
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005982 if (dst != Py_None)
5983 dstflag = delta_bool((PyDateTime_Delta *)dst);
5984 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 }
5986 return build_struct_time(GET_YEAR(self),
5987 GET_MONTH(self),
5988 GET_DAY(self),
5989 DATE_GET_HOUR(self),
5990 DATE_GET_MINUTE(self),
5991 DATE_GET_SECOND(self),
5992 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00005993}
5994
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005995static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005996local_to_seconds(int year, int month, int day,
5997 int hour, int minute, int second, int fold)
5998{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005999 long long t, a, b, u1, u2, t1, t2, lt;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006000 t = utc_to_seconds(year, month, day, hour, minute, second);
6001 /* Our goal is to solve t = local(u) for u. */
6002 lt = local(t);
6003 if (lt == -1)
6004 return -1;
6005 a = lt - t;
6006 u1 = t - a;
6007 t1 = local(u1);
6008 if (t1 == -1)
6009 return -1;
6010 if (t1 == t) {
6011 /* We found one solution, but it may not be the one we need.
6012 * Look for an earlier solution (if `fold` is 0), or a
6013 * later one (if `fold` is 1). */
6014 if (fold)
6015 u2 = u1 + max_fold_seconds;
6016 else
6017 u2 = u1 - max_fold_seconds;
6018 lt = local(u2);
6019 if (lt == -1)
6020 return -1;
6021 b = lt - u2;
6022 if (a == b)
6023 return u1;
6024 }
6025 else {
6026 b = t1 - u1;
6027 assert(a != b);
6028 }
6029 u2 = t - b;
6030 t2 = local(u2);
6031 if (t2 == -1)
6032 return -1;
6033 if (t2 == t)
6034 return u2;
6035 if (t1 == t)
6036 return u1;
6037 /* We have found both offsets a and b, but neither t - a nor t - b is
6038 * a solution. This means t is in the gap. */
6039 return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
6040}
6041
6042/* date(1970,1,1).toordinal() == 719163 */
6043#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
6044
Tim Peters2a799bf2002-12-16 20:18:38 +00006045static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05306046datetime_timestamp(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
Alexander Belopolskya4415142012-06-08 12:33:09 -04006047{
6048 PyObject *result;
6049
6050 if (HASTZINFO(self) && self->tzinfo != Py_None) {
6051 PyObject *delta;
6052 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
6053 if (delta == NULL)
6054 return NULL;
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05306055 result = delta_total_seconds(delta, NULL);
Alexander Belopolskya4415142012-06-08 12:33:09 -04006056 Py_DECREF(delta);
6057 }
6058 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07006059 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006060 seconds = local_to_seconds(GET_YEAR(self),
6061 GET_MONTH(self),
6062 GET_DAY(self),
6063 DATE_GET_HOUR(self),
6064 DATE_GET_MINUTE(self),
6065 DATE_GET_SECOND(self),
6066 DATE_GET_FOLD(self));
6067 if (seconds == -1)
Alexander Belopolskya4415142012-06-08 12:33:09 -04006068 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006069 result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
6070 DATE_GET_MICROSECOND(self) / 1e6);
Alexander Belopolskya4415142012-06-08 12:33:09 -04006071 }
6072 return result;
6073}
6074
6075static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05306076datetime_getdate(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
Tim Petersa9bc1682003-01-11 03:39:11 +00006077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006078 return new_date(GET_YEAR(self),
6079 GET_MONTH(self),
6080 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00006081}
6082
6083static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05306084datetime_gettime(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
Tim Petersa9bc1682003-01-11 03:39:11 +00006085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006086 return new_time(DATE_GET_HOUR(self),
6087 DATE_GET_MINUTE(self),
6088 DATE_GET_SECOND(self),
6089 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006090 Py_None,
6091 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00006092}
6093
6094static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05306095datetime_gettimetz(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
Tim Petersa9bc1682003-01-11 03:39:11 +00006096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006097 return new_time(DATE_GET_HOUR(self),
6098 DATE_GET_MINUTE(self),
6099 DATE_GET_SECOND(self),
6100 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006101 GET_DT_TZINFO(self),
6102 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00006103}
6104
6105static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05306106datetime_utctimetuple(PyDateTime_DateTime *self, PyObject *Py_UNUSED(ignored))
Tim Peters2a799bf2002-12-16 20:18:38 +00006107{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00006108 int y, m, d, hh, mm, ss;
6109 PyObject *tzinfo;
6110 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00006111
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00006112 tzinfo = GET_DT_TZINFO(self);
6113 if (tzinfo == Py_None) {
6114 utcself = self;
6115 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006116 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00006117 else {
6118 PyObject *offset;
6119 offset = call_utcoffset(tzinfo, (PyObject *)self);
6120 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00006121 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00006122 if (offset == Py_None) {
6123 Py_DECREF(offset);
6124 utcself = self;
6125 Py_INCREF(utcself);
6126 }
6127 else {
6128 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
6129 (PyDateTime_Delta *)offset, -1);
6130 Py_DECREF(offset);
6131 if (utcself == NULL)
6132 return NULL;
6133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006134 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00006135 y = GET_YEAR(utcself);
6136 m = GET_MONTH(utcself);
6137 d = GET_DAY(utcself);
6138 hh = DATE_GET_HOUR(utcself);
6139 mm = DATE_GET_MINUTE(utcself);
6140 ss = DATE_GET_SECOND(utcself);
6141
6142 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006143 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00006144}
6145
Tim Peters371935f2003-02-01 01:52:50 +00006146/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00006147
Tim Petersa9bc1682003-01-11 03:39:11 +00006148/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00006149 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
6150 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00006151 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00006152 */
6153static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006154datetime_getstate(PyDateTime_DateTime *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00006155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006156 PyObject *basestate;
6157 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00006158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006159 basestate = PyBytes_FromStringAndSize((char *)self->data,
6160 _PyDateTime_DATETIME_DATASIZE);
6161 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006162 if (proto > 3 && DATE_GET_FOLD(self))
6163 /* Set the first bit of the third byte */
6164 PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006165 if (! HASTZINFO(self) || self->tzinfo == Py_None)
6166 result = PyTuple_Pack(1, basestate);
6167 else
6168 result = PyTuple_Pack(2, basestate, self->tzinfo);
6169 Py_DECREF(basestate);
6170 }
6171 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00006172}
6173
6174static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02006175datetime_reduce_ex(PyDateTime_DateTime *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00006176{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02006177 int proto;
6178 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006179 return NULL;
6180
6181 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00006182}
6183
Serhiy Storchaka546ce652016-11-22 00:29:42 +02006184static PyObject *
6185datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
6186{
6187 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, 2));
6188}
6189
Tim Petersa9bc1682003-01-11 03:39:11 +00006190static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00006191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006192 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00006193
Larry Hastingsed4a1c52013-11-18 09:32:13 -08006194 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00006195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006196 {"utcnow", (PyCFunction)datetime_utcnow,
6197 METH_NOARGS | METH_CLASS,
6198 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006199
Serhiy Storchaka62be7422018-11-27 13:27:31 +02006200 {"fromtimestamp", (PyCFunction)(void(*)(void))datetime_fromtimestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006201 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
6202 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006204 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
6205 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05006206 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006208 {"strptime", (PyCFunction)datetime_strptime,
6209 METH_VARARGS | METH_CLASS,
6210 PyDoc_STR("string, format -> new datetime parsed from a string "
6211 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00006212
Serhiy Storchaka62be7422018-11-27 13:27:31 +02006213 {"combine", (PyCFunction)(void(*)(void))datetime_combine,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006214 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
6215 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006216
Paul Ganssle09dc2f52017-12-21 00:33:49 -05006217 {"fromisoformat", (PyCFunction)datetime_fromisoformat,
6218 METH_O | METH_CLASS,
6219 PyDoc_STR("string -> datetime from datetime.isoformat() output")},
6220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006221 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00006222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006223 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
6224 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006226 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
6227 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006229 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
6230 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006232 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
6233 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006235 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
6236 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006237
Alexander Belopolskya4415142012-06-08 12:33:09 -04006238 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
6239 PyDoc_STR("Return POSIX timestamp as float.")},
6240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006241 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
6242 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006243
Serhiy Storchaka62be7422018-11-27 13:27:31 +02006244 {"isoformat", (PyCFunction)(void(*)(void))datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006245 PyDoc_STR("[sep] -> string in ISO 8601 format, "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05006246 "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006247 "sep is used to separate the year from the time, and "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05006248 "defaults to 'T'.\n"
6249 "timespec specifies what components of the time to include"
6250 " (allowed values are 'auto', 'hours', 'minutes', 'seconds',"
6251 " 'milliseconds', and 'microseconds').\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006253 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
6254 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006256 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
6257 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006259 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
6260 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006261
Serhiy Storchaka62be7422018-11-27 13:27:31 +02006262 {"replace", (PyCFunction)(void(*)(void))datetime_replace, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006263 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00006264
Serhiy Storchaka62be7422018-11-27 13:27:31 +02006265 {"astimezone", (PyCFunction)(void(*)(void))datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006266 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00006267
Serhiy Storchaka546ce652016-11-22 00:29:42 +02006268 {"__reduce_ex__", (PyCFunction)datetime_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006269 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00006270
Serhiy Storchaka546ce652016-11-22 00:29:42 +02006271 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
6272 PyDoc_STR("__reduce__() -> (cls, state)")},
6273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006274 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00006275};
6276
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006277static const char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00006278PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
6279\n\
6280The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03006281instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00006282
Tim Petersa9bc1682003-01-11 03:39:11 +00006283static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006284 datetime_add, /* nb_add */
6285 datetime_subtract, /* nb_subtract */
6286 0, /* nb_multiply */
6287 0, /* nb_remainder */
6288 0, /* nb_divmod */
6289 0, /* nb_power */
6290 0, /* nb_negative */
6291 0, /* nb_positive */
6292 0, /* nb_absolute */
6293 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00006294};
6295
Neal Norwitz227b5332006-03-22 09:28:35 +00006296static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006297 PyVarObject_HEAD_INIT(NULL, 0)
6298 "datetime.datetime", /* tp_name */
6299 sizeof(PyDateTime_DateTime), /* tp_basicsize */
6300 0, /* tp_itemsize */
6301 (destructor)datetime_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02006302 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006303 0, /* tp_getattr */
6304 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02006305 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006306 (reprfunc)datetime_repr, /* tp_repr */
6307 &datetime_as_number, /* tp_as_number */
6308 0, /* tp_as_sequence */
6309 0, /* tp_as_mapping */
6310 (hashfunc)datetime_hash, /* tp_hash */
6311 0, /* tp_call */
6312 (reprfunc)datetime_str, /* tp_str */
6313 PyObject_GenericGetAttr, /* tp_getattro */
6314 0, /* tp_setattro */
6315 0, /* tp_as_buffer */
6316 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
6317 datetime_doc, /* tp_doc */
6318 0, /* tp_traverse */
6319 0, /* tp_clear */
6320 datetime_richcompare, /* tp_richcompare */
6321 0, /* tp_weaklistoffset */
6322 0, /* tp_iter */
6323 0, /* tp_iternext */
6324 datetime_methods, /* tp_methods */
6325 0, /* tp_members */
6326 datetime_getset, /* tp_getset */
6327 &PyDateTime_DateType, /* tp_base */
6328 0, /* tp_dict */
6329 0, /* tp_descr_get */
6330 0, /* tp_descr_set */
6331 0, /* tp_dictoffset */
6332 0, /* tp_init */
6333 datetime_alloc, /* tp_alloc */
6334 datetime_new, /* tp_new */
6335 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00006336};
6337
6338/* ---------------------------------------------------------------------------
6339 * Module methods and initialization.
6340 */
6341
6342static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006343 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00006344};
6345
Tim Peters9ddf40b2004-06-20 22:41:32 +00006346/* C API. Clients get at this via PyDateTime_IMPORT, defined in
6347 * datetime.h.
6348 */
6349static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006350 &PyDateTime_DateType,
6351 &PyDateTime_DateTimeType,
6352 &PyDateTime_TimeType,
6353 &PyDateTime_DeltaType,
6354 &PyDateTime_TZInfoType,
Paul Ganssle04af5b12018-01-24 17:29:30 -05006355 NULL, // PyDatetime_TimeZone_UTC not initialized yet
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006356 new_date_ex,
6357 new_datetime_ex,
6358 new_time_ex,
6359 new_delta_ex,
Paul Ganssle04af5b12018-01-24 17:29:30 -05006360 new_timezone,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006361 datetime_fromtimestamp,
Paul Ganssle4d8c8c02019-04-27 15:39:40 -04006362 datetime_date_fromtimestamp_capi,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006363 new_datetime_ex2,
6364 new_time_ex2
Tim Peters9ddf40b2004-06-20 22:41:32 +00006365};
6366
6367
Martin v. Löwis1a214512008-06-11 05:26:20 +00006368
6369static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006370 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00006371 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006372 "Fast implementation of the datetime type.",
6373 -1,
6374 module_methods,
6375 NULL,
6376 NULL,
6377 NULL,
6378 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00006379};
6380
Tim Peters2a799bf2002-12-16 20:18:38 +00006381PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00006382PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00006383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006384 PyObject *m; /* a module object */
6385 PyObject *d; /* its dict */
6386 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006387 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00006388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006389 m = PyModule_Create(&datetimemodule);
6390 if (m == NULL)
6391 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00006392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006393 if (PyType_Ready(&PyDateTime_DateType) < 0)
6394 return NULL;
6395 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
6396 return NULL;
6397 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
6398 return NULL;
6399 if (PyType_Ready(&PyDateTime_TimeType) < 0)
6400 return NULL;
6401 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
6402 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006403 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
6404 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00006405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006406 /* timedelta values */
6407 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00006408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006409 x = new_delta(0, 0, 1, 0);
6410 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
6411 return NULL;
6412 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006414 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
6415 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6416 return NULL;
6417 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006419 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
6420 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6421 return NULL;
6422 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006424 /* date values */
6425 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00006426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006427 x = new_date(1, 1, 1);
6428 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6429 return NULL;
6430 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006432 x = new_date(MAXYEAR, 12, 31);
6433 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6434 return NULL;
6435 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006437 x = new_delta(1, 0, 0, 0);
6438 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
6439 return NULL;
6440 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006442 /* time values */
6443 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00006444
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006445 x = new_time(0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006446 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6447 return NULL;
6448 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006449
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006450 x = new_time(23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006451 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6452 return NULL;
6453 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006455 x = new_delta(0, 0, 1, 0);
6456 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
6457 return NULL;
6458 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006460 /* datetime values */
6461 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00006462
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006463 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006464 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6465 return NULL;
6466 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006467
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006468 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006469 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6470 return NULL;
6471 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006473 x = new_delta(0, 0, 1, 0);
6474 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
6475 return NULL;
6476 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006477
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006478 /* timezone values */
6479 d = PyDateTime_TimeZoneType.tp_dict;
6480
6481 delta = new_delta(0, 0, 0, 0);
6482 if (delta == NULL)
6483 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00006484 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006485 Py_DECREF(delta);
6486 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
6487 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00006488 PyDateTime_TimeZone_UTC = x;
Paul Ganssle04af5b12018-01-24 17:29:30 -05006489 CAPI.TimeZone_UTC = PyDateTime_TimeZone_UTC;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006490
Paul Ganssle27b38b92019-08-15 15:08:57 -04006491 /* bpo-37642: These attributes are rounded to the nearest minute for backwards
6492 * compatibility, even though the constructor will accept a wider range of
6493 * values. This may change in the future.*/
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006494 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
6495 if (delta == NULL)
6496 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00006497 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006498 Py_DECREF(delta);
6499 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6500 return NULL;
6501 Py_DECREF(x);
6502
6503 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
6504 if (delta == NULL)
6505 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00006506 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006507 Py_DECREF(delta);
6508 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6509 return NULL;
6510 Py_DECREF(x);
6511
Alexander Belopolskya4415142012-06-08 12:33:09 -04006512 /* Epoch */
6513 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006514 PyDateTime_TimeZone_UTC, 0);
Alexander Belopolskya4415142012-06-08 12:33:09 -04006515 if (PyDateTime_Epoch == NULL)
6516 return NULL;
6517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006518 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02006519 PyModule_AddIntMacro(m, MINYEAR);
6520 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00006521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006522 Py_INCREF(&PyDateTime_DateType);
6523 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00006524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006525 Py_INCREF(&PyDateTime_DateTimeType);
6526 PyModule_AddObject(m, "datetime",
6527 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00006528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006529 Py_INCREF(&PyDateTime_TimeType);
6530 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00006531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006532 Py_INCREF(&PyDateTime_DeltaType);
6533 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00006534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006535 Py_INCREF(&PyDateTime_TZInfoType);
6536 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00006537
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006538 Py_INCREF(&PyDateTime_TimeZoneType);
6539 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
6540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006541 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
6542 if (x == NULL)
6543 return NULL;
6544 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00006545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006546 /* A 4-year cycle has an extra leap day over what we'd get from
6547 * pasting together 4 single years.
6548 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02006549 Py_BUILD_ASSERT(DI4Y == 4 * 365 + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006550 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00006551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006552 /* Similarly, a 400-year cycle has an extra leap day over what we'd
6553 * get from pasting together 4 100-year cycles.
6554 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02006555 Py_BUILD_ASSERT(DI400Y == 4 * DI100Y + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006556 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00006557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006558 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
6559 * pasting together 25 4-year cycles.
6560 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02006561 Py_BUILD_ASSERT(DI100Y == 25 * DI4Y - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006562 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00006563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006564 us_per_ms = PyLong_FromLong(1000);
6565 us_per_second = PyLong_FromLong(1000000);
6566 us_per_minute = PyLong_FromLong(60000000);
6567 seconds_per_day = PyLong_FromLong(24 * 3600);
Serhiy Storchakaba85d692017-03-30 09:09:41 +03006568 if (us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006569 us_per_minute == NULL || seconds_per_day == NULL)
6570 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00006571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006572 /* The rest are too big for 32-bit ints, but even
6573 * us_per_week fits in 40 bits, so doubles should be exact.
6574 */
6575 us_per_hour = PyLong_FromDouble(3600000000.0);
6576 us_per_day = PyLong_FromDouble(86400000000.0);
6577 us_per_week = PyLong_FromDouble(604800000000.0);
6578 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
6579 return NULL;
6580 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00006581}
Tim Petersf3615152003-01-01 21:51:37 +00006582
6583/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00006584Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00006585 x.n = x stripped of its timezone -- its naive time.
6586 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006587 return None
Tim Petersf3615152003-01-01 21:51:37 +00006588 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006589 return None
Tim Petersf3615152003-01-01 21:51:37 +00006590 x.s = x's standard offset, x.o - x.d
6591
6592Now some derived rules, where k is a duration (timedelta).
6593
65941. x.o = x.s + x.d
6595 This follows from the definition of x.s.
6596
Tim Petersc5dc4da2003-01-02 17:55:03 +000065972. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00006598 This is actually a requirement, an assumption we need to make about
6599 sane tzinfo classes.
6600
66013. The naive UTC time corresponding to x is x.n - x.o.
6602 This is again a requirement for a sane tzinfo class.
6603
66044. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00006605 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00006606
Tim Petersc5dc4da2003-01-02 17:55:03 +000066075. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00006608 Again follows from how arithmetic is defined.
6609
Tim Peters8bb5ad22003-01-24 02:44:45 +00006610Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00006611(meaning that the various tzinfo methods exist, and don't blow up or return
6612None when called).
6613
Tim Petersa9bc1682003-01-11 03:39:11 +00006614The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00006615x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00006616
6617By #3, we want
6618
Tim Peters8bb5ad22003-01-24 02:44:45 +00006619 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00006620
6621The algorithm starts by attaching tz to x.n, and calling that y. So
6622x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
6623becomes true; in effect, we want to solve [2] for k:
6624
Tim Peters8bb5ad22003-01-24 02:44:45 +00006625 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00006626
6627By #1, this is the same as
6628
Tim Peters8bb5ad22003-01-24 02:44:45 +00006629 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00006630
6631By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
6632Substituting that into [3],
6633
Tim Peters8bb5ad22003-01-24 02:44:45 +00006634 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
6635 k - (y+k).s - (y+k).d = 0; rearranging,
6636 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
6637 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00006638
Tim Peters8bb5ad22003-01-24 02:44:45 +00006639On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
6640approximate k by ignoring the (y+k).d term at first. Note that k can't be
6641very large, since all offset-returning methods return a duration of magnitude
6642less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
6643be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00006644
6645In any case, the new value is
6646
Tim Peters8bb5ad22003-01-24 02:44:45 +00006647 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00006648
Tim Peters8bb5ad22003-01-24 02:44:45 +00006649It's helpful to step back at look at [4] from a higher level: it's simply
6650mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00006651
6652At this point, if
6653
Tim Peters8bb5ad22003-01-24 02:44:45 +00006654 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00006655
6656we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00006657at the start of daylight time. Picture US Eastern for concreteness. The wall
6658time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
Tim Peters8bb5ad22003-01-24 02:44:45 +00006659sense then. The docs ask that an Eastern tzinfo class consider such a time to
6660be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
6661on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00006662the only spelling that makes sense on the local wall clock.
6663
Tim Petersc5dc4da2003-01-02 17:55:03 +00006664In fact, if [5] holds at this point, we do have the standard-time spelling,
6665but that takes a bit of proof. We first prove a stronger result. What's the
6666difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00006667
Tim Peters8bb5ad22003-01-24 02:44:45 +00006668 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00006669
Tim Petersc5dc4da2003-01-02 17:55:03 +00006670Now
6671 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00006672 (y + y.s).n = by #5
6673 y.n + y.s = since y.n = x.n
6674 x.n + y.s = since z and y are have the same tzinfo member,
6675 y.s = z.s by #2
6676 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00006677
Tim Petersc5dc4da2003-01-02 17:55:03 +00006678Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00006679
Tim Petersc5dc4da2003-01-02 17:55:03 +00006680 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00006681 x.n - ((x.n + z.s) - z.o) = expanding
6682 x.n - x.n - z.s + z.o = cancelling
6683 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00006684 z.d
Tim Petersf3615152003-01-01 21:51:37 +00006685
Tim Petersc5dc4da2003-01-02 17:55:03 +00006686So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00006687
Tim Petersc5dc4da2003-01-02 17:55:03 +00006688If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00006689spelling we wanted in the endcase described above. We're done. Contrarily,
6690if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00006691
Tim Petersc5dc4da2003-01-02 17:55:03 +00006692If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
6693add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00006694local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00006695
Tim Petersc5dc4da2003-01-02 17:55:03 +00006696Let
Tim Petersf3615152003-01-01 21:51:37 +00006697
Tim Peters4fede1a2003-01-04 00:26:59 +00006698 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00006699
Tim Peters4fede1a2003-01-04 00:26:59 +00006700and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00006701
Tim Peters8bb5ad22003-01-24 02:44:45 +00006702 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00006703
Tim Peters8bb5ad22003-01-24 02:44:45 +00006704If so, we're done. If not, the tzinfo class is insane, according to the
6705assumptions we've made. This also requires a bit of proof. As before, let's
6706compute the difference between the LHS and RHS of [8] (and skipping some of
6707the justifications for the kinds of substitutions we've done several times
6708already):
Tim Peters4fede1a2003-01-04 00:26:59 +00006709
Tim Peters8bb5ad22003-01-24 02:44:45 +00006710 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006711 x.n - (z.n + diff - z'.o) = replacing diff via [6]
6712 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
6713 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
6714 - z.n + z.n - z.o + z'.o = cancel z.n
6715 - z.o + z'.o = #1 twice
6716 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
6717 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00006718
6719So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
Tim Peters8bb5ad22003-01-24 02:44:45 +00006720we've found the UTC-equivalent so are done. In fact, we stop with [7] and
6721return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00006722
Tim Peters8bb5ad22003-01-24 02:44:45 +00006723How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
6724a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
6725would have to change the result dst() returns: we start in DST, and moving
6726a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00006727
Tim Peters8bb5ad22003-01-24 02:44:45 +00006728There isn't a sane case where this can happen. The closest it gets is at
6729the end of DST, where there's an hour in UTC with no spelling in a hybrid
6730tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
6731that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
6732UTC) because the docs insist on that, but 0:MM is taken as being in daylight
6733time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
6734clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
6735standard time. Since that's what the local clock *does*, we want to map both
6736UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00006737in local time, but so it goes -- it's the way the local clock works.
6738
Tim Peters8bb5ad22003-01-24 02:44:45 +00006739When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
6740so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
6741z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
Tim Peters4fede1a2003-01-04 00:26:59 +00006742(correctly) concludes that z' is not UTC-equivalent to x.
6743
6744Because we know z.d said z was in daylight time (else [5] would have held and
6745we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006746and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00006747return in Eastern, it follows that z'.d must be 0 (which it is in the example,
6748but the reasoning doesn't depend on the example -- it depends on there being
6749two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00006750z' must be in standard time, and is the spelling we want in this case.
6751
6752Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
6753concerned (because it takes z' as being in standard time rather than the
6754daylight time we intend here), but returning it gives the real-life "local
6755clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
6756tz.
6757
6758When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
6759the 1:MM standard time spelling we want.
6760
6761So how can this break? One of the assumptions must be violated. Two
6762possibilities:
6763
67641) [2] effectively says that y.s is invariant across all y belong to a given
6765 time zone. This isn't true if, for political reasons or continental drift,
6766 a region decides to change its base offset from UTC.
6767
67682) There may be versions of "double daylight" time where the tail end of
6769 the analysis gives up a step too early. I haven't thought about that
6770 enough to say.
6771
6772In any case, it's clear that the default fromutc() is strong enough to handle
6773"almost all" time zones: so long as the standard offset is invariant, it
6774doesn't matter if daylight time transition points change from year to year, or
6775if daylight time is skipped in some years; it doesn't matter how large or
6776small dst() may get within its bounds; and it doesn't even matter if some
6777perverse time zone returns a negative dst()). So a breaking case must be
6778pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00006779--------------------------------------------------------------------------- */