blob: 1f15367d3fa304498644f5403dfebb50522512f5 [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
5#include "Python.h"
Tim Peters2a799bf2002-12-16 20:18:38 +00006#include "structmember.h"
7
8#include <time.h>
9
Victor Stinner09e5cf22015-03-30 00:09:18 +020010#ifdef MS_WINDOWS
11# include <winsock2.h> /* struct timeval */
12#endif
13
Tim Peters9ddf40b2004-06-20 22:41:32 +000014/* Differentiate between building the core module and building extension
15 * modules.
16 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000017#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000018#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000019#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000020#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000021#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000022
Larry Hastings61272b72014-01-07 12:41:53 -080023/*[clinic input]
Larry Hastings44e2eaa2013-11-23 15:37:55 -080024module datetime
Larry Hastingsc2047262014-01-25 20:43:29 -080025class datetime.datetime "PyDateTime_DateTime *" "&PyDateTime_DateTimeType"
Larry Hastings61272b72014-01-07 12:41:53 -080026[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080027/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78142cb64b9e98bc]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080028
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030029#include "clinic/_datetimemodule.c.h"
30
Tim Peters2a799bf2002-12-16 20:18:38 +000031/* We require that C int be at least 32 bits, and use int virtually
32 * everywhere. In just a few cases we use a temp long, where a Python
33 * API returns a C long. In such cases, we have to ensure that the
34 * final result fits in a C int (this can be an issue on 64-bit boxes).
35 */
36#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000037# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000038#endif
39
40#define MINYEAR 1
41#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000042#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000043
44/* Nine decimal digits is easy to communicate, and leaves enough room
45 * so that two delta days can be added w/o fear of overflowing a signed
46 * 32-bit int, and with plenty of room left over to absorb any possible
47 * carries from adding seconds.
48 */
49#define MAX_DELTA_DAYS 999999999
50
51/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052#define GET_YEAR PyDateTime_GET_YEAR
53#define GET_MONTH PyDateTime_GET_MONTH
54#define GET_DAY PyDateTime_GET_DAY
55#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
56#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
57#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
58#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040059#define DATE_GET_FOLD PyDateTime_DATE_GET_FOLD
Tim Peters2a799bf2002-12-16 20:18:38 +000060
61/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
63 ((o)->data[1] = ((v) & 0x00ff)))
64#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
65#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000066
67/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
69#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
70#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
71#define DATE_SET_MICROSECOND(o, v) \
72 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
73 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
74 ((o)->data[9] = ((v) & 0x0000ff)))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040075#define DATE_SET_FOLD(o, v) (PyDateTime_DATE_GET_FOLD(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000076
77/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
79#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
80#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
81#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040082#define TIME_GET_FOLD PyDateTime_TIME_GET_FOLD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
84#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
85#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
86#define TIME_SET_MICROSECOND(o, v) \
87 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
88 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
89 ((o)->data[5] = ((v) & 0x0000ff)))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040090#define TIME_SET_FOLD(o, v) (PyDateTime_TIME_GET_FOLD(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000091
92/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
94#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
95#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097#define SET_TD_DAYS(o, v) ((o)->days = (v))
98#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000099#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
100
Tim Petersa032d2e2003-01-11 00:15:54 +0000101/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
102 * p->hastzinfo.
103 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000104#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
105#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
106 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
107#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
108 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +0000109/* M is a char or int claiming to be a valid month. The macro is equivalent
110 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +0000112 */
113#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
114
Tim Peters2a799bf2002-12-16 20:18:38 +0000115/* Forward declarations. */
116static PyTypeObject PyDateTime_DateType;
117static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000118static PyTypeObject PyDateTime_DeltaType;
119static PyTypeObject PyDateTime_TimeType;
120static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000121static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000122
Victor Stinnerb67f0962017-02-10 10:34:02 +0100123static int check_tzinfo_subclass(PyObject *p);
124
Martin v. Löwise75fc142013-11-07 18:46:53 +0100125_Py_IDENTIFIER(as_integer_ratio);
126_Py_IDENTIFIER(fromutc);
127_Py_IDENTIFIER(isoformat);
128_Py_IDENTIFIER(strftime);
129
Tim Peters2a799bf2002-12-16 20:18:38 +0000130/* ---------------------------------------------------------------------------
131 * Math utilities.
132 */
133
134/* k = i+j overflows iff k differs in sign from both inputs,
135 * iff k^i has sign bit set and k^j has sign bit set,
136 * iff (k^i)&(k^j) has sign bit set.
137 */
138#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000140
141/* Compute Python divmod(x, y), returning the quotient and storing the
142 * remainder into *r. The quotient is the floor of x/y, and that's
143 * the real point of this. C will probably truncate instead (C99
144 * requires truncation; C89 left it implementation-defined).
145 * Simplification: we *require* that y > 0 here. That's appropriate
146 * for all the uses made of it. This simplifies the code and makes
147 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
148 * overflow case).
149 */
150static int
151divmod(int x, int y, int *r)
152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 assert(y > 0);
156 quo = x / y;
157 *r = x - quo * y;
158 if (*r < 0) {
159 --quo;
160 *r += y;
161 }
162 assert(0 <= *r && *r < y);
163 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000164}
165
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000166/* Nearest integer to m / n for integers m and n. Half-integer results
167 * are rounded to even.
168 */
169static PyObject *
170divide_nearest(PyObject *m, PyObject *n)
171{
172 PyObject *result;
173 PyObject *temp;
174
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000175 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000176 if (temp == NULL)
177 return NULL;
178 result = PyTuple_GET_ITEM(temp, 0);
179 Py_INCREF(result);
180 Py_DECREF(temp);
181
182 return result;
183}
184
Tim Peters2a799bf2002-12-16 20:18:38 +0000185/* ---------------------------------------------------------------------------
186 * General calendrical helper functions
187 */
188
189/* For each month ordinal in 1..12, the number of days in that month,
190 * and the number of days before that month in the same year. These
191 * are correct for non-leap years only.
192 */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200193static const int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 0, /* unused; this vector uses 1-based indexing */
195 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000196};
197
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200198static const int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 0, /* unused; this vector uses 1-based indexing */
200 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000201};
202
203/* year -> 1 if leap year, else 0. */
204static int
205is_leap(int year)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 /* Cast year to unsigned. The result is the same either way, but
208 * C can generate faster code for unsigned mod than for signed
209 * mod (especially for % 4 -- a good compiler should just grab
210 * the last 2 bits when the LHS is unsigned).
211 */
212 const unsigned int ayear = (unsigned int)year;
213 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000214}
215
216/* year, month -> number of days in that month in that year */
217static int
218days_in_month(int year, int month)
219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 assert(month >= 1);
221 assert(month <= 12);
222 if (month == 2 && is_leap(year))
223 return 29;
224 else
225 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000226}
227
Martin Panter46f50722016-05-26 05:35:26 +0000228/* year, month -> number of days in year preceding first day of month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000229static int
230days_before_month(int year, int month)
231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 assert(month >= 1);
235 assert(month <= 12);
236 days = _days_before_month[month];
237 if (month > 2 && is_leap(year))
238 ++days;
239 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000240}
241
242/* year -> number of days before January 1st of year. Remember that we
243 * start with year 1, so days_before_year(1) == 0.
244 */
245static int
246days_before_year(int year)
247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 int y = year - 1;
249 /* This is incorrect if year <= 0; we really want the floor
250 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000251 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000253 assert (year >= 1);
254 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000255}
256
257/* Number of days in 4, 100, and 400 year cycles. That these have
258 * the correct values is asserted in the module init function.
259 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260#define DI4Y 1461 /* days_before_year(5); days in 4 years */
261#define DI100Y 36524 /* days_before_year(101); days in 100 years */
262#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000263
264/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
265static void
266ord_to_ymd(int ordinal, int *year, int *month, int *day)
267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
271 * leap years repeats exactly every 400 years. The basic strategy is
272 * to find the closest 400-year boundary at or before ordinal, then
273 * work with the offset from that boundary to ordinal. Life is much
274 * clearer if we subtract 1 from ordinal first -- then the values
275 * of ordinal at 400-year boundaries are exactly those divisible
276 * by DI400Y:
277 *
278 * D M Y n n-1
279 * -- --- ---- ---------- ----------------
280 * 31 Dec -400 -DI400Y -DI400Y -1
281 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
282 * ...
283 * 30 Dec 000 -1 -2
284 * 31 Dec 000 0 -1
285 * 1 Jan 001 1 0 400-year boundary
286 * 2 Jan 001 2 1
287 * 3 Jan 001 3 2
288 * ...
289 * 31 Dec 400 DI400Y DI400Y -1
290 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
291 */
292 assert(ordinal >= 1);
293 --ordinal;
294 n400 = ordinal / DI400Y;
295 n = ordinal % DI400Y;
296 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* Now n is the (non-negative) offset, in days, from January 1 of
299 * year, to the desired date. Now compute how many 100-year cycles
300 * precede n.
301 * Note that it's possible for n100 to equal 4! In that case 4 full
302 * 100-year cycles precede the desired day, which implies the
303 * desired day is December 31 at the end of a 400-year cycle.
304 */
305 n100 = n / DI100Y;
306 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 /* Now compute how many 4-year cycles precede it. */
309 n4 = n / DI4Y;
310 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 /* And now how many single years. Again n1 can be 4, and again
313 * meaning that the desired day is December 31 at the end of the
314 * 4-year cycle.
315 */
316 n1 = n / 365;
317 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 *year += n100 * 100 + n4 * 4 + n1;
320 if (n1 == 4 || n100 == 4) {
321 assert(n == 0);
322 *year -= 1;
323 *month = 12;
324 *day = 31;
325 return;
326 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 /* Now the year is correct, and n is the offset from January 1. We
329 * find the month via an estimate that's either exact or one too
330 * large.
331 */
332 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
333 assert(leapyear == is_leap(*year));
334 *month = (n + 50) >> 5;
335 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
336 if (preceding > n) {
337 /* estimate is too large */
338 *month -= 1;
339 preceding -= days_in_month(*year, *month);
340 }
341 n -= preceding;
342 assert(0 <= n);
343 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000346}
347
348/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
349static int
350ymd_to_ord(int year, int month, int day)
351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000353}
354
355/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
356static int
357weekday(int year, int month, int day)
358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000360}
361
362/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
363 * first calendar week containing a Thursday.
364 */
365static int
366iso_week1_monday(int year)
367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
369 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
370 int first_weekday = (first_day + 6) % 7;
371 /* ordinal of closest Monday at or before 1/1 */
372 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
375 week1_monday += 7;
376 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000377}
378
379/* ---------------------------------------------------------------------------
380 * Range checkers.
381 */
382
383/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
384 * If not, raise OverflowError and return -1.
385 */
386static int
387check_delta_day_range(int days)
388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
390 return 0;
391 PyErr_Format(PyExc_OverflowError,
392 "days=%d; must have magnitude <= %d",
393 days, MAX_DELTA_DAYS);
394 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000395}
396
397/* Check that date arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_date_args(int year, int month, int day)
402{
403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (year < MINYEAR || year > MAXYEAR) {
Victor Stinnerb67f0962017-02-10 10:34:02 +0100405 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return -1;
407 }
408 if (month < 1 || month > 12) {
409 PyErr_SetString(PyExc_ValueError,
410 "month must be in 1..12");
411 return -1;
412 }
413 if (day < 1 || day > days_in_month(year, month)) {
414 PyErr_SetString(PyExc_ValueError,
415 "day is out of range for month");
416 return -1;
417 }
418 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000419}
420
421/* Check that time arguments are in range. Return 0 if they are. If they
422 * aren't, raise ValueError and return -1.
423 */
424static int
Alexander Belopolsky47649ab2016-08-08 17:05:40 -0400425check_time_args(int h, int m, int s, int us, int fold)
Tim Peters2a799bf2002-12-16 20:18:38 +0000426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (h < 0 || h > 23) {
428 PyErr_SetString(PyExc_ValueError,
429 "hour must be in 0..23");
430 return -1;
431 }
432 if (m < 0 || m > 59) {
433 PyErr_SetString(PyExc_ValueError,
434 "minute must be in 0..59");
435 return -1;
436 }
437 if (s < 0 || s > 59) {
438 PyErr_SetString(PyExc_ValueError,
439 "second must be in 0..59");
440 return -1;
441 }
442 if (us < 0 || us > 999999) {
443 PyErr_SetString(PyExc_ValueError,
444 "microsecond must be in 0..999999");
445 return -1;
446 }
Alexander Belopolsky47649ab2016-08-08 17:05:40 -0400447 if (fold != 0 && fold != 1) {
448 PyErr_SetString(PyExc_ValueError,
449 "fold must be either 0 or 1");
450 return -1;
451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000453}
454
455/* ---------------------------------------------------------------------------
456 * Normalization utilities.
457 */
458
459/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
460 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
461 * at least factor, enough of *lo is converted into "hi" units so that
462 * 0 <= *lo < factor. The input values must be such that int overflow
463 * is impossible.
464 */
465static void
466normalize_pair(int *hi, int *lo, int factor)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 assert(factor > 0);
469 assert(lo != hi);
470 if (*lo < 0 || *lo >= factor) {
471 const int num_hi = divmod(*lo, factor, lo);
472 const int new_hi = *hi + num_hi;
473 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
474 *hi = new_hi;
475 }
476 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000477}
478
479/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 * 0 <= *s < 24*3600
481 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000482 * The input values must be such that the internals don't overflow.
483 * The way this routine is used, we don't get close.
484 */
485static void
486normalize_d_s_us(int *d, int *s, int *us)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (*us < 0 || *us >= 1000000) {
489 normalize_pair(s, us, 1000000);
490 /* |s| can't be bigger than about
491 * |original s| + |original us|/1000000 now.
492 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
495 if (*s < 0 || *s >= 24*3600) {
496 normalize_pair(d, s, 24*3600);
497 /* |d| can't be bigger than about
498 * |original d| +
499 * (|original s| + |original us|/1000000) / (24*3600) now.
500 */
501 }
502 assert(0 <= *s && *s < 24*3600);
503 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000504}
505
506/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 * 1 <= *m <= 12
508 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000509 * The input values must be such that the internals don't overflow.
510 * The way this routine is used, we don't get close.
511 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000512static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000513normalize_y_m_d(int *y, int *m, int *d)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000516
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000517 /* In actual use, m is always the month component extracted from a
518 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 /* Now only day can be out of bounds (year may also be out of bounds
524 * for a datetime object, but we don't care about that here).
525 * If day is out of bounds, what to do is arguable, but at least the
526 * method here is principled and explainable.
527 */
528 dim = days_in_month(*y, *m);
529 if (*d < 1 || *d > dim) {
530 /* Move day-1 days from the first of the month. First try to
531 * get off cheap if we're only one day out of range
532 * (adjustments for timezone alone can't be worse than that).
533 */
534 if (*d == 0) {
535 --*m;
536 if (*m > 0)
537 *d = days_in_month(*y, *m);
538 else {
539 --*y;
540 *m = 12;
541 *d = 31;
542 }
543 }
544 else if (*d == dim + 1) {
545 /* move forward a day */
546 ++*m;
547 *d = 1;
548 if (*m > 12) {
549 *m = 1;
550 ++*y;
551 }
552 }
553 else {
554 int ordinal = ymd_to_ord(*y, *m, 1) +
555 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000556 if (ordinal < 1 || ordinal > MAXORDINAL) {
557 goto error;
558 } else {
559 ord_to_ymd(ordinal, y, m, d);
560 return 0;
561 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 }
563 }
564 assert(*m > 0);
565 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000566 if (MINYEAR <= *y && *y <= MAXYEAR)
567 return 0;
568 error:
569 PyErr_SetString(PyExc_OverflowError,
570 "date value out of range");
571 return -1;
572
Tim Peters2a799bf2002-12-16 20:18:38 +0000573}
574
575/* Fiddle out-of-bounds months and days so that the result makes some kind
576 * of sense. The parameters are both inputs and outputs. Returns < 0 on
577 * failure, where failure means the adjusted year is out of bounds.
578 */
579static int
580normalize_date(int *year, int *month, int *day)
581{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000582 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000583}
584
585/* Force all the datetime fields into range. The parameters are both
586 * inputs and outputs. Returns < 0 on error.
587 */
588static int
589normalize_datetime(int *year, int *month, int *day,
590 int *hour, int *minute, int *second,
591 int *microsecond)
592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 normalize_pair(second, microsecond, 1000000);
594 normalize_pair(minute, second, 60);
595 normalize_pair(hour, minute, 60);
596 normalize_pair(day, hour, 24);
597 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000598}
599
600/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000601 * Basic object allocation: tp_alloc implementations. These allocate
602 * Python objects of the right size and type, and do the Python object-
603 * initialization bit. If there's not enough memory, they return NULL after
604 * setting MemoryError. All data members remain uninitialized trash.
605 *
606 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000607 * member is needed. This is ugly, imprecise, and possibly insecure.
608 * tp_basicsize for the time and datetime types is set to the size of the
609 * struct that has room for the tzinfo member, so subclasses in Python will
610 * allocate enough space for a tzinfo member whether or not one is actually
611 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
612 * part is that PyType_GenericAlloc() (which subclasses in Python end up
613 * using) just happens today to effectively ignore the nitems argument
614 * when tp_itemsize is 0, which it is for these type objects. If that
615 * changes, perhaps the callers of tp_alloc slots in this file should
616 * be changed to force a 0 nitems argument unless the type being allocated
617 * is a base type implemented in this file (so that tp_alloc is time_alloc
618 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000619 */
620
621static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000622time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 self = (PyObject *)
627 PyObject_MALLOC(aware ?
628 sizeof(PyDateTime_Time) :
629 sizeof(_PyDateTime_BaseTime));
630 if (self == NULL)
631 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100632 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000634}
635
636static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000637datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 self = (PyObject *)
642 PyObject_MALLOC(aware ?
643 sizeof(PyDateTime_DateTime) :
644 sizeof(_PyDateTime_BaseDateTime));
645 if (self == NULL)
646 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100647 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000649}
650
651/* ---------------------------------------------------------------------------
652 * Helpers for setting object fields. These work on pointers to the
653 * appropriate base class.
654 */
655
656/* For date and datetime. */
657static void
658set_date_fields(PyDateTime_Date *self, int y, int m, int d)
659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 self->hashcode = -1;
661 SET_YEAR(self, y);
662 SET_MONTH(self, m);
663 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000664}
665
666/* ---------------------------------------------------------------------------
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500667 * String parsing utilities and helper functions
668 */
669
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700670static const char *
671parse_digits(const char *ptr, int *var, size_t num_digits)
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500672{
673 for (size_t i = 0; i < num_digits; ++i) {
674 unsigned int tmp = (unsigned int)(*(ptr++) - '0');
675 if (tmp > 9) {
676 return NULL;
677 }
678 *var *= 10;
679 *var += (signed int)tmp;
680 }
681
682 return ptr;
683}
684
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700685static int
686parse_isoformat_date(const char *dtstr, int *year, int *month, int *day)
687{
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500688 /* Parse the date components of the result of date.isoformat()
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700689 *
690 * Return codes:
691 * 0: Success
692 * -1: Failed to parse date component
693 * -2: Failed to parse dateseparator
694 */
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500695 const char *p = dtstr;
696 p = parse_digits(p, year, 4);
697 if (NULL == p) {
698 return -1;
699 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100700
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500701 if (*(p++) != '-') {
702 return -2;
703 }
704
705 p = parse_digits(p, month, 2);
706 if (NULL == p) {
707 return -1;
708 }
709
710 if (*(p++) != '-') {
711 return -2;
712 }
713
714 p = parse_digits(p, day, 2);
715 if (p == NULL) {
716 return -1;
717 }
718
719 return 0;
720}
721
722static int
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700723parse_hh_mm_ss_ff(const char *tstr, const char *tstr_end, int *hour,
724 int *minute, int *second, int *microsecond)
725{
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500726 const char *p = tstr;
727 const char *p_end = tstr_end;
728 int *vals[3] = {hour, minute, second};
729
730 // Parse [HH[:MM[:SS]]]
731 for (size_t i = 0; i < 3; ++i) {
732 p = parse_digits(p, vals[i], 2);
733 if (NULL == p) {
734 return -3;
735 }
736
737 char c = *(p++);
738 if (p >= p_end) {
739 return c != '\0';
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700740 }
741 else if (c == ':') {
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500742 continue;
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700743 }
744 else if (c == '.') {
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500745 break;
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700746 }
747 else {
748 return -4; // Malformed time separator
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500749 }
750 }
751
752 // Parse .fff[fff]
753 size_t len_remains = p_end - p;
754 if (!(len_remains == 6 || len_remains == 3)) {
755 return -3;
756 }
757
758 p = parse_digits(p, microsecond, len_remains);
759 if (NULL == p) {
760 return -3;
761 }
762
763 if (len_remains == 3) {
764 *microsecond *= 1000;
765 }
766
767 // Return 1 if it's not the end of the string
768 return *p != '\0';
769}
770
771static int
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700772parse_isoformat_time(const char *dtstr, size_t dtlen, int *hour, int *minute,
773 int *second, int *microsecond, int *tzoffset,
774 int *tzmicrosecond)
775{
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500776 // Parse the time portion of a datetime.isoformat() string
777 //
778 // Return codes:
779 // 0: Success (no tzoffset)
780 // 1: Success (with tzoffset)
781 // -3: Failed to parse time component
782 // -4: Failed to parse time separator
783 // -5: Malformed timezone string
784
785 const char *p = dtstr;
786 const char *p_end = dtstr + dtlen;
787
788 const char *tzinfo_pos = p;
789 do {
790 if (*tzinfo_pos == '+' || *tzinfo_pos == '-') {
791 break;
792 }
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700793 } while (++tzinfo_pos < p_end);
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500794
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700795 int rv = parse_hh_mm_ss_ff(dtstr, tzinfo_pos, hour, minute, second,
796 microsecond);
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500797
798 if (rv < 0) {
799 return rv;
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700800 }
801 else if (tzinfo_pos == p_end) {
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500802 // We know that there's no time zone, so if there's stuff at the
803 // end of the string it's an error.
804 if (rv == 1) {
805 return -5;
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700806 }
807 else {
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500808 return 0;
809 }
810 }
811
812 // Parse time zone component
813 // Valid formats are:
814 // - +HH:MM (len 6)
815 // - +HH:MM:SS (len 9)
816 // - +HH:MM:SS.ffffff (len 16)
817 size_t tzlen = p_end - tzinfo_pos;
818 if (!(tzlen == 6 || tzlen == 9 || tzlen == 16)) {
819 return -5;
820 }
821
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700822 int tzsign = (*tzinfo_pos == '-') ? -1 : 1;
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500823 tzinfo_pos++;
824 int tzhour = 0, tzminute = 0, tzsecond = 0;
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700825 rv = parse_hh_mm_ss_ff(tzinfo_pos, p_end, &tzhour, &tzminute, &tzsecond,
826 tzmicrosecond);
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500827
828 *tzoffset = tzsign * ((tzhour * 3600) + (tzminute * 60) + tzsecond);
829 *tzmicrosecond *= tzsign;
830
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700831 return rv ? -5 : 1;
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500832}
833
Paul Ganssle09dc2f52017-12-21 00:33:49 -0500834/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000835 * Create various objects, mostly without range checking.
836 */
837
838/* Create a date instance with no range checking. */
839static PyObject *
840new_date_ex(int year, int month, int day, PyTypeObject *type)
841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000843
Victor Stinnerb67f0962017-02-10 10:34:02 +0100844 if (check_date_args(year, month, day) < 0) {
845 return NULL;
846 }
847
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700848 self = (PyDateTime_Date *)(type->tp_alloc(type, 0));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (self != NULL)
850 set_date_fields(self, year, month, day);
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700851 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000852}
853
854#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000856
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500857// Forward declaration
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700858static PyObject *
859new_datetime_ex(int, int, int, int, int, int, int, PyObject *, PyTypeObject *);
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500860
861/* Create date instance with no range checking, or call subclass constructor */
862static PyObject *
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700863new_date_subclass_ex(int year, int month, int day, PyObject *cls)
864{
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500865 PyObject *result;
866 // We have "fast path" constructors for two subclasses: date and datetime
867 if ((PyTypeObject *)cls == &PyDateTime_DateType) {
868 result = new_date_ex(year, month, day, (PyTypeObject *)cls);
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700869 }
870 else if ((PyTypeObject *)cls == &PyDateTime_DateTimeType) {
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500871 result = new_datetime_ex(year, month, day, 0, 0, 0, 0, Py_None,
872 (PyTypeObject *)cls);
Miss Islington (bot)18450be2018-10-22 15:35:15 -0700873 }
874 else {
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500875 result = PyObject_CallFunction(cls, "iii", year, month, day);
876 }
877
878 return result;
879}
880
Tim Petersb0c854d2003-05-17 15:57:00 +0000881/* Create a datetime instance with no range checking. */
882static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400883new_datetime_ex2(int year, int month, int day, int hour, int minute,
884 int second, int usecond, PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyDateTime_DateTime *self;
887 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000888
Victor Stinnerb67f0962017-02-10 10:34:02 +0100889 if (check_date_args(year, month, day) < 0) {
890 return NULL;
891 }
892 if (check_time_args(hour, minute, second, usecond, fold) < 0) {
893 return NULL;
894 }
895 if (check_tzinfo_subclass(tzinfo) < 0) {
896 return NULL;
897 }
898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
900 if (self != NULL) {
901 self->hastzinfo = aware;
902 set_date_fields((PyDateTime_Date *)self, year, month, day);
903 DATE_SET_HOUR(self, hour);
904 DATE_SET_MINUTE(self, minute);
905 DATE_SET_SECOND(self, second);
906 DATE_SET_MICROSECOND(self, usecond);
907 if (aware) {
908 Py_INCREF(tzinfo);
909 self->tzinfo = tzinfo;
910 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400911 DATE_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 }
913 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000914}
915
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400916static PyObject *
917new_datetime_ex(int year, int month, int day, int hour, int minute,
918 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
919{
920 return new_datetime_ex2(year, month, day, hour, minute, second, usecond,
921 tzinfo, 0, type);
922}
923
924#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo, fold) \
925 new_datetime_ex2(y, m, d, hh, mm, ss, us, tzinfo, fold, \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000927
Paul Ganssle9f1b7b92018-01-16 13:06:31 -0500928static PyObject *
929new_datetime_subclass_fold_ex(int year, int month, int day, int hour, int minute,
930 int second, int usecond, PyObject *tzinfo,
931 int fold, PyObject *cls) {
932 PyObject* dt;
933 if ((PyTypeObject*)cls == &PyDateTime_DateTimeType) {
934 // Use the fast path constructor
935 dt = new_datetime(year, month, day, hour, minute, second, usecond,
936 tzinfo, fold);
937 } else {
938 // Subclass
939 dt = PyObject_CallFunction(cls, "iiiiiiiO",
940 year,
941 month,
942 day,
943 hour,
944 minute,
945 second,
946 usecond,
947 tzinfo);
948 }
949
950 return dt;
951}
952
953static PyObject *
954new_datetime_subclass_ex(int year, int month, int day, int hour, int minute,
955 int second, int usecond, PyObject *tzinfo,
956 PyObject *cls) {
957 return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
958 second, usecond, tzinfo, 0,
959 cls);
960}
961
Tim Petersb0c854d2003-05-17 15:57:00 +0000962/* Create a time instance with no range checking. */
963static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400964new_time_ex2(int hour, int minute, int second, int usecond,
965 PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 PyDateTime_Time *self;
968 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000969
Victor Stinnerb67f0962017-02-10 10:34:02 +0100970 if (check_time_args(hour, minute, second, usecond, fold) < 0) {
971 return NULL;
972 }
973 if (check_tzinfo_subclass(tzinfo) < 0) {
974 return NULL;
975 }
976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
978 if (self != NULL) {
979 self->hastzinfo = aware;
980 self->hashcode = -1;
981 TIME_SET_HOUR(self, hour);
982 TIME_SET_MINUTE(self, minute);
983 TIME_SET_SECOND(self, second);
984 TIME_SET_MICROSECOND(self, usecond);
985 if (aware) {
986 Py_INCREF(tzinfo);
987 self->tzinfo = tzinfo;
988 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400989 TIME_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 }
991 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000992}
993
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400994static PyObject *
995new_time_ex(int hour, int minute, int second, int usecond,
996 PyObject *tzinfo, PyTypeObject *type)
997{
998 return new_time_ex2(hour, minute, second, usecond, tzinfo, 0, type);
999}
1000
1001#define new_time(hh, mm, ss, us, tzinfo, fold) \
1002 new_time_ex2(hh, mm, ss, us, tzinfo, fold, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001003
1004/* Create a timedelta instance. Normalize the members iff normalize is
1005 * true. Passing false is a speed optimization, if you know for sure
1006 * that seconds and microseconds are already in their proper ranges. In any
1007 * case, raises OverflowError and returns NULL if the normalized days is out
1008 * of range).
1009 */
1010static PyObject *
1011new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +00001013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (normalize)
1017 normalize_d_s_us(&days, &seconds, &microseconds);
1018 assert(0 <= seconds && seconds < 24*3600);
1019 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (check_delta_day_range(days) < 0)
1022 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
1025 if (self != NULL) {
1026 self->hashcode = -1;
1027 SET_TD_DAYS(self, days);
1028 SET_TD_SECONDS(self, seconds);
1029 SET_TD_MICROSECONDS(self, microseconds);
1030 }
1031 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +00001032}
1033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034#define new_delta(d, s, us, normalize) \
1035 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001036
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001037
1038typedef struct
1039{
1040 PyObject_HEAD
1041 PyObject *offset;
1042 PyObject *name;
1043} PyDateTime_TimeZone;
1044
Victor Stinner6ced7c42011-03-21 18:15:42 +01001045/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00001046static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya4415142012-06-08 12:33:09 -04001047/* The interned Epoch datetime instance */
1048static PyObject *PyDateTime_Epoch;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00001049
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001050/* Create new timezone instance checking offset range. This
1051 function does not check the name argument. Caller must assure
1052 that offset is a timedelta instance and name is either NULL
1053 or a unicode object. */
1054static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00001055create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001056{
1057 PyDateTime_TimeZone *self;
1058 PyTypeObject *type = &PyDateTime_TimeZoneType;
1059
1060 assert(offset != NULL);
1061 assert(PyDelta_Check(offset));
1062 assert(name == NULL || PyUnicode_Check(name));
1063
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00001064 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
1065 if (self == NULL) {
1066 return NULL;
1067 }
1068 Py_INCREF(offset);
1069 self->offset = offset;
1070 Py_XINCREF(name);
1071 self->name = name;
1072 return (PyObject *)self;
1073}
1074
1075static int delta_bool(PyDateTime_Delta *self);
1076
1077static PyObject *
1078new_timezone(PyObject *offset, PyObject *name)
1079{
1080 assert(offset != NULL);
1081 assert(PyDelta_Check(offset));
1082 assert(name == NULL || PyUnicode_Check(name));
1083
1084 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
1085 Py_INCREF(PyDateTime_TimeZone_UTC);
1086 return PyDateTime_TimeZone_UTC;
1087 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001088 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
1089 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
1090 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
1091 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04001092 " timedelta(hours=24),"
1093 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001094 return NULL;
1095 }
1096
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00001097 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00001098}
1099
Tim Petersb0c854d2003-05-17 15:57:00 +00001100/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001101 * tzinfo helpers.
1102 */
1103
Tim Peters855fe882002-12-22 03:43:39 +00001104/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
1105 * raise TypeError and return -1.
1106 */
1107static int
1108check_tzinfo_subclass(PyObject *p)
1109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if (p == Py_None || PyTZInfo_Check(p))
1111 return 0;
1112 PyErr_Format(PyExc_TypeError,
1113 "tzinfo argument must be None or of a tzinfo subclass, "
1114 "not type '%s'",
1115 Py_TYPE(p)->tp_name);
1116 return -1;
Tim Peters855fe882002-12-22 03:43:39 +00001117}
1118
Tim Peters2a799bf2002-12-16 20:18:38 +00001119/* If self has a tzinfo member, return a BORROWED reference to it. Else
1120 * return NULL, which is NOT AN ERROR. There are no error returns here,
1121 * and the caller must not decref the result.
1122 */
1123static PyObject *
1124get_tzinfo_member(PyObject *self)
1125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 if (PyDateTime_Check(self) && HASTZINFO(self))
1129 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
1130 else if (PyTime_Check(self) && HASTZINFO(self))
1131 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +00001134}
1135
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001136/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
1137 * be an instance of the tzinfo class. If the method returns None, this
1138 * returns None. If the method doesn't return None or timedelta, TypeError is
1139 * raised and this returns NULL. If it returns a timedelta and the value is
1140 * out of range or isn't a whole number of minutes, ValueError is raised and
1141 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +00001142 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001143static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001144call_tzinfo_method(PyObject *tzinfo, const char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001145{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001146 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001149 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001151
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001152 if (tzinfo == Py_None)
1153 Py_RETURN_NONE;
1154 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
1155 if (offset == Py_None || offset == NULL)
1156 return offset;
1157 if (PyDelta_Check(offset)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001158 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
1159 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
1160 Py_DECREF(offset);
1161 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
1162 " strictly between -timedelta(hours=24) and"
1163 " timedelta(hours=24).");
1164 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 }
1166 }
1167 else {
1168 PyErr_Format(PyExc_TypeError,
1169 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001170 "timedelta, not '%.200s'",
1171 name, Py_TYPE(offset)->tp_name);
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07001172 Py_DECREF(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001173 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001175
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001176 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +00001177}
1178
1179/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
1180 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
1181 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +00001182 * doesn't return None or timedelta, TypeError is raised and this returns -1.
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001183 * If utcoffset() returns an out of range timedelta,
1184 * ValueError is raised and this returns -1. Else *none is
1185 * set to 0 and the offset is returned (as timedelta, positive east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +00001186 */
Tim Peters855fe882002-12-22 03:43:39 +00001187static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001188call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
1189{
1190 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +00001191}
1192
Tim Peters2a799bf2002-12-16 20:18:38 +00001193/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
1194 * result. tzinfo must be an instance of the tzinfo class. If dst()
1195 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001196 * doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00001197 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +00001198 * ValueError is raised and this returns -1. Else *none is set to 0 and
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001199 * the offset is returned (as timedelta, positive east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +00001200 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001201static PyObject *
1202call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001203{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001204 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001205}
1206
Tim Petersbad8ff02002-12-30 20:52:32 +00001207/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +00001208 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +00001209 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +00001210 * returns NULL. If the result is a string, we ensure it is a Unicode
1211 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +00001212 */
1213static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001214call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001217 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 assert(tzinfo != NULL);
1220 assert(check_tzinfo_subclass(tzinfo) >= 0);
1221 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001224 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001225
Victor Stinner20401de2016-12-09 15:24:31 +01001226 result = _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_tzname,
1227 tzinfoarg, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001228
1229 if (result == NULL || result == Py_None)
1230 return result;
1231
1232 if (!PyUnicode_Check(result)) {
1233 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
1234 "return None or a string, not '%s'",
1235 Py_TYPE(result)->tp_name);
1236 Py_DECREF(result);
1237 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001239
1240 return result;
Tim Peters00237032002-12-27 02:21:51 +00001241}
1242
Tim Peters2a799bf2002-12-16 20:18:38 +00001243/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1244 * stuff
1245 * ", tzinfo=" + repr(tzinfo)
1246 * before the closing ")".
1247 */
1248static PyObject *
1249append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 assert(PyUnicode_Check(repr));
1254 assert(tzinfo);
1255 if (tzinfo == Py_None)
1256 return repr;
1257 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1259 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 Py_DECREF(repr);
1261 if (temp == NULL)
1262 return NULL;
1263 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1264 Py_DECREF(temp);
1265 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001266}
1267
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001268/* repr is like "someclass(arg1, arg2)". If fold isn't 0,
1269 * stuff
1270 * ", fold=" + repr(tzinfo)
1271 * before the closing ")".
1272 */
1273static PyObject *
1274append_keyword_fold(PyObject *repr, int fold)
1275{
1276 PyObject *temp;
1277
1278 assert(PyUnicode_Check(repr));
1279 if (fold == 0)
1280 return repr;
1281 /* Get rid of the trailing ')'. */
1282 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1283 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
1284 Py_DECREF(repr);
1285 if (temp == NULL)
1286 return NULL;
1287 repr = PyUnicode_FromFormat("%U, fold=%d)", temp, fold);
1288 Py_DECREF(temp);
1289 return repr;
1290}
1291
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001292static inline PyObject *
Miss Islington (bot)18450be2018-10-22 15:35:15 -07001293tzinfo_from_isoformat_results(int rv, int tzoffset, int tz_useconds)
1294{
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001295 PyObject *tzinfo;
1296 if (rv == 1) {
1297 // Create a timezone from offset in seconds (0 returns UTC)
1298 if (tzoffset == 0) {
1299 Py_INCREF(PyDateTime_TimeZone_UTC);
1300 return PyDateTime_TimeZone_UTC;
1301 }
1302
1303 PyObject *delta = new_delta(0, tzoffset, tz_useconds, 1);
Miss Islington (bot)c7f54352018-08-24 12:13:57 -04001304 if (delta == NULL) {
1305 return NULL;
1306 }
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001307 tzinfo = new_timezone(delta, NULL);
Miss Islington (bot)c7f54352018-08-24 12:13:57 -04001308 Py_DECREF(delta);
Miss Islington (bot)18450be2018-10-22 15:35:15 -07001309 }
1310 else {
Paul Ganssle09dc2f52017-12-21 00:33:49 -05001311 tzinfo = Py_None;
1312 Py_INCREF(Py_None);
1313 }
1314
1315 return tzinfo;
1316}
1317
Tim Peters2a799bf2002-12-16 20:18:38 +00001318/* ---------------------------------------------------------------------------
1319 * String format helpers.
1320 */
1321
1322static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001323format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001324{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001325 static const char * const DayNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1327 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001328 static const char * const MonthNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1330 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1331 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1336 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1337 GET_DAY(date), hours, minutes, seconds,
1338 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001339}
1340
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001341static PyObject *delta_negative(PyDateTime_Delta *self);
1342
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001343/* Add formatted UTC offset string to buf. buf has no more than
Tim Peters2a799bf2002-12-16 20:18:38 +00001344 * buflen bytes remaining. The UTC offset is gotten by calling
1345 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1346 * *buf, and that's all. Else the returned value is checked for sanity (an
1347 * integer in range), and if that's OK it's converted to an hours & minutes
1348 * string of the form
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001349 * sign HH sep MM [sep SS [. UUUUUU]]
Tim Peters2a799bf2002-12-16 20:18:38 +00001350 * Returns 0 if everything is OK. If the return value from utcoffset() is
1351 * bogus, an appropriate exception is set and -1 is returned.
1352 */
1353static int
Tim Peters328fff72002-12-20 01:31:27 +00001354format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001356{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001357 PyObject *offset;
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001358 int hours, minutes, seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001362
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001363 offset = call_utcoffset(tzinfo, tzinfoarg);
1364 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001366 if (offset == Py_None) {
1367 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 *buf = '\0';
1369 return 0;
1370 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001371 /* Offset is normalized, so it is negative if days < 0 */
1372 if (GET_TD_DAYS(offset) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 sign = '-';
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03001374 Py_SETREF(offset, delta_negative((PyDateTime_Delta *)offset));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001375 if (offset == NULL)
1376 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001378 else {
1379 sign = '+';
1380 }
1381 /* Offset is not negative here. */
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001382 microseconds = GET_TD_MICROSECONDS(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001383 seconds = GET_TD_SECONDS(offset);
1384 Py_DECREF(offset);
1385 minutes = divmod(seconds, 60, &seconds);
1386 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001387 if (microseconds) {
1388 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d.%06d", sign,
1389 hours, sep, minutes, sep, seconds, microseconds);
1390 return 0;
1391 }
1392 if (seconds) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001393 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d", sign, hours,
1394 sep, minutes, sep, seconds);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001395 return 0;
1396 }
1397 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001399}
1400
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001401static PyObject *
1402make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 PyObject *temp;
1405 PyObject *tzinfo = get_tzinfo_member(object);
1406 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001407 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (Zreplacement == NULL)
1410 return NULL;
1411 if (tzinfo == Py_None || tzinfo == NULL)
1412 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 assert(tzinfoarg != NULL);
1415 temp = call_tzname(tzinfo, tzinfoarg);
1416 if (temp == NULL)
1417 goto Error;
1418 if (temp == Py_None) {
1419 Py_DECREF(temp);
1420 return Zreplacement;
1421 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 assert(PyUnicode_Check(temp));
1424 /* Since the tzname is getting stuffed into the
1425 * format, we have to double any % signs so that
1426 * strftime doesn't treat them as format codes.
1427 */
1428 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001429 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 Py_DECREF(temp);
1431 if (Zreplacement == NULL)
1432 return NULL;
1433 if (!PyUnicode_Check(Zreplacement)) {
1434 PyErr_SetString(PyExc_TypeError,
1435 "tzname.replace() did not return a string");
1436 goto Error;
1437 }
1438 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001439
1440 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 Py_DECREF(Zreplacement);
1442 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001443}
1444
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001445static PyObject *
1446make_freplacement(PyObject *object)
1447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 char freplacement[64];
1449 if (PyTime_Check(object))
1450 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1451 else if (PyDateTime_Check(object))
1452 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1453 else
1454 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001457}
1458
Tim Peters2a799bf2002-12-16 20:18:38 +00001459/* I sure don't want to reproduce the strftime code from the time module,
1460 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001461 * giving special meanings to the %z, %Z and %f format codes via a
1462 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001463 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1464 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001465 */
1466static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001467wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1473 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1474 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 const char *pin; /* pointer to next char in input format */
1477 Py_ssize_t flen; /* length of input format */
1478 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyObject *newfmt = NULL; /* py string, the output format */
1481 char *pnew; /* pointer to available byte in output format */
1482 size_t totalnew; /* number bytes total in output format buffer,
1483 exclusive of trailing \0 */
1484 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 const char *ptoappend; /* ptr to string to append to output buffer */
1487 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 assert(object && format && timetuple);
1490 assert(PyUnicode_Check(format));
1491 /* Convert the input format to a C string and size */
Serhiy Storchaka06515832016-11-20 09:13:07 +02001492 pin = PyUnicode_AsUTF8AndSize(format, &flen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (!pin)
1494 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 /* Scan the input format, looking for %z/%Z/%f escapes, building
1497 * a new format. Since computing the replacements for those codes
1498 * is expensive, don't unless they're actually used.
1499 */
1500 if (flen > INT_MAX - 1) {
1501 PyErr_NoMemory();
1502 goto Done;
1503 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 totalnew = flen + 1; /* realistic if no %z/%Z */
1506 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1507 if (newfmt == NULL) goto Done;
1508 pnew = PyBytes_AsString(newfmt);
1509 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 while ((ch = *pin++) != '\0') {
1512 if (ch != '%') {
1513 ptoappend = pin - 1;
1514 ntoappend = 1;
1515 }
1516 else if ((ch = *pin++) == '\0') {
1517 /* There's a lone trailing %; doesn't make sense. */
1518 PyErr_SetString(PyExc_ValueError, "strftime format "
1519 "ends with raw %");
1520 goto Done;
1521 }
1522 /* A % has been seen and ch is the character after it. */
1523 else if (ch == 'z') {
1524 if (zreplacement == NULL) {
1525 /* format utcoffset */
1526 char buf[100];
1527 PyObject *tzinfo = get_tzinfo_member(object);
1528 zreplacement = PyBytes_FromStringAndSize("", 0);
1529 if (zreplacement == NULL) goto Done;
1530 if (tzinfo != Py_None && tzinfo != NULL) {
1531 assert(tzinfoarg != NULL);
1532 if (format_utcoffset(buf,
1533 sizeof(buf),
1534 "",
1535 tzinfo,
1536 tzinfoarg) < 0)
1537 goto Done;
1538 Py_DECREF(zreplacement);
1539 zreplacement =
1540 PyBytes_FromStringAndSize(buf,
1541 strlen(buf));
1542 if (zreplacement == NULL)
1543 goto Done;
1544 }
1545 }
1546 assert(zreplacement != NULL);
1547 ptoappend = PyBytes_AS_STRING(zreplacement);
1548 ntoappend = PyBytes_GET_SIZE(zreplacement);
1549 }
1550 else if (ch == 'Z') {
1551 /* format tzname */
1552 if (Zreplacement == NULL) {
1553 Zreplacement = make_Zreplacement(object,
1554 tzinfoarg);
1555 if (Zreplacement == NULL)
1556 goto Done;
1557 }
1558 assert(Zreplacement != NULL);
1559 assert(PyUnicode_Check(Zreplacement));
Serhiy Storchaka06515832016-11-20 09:13:07 +02001560 ptoappend = PyUnicode_AsUTF8AndSize(Zreplacement,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001562 if (ptoappend == NULL)
1563 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 }
1565 else if (ch == 'f') {
1566 /* format microseconds */
1567 if (freplacement == NULL) {
1568 freplacement = make_freplacement(object);
1569 if (freplacement == NULL)
1570 goto Done;
1571 }
1572 assert(freplacement != NULL);
1573 assert(PyBytes_Check(freplacement));
1574 ptoappend = PyBytes_AS_STRING(freplacement);
1575 ntoappend = PyBytes_GET_SIZE(freplacement);
1576 }
1577 else {
1578 /* percent followed by neither z nor Z */
1579 ptoappend = pin - 2;
1580 ntoappend = 2;
1581 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* Append the ntoappend chars starting at ptoappend to
1584 * the new format.
1585 */
1586 if (ntoappend == 0)
1587 continue;
1588 assert(ptoappend != NULL);
1589 assert(ntoappend > 0);
1590 while (usednew + ntoappend > totalnew) {
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001591 if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyErr_NoMemory();
1593 goto Done;
1594 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001595 totalnew <<= 1;
1596 if (_PyBytes_Resize(&newfmt, totalnew) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 pnew = PyBytes_AsString(newfmt) + usednew;
1599 }
1600 memcpy(pnew, ptoappend, ntoappend);
1601 pnew += ntoappend;
1602 usednew += ntoappend;
1603 assert(usednew <= totalnew);
1604 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1607 goto Done;
1608 {
1609 PyObject *format;
1610 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 if (time == NULL)
1613 goto Done;
1614 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1615 if (format != NULL) {
Victor Stinner20401de2016-12-09 15:24:31 +01001616 result = _PyObject_CallMethodIdObjArgs(time, &PyId_strftime,
1617 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 Py_DECREF(format);
1619 }
1620 Py_DECREF(time);
1621 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001622 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 Py_XDECREF(freplacement);
1624 Py_XDECREF(zreplacement);
1625 Py_XDECREF(Zreplacement);
1626 Py_XDECREF(newfmt);
1627 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001628}
1629
Tim Peters2a799bf2002-12-16 20:18:38 +00001630/* ---------------------------------------------------------------------------
1631 * Wrap functions from the time module. These aren't directly available
1632 * from C. Perhaps they should be.
1633 */
1634
1635/* Call time.time() and return its result (a Python float). */
1636static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001637time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 PyObject *result = NULL;
1640 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001643 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001644
Victor Stinnerad8c83a2016-09-05 17:53:15 -07001645 result = _PyObject_CallMethodId(time, &PyId_time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 Py_DECREF(time);
1647 }
1648 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001649}
1650
1651/* Build a time.struct_time. The weekday and day number are automatically
1652 * computed from the y,m,d args.
1653 */
1654static PyObject *
1655build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 PyObject *time;
Victor Stinner2b635972016-12-09 00:38:16 +01001658 PyObject *result;
1659 _Py_IDENTIFIER(struct_time);
1660 PyObject *args;
1661
Tim Peters2a799bf2002-12-16 20:18:38 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 time = PyImport_ImportModuleNoBlock("time");
Victor Stinner2b635972016-12-09 00:38:16 +01001664 if (time == NULL) {
1665 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 }
Victor Stinner2b635972016-12-09 00:38:16 +01001667
1668 args = Py_BuildValue("iiiiiiiii",
1669 y, m, d,
1670 hh, mm, ss,
1671 weekday(y, m, d),
1672 days_before_month(y, m) + d,
1673 dstflag);
1674 if (args == NULL) {
1675 Py_DECREF(time);
1676 return NULL;
1677 }
1678
1679 result = _PyObject_CallMethodIdObjArgs(time, &PyId_struct_time,
1680 args, NULL);
1681 Py_DECREF(time);
Victor Stinnerddc120f2016-12-09 15:35:40 +01001682 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001684}
1685
1686/* ---------------------------------------------------------------------------
1687 * Miscellaneous helpers.
1688 */
1689
Mark Dickinsone94c6792009-02-02 20:36:42 +00001690/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001691 * The comparisons here all most naturally compute a cmp()-like result.
1692 * This little helper turns that into a bool result for rich comparisons.
1693 */
1694static PyObject *
1695diff_to_bool(int diff, int op)
1696{
stratakise8b19652017-11-02 11:32:54 +01001697 Py_RETURN_RICHCOMPARE(diff, 0, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001698}
1699
Tim Peters07534a62003-02-07 22:50:28 +00001700/* Raises a "can't compare" TypeError and returns NULL. */
1701static PyObject *
1702cmperror(PyObject *a, PyObject *b)
1703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 PyErr_Format(PyExc_TypeError,
1705 "can't compare %s to %s",
1706 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1707 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001708}
1709
Tim Peters2a799bf2002-12-16 20:18:38 +00001710/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001711 * Cached Python objects; these are set by the module init function.
1712 */
1713
1714/* Conversion factors. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715static PyObject *us_per_ms = NULL; /* 1000 */
1716static PyObject *us_per_second = NULL; /* 1000000 */
1717static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001718static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
1719static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
1720static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
Tim Peters2a799bf2002-12-16 20:18:38 +00001721static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1722
Tim Peters2a799bf2002-12-16 20:18:38 +00001723/* ---------------------------------------------------------------------------
1724 * Class implementations.
1725 */
1726
1727/*
1728 * PyDateTime_Delta implementation.
1729 */
1730
1731/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Serhiy Storchaka95949422013-08-27 19:40:23 +03001733 * as a Python int.
Tim Peters2a799bf2002-12-16 20:18:38 +00001734 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1735 * due to ubiquitous overflow possibilities.
1736 */
1737static PyObject *
1738delta_to_microseconds(PyDateTime_Delta *self)
1739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 PyObject *x1 = NULL;
1741 PyObject *x2 = NULL;
1742 PyObject *x3 = NULL;
1743 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1746 if (x1 == NULL)
1747 goto Done;
1748 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1749 if (x2 == NULL)
1750 goto Done;
1751 Py_DECREF(x1);
1752 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 /* x2 has days in seconds */
1755 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1756 if (x1 == NULL)
1757 goto Done;
1758 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1759 if (x3 == NULL)
1760 goto Done;
1761 Py_DECREF(x1);
1762 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001763 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 /* x3 has days+seconds in seconds */
1766 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1767 if (x1 == NULL)
1768 goto Done;
1769 Py_DECREF(x3);
1770 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 /* x1 has days+seconds in us */
1773 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1774 if (x2 == NULL)
1775 goto Done;
1776 result = PyNumber_Add(x1, x2);
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03001777 assert(result == NULL || PyLong_CheckExact(result));
Tim Peters2a799bf2002-12-16 20:18:38 +00001778
1779Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 Py_XDECREF(x1);
1781 Py_XDECREF(x2);
1782 Py_XDECREF(x3);
1783 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001784}
1785
Serhiy Storchaka95949422013-08-27 19:40:23 +03001786/* Convert a number of us (as a Python int) to a timedelta.
Tim Peters2a799bf2002-12-16 20:18:38 +00001787 */
1788static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001789microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 int us;
1792 int s;
1793 int d;
1794 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 PyObject *tuple = NULL;
1797 PyObject *num = NULL;
1798 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001799
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03001800 assert(PyLong_CheckExact(pyus));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 tuple = PyNumber_Divmod(pyus, us_per_second);
1802 if (tuple == NULL)
1803 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 num = PyTuple_GetItem(tuple, 1); /* us */
1806 if (num == NULL)
1807 goto Done;
1808 temp = PyLong_AsLong(num);
1809 num = NULL;
1810 if (temp == -1 && PyErr_Occurred())
1811 goto Done;
1812 assert(0 <= temp && temp < 1000000);
1813 us = (int)temp;
1814 if (us < 0) {
1815 /* The divisor was positive, so this must be an error. */
1816 assert(PyErr_Occurred());
1817 goto Done;
1818 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1821 if (num == NULL)
1822 goto Done;
1823 Py_INCREF(num);
1824 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 tuple = PyNumber_Divmod(num, seconds_per_day);
1827 if (tuple == NULL)
1828 goto Done;
1829 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 num = PyTuple_GetItem(tuple, 1); /* seconds */
1832 if (num == NULL)
1833 goto Done;
1834 temp = PyLong_AsLong(num);
1835 num = NULL;
1836 if (temp == -1 && PyErr_Occurred())
1837 goto Done;
1838 assert(0 <= temp && temp < 24*3600);
1839 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (s < 0) {
1842 /* The divisor was positive, so this must be an error. */
1843 assert(PyErr_Occurred());
1844 goto Done;
1845 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1848 if (num == NULL)
1849 goto Done;
1850 Py_INCREF(num);
1851 temp = PyLong_AsLong(num);
1852 if (temp == -1 && PyErr_Occurred())
1853 goto Done;
1854 d = (int)temp;
1855 if ((long)d != temp) {
1856 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1857 "large to fit in a C int");
1858 goto Done;
1859 }
1860 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001861
1862Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 Py_XDECREF(tuple);
1864 Py_XDECREF(num);
1865 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001866}
1867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868#define microseconds_to_delta(pymicros) \
1869 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001870
Tim Peters2a799bf2002-12-16 20:18:38 +00001871static PyObject *
1872multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 PyObject *pyus_in;
1875 PyObject *pyus_out;
1876 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 pyus_in = delta_to_microseconds(delta);
1879 if (pyus_in == NULL)
1880 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1883 Py_DECREF(pyus_in);
1884 if (pyus_out == NULL)
1885 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 result = microseconds_to_delta(pyus_out);
1888 Py_DECREF(pyus_out);
1889 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001890}
1891
1892static PyObject *
Oren Milman865e4b42017-09-19 15:58:11 +03001893get_float_as_integer_ratio(PyObject *floatobj)
1894{
1895 PyObject *ratio;
1896
1897 assert(floatobj && PyFloat_Check(floatobj));
1898 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
1899 if (ratio == NULL) {
1900 return NULL;
1901 }
1902 if (!PyTuple_Check(ratio)) {
1903 PyErr_Format(PyExc_TypeError,
1904 "unexpected return type from as_integer_ratio(): "
1905 "expected tuple, got '%.200s'",
1906 Py_TYPE(ratio)->tp_name);
1907 Py_DECREF(ratio);
1908 return NULL;
1909 }
1910 if (PyTuple_Size(ratio) != 2) {
1911 PyErr_SetString(PyExc_ValueError,
1912 "as_integer_ratio() must return a 2-tuple");
1913 Py_DECREF(ratio);
1914 return NULL;
1915 }
1916 return ratio;
1917}
1918
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03001919/* op is 0 for multiplication, 1 for division */
Oren Milman865e4b42017-09-19 15:58:11 +03001920static PyObject *
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03001921multiply_truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *floatobj, int op)
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001922{
1923 PyObject *result = NULL;
1924 PyObject *pyus_in = NULL, *temp, *pyus_out;
1925 PyObject *ratio = NULL;
1926
1927 pyus_in = delta_to_microseconds(delta);
1928 if (pyus_in == NULL)
1929 return NULL;
Oren Milman865e4b42017-09-19 15:58:11 +03001930 ratio = get_float_as_integer_ratio(floatobj);
1931 if (ratio == NULL) {
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001932 goto error;
Oren Milman865e4b42017-09-19 15:58:11 +03001933 }
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03001934 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, op));
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001935 Py_DECREF(pyus_in);
1936 pyus_in = NULL;
1937 if (temp == NULL)
1938 goto error;
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03001939 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, !op));
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001940 Py_DECREF(temp);
1941 if (pyus_out == NULL)
1942 goto error;
1943 result = microseconds_to_delta(pyus_out);
1944 Py_DECREF(pyus_out);
1945 error:
1946 Py_XDECREF(pyus_in);
1947 Py_XDECREF(ratio);
1948
1949 return result;
1950}
1951
1952static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001953divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 PyObject *pyus_in;
1956 PyObject *pyus_out;
1957 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 pyus_in = delta_to_microseconds(delta);
1960 if (pyus_in == NULL)
1961 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1964 Py_DECREF(pyus_in);
1965 if (pyus_out == NULL)
1966 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 result = microseconds_to_delta(pyus_out);
1969 Py_DECREF(pyus_out);
1970 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001971}
1972
1973static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001974divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 PyObject *pyus_left;
1977 PyObject *pyus_right;
1978 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 pyus_left = delta_to_microseconds(left);
1981 if (pyus_left == NULL)
1982 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 pyus_right = delta_to_microseconds(right);
1985 if (pyus_right == NULL) {
1986 Py_DECREF(pyus_left);
1987 return NULL;
1988 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1991 Py_DECREF(pyus_left);
1992 Py_DECREF(pyus_right);
1993 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001994}
1995
1996static PyObject *
1997truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 PyObject *pyus_left;
2000 PyObject *pyus_right;
2001 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 pyus_left = delta_to_microseconds(left);
2004 if (pyus_left == NULL)
2005 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 pyus_right = delta_to_microseconds(right);
2008 if (pyus_right == NULL) {
2009 Py_DECREF(pyus_left);
2010 return NULL;
2011 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 result = PyNumber_TrueDivide(pyus_left, pyus_right);
2014 Py_DECREF(pyus_left);
2015 Py_DECREF(pyus_right);
2016 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002017}
2018
2019static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002020truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
2021{
2022 PyObject *result;
2023 PyObject *pyus_in, *pyus_out;
2024 pyus_in = delta_to_microseconds(delta);
2025 if (pyus_in == NULL)
2026 return NULL;
2027 pyus_out = divide_nearest(pyus_in, i);
2028 Py_DECREF(pyus_in);
2029 if (pyus_out == NULL)
2030 return NULL;
2031 result = microseconds_to_delta(pyus_out);
2032 Py_DECREF(pyus_out);
2033
2034 return result;
2035}
2036
2037static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002038delta_add(PyObject *left, PyObject *right)
2039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if (PyDelta_Check(left) && PyDelta_Check(right)) {
2043 /* delta + delta */
2044 /* The C-level additions can't overflow because of the
2045 * invariant bounds.
2046 */
2047 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
2048 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
2049 int microseconds = GET_TD_MICROSECONDS(left) +
2050 GET_TD_MICROSECONDS(right);
2051 result = new_delta(days, seconds, microseconds, 1);
2052 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (result == Py_NotImplemented)
2055 Py_INCREF(result);
2056 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002057}
2058
2059static PyObject *
2060delta_negative(PyDateTime_Delta *self)
2061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 return new_delta(-GET_TD_DAYS(self),
2063 -GET_TD_SECONDS(self),
2064 -GET_TD_MICROSECONDS(self),
2065 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002066}
2067
2068static PyObject *
2069delta_positive(PyDateTime_Delta *self)
2070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 /* Could optimize this (by returning self) if this isn't a
2072 * subclass -- but who uses unary + ? Approximately nobody.
2073 */
2074 return new_delta(GET_TD_DAYS(self),
2075 GET_TD_SECONDS(self),
2076 GET_TD_MICROSECONDS(self),
2077 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002078}
2079
2080static PyObject *
2081delta_abs(PyDateTime_Delta *self)
2082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 assert(GET_TD_MICROSECONDS(self) >= 0);
2086 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (GET_TD_DAYS(self) < 0)
2089 result = delta_negative(self);
2090 else
2091 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002094}
2095
2096static PyObject *
2097delta_subtract(PyObject *left, PyObject *right)
2098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (PyDelta_Check(left) && PyDelta_Check(right)) {
2102 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04002103 /* The C-level additions can't overflow because of the
2104 * invariant bounds.
2105 */
2106 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
2107 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
2108 int microseconds = GET_TD_MICROSECONDS(left) -
2109 GET_TD_MICROSECONDS(right);
2110 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (result == Py_NotImplemented)
2114 Py_INCREF(result);
2115 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002116}
2117
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002118static int
2119delta_cmp(PyObject *self, PyObject *other)
2120{
2121 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
2122 if (diff == 0) {
2123 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
2124 if (diff == 0)
2125 diff = GET_TD_MICROSECONDS(self) -
2126 GET_TD_MICROSECONDS(other);
2127 }
2128 return diff;
2129}
2130
Tim Peters2a799bf2002-12-16 20:18:38 +00002131static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002132delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002135 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 return diff_to_bool(diff, op);
2137 }
2138 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05002139 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002141}
2142
2143static PyObject *delta_getstate(PyDateTime_Delta *self);
2144
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002145static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002146delta_hash(PyDateTime_Delta *self)
2147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (self->hashcode == -1) {
2149 PyObject *temp = delta_getstate(self);
2150 if (temp != NULL) {
2151 self->hashcode = PyObject_Hash(temp);
2152 Py_DECREF(temp);
2153 }
2154 }
2155 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002156}
2157
2158static PyObject *
2159delta_multiply(PyObject *left, PyObject *right)
2160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (PyDelta_Check(left)) {
2164 /* delta * ??? */
2165 if (PyLong_Check(right))
2166 result = multiply_int_timedelta(right,
2167 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002168 else if (PyFloat_Check(right))
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03002169 result = multiply_truedivide_timedelta_float(
2170 (PyDateTime_Delta *) left, right, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 }
2172 else if (PyLong_Check(left))
2173 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002174 (PyDateTime_Delta *) right);
2175 else if (PyFloat_Check(left))
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03002176 result = multiply_truedivide_timedelta_float(
2177 (PyDateTime_Delta *) right, left, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (result == Py_NotImplemented)
2180 Py_INCREF(result);
2181 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002182}
2183
2184static PyObject *
2185delta_divide(PyObject *left, PyObject *right)
2186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (PyDelta_Check(left)) {
2190 /* delta * ??? */
2191 if (PyLong_Check(right))
2192 result = divide_timedelta_int(
2193 (PyDateTime_Delta *)left,
2194 right);
2195 else if (PyDelta_Check(right))
2196 result = divide_timedelta_timedelta(
2197 (PyDateTime_Delta *)left,
2198 (PyDateTime_Delta *)right);
2199 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 if (result == Py_NotImplemented)
2202 Py_INCREF(result);
2203 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002204}
2205
Mark Dickinson7c186e22010-04-20 22:32:49 +00002206static PyObject *
2207delta_truedivide(PyObject *left, PyObject *right)
2208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 if (PyDelta_Check(left)) {
2212 if (PyDelta_Check(right))
2213 result = truedivide_timedelta_timedelta(
2214 (PyDateTime_Delta *)left,
2215 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002216 else if (PyFloat_Check(right))
Serhiy Storchakadb12ef72017-10-04 20:30:09 +03002217 result = multiply_truedivide_timedelta_float(
2218 (PyDateTime_Delta *)left, right, 1);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00002219 else if (PyLong_Check(right))
2220 result = truedivide_timedelta_int(
2221 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 if (result == Py_NotImplemented)
2225 Py_INCREF(result);
2226 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002227}
2228
2229static PyObject *
2230delta_remainder(PyObject *left, PyObject *right)
2231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 PyObject *pyus_left;
2233 PyObject *pyus_right;
2234 PyObject *pyus_remainder;
2235 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002236
Brian Curtindfc80e32011-08-10 20:28:54 -05002237 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2238 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2241 if (pyus_left == NULL)
2242 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2245 if (pyus_right == NULL) {
2246 Py_DECREF(pyus_left);
2247 return NULL;
2248 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
2251 Py_DECREF(pyus_left);
2252 Py_DECREF(pyus_right);
2253 if (pyus_remainder == NULL)
2254 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 remainder = microseconds_to_delta(pyus_remainder);
2257 Py_DECREF(pyus_remainder);
2258 if (remainder == NULL)
2259 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002262}
2263
2264static PyObject *
2265delta_divmod(PyObject *left, PyObject *right)
2266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 PyObject *pyus_left;
2268 PyObject *pyus_right;
2269 PyObject *divmod;
2270 PyObject *delta;
2271 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002272
Brian Curtindfc80e32011-08-10 20:28:54 -05002273 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2274 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2277 if (pyus_left == NULL)
2278 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2281 if (pyus_right == NULL) {
2282 Py_DECREF(pyus_left);
2283 return NULL;
2284 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 divmod = PyNumber_Divmod(pyus_left, pyus_right);
2287 Py_DECREF(pyus_left);
2288 Py_DECREF(pyus_right);
2289 if (divmod == NULL)
2290 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 assert(PyTuple_Size(divmod) == 2);
2293 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
2294 if (delta == NULL) {
2295 Py_DECREF(divmod);
2296 return NULL;
2297 }
2298 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
2299 Py_DECREF(delta);
2300 Py_DECREF(divmod);
2301 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002302}
2303
Tim Peters2a799bf2002-12-16 20:18:38 +00002304/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2305 * timedelta constructor. sofar is the # of microseconds accounted for
2306 * so far, and there are factor microseconds per current unit, the number
2307 * of which is given by num. num * factor is added to sofar in a
2308 * numerically careful way, and that's the result. Any fractional
2309 * microseconds left over (this can happen if num is a float type) are
2310 * added into *leftover.
2311 * Note that there are many ways this can give an error (NULL) return.
2312 */
2313static PyObject *
2314accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2315 double *leftover)
2316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyObject *prod;
2318 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 if (PyLong_Check(num)) {
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03002323 prod = PyNumber_Multiply(factor, num);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (prod == NULL)
2325 return NULL;
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03002326 assert(PyLong_CheckExact(prod));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 sum = PyNumber_Add(sofar, prod);
2328 Py_DECREF(prod);
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03002329 assert(sum == NULL || PyLong_CheckExact(sum));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return sum;
2331 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 if (PyFloat_Check(num)) {
2334 double dnum;
2335 double fracpart;
2336 double intpart;
2337 PyObject *x;
2338 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* The Plan: decompose num into an integer part and a
2341 * fractional part, num = intpart + fracpart.
2342 * Then num * factor ==
2343 * intpart * factor + fracpart * factor
2344 * and the LHS can be computed exactly in long arithmetic.
2345 * The RHS is again broken into an int part and frac part.
2346 * and the frac part is added into *leftover.
2347 */
2348 dnum = PyFloat_AsDouble(num);
2349 if (dnum == -1.0 && PyErr_Occurred())
2350 return NULL;
2351 fracpart = modf(dnum, &intpart);
2352 x = PyLong_FromDouble(intpart);
2353 if (x == NULL)
2354 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 prod = PyNumber_Multiply(x, factor);
2357 Py_DECREF(x);
2358 if (prod == NULL)
2359 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 sum = PyNumber_Add(sofar, prod);
2362 Py_DECREF(prod);
2363 if (sum == NULL)
2364 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 if (fracpart == 0.0)
2367 return sum;
2368 /* So far we've lost no information. Dealing with the
2369 * fractional part requires float arithmetic, and may
2370 * lose a little info.
2371 */
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03002372 assert(PyLong_CheckExact(factor));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 dnum *= fracpart;
2376 fracpart = modf(dnum, &intpart);
2377 x = PyLong_FromDouble(intpart);
2378 if (x == NULL) {
2379 Py_DECREF(sum);
2380 return NULL;
2381 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 y = PyNumber_Add(sum, x);
2384 Py_DECREF(sum);
2385 Py_DECREF(x);
2386 *leftover += fracpart;
Serhiy Storchaka4ffd4652017-10-23 17:12:28 +03002387 assert(y == NULL || PyLong_CheckExact(y));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 return y;
2389 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 PyErr_Format(PyExc_TypeError,
2392 "unsupported type for timedelta %s component: %s",
2393 tag, Py_TYPE(num)->tp_name);
2394 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002395}
2396
2397static PyObject *
2398delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* Argument objects. */
2403 PyObject *day = NULL;
2404 PyObject *second = NULL;
2405 PyObject *us = NULL;
2406 PyObject *ms = NULL;
2407 PyObject *minute = NULL;
2408 PyObject *hour = NULL;
2409 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 PyObject *x = NULL; /* running sum of microseconds */
2412 PyObject *y = NULL; /* temp sum of microseconds */
2413 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 static char *keywords[] = {
2416 "days", "seconds", "microseconds", "milliseconds",
2417 "minutes", "hours", "weeks", NULL
2418 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2421 keywords,
2422 &day, &second, &us,
2423 &ms, &minute, &hour, &week) == 0)
2424 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 x = PyLong_FromLong(0);
2427 if (x == NULL)
2428 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430#define CLEANUP \
2431 Py_DECREF(x); \
2432 x = y; \
2433 if (x == NULL) \
2434 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 if (us) {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002437 y = accum("microseconds", x, us, _PyLong_One, &leftover_us);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 CLEANUP;
2439 }
2440 if (ms) {
2441 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2442 CLEANUP;
2443 }
2444 if (second) {
2445 y = accum("seconds", x, second, us_per_second, &leftover_us);
2446 CLEANUP;
2447 }
2448 if (minute) {
2449 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2450 CLEANUP;
2451 }
2452 if (hour) {
2453 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2454 CLEANUP;
2455 }
2456 if (day) {
2457 y = accum("days", x, day, us_per_day, &leftover_us);
2458 CLEANUP;
2459 }
2460 if (week) {
2461 y = accum("weeks", x, week, us_per_week, &leftover_us);
2462 CLEANUP;
2463 }
2464 if (leftover_us) {
2465 /* Round to nearest whole # of us, and add into x. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002466 double whole_us = round(leftover_us);
Victor Stinner69cc4872015-09-08 23:58:54 +02002467 int x_is_odd;
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002468 PyObject *temp;
2469
Victor Stinner69cc4872015-09-08 23:58:54 +02002470 whole_us = round(leftover_us);
2471 if (fabs(whole_us - leftover_us) == 0.5) {
2472 /* We're exactly halfway between two integers. In order
2473 * to do round-half-to-even, we must determine whether x
2474 * is odd. Note that x is odd when it's last bit is 1. The
2475 * code below uses bitwise and operation to check the last
2476 * bit. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002477 temp = PyNumber_And(x, _PyLong_One); /* temp <- x & 1 */
Victor Stinner69cc4872015-09-08 23:58:54 +02002478 if (temp == NULL) {
2479 Py_DECREF(x);
2480 goto Done;
2481 }
2482 x_is_odd = PyObject_IsTrue(temp);
2483 Py_DECREF(temp);
2484 if (x_is_odd == -1) {
2485 Py_DECREF(x);
2486 goto Done;
2487 }
2488 whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2489 }
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002490
Victor Stinner36a5a062013-08-28 01:53:39 +02002491 temp = PyLong_FromLong((long)whole_us);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 if (temp == NULL) {
2494 Py_DECREF(x);
2495 goto Done;
2496 }
2497 y = PyNumber_Add(x, temp);
2498 Py_DECREF(temp);
2499 CLEANUP;
2500 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 self = microseconds_to_delta_ex(x, type);
2503 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002504Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002506
2507#undef CLEANUP
2508}
2509
2510static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002511delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 return (GET_TD_DAYS(self) != 0
2514 || GET_TD_SECONDS(self) != 0
2515 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002516}
2517
2518static PyObject *
2519delta_repr(PyDateTime_Delta *self)
2520{
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +02002521 PyObject *args = PyUnicode_FromString("");
Tim Peters2a799bf2002-12-16 20:18:38 +00002522
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +02002523 if (args == NULL) {
2524 return NULL;
2525 }
2526
2527 const char *sep = "";
2528
2529 if (GET_TD_DAYS(self) != 0) {
2530 Py_SETREF(args, PyUnicode_FromFormat("days=%d", GET_TD_DAYS(self)));
2531 if (args == NULL) {
2532 return NULL;
2533 }
2534 sep = ", ";
2535 }
2536
2537 if (GET_TD_SECONDS(self) != 0) {
2538 Py_SETREF(args, PyUnicode_FromFormat("%U%sseconds=%d", args, sep,
2539 GET_TD_SECONDS(self)));
2540 if (args == NULL) {
2541 return NULL;
2542 }
2543 sep = ", ";
2544 }
2545
2546 if (GET_TD_MICROSECONDS(self) != 0) {
2547 Py_SETREF(args, PyUnicode_FromFormat("%U%smicroseconds=%d", args, sep,
2548 GET_TD_MICROSECONDS(self)));
2549 if (args == NULL) {
2550 return NULL;
2551 }
2552 }
2553
2554 if (PyUnicode_GET_LENGTH(args) == 0) {
2555 Py_SETREF(args, PyUnicode_FromString("0"));
2556 if (args == NULL) {
2557 return NULL;
2558 }
2559 }
2560
2561 PyObject *repr = PyUnicode_FromFormat("%s(%S)", Py_TYPE(self)->tp_name,
2562 args);
2563 Py_DECREF(args);
2564 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00002565}
2566
2567static PyObject *
2568delta_str(PyDateTime_Delta *self)
2569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 int us = GET_TD_MICROSECONDS(self);
2571 int seconds = GET_TD_SECONDS(self);
2572 int minutes = divmod(seconds, 60, &seconds);
2573 int hours = divmod(minutes, 60, &minutes);
2574 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 if (days) {
2577 if (us)
2578 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2579 days, (days == 1 || days == -1) ? "" : "s",
2580 hours, minutes, seconds, us);
2581 else
2582 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2583 days, (days == 1 || days == -1) ? "" : "s",
2584 hours, minutes, seconds);
2585 } else {
2586 if (us)
2587 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2588 hours, minutes, seconds, us);
2589 else
2590 return PyUnicode_FromFormat("%d:%02d:%02d",
2591 hours, minutes, seconds);
2592 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002593
Tim Peters2a799bf2002-12-16 20:18:38 +00002594}
2595
Tim Peters371935f2003-02-01 01:52:50 +00002596/* Pickle support, a simple use of __reduce__. */
2597
Tim Petersb57f8f02003-02-01 02:54:15 +00002598/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002599static PyObject *
2600delta_getstate(PyDateTime_Delta *self)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 return Py_BuildValue("iii", GET_TD_DAYS(self),
2603 GET_TD_SECONDS(self),
2604 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002605}
2606
Tim Peters2a799bf2002-12-16 20:18:38 +00002607static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002608delta_total_seconds(PyObject *self)
2609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 PyObject *total_seconds;
2611 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2614 if (total_microseconds == NULL)
2615 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002616
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002617 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002621}
2622
2623static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002624delta_reduce(PyDateTime_Delta* self)
2625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002627}
2628
2629#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2630
2631static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 {"days", T_INT, OFFSET(days), READONLY,
2634 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 {"seconds", T_INT, OFFSET(seconds), READONLY,
2637 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2640 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2641 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002642};
2643
2644static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2646 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2649 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002652};
2653
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002654static const char delta_doc[] =
Miss Islington (bot)ef7f29f2018-10-19 16:02:13 -07002655PyDoc_STR("Difference between two datetime values.\n\n"
2656 "timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, "
2657 "minutes=0, hours=0, weeks=0)\n\n"
2658 "All arguments are optional and default to 0.\n"
2659 "Arguments may be integers or floats, and may be positive or negative.");
Tim Peters2a799bf2002-12-16 20:18:38 +00002660
2661static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 delta_add, /* nb_add */
2663 delta_subtract, /* nb_subtract */
2664 delta_multiply, /* nb_multiply */
2665 delta_remainder, /* nb_remainder */
2666 delta_divmod, /* nb_divmod */
2667 0, /* nb_power */
2668 (unaryfunc)delta_negative, /* nb_negative */
2669 (unaryfunc)delta_positive, /* nb_positive */
2670 (unaryfunc)delta_abs, /* nb_absolute */
2671 (inquiry)delta_bool, /* nb_bool */
2672 0, /*nb_invert*/
2673 0, /*nb_lshift*/
2674 0, /*nb_rshift*/
2675 0, /*nb_and*/
2676 0, /*nb_xor*/
2677 0, /*nb_or*/
2678 0, /*nb_int*/
2679 0, /*nb_reserved*/
2680 0, /*nb_float*/
2681 0, /*nb_inplace_add*/
2682 0, /*nb_inplace_subtract*/
2683 0, /*nb_inplace_multiply*/
2684 0, /*nb_inplace_remainder*/
2685 0, /*nb_inplace_power*/
2686 0, /*nb_inplace_lshift*/
2687 0, /*nb_inplace_rshift*/
2688 0, /*nb_inplace_and*/
2689 0, /*nb_inplace_xor*/
2690 0, /*nb_inplace_or*/
2691 delta_divide, /* nb_floor_divide */
2692 delta_truedivide, /* nb_true_divide */
2693 0, /* nb_inplace_floor_divide */
2694 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002695};
2696
2697static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 PyVarObject_HEAD_INIT(NULL, 0)
2699 "datetime.timedelta", /* tp_name */
2700 sizeof(PyDateTime_Delta), /* tp_basicsize */
2701 0, /* tp_itemsize */
2702 0, /* tp_dealloc */
2703 0, /* tp_print */
2704 0, /* tp_getattr */
2705 0, /* tp_setattr */
2706 0, /* tp_reserved */
2707 (reprfunc)delta_repr, /* tp_repr */
2708 &delta_as_number, /* tp_as_number */
2709 0, /* tp_as_sequence */
2710 0, /* tp_as_mapping */
2711 (hashfunc)delta_hash, /* tp_hash */
2712 0, /* tp_call */
2713 (reprfunc)delta_str, /* tp_str */
2714 PyObject_GenericGetAttr, /* tp_getattro */
2715 0, /* tp_setattro */
2716 0, /* tp_as_buffer */
2717 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2718 delta_doc, /* tp_doc */
2719 0, /* tp_traverse */
2720 0, /* tp_clear */
2721 delta_richcompare, /* tp_richcompare */
2722 0, /* tp_weaklistoffset */
2723 0, /* tp_iter */
2724 0, /* tp_iternext */
2725 delta_methods, /* tp_methods */
2726 delta_members, /* tp_members */
2727 0, /* tp_getset */
2728 0, /* tp_base */
2729 0, /* tp_dict */
2730 0, /* tp_descr_get */
2731 0, /* tp_descr_set */
2732 0, /* tp_dictoffset */
2733 0, /* tp_init */
2734 0, /* tp_alloc */
2735 delta_new, /* tp_new */
2736 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002737};
2738
2739/*
2740 * PyDateTime_Date implementation.
2741 */
2742
2743/* Accessor properties. */
2744
2745static PyObject *
2746date_year(PyDateTime_Date *self, void *unused)
2747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002749}
2750
2751static PyObject *
2752date_month(PyDateTime_Date *self, void *unused)
2753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002755}
2756
2757static PyObject *
2758date_day(PyDateTime_Date *self, void *unused)
2759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002761}
2762
2763static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 {"year", (getter)date_year},
2765 {"month", (getter)date_month},
2766 {"day", (getter)date_day},
2767 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002768};
2769
2770/* Constructors. */
2771
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002772static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002773
Tim Peters2a799bf2002-12-16 20:18:38 +00002774static PyObject *
2775date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 PyObject *self = NULL;
2778 PyObject *state;
2779 int year;
2780 int month;
2781 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 /* Check for invocation from pickle with __getstate__ state */
2784 if (PyTuple_GET_SIZE(args) == 1 &&
2785 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2786 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2787 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2788 {
2789 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2792 if (me != NULL) {
2793 char *pdata = PyBytes_AS_STRING(state);
2794 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2795 me->hashcode = -1;
2796 }
2797 return (PyObject *)me;
2798 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2801 &year, &month, &day)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 self = new_date_ex(year, month, day, type);
2803 }
2804 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002805}
2806
2807/* Return new date from localtime(t). */
2808static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002809date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002810{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002811 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002813
Victor Stinnere4a994d2015-03-30 01:10:14 +02002814 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002816
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04002817 if (_PyTime_localtime(t, &tm) != 0)
Victor Stinner21f58932012-03-14 00:15:40 +01002818 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01002819
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05002820 return new_date_subclass_ex(tm.tm_year + 1900,
2821 tm.tm_mon + 1,
2822 tm.tm_mday,
2823 cls);
Tim Peters2a799bf2002-12-16 20:18:38 +00002824}
2825
2826/* Return new date from current time.
2827 * We say this is equivalent to fromtimestamp(time.time()), and the
2828 * only way to be sure of that is to *call* time.time(). That's not
2829 * generally the same as calling C's time.
2830 */
2831static PyObject *
2832date_today(PyObject *cls, PyObject *dummy)
2833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 PyObject *time;
2835 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002836 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 time = time_time();
2839 if (time == NULL)
2840 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 /* Note well: today() is a class method, so this may not call
2843 * date.fromtimestamp. For example, it may call
2844 * datetime.fromtimestamp. That's why we need all the accuracy
2845 * time.time() delivers; if someone were gonzo about optimization,
2846 * date.today() could get away with plain C time().
2847 */
Victor Stinner20401de2016-12-09 15:24:31 +01002848 result = _PyObject_CallMethodIdObjArgs(cls, &PyId_fromtimestamp,
2849 time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 Py_DECREF(time);
2851 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002852}
2853
2854/* Return new date from given timestamp (Python timestamp -- a double). */
2855static PyObject *
2856date_fromtimestamp(PyObject *cls, PyObject *args)
2857{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002858 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002860
Victor Stinner5d272cc2012-03-13 13:35:55 +01002861 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2862 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002864}
2865
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002866
Tim Peters2a799bf2002-12-16 20:18:38 +00002867/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2868 * the ordinal is out of range.
2869 */
2870static PyObject *
2871date_fromordinal(PyObject *cls, PyObject *args)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 PyObject *result = NULL;
2874 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2877 int year;
2878 int month;
2879 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 if (ordinal < 1)
2882 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2883 ">= 1");
2884 else {
2885 ord_to_ymd(ordinal, &year, &month, &day);
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05002886 result = new_date_subclass_ex(year, month, day, cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 }
2888 }
2889 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002890}
2891
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002892/* Return the new date from a string as generated by date.isoformat() */
2893static PyObject *
Miss Islington (bot)18450be2018-10-22 15:35:15 -07002894date_fromisoformat(PyObject *cls, PyObject *dtstr)
2895{
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002896 assert(dtstr != NULL);
2897
2898 if (!PyUnicode_Check(dtstr)) {
Miss Islington (bot)18450be2018-10-22 15:35:15 -07002899 PyErr_SetString(PyExc_TypeError,
2900 "fromisoformat: argument must be str");
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002901 return NULL;
2902 }
2903
2904 Py_ssize_t len;
2905
Miss Islington (bot)18450be2018-10-22 15:35:15 -07002906 const char *dt_ptr = PyUnicode_AsUTF8AndSize(dtstr, &len);
Miss Islington (bot)89b16542018-08-23 11:54:33 -04002907 if (dt_ptr == NULL) {
2908 goto invalid_string_error;
2909 }
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002910
2911 int year = 0, month = 0, day = 0;
2912
2913 int rv;
2914 if (len == 10) {
2915 rv = parse_isoformat_date(dt_ptr, &year, &month, &day);
Miss Islington (bot)18450be2018-10-22 15:35:15 -07002916 }
2917 else {
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002918 rv = -1;
2919 }
2920
2921 if (rv < 0) {
Miss Islington (bot)89b16542018-08-23 11:54:33 -04002922 goto invalid_string_error;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002923 }
2924
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05002925 return new_date_subclass_ex(year, month, day, cls);
Miss Islington (bot)89b16542018-08-23 11:54:33 -04002926
2927invalid_string_error:
Miss Islington (bot)18450be2018-10-22 15:35:15 -07002928 PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", dtstr);
Miss Islington (bot)89b16542018-08-23 11:54:33 -04002929 return NULL;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05002930}
2931
Tim Peters2a799bf2002-12-16 20:18:38 +00002932/*
2933 * Date arithmetic.
2934 */
2935
2936/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2937 * instead.
2938 */
2939static PyObject *
2940add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 PyObject *result = NULL;
2943 int year = GET_YEAR(date);
2944 int month = GET_MONTH(date);
2945 int deltadays = GET_TD_DAYS(delta);
2946 /* C-level overflow is impossible because |deltadays| < 1e9. */
2947 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 if (normalize_date(&year, &month, &day) >= 0)
2950 result = new_date(year, month, day);
2951 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002952}
2953
2954static PyObject *
2955date_add(PyObject *left, PyObject *right)
2956{
Brian Curtindfc80e32011-08-10 20:28:54 -05002957 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2958 Py_RETURN_NOTIMPLEMENTED;
2959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 if (PyDate_Check(left)) {
2961 /* date + ??? */
2962 if (PyDelta_Check(right))
2963 /* date + delta */
2964 return add_date_timedelta((PyDateTime_Date *) left,
2965 (PyDateTime_Delta *) right,
2966 0);
2967 }
2968 else {
2969 /* ??? + date
2970 * 'right' must be one of us, or we wouldn't have been called
2971 */
2972 if (PyDelta_Check(left))
2973 /* delta + date */
2974 return add_date_timedelta((PyDateTime_Date *) right,
2975 (PyDateTime_Delta *) left,
2976 0);
2977 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002978 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002979}
2980
2981static PyObject *
2982date_subtract(PyObject *left, PyObject *right)
2983{
Brian Curtindfc80e32011-08-10 20:28:54 -05002984 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2985 Py_RETURN_NOTIMPLEMENTED;
2986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 if (PyDate_Check(left)) {
2988 if (PyDate_Check(right)) {
2989 /* date - date */
2990 int left_ord = ymd_to_ord(GET_YEAR(left),
2991 GET_MONTH(left),
2992 GET_DAY(left));
2993 int right_ord = ymd_to_ord(GET_YEAR(right),
2994 GET_MONTH(right),
2995 GET_DAY(right));
2996 return new_delta(left_ord - right_ord, 0, 0, 0);
2997 }
2998 if (PyDelta_Check(right)) {
2999 /* date - delta */
3000 return add_date_timedelta((PyDateTime_Date *) left,
3001 (PyDateTime_Delta *) right,
3002 1);
3003 }
3004 }
Brian Curtindfc80e32011-08-10 20:28:54 -05003005 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00003006}
3007
3008
3009/* Various ways to turn a date into a string. */
3010
3011static PyObject *
3012date_repr(PyDateTime_Date *self)
3013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 return PyUnicode_FromFormat("%s(%d, %d, %d)",
3015 Py_TYPE(self)->tp_name,
3016 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003017}
3018
3019static PyObject *
3020date_isoformat(PyDateTime_Date *self)
3021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 return PyUnicode_FromFormat("%04d-%02d-%02d",
3023 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003024}
3025
Tim Peterse2df5ff2003-05-02 18:39:55 +00003026/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003027static PyObject *
3028date_str(PyDateTime_Date *self)
3029{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003030 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00003031}
3032
3033
3034static PyObject *
3035date_ctime(PyDateTime_Date *self)
3036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00003038}
3039
3040static PyObject *
3041date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
3042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 /* This method can be inherited, and needs to call the
3044 * timetuple() method appropriate to self's class.
3045 */
3046 PyObject *result;
3047 PyObject *tuple;
3048 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003049 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3053 &format))
3054 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003055
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003056 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 if (tuple == NULL)
3058 return NULL;
3059 result = wrap_strftime((PyObject *)self, format, tuple,
3060 (PyObject *)self);
3061 Py_DECREF(tuple);
3062 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003063}
3064
Eric Smith1ba31142007-09-11 18:06:02 +00003065static PyObject *
3066date_format(PyDateTime_Date *self, PyObject *args)
3067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00003069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 if (!PyArg_ParseTuple(args, "U:__format__", &format))
3071 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00003072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01003074 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00003076
Victor Stinner20401de2016-12-09 15:24:31 +01003077 return _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_strftime,
3078 format, NULL);
Eric Smith1ba31142007-09-11 18:06:02 +00003079}
3080
Tim Peters2a799bf2002-12-16 20:18:38 +00003081/* ISO methods. */
3082
3083static PyObject *
3084date_isoweekday(PyDateTime_Date *self)
3085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003089}
3090
3091static PyObject *
3092date_isocalendar(PyDateTime_Date *self)
3093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 int year = GET_YEAR(self);
3095 int week1_monday = iso_week1_monday(year);
3096 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
3097 int week;
3098 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 week = divmod(today - week1_monday, 7, &day);
3101 if (week < 0) {
3102 --year;
3103 week1_monday = iso_week1_monday(year);
3104 week = divmod(today - week1_monday, 7, &day);
3105 }
3106 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
3107 ++year;
3108 week = 0;
3109 }
3110 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003111}
3112
3113/* Miscellaneous methods. */
3114
Tim Peters2a799bf2002-12-16 20:18:38 +00003115static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003116date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00003117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 if (PyDate_Check(other)) {
3119 int diff = memcmp(((PyDateTime_Date *)self)->data,
3120 ((PyDateTime_Date *)other)->data,
3121 _PyDateTime_DATE_DATASIZE);
3122 return diff_to_bool(diff, op);
3123 }
Brian Curtindfc80e32011-08-10 20:28:54 -05003124 else
3125 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00003126}
3127
3128static PyObject *
3129date_timetuple(PyDateTime_Date *self)
3130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 return build_struct_time(GET_YEAR(self),
3132 GET_MONTH(self),
3133 GET_DAY(self),
3134 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003135}
3136
Tim Peters12bf3392002-12-24 05:41:27 +00003137static PyObject *
3138date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
3139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 PyObject *clone;
3141 PyObject *tuple;
3142 int year = GET_YEAR(self);
3143 int month = GET_MONTH(self);
3144 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
3147 &year, &month, &day))
3148 return NULL;
3149 tuple = Py_BuildValue("iii", year, month, day);
3150 if (tuple == NULL)
3151 return NULL;
3152 clone = date_new(Py_TYPE(self), tuple, NULL);
3153 Py_DECREF(tuple);
3154 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003155}
3156
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003157static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003158generic_hash(unsigned char *data, int len)
3159{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08003160 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003161}
3162
3163
3164static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003165
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003166static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00003167date_hash(PyDateTime_Date *self)
3168{
Benjamin Petersondec2df32016-09-09 17:46:24 -07003169 if (self->hashcode == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 self->hashcode = generic_hash(
3171 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Benjamin Petersondec2df32016-09-09 17:46:24 -07003172 }
Guido van Rossum254348e2007-11-21 19:29:53 +00003173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00003175}
3176
3177static PyObject *
3178date_toordinal(PyDateTime_Date *self)
3179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
3181 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00003182}
3183
3184static PyObject *
3185date_weekday(PyDateTime_Date *self)
3186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00003190}
3191
Tim Peters371935f2003-02-01 01:52:50 +00003192/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003193
Tim Petersb57f8f02003-02-01 02:54:15 +00003194/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00003195static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003196date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 PyObject* field;
3199 field = PyBytes_FromStringAndSize((char*)self->data,
3200 _PyDateTime_DATE_DATASIZE);
3201 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00003202}
3203
3204static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003205date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003208}
3209
3210static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00003213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
3215 METH_CLASS,
3216 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
3217 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
3220 METH_CLASS,
3221 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
3222 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003223
Paul Ganssle09dc2f52017-12-21 00:33:49 -05003224 {"fromisoformat", (PyCFunction)date_fromisoformat, METH_O |
3225 METH_CLASS,
3226 PyDoc_STR("str -> Construct a date from the output of date.isoformat()")},
3227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
3229 PyDoc_STR("Current date or datetime: same as "
3230 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00003233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
3235 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
3238 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3241 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
3244 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
3247 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
3248 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
3251 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
3254 PyDoc_STR("Return the day of the week represented by the date.\n"
3255 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
3258 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
3259 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
3262 PyDoc_STR("Return the day of the week represented by the date.\n"
3263 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
3266 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
3269 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003272};
3273
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003274static const char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003275PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00003276
3277static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 date_add, /* nb_add */
3279 date_subtract, /* nb_subtract */
3280 0, /* nb_multiply */
3281 0, /* nb_remainder */
3282 0, /* nb_divmod */
3283 0, /* nb_power */
3284 0, /* nb_negative */
3285 0, /* nb_positive */
3286 0, /* nb_absolute */
3287 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003288};
3289
3290static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 PyVarObject_HEAD_INIT(NULL, 0)
3292 "datetime.date", /* tp_name */
3293 sizeof(PyDateTime_Date), /* tp_basicsize */
3294 0, /* tp_itemsize */
3295 0, /* tp_dealloc */
3296 0, /* tp_print */
3297 0, /* tp_getattr */
3298 0, /* tp_setattr */
3299 0, /* tp_reserved */
3300 (reprfunc)date_repr, /* tp_repr */
3301 &date_as_number, /* tp_as_number */
3302 0, /* tp_as_sequence */
3303 0, /* tp_as_mapping */
3304 (hashfunc)date_hash, /* tp_hash */
3305 0, /* tp_call */
3306 (reprfunc)date_str, /* tp_str */
3307 PyObject_GenericGetAttr, /* tp_getattro */
3308 0, /* tp_setattro */
3309 0, /* tp_as_buffer */
3310 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3311 date_doc, /* tp_doc */
3312 0, /* tp_traverse */
3313 0, /* tp_clear */
3314 date_richcompare, /* tp_richcompare */
3315 0, /* tp_weaklistoffset */
3316 0, /* tp_iter */
3317 0, /* tp_iternext */
3318 date_methods, /* tp_methods */
3319 0, /* tp_members */
3320 date_getset, /* tp_getset */
3321 0, /* tp_base */
3322 0, /* tp_dict */
3323 0, /* tp_descr_get */
3324 0, /* tp_descr_set */
3325 0, /* tp_dictoffset */
3326 0, /* tp_init */
3327 0, /* tp_alloc */
3328 date_new, /* tp_new */
3329 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003330};
3331
3332/*
Tim Peters2a799bf2002-12-16 20:18:38 +00003333 * PyDateTime_TZInfo implementation.
3334 */
3335
3336/* This is a pure abstract base class, so doesn't do anything beyond
3337 * raising NotImplemented exceptions. Real tzinfo classes need
3338 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00003339 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00003340 * be subclasses of this tzinfo class, which is easy and quick to check).
3341 *
3342 * Note: For reasons having to do with pickling of subclasses, we have
3343 * to allow tzinfo objects to be instantiated. This wasn't an issue
3344 * in the Python implementation (__init__() could raise NotImplementedError
3345 * there without ill effect), but doing so in the C implementation hit a
3346 * brick wall.
3347 */
3348
3349static PyObject *
3350tzinfo_nogo(const char* methodname)
3351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 PyErr_Format(PyExc_NotImplementedError,
3353 "a tzinfo subclass must implement %s()",
3354 methodname);
3355 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003356}
3357
3358/* Methods. A subclass must implement these. */
3359
Tim Peters52dcce22003-01-23 16:36:11 +00003360static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003361tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00003364}
3365
Tim Peters52dcce22003-01-23 16:36:11 +00003366static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003367tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00003370}
3371
Tim Peters52dcce22003-01-23 16:36:11 +00003372static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003373tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003376}
3377
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003378
3379static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
3380 PyDateTime_Delta *delta,
3381 int factor);
3382static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
3383static PyObject *datetime_dst(PyObject *self, PyObject *);
3384
Tim Peters52dcce22003-01-23 16:36:11 +00003385static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003386tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003387{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003388 PyObject *result = NULL;
3389 PyObject *off = NULL, *dst = NULL;
3390 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003391
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003392 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 PyErr_SetString(PyExc_TypeError,
3394 "fromutc: argument must be a datetime");
3395 return NULL;
3396 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003397 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3399 "is not self");
3400 return NULL;
3401 }
Tim Peters52dcce22003-01-23 16:36:11 +00003402
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003403 off = datetime_utcoffset(dt, NULL);
3404 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003406 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3408 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003409 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 }
Tim Peters52dcce22003-01-23 16:36:11 +00003411
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003412 dst = datetime_dst(dt, NULL);
3413 if (dst == NULL)
3414 goto Fail;
3415 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3417 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003418 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 }
Tim Peters52dcce22003-01-23 16:36:11 +00003420
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003421 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3422 if (delta == NULL)
3423 goto Fail;
3424 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003427
3428 Py_DECREF(dst);
3429 dst = call_dst(GET_DT_TZINFO(dt), result);
3430 if (dst == NULL)
3431 goto Fail;
3432 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 goto Inconsistent;
Alexander Belopolskyc79447b2015-09-27 21:41:55 -04003434 if (delta_bool((PyDateTime_Delta *)dst) != 0) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03003435 Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
Serhiy Storchaka576f1322016-01-05 21:27:54 +02003436 (PyDateTime_Delta *)dst, 1));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003437 if (result == NULL)
3438 goto Fail;
3439 }
3440 Py_DECREF(delta);
3441 Py_DECREF(dst);
3442 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003444
3445Inconsistent:
Miss Islington (bot)7beb8c52018-11-05 06:52:58 -08003446 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave "
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003447 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003448
Miss Islington (bot)e86db342018-02-03 17:41:43 -08003449 /* fall through to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003450Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003451 Py_XDECREF(off);
3452 Py_XDECREF(dst);
3453 Py_XDECREF(delta);
3454 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003456}
3457
Tim Peters2a799bf2002-12-16 20:18:38 +00003458/*
3459 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003460 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003461 */
3462
Guido van Rossum177e41a2003-01-30 22:06:23 +00003463static PyObject *
3464tzinfo_reduce(PyObject *self)
3465{
Victor Stinnerd1584d32016-08-23 00:11:04 +02003466 PyObject *args, *state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003468 _Py_IDENTIFIER(__getinitargs__);
3469 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003470
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003471 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 if (getinitargs != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003473 args = _PyObject_CallNoArg(getinitargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 Py_DECREF(getinitargs);
3475 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 return NULL;
3477 }
3478 }
3479 else {
3480 PyErr_Clear();
Victor Stinnerd1584d32016-08-23 00:11:04 +02003481
3482 args = PyTuple_New(0);
3483 if (args == NULL) {
3484 return NULL;
3485 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003487
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003488 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 if (getstate != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003490 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 Py_DECREF(getstate);
3492 if (state == NULL) {
3493 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 return NULL;
3495 }
3496 }
3497 else {
3498 PyObject **dictptr;
3499 PyErr_Clear();
3500 state = Py_None;
3501 dictptr = _PyObject_GetDictPtr(self);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02003502 if (dictptr && *dictptr && PyDict_GET_SIZE(*dictptr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 state = *dictptr;
Victor Stinnerd1584d32016-08-23 00:11:04 +02003504 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 Py_INCREF(state);
3506 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 if (state == Py_None) {
3509 Py_DECREF(state);
3510 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3511 }
3512 else
3513 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003514}
Tim Peters2a799bf2002-12-16 20:18:38 +00003515
3516static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3519 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003522 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3523 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 {"dst", (PyCFunction)tzinfo_dst, METH_O,
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003526 PyDoc_STR("datetime -> DST offset as timedelta positive east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003529 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3532 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003535};
3536
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003537static const char tzinfo_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00003538PyDoc_STR("Abstract base class for time zone info objects.");
3539
Neal Norwitz227b5332006-03-22 09:28:35 +00003540static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 PyVarObject_HEAD_INIT(NULL, 0)
3542 "datetime.tzinfo", /* tp_name */
3543 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3544 0, /* tp_itemsize */
3545 0, /* tp_dealloc */
3546 0, /* tp_print */
3547 0, /* tp_getattr */
3548 0, /* tp_setattr */
3549 0, /* tp_reserved */
3550 0, /* tp_repr */
3551 0, /* tp_as_number */
3552 0, /* tp_as_sequence */
3553 0, /* tp_as_mapping */
3554 0, /* tp_hash */
3555 0, /* tp_call */
3556 0, /* tp_str */
3557 PyObject_GenericGetAttr, /* tp_getattro */
3558 0, /* tp_setattro */
3559 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003560 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 tzinfo_doc, /* tp_doc */
3562 0, /* tp_traverse */
3563 0, /* tp_clear */
3564 0, /* tp_richcompare */
3565 0, /* tp_weaklistoffset */
3566 0, /* tp_iter */
3567 0, /* tp_iternext */
3568 tzinfo_methods, /* tp_methods */
3569 0, /* tp_members */
3570 0, /* tp_getset */
3571 0, /* tp_base */
3572 0, /* tp_dict */
3573 0, /* tp_descr_get */
3574 0, /* tp_descr_set */
3575 0, /* tp_dictoffset */
3576 0, /* tp_init */
3577 0, /* tp_alloc */
3578 PyType_GenericNew, /* tp_new */
3579 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003580};
3581
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003582static char *timezone_kws[] = {"offset", "name", NULL};
3583
3584static PyObject *
3585timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3586{
3587 PyObject *offset;
3588 PyObject *name = NULL;
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03003589 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|U:timezone", timezone_kws,
3590 &PyDateTime_DeltaType, &offset, &name))
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003591 return new_timezone(offset, name);
3592
3593 return NULL;
3594}
3595
3596static void
3597timezone_dealloc(PyDateTime_TimeZone *self)
3598{
3599 Py_CLEAR(self->offset);
3600 Py_CLEAR(self->name);
3601 Py_TYPE(self)->tp_free((PyObject *)self);
3602}
3603
3604static PyObject *
3605timezone_richcompare(PyDateTime_TimeZone *self,
3606 PyDateTime_TimeZone *other, int op)
3607{
Brian Curtindfc80e32011-08-10 20:28:54 -05003608 if (op != Py_EQ && op != Py_NE)
3609 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003610 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003611 if (op == Py_EQ)
3612 Py_RETURN_FALSE;
3613 else
3614 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003615 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003616 return delta_richcompare(self->offset, other->offset, op);
3617}
3618
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003619static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003620timezone_hash(PyDateTime_TimeZone *self)
3621{
3622 return delta_hash((PyDateTime_Delta *)self->offset);
3623}
3624
3625/* Check argument type passed to tzname, utcoffset, or dst methods.
3626 Returns 0 for good argument. Returns -1 and sets exception info
3627 otherwise.
3628 */
3629static int
3630_timezone_check_argument(PyObject *dt, const char *meth)
3631{
3632 if (dt == Py_None || PyDateTime_Check(dt))
3633 return 0;
3634 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3635 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3636 return -1;
3637}
3638
3639static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003640timezone_repr(PyDateTime_TimeZone *self)
3641{
3642 /* Note that although timezone is not subclassable, it is convenient
3643 to use Py_TYPE(self)->tp_name here. */
3644 const char *type_name = Py_TYPE(self)->tp_name;
3645
3646 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3647 return PyUnicode_FromFormat("%s.utc", type_name);
3648
3649 if (self->name == NULL)
3650 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3651
3652 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3653 self->name);
3654}
3655
3656
3657static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003658timezone_str(PyDateTime_TimeZone *self)
3659{
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003660 int hours, minutes, seconds, microseconds;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003661 PyObject *offset;
3662 char sign;
3663
3664 if (self->name != NULL) {
3665 Py_INCREF(self->name);
3666 return self->name;
3667 }
Victor Stinner90fd8952015-09-08 00:12:49 +02003668 if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04003669 (GET_TD_DAYS(self->offset) == 0 &&
3670 GET_TD_SECONDS(self->offset) == 0 &&
3671 GET_TD_MICROSECONDS(self->offset) == 0))
3672 return PyUnicode_FromString("UTC");
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003673 /* Offset is normalized, so it is negative if days < 0 */
3674 if (GET_TD_DAYS(self->offset) < 0) {
3675 sign = '-';
3676 offset = delta_negative((PyDateTime_Delta *)self->offset);
3677 if (offset == NULL)
3678 return NULL;
3679 }
3680 else {
3681 sign = '+';
3682 offset = self->offset;
3683 Py_INCREF(offset);
3684 }
3685 /* Offset is not negative here. */
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003686 microseconds = GET_TD_MICROSECONDS(offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003687 seconds = GET_TD_SECONDS(offset);
3688 Py_DECREF(offset);
3689 minutes = divmod(seconds, 60, &seconds);
3690 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003691 if (microseconds != 0) {
3692 return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d.%06d",
3693 sign, hours, minutes,
3694 seconds, microseconds);
3695 }
3696 if (seconds != 0) {
3697 return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d",
3698 sign, hours, minutes, seconds);
3699 }
Victor Stinner6ced7c42011-03-21 18:15:42 +01003700 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003701}
3702
3703static PyObject *
3704timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3705{
3706 if (_timezone_check_argument(dt, "tzname") == -1)
3707 return NULL;
3708
3709 return timezone_str(self);
3710}
3711
3712static PyObject *
3713timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3714{
3715 if (_timezone_check_argument(dt, "utcoffset") == -1)
3716 return NULL;
3717
3718 Py_INCREF(self->offset);
3719 return self->offset;
3720}
3721
3722static PyObject *
3723timezone_dst(PyObject *self, PyObject *dt)
3724{
3725 if (_timezone_check_argument(dt, "dst") == -1)
3726 return NULL;
3727
3728 Py_RETURN_NONE;
3729}
3730
3731static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003732timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3733{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003734 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003735 PyErr_SetString(PyExc_TypeError,
3736 "fromutc: argument must be a datetime");
3737 return NULL;
3738 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003739 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003740 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3741 "is not self");
3742 return NULL;
3743 }
3744
3745 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3746}
3747
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003748static PyObject *
3749timezone_getinitargs(PyDateTime_TimeZone *self)
3750{
3751 if (self->name == NULL)
3752 return Py_BuildValue("(O)", self->offset);
3753 return Py_BuildValue("(OO)", self->offset, self->name);
3754}
3755
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003756static PyMethodDef timezone_methods[] = {
3757 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3758 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003759 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003760
3761 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003762 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003763
3764 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003765 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003766
3767 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3768 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3769
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003770 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3771 PyDoc_STR("pickle support")},
3772
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003773 {NULL, NULL}
3774};
3775
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003776static const char timezone_doc[] =
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003777PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3778
3779static PyTypeObject PyDateTime_TimeZoneType = {
3780 PyVarObject_HEAD_INIT(NULL, 0)
3781 "datetime.timezone", /* tp_name */
3782 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3783 0, /* tp_itemsize */
3784 (destructor)timezone_dealloc, /* tp_dealloc */
3785 0, /* tp_print */
3786 0, /* tp_getattr */
3787 0, /* tp_setattr */
3788 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003789 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003790 0, /* tp_as_number */
3791 0, /* tp_as_sequence */
3792 0, /* tp_as_mapping */
3793 (hashfunc)timezone_hash, /* tp_hash */
3794 0, /* tp_call */
3795 (reprfunc)timezone_str, /* tp_str */
3796 0, /* tp_getattro */
3797 0, /* tp_setattro */
3798 0, /* tp_as_buffer */
3799 Py_TPFLAGS_DEFAULT, /* tp_flags */
3800 timezone_doc, /* tp_doc */
3801 0, /* tp_traverse */
3802 0, /* tp_clear */
3803 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3804 0, /* tp_weaklistoffset */
3805 0, /* tp_iter */
3806 0, /* tp_iternext */
3807 timezone_methods, /* tp_methods */
3808 0, /* tp_members */
3809 0, /* tp_getset */
3810 &PyDateTime_TZInfoType, /* tp_base */
3811 0, /* tp_dict */
3812 0, /* tp_descr_get */
3813 0, /* tp_descr_set */
3814 0, /* tp_dictoffset */
3815 0, /* tp_init */
3816 0, /* tp_alloc */
3817 timezone_new, /* tp_new */
3818};
3819
Tim Peters2a799bf2002-12-16 20:18:38 +00003820/*
Tim Peters37f39822003-01-10 03:49:02 +00003821 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003822 */
3823
Tim Peters37f39822003-01-10 03:49:02 +00003824/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003825 */
3826
3827static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003828time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003831}
3832
Tim Peters37f39822003-01-10 03:49:02 +00003833static PyObject *
3834time_minute(PyDateTime_Time *self, void *unused)
3835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003837}
3838
3839/* The name time_second conflicted with some platform header file. */
3840static PyObject *
3841py_time_second(PyDateTime_Time *self, void *unused)
3842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003843 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003844}
3845
3846static PyObject *
3847time_microsecond(PyDateTime_Time *self, void *unused)
3848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003850}
3851
3852static PyObject *
3853time_tzinfo(PyDateTime_Time *self, void *unused)
3854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3856 Py_INCREF(result);
3857 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003858}
3859
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003860static PyObject *
3861time_fold(PyDateTime_Time *self, void *unused)
3862{
3863 return PyLong_FromLong(TIME_GET_FOLD(self));
3864}
3865
Tim Peters37f39822003-01-10 03:49:02 +00003866static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 {"hour", (getter)time_hour},
3868 {"minute", (getter)time_minute},
3869 {"second", (getter)py_time_second},
3870 {"microsecond", (getter)time_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003871 {"tzinfo", (getter)time_tzinfo},
3872 {"fold", (getter)time_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003874};
3875
3876/*
3877 * Constructors.
3878 */
3879
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003880static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003881 "tzinfo", "fold", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003882
Tim Peters2a799bf2002-12-16 20:18:38 +00003883static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003884time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 PyObject *self = NULL;
3887 PyObject *state;
3888 int hour = 0;
3889 int minute = 0;
3890 int second = 0;
3891 int usecond = 0;
3892 PyObject *tzinfo = Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003893 int fold = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 /* Check for invocation from pickle with __getstate__ state */
3896 if (PyTuple_GET_SIZE(args) >= 1 &&
3897 PyTuple_GET_SIZE(args) <= 2 &&
3898 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3899 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003900 (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 {
3902 PyDateTime_Time *me;
3903 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 if (PyTuple_GET_SIZE(args) == 2) {
3906 tzinfo = PyTuple_GET_ITEM(args, 1);
3907 if (check_tzinfo_subclass(tzinfo) < 0) {
3908 PyErr_SetString(PyExc_TypeError, "bad "
3909 "tzinfo state arg");
3910 return NULL;
3911 }
3912 }
3913 aware = (char)(tzinfo != Py_None);
3914 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3915 if (me != NULL) {
3916 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3919 me->hashcode = -1;
3920 me->hastzinfo = aware;
3921 if (aware) {
3922 Py_INCREF(tzinfo);
3923 me->tzinfo = tzinfo;
3924 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003925 if (pdata[0] & (1 << 7)) {
3926 me->data[0] -= 128;
3927 me->fold = 1;
3928 }
3929 else {
3930 me->fold = 0;
3931 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 }
3933 return (PyObject *)me;
3934 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003935
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003936 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 &hour, &minute, &second, &usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003938 &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003939 self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
3940 type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 }
3942 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003943}
3944
3945/*
3946 * Destructor.
3947 */
3948
3949static void
Tim Peters37f39822003-01-10 03:49:02 +00003950time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 if (HASTZINFO(self)) {
3953 Py_XDECREF(self->tzinfo);
3954 }
3955 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003956}
3957
3958/*
Tim Peters855fe882002-12-22 03:43:39 +00003959 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003960 */
3961
Tim Peters2a799bf2002-12-16 20:18:38 +00003962/* These are all METH_NOARGS, so don't need to check the arglist. */
3963static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003964time_utcoffset(PyObject *self, PyObject *unused) {
3965 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003966}
3967
3968static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003969time_dst(PyObject *self, PyObject *unused) {
3970 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003971}
3972
3973static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003974time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003975 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003976}
3977
3978/*
Tim Peters37f39822003-01-10 03:49:02 +00003979 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003980 */
3981
3982static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003983time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 const char *type_name = Py_TYPE(self)->tp_name;
3986 int h = TIME_GET_HOUR(self);
3987 int m = TIME_GET_MINUTE(self);
3988 int s = TIME_GET_SECOND(self);
3989 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003990 int fold = TIME_GET_FOLD(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 if (us)
3994 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3995 type_name, h, m, s, us);
3996 else if (s)
3997 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3998 type_name, h, m, s);
3999 else
4000 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
4001 if (result != NULL && HASTZINFO(self))
4002 result = append_keyword_tzinfo(result, self->tzinfo);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004003 if (result != NULL && fold)
4004 result = append_keyword_fold(result, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004006}
4007
Tim Peters37f39822003-01-10 03:49:02 +00004008static PyObject *
4009time_str(PyDateTime_Time *self)
4010{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07004011 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters37f39822003-01-10 03:49:02 +00004012}
Tim Peters2a799bf2002-12-16 20:18:38 +00004013
4014static PyObject *
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004015time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 char buf[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004018 char *timespec = NULL;
4019 static char *keywords[] = {"timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02004021 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004022 static char *specs[][2] = {
4023 {"hours", "%02d"},
4024 {"minutes", "%02d:%02d"},
4025 {"seconds", "%02d:%02d:%02d"},
4026 {"milliseconds", "%02d:%02d:%02d.%03d"},
4027 {"microseconds", "%02d:%02d:%02d.%06d"},
4028 };
4029 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00004030
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004031 if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
4032 return NULL;
4033
4034 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4035 if (us == 0) {
4036 /* seconds */
4037 given_spec = 2;
4038 }
4039 else {
4040 /* microseconds */
4041 given_spec = 4;
4042 }
4043 }
4044 else {
4045 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4046 if (strcmp(timespec, specs[given_spec][0]) == 0) {
4047 if (given_spec == 3) {
4048 /* milliseconds */
4049 us = us / 1000;
4050 }
4051 break;
4052 }
4053 }
4054 }
4055
4056 if (given_spec == Py_ARRAY_LENGTH(specs)) {
4057 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4058 return NULL;
4059 }
4060 else {
4061 result = PyUnicode_FromFormat(specs[given_spec][1],
4062 TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
4063 TIME_GET_SECOND(self), us);
4064 }
Tim Peters37f39822003-01-10 03:49:02 +00004065
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004066 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004067 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 /* We need to append the UTC offset. */
4070 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4071 Py_None) < 0) {
4072 Py_DECREF(result);
4073 return NULL;
4074 }
4075 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
4076 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004077}
4078
Tim Peters37f39822003-01-10 03:49:02 +00004079static PyObject *
4080time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
4081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 PyObject *result;
4083 PyObject *tuple;
4084 PyObject *format;
4085 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00004086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
4088 &format))
4089 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 /* Python's strftime does insane things with the year part of the
4092 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00004093 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 */
4095 tuple = Py_BuildValue("iiiiiiiii",
4096 1900, 1, 1, /* year, month, day */
4097 TIME_GET_HOUR(self),
4098 TIME_GET_MINUTE(self),
4099 TIME_GET_SECOND(self),
4100 0, 1, -1); /* weekday, daynum, dst */
4101 if (tuple == NULL)
4102 return NULL;
4103 assert(PyTuple_Size(tuple) == 9);
4104 result = wrap_strftime((PyObject *)self, format, tuple,
4105 Py_None);
4106 Py_DECREF(tuple);
4107 return result;
Tim Peters37f39822003-01-10 03:49:02 +00004108}
Tim Peters2a799bf2002-12-16 20:18:38 +00004109
4110/*
4111 * Miscellaneous methods.
4112 */
4113
Tim Peters37f39822003-01-10 03:49:02 +00004114static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004115time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00004116{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004117 PyObject *result = NULL;
4118 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00004120
Brian Curtindfc80e32011-08-10 20:28:54 -05004121 if (! PyTime_Check(other))
4122 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004123
4124 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 diff = memcmp(((PyDateTime_Time *)self)->data,
4126 ((PyDateTime_Time *)other)->data,
4127 _PyDateTime_TIME_DATASIZE);
4128 return diff_to_bool(diff, op);
4129 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004130 offset1 = time_utcoffset(self, NULL);
4131 if (offset1 == NULL)
4132 return NULL;
4133 offset2 = time_utcoffset(other, NULL);
4134 if (offset2 == NULL)
4135 goto done;
4136 /* If they're both naive, or both aware and have the same offsets,
4137 * we get off cheap. Note that if they're both naive, offset1 ==
4138 * offset2 == Py_None at this point.
4139 */
4140 if ((offset1 == offset2) ||
4141 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4142 delta_cmp(offset1, offset2) == 0)) {
4143 diff = memcmp(((PyDateTime_Time *)self)->data,
4144 ((PyDateTime_Time *)other)->data,
4145 _PyDateTime_TIME_DATASIZE);
4146 result = diff_to_bool(diff, op);
4147 }
4148 /* The hard case: both aware with different UTC offsets */
4149 else if (offset1 != Py_None && offset2 != Py_None) {
4150 int offsecs1, offsecs2;
4151 assert(offset1 != offset2); /* else last "if" handled it */
4152 offsecs1 = TIME_GET_HOUR(self) * 3600 +
4153 TIME_GET_MINUTE(self) * 60 +
4154 TIME_GET_SECOND(self) -
4155 GET_TD_DAYS(offset1) * 86400 -
4156 GET_TD_SECONDS(offset1);
4157 offsecs2 = TIME_GET_HOUR(other) * 3600 +
4158 TIME_GET_MINUTE(other) * 60 +
4159 TIME_GET_SECOND(other) -
4160 GET_TD_DAYS(offset2) * 86400 -
4161 GET_TD_SECONDS(offset2);
4162 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 if (diff == 0)
4164 diff = TIME_GET_MICROSECOND(self) -
4165 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004166 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004168 else if (op == Py_EQ) {
4169 result = Py_False;
4170 Py_INCREF(result);
4171 }
4172 else if (op == Py_NE) {
4173 result = Py_True;
4174 Py_INCREF(result);
4175 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004176 else {
4177 PyErr_SetString(PyExc_TypeError,
4178 "can't compare offset-naive and "
4179 "offset-aware times");
4180 }
4181 done:
4182 Py_DECREF(offset1);
4183 Py_XDECREF(offset2);
4184 return result;
Tim Peters37f39822003-01-10 03:49:02 +00004185}
4186
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004187static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00004188time_hash(PyDateTime_Time *self)
4189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004191 PyObject *offset, *self0;
Victor Stinner423c16b2017-01-03 23:47:12 +01004192 if (TIME_GET_FOLD(self)) {
4193 self0 = new_time_ex2(TIME_GET_HOUR(self),
4194 TIME_GET_MINUTE(self),
4195 TIME_GET_SECOND(self),
4196 TIME_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004197 HASTZINFO(self) ? self->tzinfo : Py_None,
4198 0, Py_TYPE(self));
4199 if (self0 == NULL)
4200 return -1;
4201 }
4202 else {
4203 self0 = (PyObject *)self;
4204 Py_INCREF(self0);
4205 }
4206 offset = time_utcoffset(self0, NULL);
4207 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004208
4209 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004213 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 self->hashcode = generic_hash(
4215 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004217 PyObject *temp1, *temp2;
4218 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004220 seconds = TIME_GET_HOUR(self) * 3600 +
4221 TIME_GET_MINUTE(self) * 60 +
4222 TIME_GET_SECOND(self);
4223 microseconds = TIME_GET_MICROSECOND(self);
4224 temp1 = new_delta(0, seconds, microseconds, 1);
4225 if (temp1 == NULL) {
4226 Py_DECREF(offset);
4227 return -1;
4228 }
4229 temp2 = delta_subtract(temp1, offset);
4230 Py_DECREF(temp1);
4231 if (temp2 == NULL) {
4232 Py_DECREF(offset);
4233 return -1;
4234 }
4235 self->hashcode = PyObject_Hash(temp2);
4236 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004238 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 }
4240 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00004241}
Tim Peters2a799bf2002-12-16 20:18:38 +00004242
Tim Peters12bf3392002-12-24 05:41:27 +00004243static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00004244time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 PyObject *clone;
4247 PyObject *tuple;
4248 int hh = TIME_GET_HOUR(self);
4249 int mm = TIME_GET_MINUTE(self);
4250 int ss = TIME_GET_SECOND(self);
4251 int us = TIME_GET_MICROSECOND(self);
4252 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004253 int fold = TIME_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00004254
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004255 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 time_kws,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004257 &hh, &mm, &ss, &us, &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03004259 if (fold != 0 && fold != 1) {
4260 PyErr_SetString(PyExc_ValueError,
4261 "fold must be either 0 or 1");
4262 return NULL;
4263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
4265 if (tuple == NULL)
4266 return NULL;
4267 clone = time_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04004268 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004269 TIME_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04004270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 Py_DECREF(tuple);
4272 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004273}
4274
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004275static PyObject *
4276time_fromisoformat(PyObject *cls, PyObject *tstr) {
4277 assert(tstr != NULL);
4278
4279 if (!PyUnicode_Check(tstr)) {
4280 PyErr_SetString(PyExc_TypeError, "fromisoformat: argument must be str");
4281 return NULL;
4282 }
4283
4284 Py_ssize_t len;
4285 const char *p = PyUnicode_AsUTF8AndSize(tstr, &len);
4286
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004287 if (p == NULL) {
4288 goto invalid_string_error;
4289 }
4290
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004291 int hour = 0, minute = 0, second = 0, microsecond = 0;
4292 int tzoffset, tzimicrosecond = 0;
4293 int rv = parse_isoformat_time(p, len,
4294 &hour, &minute, &second, &microsecond,
4295 &tzoffset, &tzimicrosecond);
4296
4297 if (rv < 0) {
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004298 goto invalid_string_error;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004299 }
4300
4301 PyObject *tzinfo = tzinfo_from_isoformat_results(rv, tzoffset,
4302 tzimicrosecond);
4303
4304 if (tzinfo == NULL) {
4305 return NULL;
4306 }
4307
4308 PyObject *t;
4309 if ( (PyTypeObject *)cls == &PyDateTime_TimeType ) {
4310 t = new_time(hour, minute, second, microsecond, tzinfo, 0);
4311 } else {
4312 t = PyObject_CallFunction(cls, "iiiiO",
4313 hour, minute, second, microsecond, tzinfo);
4314 }
4315
4316 Py_DECREF(tzinfo);
4317 return t;
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004318
4319invalid_string_error:
4320 PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", tstr);
4321 return NULL;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004322}
4323
4324
Tim Peters371935f2003-02-01 01:52:50 +00004325/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00004326
Tim Peters33e0f382003-01-10 02:05:14 +00004327/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004328 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4329 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004330 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004331 */
4332static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004333time_getstate(PyDateTime_Time *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00004334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 PyObject *basestate;
4336 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 basestate = PyBytes_FromStringAndSize((char *)self->data,
4339 _PyDateTime_TIME_DATASIZE);
4340 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004341 if (proto > 3 && TIME_GET_FOLD(self))
4342 /* Set the first bit of the first byte */
4343 PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4345 result = PyTuple_Pack(1, basestate);
4346 else
4347 result = PyTuple_Pack(2, basestate, self->tzinfo);
4348 Py_DECREF(basestate);
4349 }
4350 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004351}
4352
4353static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004354time_reduce_ex(PyDateTime_Time *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00004355{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004356 int proto;
4357 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004358 return NULL;
4359
4360 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00004361}
4362
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004363static PyObject *
4364time_reduce(PyDateTime_Time *self, PyObject *arg)
4365{
4366 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, 2));
4367}
4368
Tim Peters37f39822003-01-10 03:49:02 +00004369static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004370
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004371 {"isoformat", (PyCFunction)time_isoformat, METH_VARARGS | METH_KEYWORDS,
4372 PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
4373 "[+HH:MM].\n\n"
4374 "timespec specifies what components of the time to include.\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
4377 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 {"__format__", (PyCFunction)date_format, METH_VARARGS,
4380 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
4383 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
4386 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 {"dst", (PyCFunction)time_dst, METH_NOARGS,
4389 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
4392 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004393
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004394 {"fromisoformat", (PyCFunction)time_fromisoformat, METH_O | METH_CLASS,
4395 PyDoc_STR("string -> time from time.isoformat() output")},
4396
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004397 {"__reduce_ex__", (PyCFunction)time_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004398 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004399
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004400 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
4401 PyDoc_STR("__reduce__() -> (cls, state)")},
4402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004404};
4405
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004406static const char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004407PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
4408\n\
4409All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03004410a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004411
Neal Norwitz227b5332006-03-22 09:28:35 +00004412static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 PyVarObject_HEAD_INIT(NULL, 0)
4414 "datetime.time", /* tp_name */
4415 sizeof(PyDateTime_Time), /* tp_basicsize */
4416 0, /* tp_itemsize */
4417 (destructor)time_dealloc, /* tp_dealloc */
4418 0, /* tp_print */
4419 0, /* tp_getattr */
4420 0, /* tp_setattr */
4421 0, /* tp_reserved */
4422 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05004423 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 0, /* tp_as_sequence */
4425 0, /* tp_as_mapping */
4426 (hashfunc)time_hash, /* tp_hash */
4427 0, /* tp_call */
4428 (reprfunc)time_str, /* tp_str */
4429 PyObject_GenericGetAttr, /* tp_getattro */
4430 0, /* tp_setattro */
4431 0, /* tp_as_buffer */
4432 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4433 time_doc, /* tp_doc */
4434 0, /* tp_traverse */
4435 0, /* tp_clear */
4436 time_richcompare, /* tp_richcompare */
4437 0, /* tp_weaklistoffset */
4438 0, /* tp_iter */
4439 0, /* tp_iternext */
4440 time_methods, /* tp_methods */
4441 0, /* tp_members */
4442 time_getset, /* tp_getset */
4443 0, /* tp_base */
4444 0, /* tp_dict */
4445 0, /* tp_descr_get */
4446 0, /* tp_descr_set */
4447 0, /* tp_dictoffset */
4448 0, /* tp_init */
4449 time_alloc, /* tp_alloc */
4450 time_new, /* tp_new */
4451 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004452};
4453
4454/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004455 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00004456 */
4457
Tim Petersa9bc1682003-01-11 03:39:11 +00004458/* Accessor properties. Properties for day, month, and year are inherited
4459 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004460 */
4461
4462static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004463datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00004464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004466}
4467
Tim Petersa9bc1682003-01-11 03:39:11 +00004468static PyObject *
4469datetime_minute(PyDateTime_DateTime *self, void *unused)
4470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004472}
4473
4474static PyObject *
4475datetime_second(PyDateTime_DateTime *self, void *unused)
4476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004478}
4479
4480static PyObject *
4481datetime_microsecond(PyDateTime_DateTime *self, void *unused)
4482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004484}
4485
4486static PyObject *
4487datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
4488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4490 Py_INCREF(result);
4491 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004492}
4493
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004494static PyObject *
4495datetime_fold(PyDateTime_DateTime *self, void *unused)
4496{
4497 return PyLong_FromLong(DATE_GET_FOLD(self));
4498}
4499
Tim Petersa9bc1682003-01-11 03:39:11 +00004500static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 {"hour", (getter)datetime_hour},
4502 {"minute", (getter)datetime_minute},
4503 {"second", (getter)datetime_second},
4504 {"microsecond", (getter)datetime_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004505 {"tzinfo", (getter)datetime_tzinfo},
4506 {"fold", (getter)datetime_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004508};
4509
4510/*
4511 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004512 */
4513
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004514static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 "year", "month", "day", "hour", "minute", "second",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004516 "microsecond", "tzinfo", "fold", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004517};
4518
Tim Peters2a799bf2002-12-16 20:18:38 +00004519static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004520datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 PyObject *self = NULL;
4523 PyObject *state;
4524 int year;
4525 int month;
4526 int day;
4527 int hour = 0;
4528 int minute = 0;
4529 int second = 0;
4530 int usecond = 0;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004531 int fold = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 /* Check for invocation from pickle with __getstate__ state */
4535 if (PyTuple_GET_SIZE(args) >= 1 &&
4536 PyTuple_GET_SIZE(args) <= 2 &&
4537 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4538 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004539 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 {
4541 PyDateTime_DateTime *me;
4542 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 if (PyTuple_GET_SIZE(args) == 2) {
4545 tzinfo = PyTuple_GET_ITEM(args, 1);
4546 if (check_tzinfo_subclass(tzinfo) < 0) {
4547 PyErr_SetString(PyExc_TypeError, "bad "
4548 "tzinfo state arg");
4549 return NULL;
4550 }
4551 }
4552 aware = (char)(tzinfo != Py_None);
4553 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4554 if (me != NULL) {
4555 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4558 me->hashcode = -1;
4559 me->hastzinfo = aware;
4560 if (aware) {
4561 Py_INCREF(tzinfo);
4562 me->tzinfo = tzinfo;
4563 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004564 if (pdata[2] & (1 << 7)) {
4565 me->data[2] -= 128;
4566 me->fold = 1;
4567 }
4568 else {
4569 me->fold = 0;
4570 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 }
4572 return (PyObject *)me;
4573 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004574
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004575 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 &year, &month, &day, &hour, &minute,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004577 &second, &usecond, &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004578 self = new_datetime_ex2(year, month, day,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 hour, minute, second, usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004580 tzinfo, fold, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 }
4582 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004583}
4584
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004585/* TM_FUNC is the shared type of _PyTime_localtime() and
4586 * _PyTime_gmtime(). */
4587typedef int (*TM_FUNC)(time_t timer, struct tm*);
Tim Petersa9bc1682003-01-11 03:39:11 +00004588
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004589/* As of version 2015f max fold in IANA database is
4590 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004591static long long max_fold_seconds = 24 * 3600;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004592/* NB: date(1970,1,1).toordinal() == 719163 */
Benjamin Petersonac965ca2016-09-18 18:12:21 -07004593static long long epoch = 719163LL * 24 * 60 * 60;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004594
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004595static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004596utc_to_seconds(int year, int month, int day,
4597 int hour, int minute, int second)
4598{
Victor Stinnerb67f0962017-02-10 10:34:02 +01004599 long long ordinal;
4600
4601 /* ymd_to_ord() doesn't support year <= 0 */
4602 if (year < MINYEAR || year > MAXYEAR) {
4603 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
4604 return -1;
4605 }
4606
4607 ordinal = ymd_to_ord(year, month, day);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004608 return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
4609}
4610
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004611static long long
4612local(long long u)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004613{
4614 struct tm local_time;
Alexander Belopolsky8e1d3a22016-07-25 13:54:51 -04004615 time_t t;
4616 u -= epoch;
4617 t = u;
4618 if (t != u) {
4619 PyErr_SetString(PyExc_OverflowError,
4620 "timestamp out of range for platform time_t");
4621 return -1;
4622 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004623 if (_PyTime_localtime(t, &local_time) != 0)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004624 return -1;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004625 return utc_to_seconds(local_time.tm_year + 1900,
4626 local_time.tm_mon + 1,
4627 local_time.tm_mday,
4628 local_time.tm_hour,
4629 local_time.tm_min,
4630 local_time.tm_sec);
4631}
4632
Tim Petersa9bc1682003-01-11 03:39:11 +00004633/* Internal helper.
4634 * Build datetime from a time_t and a distinct count of microseconds.
4635 * Pass localtime or gmtime for f, to control the interpretation of timet.
4636 */
4637static PyObject *
4638datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004640{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004641 struct tm tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004642 int year, month, day, hour, minute, second, fold = 0;
Tim Petersa9bc1682003-01-11 03:39:11 +00004643
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004644 if (f(timet, &tm) != 0)
4645 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01004646
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004647 year = tm.tm_year + 1900;
4648 month = tm.tm_mon + 1;
4649 day = tm.tm_mday;
4650 hour = tm.tm_hour;
4651 minute = tm.tm_min;
Victor Stinner21f58932012-03-14 00:15:40 +01004652 /* The platform localtime/gmtime may insert leap seconds,
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004653 * indicated by tm.tm_sec > 59. We don't care about them,
Victor Stinner21f58932012-03-14 00:15:40 +01004654 * except to the extent that passing them on to the datetime
4655 * constructor would raise ValueError for a reason that
4656 * made no sense to the user.
4657 */
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004658 second = Py_MIN(59, tm.tm_sec);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004659
Victor Stinnerb67f0962017-02-10 10:34:02 +01004660 /* local timezone requires to compute fold */
Miss Islington (bot)97364932018-07-25 13:34:09 -07004661 if (tzinfo == Py_None && f == _PyTime_localtime
4662 /* On Windows, passing a negative value to local results
4663 * in an OSError because localtime_s on Windows does
4664 * not support negative timestamps. Unfortunately this
4665 * means that fold detection for time values between
4666 * 0 and max_fold_seconds will result in an identical
4667 * error since we subtract max_fold_seconds to detect a
4668 * fold. However, since we know there haven't been any
4669 * folds in the interval [0, max_fold_seconds) in any
4670 * timezone, we can hackily just forego fold detection
4671 * for this time range.
4672 */
4673#ifdef MS_WINDOWS
4674 && (timet - max_fold_seconds > 0)
4675#endif
4676 ) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004677 long long probe_seconds, result_seconds, transition;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004678
4679 result_seconds = utc_to_seconds(year, month, day,
4680 hour, minute, second);
4681 /* Probe max_fold_seconds to detect a fold. */
4682 probe_seconds = local(epoch + timet - max_fold_seconds);
4683 if (probe_seconds == -1)
4684 return NULL;
4685 transition = result_seconds - probe_seconds - max_fold_seconds;
4686 if (transition < 0) {
4687 probe_seconds = local(epoch + timet + transition);
4688 if (probe_seconds == -1)
4689 return NULL;
4690 if (probe_seconds == result_seconds)
4691 fold = 1;
4692 }
4693 }
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05004694 return new_datetime_subclass_fold_ex(year, month, day, hour, minute,
4695 second, us, tzinfo, fold, cls);
Tim Petersa9bc1682003-01-11 03:39:11 +00004696}
4697
4698/* Internal helper.
4699 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4700 * to control the interpretation of the timestamp. Since a double doesn't
4701 * have enough bits to cover a datetime's full range of precision, it's
4702 * better to call datetime_from_timet_and_us provided you have a way
4703 * to get that much precision (e.g., C time() isn't good enough).
4704 */
4705static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004706datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004710 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004711
Victor Stinnere4a994d2015-03-30 01:10:14 +02004712 if (_PyTime_ObjectToTimeval(timestamp,
Victor Stinner7667f582015-09-09 01:02:23 +02004713 &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004715
Victor Stinner21f58932012-03-14 00:15:40 +01004716 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004717}
4718
4719/* Internal helper.
4720 * Build most accurate possible datetime for current time. Pass localtime or
4721 * gmtime for f as appropriate.
4722 */
4723static PyObject *
4724datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4725{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004726 _PyTime_t ts = _PyTime_GetSystemClock();
Victor Stinner1e2b6882015-09-18 13:23:02 +02004727 time_t secs;
4728 int us;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004729
Victor Stinner1e2b6882015-09-18 13:23:02 +02004730 if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner09e5cf22015-03-30 00:09:18 +02004731 return NULL;
Victor Stinner1e2b6882015-09-18 13:23:02 +02004732 assert(0 <= us && us <= 999999);
Victor Stinner09e5cf22015-03-30 00:09:18 +02004733
Victor Stinner1e2b6882015-09-18 13:23:02 +02004734 return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004735}
4736
Larry Hastings61272b72014-01-07 12:41:53 -08004737/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004738
4739@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004740datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004741
4742 tz: object = None
4743 Timezone object.
4744
4745Returns new datetime object representing current time local to tz.
4746
4747If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004748[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004749
Larry Hastings31826802013-10-19 00:09:25 -07004750static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004751datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03004752/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004755
Larry Hastings31826802013-10-19 00:09:25 -07004756 /* Return best possible local time -- this isn't constrained by the
4757 * precision of a timestamp.
4758 */
4759 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004761
Larry Hastings5c661892014-01-24 06:17:25 -08004762 self = datetime_best_possible((PyObject *)type,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004763 tz == Py_None ? _PyTime_localtime :
4764 _PyTime_gmtime,
Larry Hastings31826802013-10-19 00:09:25 -07004765 tz);
4766 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004768 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 }
4770 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004771}
4772
Tim Petersa9bc1682003-01-11 03:39:11 +00004773/* Return best possible UTC time -- this isn't constrained by the
4774 * precision of a timestamp.
4775 */
4776static PyObject *
4777datetime_utcnow(PyObject *cls, PyObject *dummy)
4778{
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004779 return datetime_best_possible(cls, _PyTime_gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004780}
4781
Tim Peters2a799bf2002-12-16 20:18:38 +00004782/* Return new local datetime from timestamp (Python timestamp -- a double). */
4783static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004784datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004787 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 PyObject *tzinfo = Py_None;
4789 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004790
Victor Stinner5d272cc2012-03-13 13:35:55 +01004791 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004792 keywords, &timestamp, &tzinfo))
4793 return NULL;
4794 if (check_tzinfo_subclass(tzinfo) < 0)
4795 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 self = datetime_from_timestamp(cls,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004798 tzinfo == Py_None ? _PyTime_localtime :
4799 _PyTime_gmtime,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 timestamp,
4801 tzinfo);
4802 if (self != NULL && tzinfo != Py_None) {
4803 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004804 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 }
4806 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004807}
4808
Tim Petersa9bc1682003-01-11 03:39:11 +00004809/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4810static PyObject *
4811datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4812{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004813 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004815
Victor Stinner5d272cc2012-03-13 13:35:55 +01004816 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004817 result = datetime_from_timestamp(cls, _PyTime_gmtime, timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 Py_None);
4819 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004820}
4821
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004822/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004823static PyObject *
4824datetime_strptime(PyObject *cls, PyObject *args)
4825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004827 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004828 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004829
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004830 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004832
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004833 if (module == NULL) {
4834 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004835 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004836 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 }
Victor Stinner20401de2016-12-09 15:24:31 +01004838 return _PyObject_CallMethodIdObjArgs(module, &PyId__strptime_datetime,
4839 cls, string, format, NULL);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004840}
4841
Tim Petersa9bc1682003-01-11 03:39:11 +00004842/* Return new datetime from date/datetime and time arguments. */
4843static PyObject *
4844datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4845{
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004846 static char *keywords[] = {"date", "time", "tzinfo", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 PyObject *date;
4848 PyObject *time;
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004849 PyObject *tzinfo = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004851
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004852 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 &PyDateTime_DateType, &date,
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004854 &PyDateTime_TimeType, &time, &tzinfo)) {
4855 if (tzinfo == NULL) {
4856 if (HASTZINFO(time))
4857 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4858 else
4859 tzinfo = Py_None;
4860 }
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05004861 result = new_datetime_subclass_fold_ex(GET_YEAR(date),
4862 GET_MONTH(date),
4863 GET_DAY(date),
4864 TIME_GET_HOUR(time),
4865 TIME_GET_MINUTE(time),
4866 TIME_GET_SECOND(time),
4867 TIME_GET_MICROSECOND(time),
4868 tzinfo,
4869 TIME_GET_FOLD(time),
4870 cls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004871 }
4872 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004873}
Tim Peters2a799bf2002-12-16 20:18:38 +00004874
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004875static PyObject *
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004876_sanitize_isoformat_str(PyObject *dtstr)
4877{
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004878 // `fromisoformat` allows surrogate characters in exactly one position,
4879 // the separator; to allow datetime_fromisoformat to make the simplifying
4880 // assumption that all valid strings can be encoded in UTF-8, this function
4881 // replaces any surrogate character separators with `T`.
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004882 //
4883 // The result of this, if not NULL, returns a new reference
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004884 Py_ssize_t len = PyUnicode_GetLength(dtstr);
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004885 if (len < 0) {
4886 return NULL;
4887 }
4888
4889 if (len <= 10 ||
4890 !Py_UNICODE_IS_SURROGATE(PyUnicode_READ_CHAR(dtstr, 10))) {
4891 Py_INCREF(dtstr);
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004892 return dtstr;
4893 }
4894
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004895 PyObject *str_out = _PyUnicode_Copy(dtstr);
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004896 if (str_out == NULL) {
4897 return NULL;
4898 }
4899
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004900 if (PyUnicode_WriteChar(str_out, 10, (Py_UCS4)'T')) {
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004901 Py_DECREF(str_out);
4902 return NULL;
4903 }
4904
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004905 return str_out;
4906}
4907
4908static PyObject *
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004909datetime_fromisoformat(PyObject *cls, PyObject *dtstr)
4910{
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004911 assert(dtstr != NULL);
4912
4913 if (!PyUnicode_Check(dtstr)) {
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004914 PyErr_SetString(PyExc_TypeError,
4915 "fromisoformat: argument must be str");
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004916 return NULL;
4917 }
4918
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004919 PyObject *dtstr_clean = _sanitize_isoformat_str(dtstr);
4920 if (dtstr_clean == NULL) {
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004921 goto error;
4922 }
4923
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004924 Py_ssize_t len;
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004925 const char *dt_ptr = PyUnicode_AsUTF8AndSize(dtstr_clean, &len);
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004926
4927 if (dt_ptr == NULL) {
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004928 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4929 // Encoding errors are invalid string errors at this point
4930 goto invalid_string_error;
4931 }
4932 else {
4933 goto error;
4934 }
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004935 }
4936
4937 const char *p = dt_ptr;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004938
4939 int year = 0, month = 0, day = 0;
4940 int hour = 0, minute = 0, second = 0, microsecond = 0;
4941 int tzoffset = 0, tzusec = 0;
4942
4943 // date has a fixed length of 10
4944 int rv = parse_isoformat_date(p, &year, &month, &day);
4945
4946 if (!rv && len > 10) {
4947 // In UTF-8, the length of multi-byte characters is encoded in the MSB
4948 if ((p[10] & 0x80) == 0) {
4949 p += 11;
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004950 }
4951 else {
4952 switch (p[10] & 0xf0) {
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004953 case 0xe0:
4954 p += 13;
4955 break;
4956 case 0xf0:
4957 p += 14;
4958 break;
4959 default:
4960 p += 12;
4961 break;
4962 }
4963 }
4964
4965 len -= (p - dt_ptr);
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004966 rv = parse_isoformat_time(p, len, &hour, &minute, &second,
4967 &microsecond, &tzoffset, &tzusec);
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004968 }
4969 if (rv < 0) {
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004970 goto invalid_string_error;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004971 }
4972
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004973 PyObject *tzinfo = tzinfo_from_isoformat_results(rv, tzoffset, tzusec);
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004974 if (tzinfo == NULL) {
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004975 goto error;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004976 }
4977
Paul Ganssle9f1b7b92018-01-16 13:06:31 -05004978 PyObject *dt = new_datetime_subclass_ex(year, month, day, hour, minute,
4979 second, microsecond, tzinfo, cls);
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004980
4981 Py_DECREF(tzinfo);
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004982 Py_DECREF(dtstr_clean);
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004983 return dt;
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004984
4985invalid_string_error:
4986 PyErr_Format(PyExc_ValueError, "Invalid isoformat string: %R", dtstr);
4987
4988error:
Miss Islington (bot)18450be2018-10-22 15:35:15 -07004989 Py_XDECREF(dtstr_clean);
Miss Islington (bot)89b16542018-08-23 11:54:33 -04004990
4991 return NULL;
Paul Ganssle09dc2f52017-12-21 00:33:49 -05004992}
4993
Tim Peters2a799bf2002-12-16 20:18:38 +00004994/*
4995 * Destructor.
4996 */
4997
4998static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004999datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 if (HASTZINFO(self)) {
5002 Py_XDECREF(self->tzinfo);
5003 }
5004 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00005005}
5006
5007/*
5008 * Indirect access to tzinfo methods.
5009 */
5010
Tim Peters2a799bf2002-12-16 20:18:38 +00005011/* These are all METH_NOARGS, so don't need to check the arglist. */
5012static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005013datetime_utcoffset(PyObject *self, PyObject *unused) {
5014 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00005015}
5016
5017static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005018datetime_dst(PyObject *self, PyObject *unused) {
5019 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00005020}
5021
5022static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005023datetime_tzname(PyObject *self, PyObject *unused) {
5024 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00005025}
5026
5027/*
Tim Petersa9bc1682003-01-11 03:39:11 +00005028 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00005029 */
5030
Tim Petersa9bc1682003-01-11 03:39:11 +00005031/* factor must be 1 (to add) or -1 (to subtract). The result inherits
5032 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00005033 */
5034static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005035add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00005037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 /* Note that the C-level additions can't overflow, because of
5039 * invariant bounds on the member values.
5040 */
5041 int year = GET_YEAR(date);
5042 int month = GET_MONTH(date);
5043 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
5044 int hour = DATE_GET_HOUR(date);
5045 int minute = DATE_GET_MINUTE(date);
5046 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
5047 int microsecond = DATE_GET_MICROSECOND(date) +
5048 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00005049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 assert(factor == 1 || factor == -1);
5051 if (normalize_datetime(&year, &month, &day,
Victor Stinnerb67f0962017-02-10 10:34:02 +01005052 &hour, &minute, &second, &microsecond) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 return NULL;
Victor Stinnerb67f0962017-02-10 10:34:02 +01005054 }
5055
5056 return new_datetime(year, month, day,
5057 hour, minute, second, microsecond,
5058 HASTZINFO(date) ? date->tzinfo : Py_None, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005059}
5060
5061static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005062datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00005063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 if (PyDateTime_Check(left)) {
5065 /* datetime + ??? */
5066 if (PyDelta_Check(right))
5067 /* datetime + delta */
5068 return add_datetime_timedelta(
5069 (PyDateTime_DateTime *)left,
5070 (PyDateTime_Delta *)right,
5071 1);
5072 }
5073 else if (PyDelta_Check(left)) {
5074 /* delta + datetime */
5075 return add_datetime_timedelta((PyDateTime_DateTime *) right,
5076 (PyDateTime_Delta *) left,
5077 1);
5078 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005079 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00005080}
5081
5082static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005083datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00005084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00005086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 if (PyDateTime_Check(left)) {
5088 /* datetime - ??? */
5089 if (PyDateTime_Check(right)) {
5090 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005091 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00005093
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005094 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
5095 offset2 = offset1 = Py_None;
5096 Py_INCREF(offset1);
5097 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005099 else {
5100 offset1 = datetime_utcoffset(left, NULL);
5101 if (offset1 == NULL)
5102 return NULL;
5103 offset2 = datetime_utcoffset(right, NULL);
5104 if (offset2 == NULL) {
5105 Py_DECREF(offset1);
5106 return NULL;
5107 }
5108 if ((offset1 != Py_None) != (offset2 != Py_None)) {
5109 PyErr_SetString(PyExc_TypeError,
5110 "can't subtract offset-naive and "
5111 "offset-aware datetimes");
5112 Py_DECREF(offset1);
5113 Py_DECREF(offset2);
5114 return NULL;
5115 }
5116 }
5117 if ((offset1 != offset2) &&
5118 delta_cmp(offset1, offset2) != 0) {
5119 offdiff = delta_subtract(offset1, offset2);
5120 if (offdiff == NULL) {
5121 Py_DECREF(offset1);
5122 Py_DECREF(offset2);
5123 return NULL;
5124 }
5125 }
5126 Py_DECREF(offset1);
5127 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 delta_d = ymd_to_ord(GET_YEAR(left),
5129 GET_MONTH(left),
5130 GET_DAY(left)) -
5131 ymd_to_ord(GET_YEAR(right),
5132 GET_MONTH(right),
5133 GET_DAY(right));
5134 /* These can't overflow, since the values are
5135 * normalized. At most this gives the number of
5136 * seconds in one day.
5137 */
5138 delta_s = (DATE_GET_HOUR(left) -
5139 DATE_GET_HOUR(right)) * 3600 +
5140 (DATE_GET_MINUTE(left) -
5141 DATE_GET_MINUTE(right)) * 60 +
5142 (DATE_GET_SECOND(left) -
5143 DATE_GET_SECOND(right));
5144 delta_us = DATE_GET_MICROSECOND(left) -
5145 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01005147 if (result == NULL)
5148 return NULL;
5149
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005150 if (offdiff != NULL) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03005151 Py_SETREF(result, delta_subtract(result, offdiff));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005152 Py_DECREF(offdiff);
5153 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 }
5155 else if (PyDelta_Check(right)) {
5156 /* datetime - delta */
5157 result = add_datetime_timedelta(
5158 (PyDateTime_DateTime *)left,
5159 (PyDateTime_Delta *)right,
5160 -1);
5161 }
5162 }
Tim Peters2a799bf2002-12-16 20:18:38 +00005163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 if (result == Py_NotImplemented)
5165 Py_INCREF(result);
5166 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005167}
5168
5169/* Various ways to turn a datetime into a string. */
5170
5171static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005172datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 const char *type_name = Py_TYPE(self)->tp_name;
5175 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00005176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 if (DATE_GET_MICROSECOND(self)) {
5178 baserepr = PyUnicode_FromFormat(
5179 "%s(%d, %d, %d, %d, %d, %d, %d)",
5180 type_name,
5181 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
5182 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
5183 DATE_GET_SECOND(self),
5184 DATE_GET_MICROSECOND(self));
5185 }
5186 else if (DATE_GET_SECOND(self)) {
5187 baserepr = PyUnicode_FromFormat(
5188 "%s(%d, %d, %d, %d, %d, %d)",
5189 type_name,
5190 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
5191 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
5192 DATE_GET_SECOND(self));
5193 }
5194 else {
5195 baserepr = PyUnicode_FromFormat(
5196 "%s(%d, %d, %d, %d, %d)",
5197 type_name,
5198 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
5199 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
5200 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005201 if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
5202 baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 if (baserepr == NULL || ! HASTZINFO(self))
5204 return baserepr;
5205 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00005206}
5207
Tim Petersa9bc1682003-01-11 03:39:11 +00005208static PyObject *
5209datetime_str(PyDateTime_DateTime *self)
5210{
Victor Stinner4c381542016-12-09 00:33:39 +01005211 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "s", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00005212}
Tim Peters2a799bf2002-12-16 20:18:38 +00005213
5214static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005215datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00005216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 int sep = 'T';
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005218 char *timespec = NULL;
5219 static char *keywords[] = {"sep", "timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 char buffer[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005221 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 int us = DATE_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005223 static char *specs[][2] = {
5224 {"hours", "%04d-%02d-%02d%c%02d"},
5225 {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
5226 {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
5227 {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
5228 {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
5229 };
5230 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00005231
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005232 if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 return NULL;
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005234
5235 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
5236 if (us == 0) {
5237 /* seconds */
5238 given_spec = 2;
5239 }
5240 else {
5241 /* microseconds */
5242 given_spec = 4;
5243 }
5244 }
5245 else {
5246 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
5247 if (strcmp(timespec, specs[given_spec][0]) == 0) {
5248 if (given_spec == 3) {
5249 us = us / 1000;
5250 }
5251 break;
5252 }
5253 }
5254 }
5255
5256 if (given_spec == Py_ARRAY_LENGTH(specs)) {
5257 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
5258 return NULL;
5259 }
5260 else {
5261 result = PyUnicode_FromFormat(specs[given_spec][1],
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 GET_YEAR(self), GET_MONTH(self),
5263 GET_DAY(self), (int)sep,
5264 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
5265 DATE_GET_SECOND(self), us);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005266 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00005267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 if (!result || !HASTZINFO(self))
5269 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 /* We need to append the UTC offset. */
5272 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
5273 (PyObject *)self) < 0) {
5274 Py_DECREF(result);
5275 return NULL;
5276 }
5277 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
5278 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005279}
5280
Tim Petersa9bc1682003-01-11 03:39:11 +00005281static PyObject *
5282datetime_ctime(PyDateTime_DateTime *self)
5283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005284 return format_ctime((PyDateTime_Date *)self,
5285 DATE_GET_HOUR(self),
5286 DATE_GET_MINUTE(self),
5287 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005288}
5289
Tim Peters2a799bf2002-12-16 20:18:38 +00005290/* Miscellaneous methods. */
5291
Tim Petersa9bc1682003-01-11 03:39:11 +00005292static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005293flip_fold(PyObject *dt)
5294{
5295 return new_datetime_ex2(GET_YEAR(dt),
5296 GET_MONTH(dt),
5297 GET_DAY(dt),
5298 DATE_GET_HOUR(dt),
5299 DATE_GET_MINUTE(dt),
5300 DATE_GET_SECOND(dt),
5301 DATE_GET_MICROSECOND(dt),
5302 HASTZINFO(dt) ?
5303 ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
5304 !DATE_GET_FOLD(dt),
5305 Py_TYPE(dt));
5306}
5307
5308static PyObject *
5309get_flip_fold_offset(PyObject *dt)
5310{
5311 PyObject *result, *flip_dt;
5312
5313 flip_dt = flip_fold(dt);
5314 if (flip_dt == NULL)
5315 return NULL;
5316 result = datetime_utcoffset(flip_dt, NULL);
5317 Py_DECREF(flip_dt);
5318 return result;
5319}
5320
5321/* PEP 495 exception: Whenever one or both of the operands in
5322 * inter-zone comparison is such that its utcoffset() depends
Serhiy Storchakafd936662018-03-28 23:05:24 +03005323 * on the value of its fold attribute, the result is False.
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005324 *
5325 * Return 1 if exception applies, 0 if not, and -1 on error.
5326 */
5327static int
5328pep495_eq_exception(PyObject *self, PyObject *other,
5329 PyObject *offset_self, PyObject *offset_other)
5330{
5331 int result = 0;
5332 PyObject *flip_offset;
5333
5334 flip_offset = get_flip_fold_offset(self);
5335 if (flip_offset == NULL)
5336 return -1;
5337 if (flip_offset != offset_self &&
5338 delta_cmp(flip_offset, offset_self))
5339 {
5340 result = 1;
5341 goto done;
5342 }
5343 Py_DECREF(flip_offset);
5344
5345 flip_offset = get_flip_fold_offset(other);
5346 if (flip_offset == NULL)
5347 return -1;
5348 if (flip_offset != offset_other &&
5349 delta_cmp(flip_offset, offset_other))
5350 result = 1;
5351 done:
5352 Py_DECREF(flip_offset);
5353 return result;
5354}
5355
5356static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00005357datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00005358{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005359 PyObject *result = NULL;
5360 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00005362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 if (! PyDateTime_Check(other)) {
5364 if (PyDate_Check(other)) {
5365 /* Prevent invocation of date_richcompare. We want to
5366 return NotImplemented here to give the other object
5367 a chance. But since DateTime is a subclass of
5368 Date, if the other object is a Date, it would
5369 compute an ordering based on the date part alone,
5370 and we don't want that. So force unequal or
5371 uncomparable here in that case. */
5372 if (op == Py_EQ)
5373 Py_RETURN_FALSE;
5374 if (op == Py_NE)
5375 Py_RETURN_TRUE;
5376 return cmperror(self, other);
5377 }
Brian Curtindfc80e32011-08-10 20:28:54 -05005378 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 }
Tim Petersa9bc1682003-01-11 03:39:11 +00005380
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005381 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 diff = memcmp(((PyDateTime_DateTime *)self)->data,
5383 ((PyDateTime_DateTime *)other)->data,
5384 _PyDateTime_DATETIME_DATASIZE);
5385 return diff_to_bool(diff, op);
5386 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005387 offset1 = datetime_utcoffset(self, NULL);
5388 if (offset1 == NULL)
5389 return NULL;
5390 offset2 = datetime_utcoffset(other, NULL);
5391 if (offset2 == NULL)
5392 goto done;
5393 /* If they're both naive, or both aware and have the same offsets,
5394 * we get off cheap. Note that if they're both naive, offset1 ==
5395 * offset2 == Py_None at this point.
5396 */
5397 if ((offset1 == offset2) ||
5398 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
5399 delta_cmp(offset1, offset2) == 0)) {
5400 diff = memcmp(((PyDateTime_DateTime *)self)->data,
5401 ((PyDateTime_DateTime *)other)->data,
5402 _PyDateTime_DATETIME_DATASIZE);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005403 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
5404 int ex = pep495_eq_exception(self, other, offset1, offset2);
5405 if (ex == -1)
5406 goto done;
5407 if (ex)
5408 diff = 1;
5409 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005410 result = diff_to_bool(diff, op);
5411 }
5412 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00005414
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005415 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005416 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
5417 other);
5418 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005419 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 diff = GET_TD_DAYS(delta);
5421 if (diff == 0)
5422 diff = GET_TD_SECONDS(delta) |
5423 GET_TD_MICROSECONDS(delta);
5424 Py_DECREF(delta);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005425 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
5426 int ex = pep495_eq_exception(self, other, offset1, offset2);
5427 if (ex == -1)
5428 goto done;
5429 if (ex)
5430 diff = 1;
5431 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005432 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04005434 else if (op == Py_EQ) {
5435 result = Py_False;
5436 Py_INCREF(result);
5437 }
5438 else if (op == Py_NE) {
5439 result = Py_True;
5440 Py_INCREF(result);
5441 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005442 else {
5443 PyErr_SetString(PyExc_TypeError,
5444 "can't compare offset-naive and "
5445 "offset-aware datetimes");
5446 }
5447 done:
5448 Py_DECREF(offset1);
5449 Py_XDECREF(offset2);
5450 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00005451}
5452
Benjamin Peterson8f67d082010-10-17 20:54:53 +00005453static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00005454datetime_hash(PyDateTime_DateTime *self)
5455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005457 PyObject *offset, *self0;
5458 if (DATE_GET_FOLD(self)) {
5459 self0 = new_datetime_ex2(GET_YEAR(self),
5460 GET_MONTH(self),
5461 GET_DAY(self),
5462 DATE_GET_HOUR(self),
5463 DATE_GET_MINUTE(self),
5464 DATE_GET_SECOND(self),
5465 DATE_GET_MICROSECOND(self),
5466 HASTZINFO(self) ? self->tzinfo : Py_None,
5467 0, Py_TYPE(self));
5468 if (self0 == NULL)
5469 return -1;
5470 }
5471 else {
5472 self0 = (PyObject *)self;
5473 Py_INCREF(self0);
5474 }
5475 offset = datetime_utcoffset(self0, NULL);
5476 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005477
5478 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00005480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005482 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 self->hashcode = generic_hash(
5484 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005485 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005486 PyObject *temp1, *temp2;
5487 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00005488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 assert(HASTZINFO(self));
5490 days = ymd_to_ord(GET_YEAR(self),
5491 GET_MONTH(self),
5492 GET_DAY(self));
5493 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005494 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005496 temp1 = new_delta(days, seconds,
5497 DATE_GET_MICROSECOND(self),
5498 1);
5499 if (temp1 == NULL) {
5500 Py_DECREF(offset);
5501 return -1;
5502 }
5503 temp2 = delta_subtract(temp1, offset);
5504 Py_DECREF(temp1);
5505 if (temp2 == NULL) {
5506 Py_DECREF(offset);
5507 return -1;
5508 }
5509 self->hashcode = PyObject_Hash(temp2);
5510 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005512 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 }
5514 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00005515}
Tim Peters2a799bf2002-12-16 20:18:38 +00005516
5517static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005518datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00005519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 PyObject *clone;
5521 PyObject *tuple;
5522 int y = GET_YEAR(self);
5523 int m = GET_MONTH(self);
5524 int d = GET_DAY(self);
5525 int hh = DATE_GET_HOUR(self);
5526 int mm = DATE_GET_MINUTE(self);
5527 int ss = DATE_GET_SECOND(self);
5528 int us = DATE_GET_MICROSECOND(self);
5529 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005530 int fold = DATE_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00005531
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005532 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 datetime_kws,
5534 &y, &m, &d, &hh, &mm, &ss, &us,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005535 &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03005537 if (fold != 0 && fold != 1) {
5538 PyErr_SetString(PyExc_ValueError,
5539 "fold must be either 0 or 1");
5540 return NULL;
5541 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
5543 if (tuple == NULL)
5544 return NULL;
5545 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005546 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005547 DATE_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005548 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 Py_DECREF(tuple);
5550 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00005551}
5552
5553static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005554local_timezone_from_timestamp(time_t timestamp)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005555{
5556 PyObject *result = NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005557 PyObject *delta;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005558 struct tm local_time_tm;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005559 PyObject *nameo = NULL;
5560 const char *zone = NULL;
5561
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005562 if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005563 return NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005564#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005565 zone = local_time_tm.tm_zone;
5566 delta = new_delta(0, local_time_tm.tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005567#else /* HAVE_STRUCT_TM_TM_ZONE */
5568 {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005569 PyObject *local_time, *utc_time;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005570 struct tm utc_time_tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005571 char buf[100];
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005572 strftime(buf, sizeof(buf), "%Z", &local_time_tm);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005573 zone = buf;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005574 local_time = new_datetime(local_time_tm.tm_year + 1900,
5575 local_time_tm.tm_mon + 1,
5576 local_time_tm.tm_mday,
5577 local_time_tm.tm_hour,
5578 local_time_tm.tm_min,
5579 local_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005580 if (local_time == NULL) {
5581 return NULL;
5582 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005583 if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005584 return NULL;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005585 utc_time = new_datetime(utc_time_tm.tm_year + 1900,
5586 utc_time_tm.tm_mon + 1,
5587 utc_time_tm.tm_mday,
5588 utc_time_tm.tm_hour,
5589 utc_time_tm.tm_min,
5590 utc_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005591 if (utc_time == NULL) {
5592 Py_DECREF(local_time);
5593 return NULL;
5594 }
5595 delta = datetime_subtract(local_time, utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005596 Py_DECREF(local_time);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005597 Py_DECREF(utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005598 }
5599#endif /* HAVE_STRUCT_TM_TM_ZONE */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005600 if (delta == NULL) {
5601 return NULL;
5602 }
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005603 if (zone != NULL) {
5604 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
5605 if (nameo == NULL)
5606 goto error;
5607 }
5608 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02005609 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005610 error:
5611 Py_DECREF(delta);
5612 return result;
5613}
5614
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005615static PyObject *
5616local_timezone(PyDateTime_DateTime *utc_time)
5617{
5618 time_t timestamp;
5619 PyObject *delta;
5620 PyObject *one_second;
5621 PyObject *seconds;
5622
5623 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
5624 if (delta == NULL)
5625 return NULL;
5626 one_second = new_delta(0, 1, 0, 0);
5627 if (one_second == NULL) {
5628 Py_DECREF(delta);
5629 return NULL;
5630 }
5631 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
5632 (PyDateTime_Delta *)one_second);
5633 Py_DECREF(one_second);
5634 Py_DECREF(delta);
5635 if (seconds == NULL)
5636 return NULL;
5637 timestamp = _PyLong_AsTime_t(seconds);
5638 Py_DECREF(seconds);
5639 if (timestamp == -1 && PyErr_Occurred())
5640 return NULL;
5641 return local_timezone_from_timestamp(timestamp);
5642}
5643
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005644static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005645local_to_seconds(int year, int month, int day,
5646 int hour, int minute, int second, int fold);
5647
5648static PyObject *
5649local_timezone_from_local(PyDateTime_DateTime *local_dt)
5650{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005651 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005652 time_t timestamp;
5653 seconds = local_to_seconds(GET_YEAR(local_dt),
5654 GET_MONTH(local_dt),
5655 GET_DAY(local_dt),
5656 DATE_GET_HOUR(local_dt),
5657 DATE_GET_MINUTE(local_dt),
5658 DATE_GET_SECOND(local_dt),
5659 DATE_GET_FOLD(local_dt));
5660 if (seconds == -1)
5661 return NULL;
5662 /* XXX: add bounds check */
5663 timestamp = seconds - epoch;
5664 return local_timezone_from_timestamp(timestamp);
5665}
5666
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005667static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00005668datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00005669{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005670 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005671 PyObject *offset;
5672 PyObject *temp;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005673 PyObject *self_tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005674 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00005676
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005677 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07005678 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005679 return NULL;
5680
5681 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00005683
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005684 if (!HASTZINFO(self) || self->tzinfo == Py_None) {
Miss Islington (bot)037e9122018-06-10 15:02:24 -07005685 naive:
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005686 self_tzinfo = local_timezone_from_local(self);
5687 if (self_tzinfo == NULL)
5688 return NULL;
5689 } else {
5690 self_tzinfo = self->tzinfo;
5691 Py_INCREF(self_tzinfo);
5692 }
Tim Peters521fc152002-12-31 17:36:56 +00005693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 /* Conversion to self's own time zone is a NOP. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005695 if (self_tzinfo == tzinfo) {
5696 Py_DECREF(self_tzinfo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005698 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 }
Tim Peters521fc152002-12-31 17:36:56 +00005700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 /* Convert self to UTC. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005702 offset = call_utcoffset(self_tzinfo, (PyObject *)self);
5703 Py_DECREF(self_tzinfo);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005704 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 return NULL;
Miss Islington (bot)037e9122018-06-10 15:02:24 -07005706 else if(offset == Py_None) {
5707 Py_DECREF(offset);
5708 goto naive;
5709 }
5710 else if (!PyDelta_Check(offset)) {
5711 Py_DECREF(offset);
5712 PyErr_Format(PyExc_TypeError, "utcoffset() returned %.200s,"
5713 " expected timedelta or None", Py_TYPE(offset)->tp_name);
5714 return NULL;
5715 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005716 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005717 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5718 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005719 Py_DECREF(offset);
5720 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00005722
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005723 /* Make sure result is aware and UTC. */
5724 if (!HASTZINFO(result)) {
5725 temp = (PyObject *)result;
5726 result = (PyDateTime_DateTime *)
5727 new_datetime_ex2(GET_YEAR(result),
5728 GET_MONTH(result),
5729 GET_DAY(result),
5730 DATE_GET_HOUR(result),
5731 DATE_GET_MINUTE(result),
5732 DATE_GET_SECOND(result),
5733 DATE_GET_MICROSECOND(result),
5734 PyDateTime_TimeZone_UTC,
5735 DATE_GET_FOLD(result),
5736 Py_TYPE(result));
5737 Py_DECREF(temp);
5738 if (result == NULL)
5739 return NULL;
5740 }
5741 else {
5742 /* Result is already aware - just replace tzinfo. */
5743 temp = result->tzinfo;
5744 result->tzinfo = PyDateTime_TimeZone_UTC;
5745 Py_INCREF(result->tzinfo);
5746 Py_DECREF(temp);
5747 }
5748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005750 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005751 if (tzinfo == Py_None) {
5752 tzinfo = local_timezone(result);
5753 if (tzinfo == NULL) {
5754 Py_DECREF(result);
5755 return NULL;
5756 }
5757 }
5758 else
5759 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005760 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005761 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00005762
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005763 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005764 result = (PyDateTime_DateTime *)
Victor Stinner20401de2016-12-09 15:24:31 +01005765 _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_fromutc, temp, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005766 Py_DECREF(temp);
5767
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005768 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00005769}
5770
5771static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005772datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00005775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005777 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00005778
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005779 dst = call_dst(self->tzinfo, (PyObject *)self);
5780 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005782
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005783 if (dst != Py_None)
5784 dstflag = delta_bool((PyDateTime_Delta *)dst);
5785 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005786 }
5787 return build_struct_time(GET_YEAR(self),
5788 GET_MONTH(self),
5789 GET_DAY(self),
5790 DATE_GET_HOUR(self),
5791 DATE_GET_MINUTE(self),
5792 DATE_GET_SECOND(self),
5793 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00005794}
5795
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005796static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005797local_to_seconds(int year, int month, int day,
5798 int hour, int minute, int second, int fold)
5799{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005800 long long t, a, b, u1, u2, t1, t2, lt;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005801 t = utc_to_seconds(year, month, day, hour, minute, second);
5802 /* Our goal is to solve t = local(u) for u. */
5803 lt = local(t);
5804 if (lt == -1)
5805 return -1;
5806 a = lt - t;
5807 u1 = t - a;
5808 t1 = local(u1);
5809 if (t1 == -1)
5810 return -1;
5811 if (t1 == t) {
5812 /* We found one solution, but it may not be the one we need.
5813 * Look for an earlier solution (if `fold` is 0), or a
5814 * later one (if `fold` is 1). */
5815 if (fold)
5816 u2 = u1 + max_fold_seconds;
5817 else
5818 u2 = u1 - max_fold_seconds;
5819 lt = local(u2);
5820 if (lt == -1)
5821 return -1;
5822 b = lt - u2;
5823 if (a == b)
5824 return u1;
5825 }
5826 else {
5827 b = t1 - u1;
5828 assert(a != b);
5829 }
5830 u2 = t - b;
5831 t2 = local(u2);
5832 if (t2 == -1)
5833 return -1;
5834 if (t2 == t)
5835 return u2;
5836 if (t1 == t)
5837 return u1;
5838 /* We have found both offsets a and b, but neither t - a nor t - b is
5839 * a solution. This means t is in the gap. */
5840 return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
5841}
5842
5843/* date(1970,1,1).toordinal() == 719163 */
5844#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
5845
Tim Peters2a799bf2002-12-16 20:18:38 +00005846static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04005847datetime_timestamp(PyDateTime_DateTime *self)
5848{
5849 PyObject *result;
5850
5851 if (HASTZINFO(self) && self->tzinfo != Py_None) {
5852 PyObject *delta;
5853 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
5854 if (delta == NULL)
5855 return NULL;
5856 result = delta_total_seconds(delta);
5857 Py_DECREF(delta);
5858 }
5859 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005860 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005861 seconds = local_to_seconds(GET_YEAR(self),
5862 GET_MONTH(self),
5863 GET_DAY(self),
5864 DATE_GET_HOUR(self),
5865 DATE_GET_MINUTE(self),
5866 DATE_GET_SECOND(self),
5867 DATE_GET_FOLD(self));
5868 if (seconds == -1)
Alexander Belopolskya4415142012-06-08 12:33:09 -04005869 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005870 result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
5871 DATE_GET_MICROSECOND(self) / 1e6);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005872 }
5873 return result;
5874}
5875
5876static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005877datetime_getdate(PyDateTime_DateTime *self)
5878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005879 return new_date(GET_YEAR(self),
5880 GET_MONTH(self),
5881 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005882}
5883
5884static PyObject *
5885datetime_gettime(PyDateTime_DateTime *self)
5886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005887 return new_time(DATE_GET_HOUR(self),
5888 DATE_GET_MINUTE(self),
5889 DATE_GET_SECOND(self),
5890 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005891 Py_None,
5892 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005893}
5894
5895static PyObject *
5896datetime_gettimetz(PyDateTime_DateTime *self)
5897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 return new_time(DATE_GET_HOUR(self),
5899 DATE_GET_MINUTE(self),
5900 DATE_GET_SECOND(self),
5901 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005902 GET_DT_TZINFO(self),
5903 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005904}
5905
5906static PyObject *
5907datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005908{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005909 int y, m, d, hh, mm, ss;
5910 PyObject *tzinfo;
5911 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00005912
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005913 tzinfo = GET_DT_TZINFO(self);
5914 if (tzinfo == Py_None) {
5915 utcself = self;
5916 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005918 else {
5919 PyObject *offset;
5920 offset = call_utcoffset(tzinfo, (PyObject *)self);
5921 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00005922 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005923 if (offset == Py_None) {
5924 Py_DECREF(offset);
5925 utcself = self;
5926 Py_INCREF(utcself);
5927 }
5928 else {
5929 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5930 (PyDateTime_Delta *)offset, -1);
5931 Py_DECREF(offset);
5932 if (utcself == NULL)
5933 return NULL;
5934 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005936 y = GET_YEAR(utcself);
5937 m = GET_MONTH(utcself);
5938 d = GET_DAY(utcself);
5939 hh = DATE_GET_HOUR(utcself);
5940 mm = DATE_GET_MINUTE(utcself);
5941 ss = DATE_GET_SECOND(utcself);
5942
5943 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005944 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005945}
5946
Tim Peters371935f2003-02-01 01:52:50 +00005947/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00005948
Tim Petersa9bc1682003-01-11 03:39:11 +00005949/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00005950 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5951 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00005952 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00005953 */
5954static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005955datetime_getstate(PyDateTime_DateTime *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00005956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 PyObject *basestate;
5958 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 basestate = PyBytes_FromStringAndSize((char *)self->data,
5961 _PyDateTime_DATETIME_DATASIZE);
5962 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005963 if (proto > 3 && DATE_GET_FOLD(self))
5964 /* Set the first bit of the third byte */
5965 PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005966 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5967 result = PyTuple_Pack(1, basestate);
5968 else
5969 result = PyTuple_Pack(2, basestate, self->tzinfo);
5970 Py_DECREF(basestate);
5971 }
5972 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005973}
5974
5975static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005976datetime_reduce_ex(PyDateTime_DateTime *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00005977{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005978 int proto;
5979 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005980 return NULL;
5981
5982 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00005983}
5984
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005985static PyObject *
5986datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
5987{
5988 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, 2));
5989}
5990
Tim Petersa9bc1682003-01-11 03:39:11 +00005991static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005994
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005995 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005997 {"utcnow", (PyCFunction)datetime_utcnow,
5998 METH_NOARGS | METH_CLASS,
5999 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006001 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
6002 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
6003 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006005 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
6006 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05006007 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006009 {"strptime", (PyCFunction)datetime_strptime,
6010 METH_VARARGS | METH_CLASS,
6011 PyDoc_STR("string, format -> new datetime parsed from a string "
6012 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00006013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 {"combine", (PyCFunction)datetime_combine,
6015 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
6016 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006017
Paul Ganssle09dc2f52017-12-21 00:33:49 -05006018 {"fromisoformat", (PyCFunction)datetime_fromisoformat,
6019 METH_O | METH_CLASS,
6020 PyDoc_STR("string -> datetime from datetime.isoformat() output")},
6021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006022 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00006023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006024 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
6025 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006027 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
6028 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006030 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
6031 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006033 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
6034 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00006035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006036 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
6037 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006038
Alexander Belopolskya4415142012-06-08 12:33:09 -04006039 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
6040 PyDoc_STR("Return POSIX timestamp as float.")},
6041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006042 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
6043 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006045 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
6046 PyDoc_STR("[sep] -> string in ISO 8601 format, "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05006047 "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006048 "sep is used to separate the year from the time, and "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05006049 "defaults to 'T'.\n"
6050 "timespec specifies what components of the time to include"
6051 " (allowed values are 'auto', 'hours', 'minutes', 'seconds',"
6052 " 'milliseconds', and 'microseconds').\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006054 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
6055 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006057 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
6058 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006060 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
6061 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00006062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006063 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
6064 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00006065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006066 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
6067 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00006068
Serhiy Storchaka546ce652016-11-22 00:29:42 +02006069 {"__reduce_ex__", (PyCFunction)datetime_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006070 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00006071
Serhiy Storchaka546ce652016-11-22 00:29:42 +02006072 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
6073 PyDoc_STR("__reduce__() -> (cls, state)")},
6074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006075 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00006076};
6077
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006078static const char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00006079PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
6080\n\
6081The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03006082instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00006083
Tim Petersa9bc1682003-01-11 03:39:11 +00006084static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006085 datetime_add, /* nb_add */
6086 datetime_subtract, /* nb_subtract */
6087 0, /* nb_multiply */
6088 0, /* nb_remainder */
6089 0, /* nb_divmod */
6090 0, /* nb_power */
6091 0, /* nb_negative */
6092 0, /* nb_positive */
6093 0, /* nb_absolute */
6094 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00006095};
6096
Neal Norwitz227b5332006-03-22 09:28:35 +00006097static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006098 PyVarObject_HEAD_INIT(NULL, 0)
6099 "datetime.datetime", /* tp_name */
6100 sizeof(PyDateTime_DateTime), /* tp_basicsize */
6101 0, /* tp_itemsize */
6102 (destructor)datetime_dealloc, /* tp_dealloc */
6103 0, /* tp_print */
6104 0, /* tp_getattr */
6105 0, /* tp_setattr */
6106 0, /* tp_reserved */
6107 (reprfunc)datetime_repr, /* tp_repr */
6108 &datetime_as_number, /* tp_as_number */
6109 0, /* tp_as_sequence */
6110 0, /* tp_as_mapping */
6111 (hashfunc)datetime_hash, /* tp_hash */
6112 0, /* tp_call */
6113 (reprfunc)datetime_str, /* tp_str */
6114 PyObject_GenericGetAttr, /* tp_getattro */
6115 0, /* tp_setattro */
6116 0, /* tp_as_buffer */
6117 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
6118 datetime_doc, /* tp_doc */
6119 0, /* tp_traverse */
6120 0, /* tp_clear */
6121 datetime_richcompare, /* tp_richcompare */
6122 0, /* tp_weaklistoffset */
6123 0, /* tp_iter */
6124 0, /* tp_iternext */
6125 datetime_methods, /* tp_methods */
6126 0, /* tp_members */
6127 datetime_getset, /* tp_getset */
6128 &PyDateTime_DateType, /* tp_base */
6129 0, /* tp_dict */
6130 0, /* tp_descr_get */
6131 0, /* tp_descr_set */
6132 0, /* tp_dictoffset */
6133 0, /* tp_init */
6134 datetime_alloc, /* tp_alloc */
6135 datetime_new, /* tp_new */
6136 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00006137};
6138
6139/* ---------------------------------------------------------------------------
6140 * Module methods and initialization.
6141 */
6142
6143static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006144 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00006145};
6146
Tim Peters9ddf40b2004-06-20 22:41:32 +00006147/* C API. Clients get at this via PyDateTime_IMPORT, defined in
6148 * datetime.h.
6149 */
6150static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006151 &PyDateTime_DateType,
6152 &PyDateTime_DateTimeType,
6153 &PyDateTime_TimeType,
6154 &PyDateTime_DeltaType,
6155 &PyDateTime_TZInfoType,
Paul Ganssle04af5b12018-01-24 17:29:30 -05006156 NULL, // PyDatetime_TimeZone_UTC not initialized yet
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006157 new_date_ex,
6158 new_datetime_ex,
6159 new_time_ex,
6160 new_delta_ex,
Paul Ganssle04af5b12018-01-24 17:29:30 -05006161 new_timezone,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006162 datetime_fromtimestamp,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006163 date_fromtimestamp,
6164 new_datetime_ex2,
6165 new_time_ex2
Tim Peters9ddf40b2004-06-20 22:41:32 +00006166};
6167
6168
Martin v. Löwis1a214512008-06-11 05:26:20 +00006169
6170static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006171 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00006172 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006173 "Fast implementation of the datetime type.",
6174 -1,
6175 module_methods,
6176 NULL,
6177 NULL,
6178 NULL,
6179 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00006180};
6181
Tim Peters2a799bf2002-12-16 20:18:38 +00006182PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00006183PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00006184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006185 PyObject *m; /* a module object */
6186 PyObject *d; /* its dict */
6187 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006188 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00006189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006190 m = PyModule_Create(&datetimemodule);
6191 if (m == NULL)
6192 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00006193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006194 if (PyType_Ready(&PyDateTime_DateType) < 0)
6195 return NULL;
6196 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
6197 return NULL;
6198 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
6199 return NULL;
6200 if (PyType_Ready(&PyDateTime_TimeType) < 0)
6201 return NULL;
6202 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
6203 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006204 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
6205 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00006206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006207 /* timedelta values */
6208 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00006209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006210 x = new_delta(0, 0, 1, 0);
6211 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
6212 return NULL;
6213 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006215 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
6216 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6217 return NULL;
6218 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006220 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
6221 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6222 return NULL;
6223 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006225 /* date values */
6226 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00006227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006228 x = new_date(1, 1, 1);
6229 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6230 return NULL;
6231 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006233 x = new_date(MAXYEAR, 12, 31);
6234 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6235 return NULL;
6236 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006238 x = new_delta(1, 0, 0, 0);
6239 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
6240 return NULL;
6241 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006243 /* time values */
6244 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00006245
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006246 x = new_time(0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006247 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6248 return NULL;
6249 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006250
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006251 x = new_time(23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006252 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6253 return NULL;
6254 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006256 x = new_delta(0, 0, 1, 0);
6257 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
6258 return NULL;
6259 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006261 /* datetime values */
6262 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00006263
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006264 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006265 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6266 return NULL;
6267 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006268
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006269 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006270 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6271 return NULL;
6272 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006274 x = new_delta(0, 0, 1, 0);
6275 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
6276 return NULL;
6277 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00006278
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006279 /* timezone values */
6280 d = PyDateTime_TimeZoneType.tp_dict;
6281
6282 delta = new_delta(0, 0, 0, 0);
6283 if (delta == NULL)
6284 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00006285 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006286 Py_DECREF(delta);
6287 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
6288 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00006289 PyDateTime_TimeZone_UTC = x;
Paul Ganssle04af5b12018-01-24 17:29:30 -05006290 CAPI.TimeZone_UTC = PyDateTime_TimeZone_UTC;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006291
6292 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
6293 if (delta == NULL)
6294 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00006295 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006296 Py_DECREF(delta);
6297 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
6298 return NULL;
6299 Py_DECREF(x);
6300
6301 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
6302 if (delta == NULL)
6303 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00006304 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006305 Py_DECREF(delta);
6306 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
6307 return NULL;
6308 Py_DECREF(x);
6309
Alexander Belopolskya4415142012-06-08 12:33:09 -04006310 /* Epoch */
6311 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04006312 PyDateTime_TimeZone_UTC, 0);
Alexander Belopolskya4415142012-06-08 12:33:09 -04006313 if (PyDateTime_Epoch == NULL)
6314 return NULL;
6315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006316 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02006317 PyModule_AddIntMacro(m, MINYEAR);
6318 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00006319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006320 Py_INCREF(&PyDateTime_DateType);
6321 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00006322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006323 Py_INCREF(&PyDateTime_DateTimeType);
6324 PyModule_AddObject(m, "datetime",
6325 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00006326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006327 Py_INCREF(&PyDateTime_TimeType);
6328 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00006329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006330 Py_INCREF(&PyDateTime_DeltaType);
6331 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00006332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006333 Py_INCREF(&PyDateTime_TZInfoType);
6334 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00006335
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00006336 Py_INCREF(&PyDateTime_TimeZoneType);
6337 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
6338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006339 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
6340 if (x == NULL)
6341 return NULL;
6342 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00006343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006344 /* A 4-year cycle has an extra leap day over what we'd get from
6345 * pasting together 4 single years.
6346 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02006347 Py_BUILD_ASSERT(DI4Y == 4 * 365 + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006348 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00006349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006350 /* Similarly, a 400-year cycle has an extra leap day over what we'd
6351 * get from pasting together 4 100-year cycles.
6352 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02006353 Py_BUILD_ASSERT(DI400Y == 4 * DI100Y + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006354 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00006355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006356 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
6357 * pasting together 25 4-year cycles.
6358 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02006359 Py_BUILD_ASSERT(DI100Y == 25 * DI4Y - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006360 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00006361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006362 us_per_ms = PyLong_FromLong(1000);
6363 us_per_second = PyLong_FromLong(1000000);
6364 us_per_minute = PyLong_FromLong(60000000);
6365 seconds_per_day = PyLong_FromLong(24 * 3600);
Serhiy Storchakaba85d692017-03-30 09:09:41 +03006366 if (us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006367 us_per_minute == NULL || seconds_per_day == NULL)
6368 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00006369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006370 /* The rest are too big for 32-bit ints, but even
6371 * us_per_week fits in 40 bits, so doubles should be exact.
6372 */
6373 us_per_hour = PyLong_FromDouble(3600000000.0);
6374 us_per_day = PyLong_FromDouble(86400000000.0);
6375 us_per_week = PyLong_FromDouble(604800000000.0);
6376 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
6377 return NULL;
6378 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00006379}
Tim Petersf3615152003-01-01 21:51:37 +00006380
6381/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00006382Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00006383 x.n = x stripped of its timezone -- its naive time.
6384 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006385 return None
Tim Petersf3615152003-01-01 21:51:37 +00006386 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006387 return None
Tim Petersf3615152003-01-01 21:51:37 +00006388 x.s = x's standard offset, x.o - x.d
6389
6390Now some derived rules, where k is a duration (timedelta).
6391
63921. x.o = x.s + x.d
6393 This follows from the definition of x.s.
6394
Tim Petersc5dc4da2003-01-02 17:55:03 +000063952. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00006396 This is actually a requirement, an assumption we need to make about
6397 sane tzinfo classes.
6398
63993. The naive UTC time corresponding to x is x.n - x.o.
6400 This is again a requirement for a sane tzinfo class.
6401
64024. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00006403 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00006404
Tim Petersc5dc4da2003-01-02 17:55:03 +000064055. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00006406 Again follows from how arithmetic is defined.
6407
Tim Peters8bb5ad22003-01-24 02:44:45 +00006408Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00006409(meaning that the various tzinfo methods exist, and don't blow up or return
6410None when called).
6411
Tim Petersa9bc1682003-01-11 03:39:11 +00006412The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00006413x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00006414
6415By #3, we want
6416
Tim Peters8bb5ad22003-01-24 02:44:45 +00006417 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00006418
6419The algorithm starts by attaching tz to x.n, and calling that y. So
6420x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
6421becomes true; in effect, we want to solve [2] for k:
6422
Tim Peters8bb5ad22003-01-24 02:44:45 +00006423 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00006424
6425By #1, this is the same as
6426
Tim Peters8bb5ad22003-01-24 02:44:45 +00006427 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00006428
6429By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
6430Substituting that into [3],
6431
Tim Peters8bb5ad22003-01-24 02:44:45 +00006432 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
6433 k - (y+k).s - (y+k).d = 0; rearranging,
6434 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
6435 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00006436
Tim Peters8bb5ad22003-01-24 02:44:45 +00006437On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
6438approximate k by ignoring the (y+k).d term at first. Note that k can't be
6439very large, since all offset-returning methods return a duration of magnitude
6440less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
6441be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00006442
6443In any case, the new value is
6444
Tim Peters8bb5ad22003-01-24 02:44:45 +00006445 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00006446
Tim Peters8bb5ad22003-01-24 02:44:45 +00006447It's helpful to step back at look at [4] from a higher level: it's simply
6448mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00006449
6450At this point, if
6451
Tim Peters8bb5ad22003-01-24 02:44:45 +00006452 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00006453
6454we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00006455at the start of daylight time. Picture US Eastern for concreteness. The wall
6456time 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 +00006457sense then. The docs ask that an Eastern tzinfo class consider such a time to
6458be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
6459on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00006460the only spelling that makes sense on the local wall clock.
6461
Tim Petersc5dc4da2003-01-02 17:55:03 +00006462In fact, if [5] holds at this point, we do have the standard-time spelling,
6463but that takes a bit of proof. We first prove a stronger result. What's the
6464difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00006465
Tim Peters8bb5ad22003-01-24 02:44:45 +00006466 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00006467
Tim Petersc5dc4da2003-01-02 17:55:03 +00006468Now
6469 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00006470 (y + y.s).n = by #5
6471 y.n + y.s = since y.n = x.n
6472 x.n + y.s = since z and y are have the same tzinfo member,
6473 y.s = z.s by #2
6474 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00006475
Tim Petersc5dc4da2003-01-02 17:55:03 +00006476Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00006477
Tim Petersc5dc4da2003-01-02 17:55:03 +00006478 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00006479 x.n - ((x.n + z.s) - z.o) = expanding
6480 x.n - x.n - z.s + z.o = cancelling
6481 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00006482 z.d
Tim Petersf3615152003-01-01 21:51:37 +00006483
Tim Petersc5dc4da2003-01-02 17:55:03 +00006484So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00006485
Tim Petersc5dc4da2003-01-02 17:55:03 +00006486If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00006487spelling we wanted in the endcase described above. We're done. Contrarily,
6488if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00006489
Tim Petersc5dc4da2003-01-02 17:55:03 +00006490If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
6491add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00006492local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00006493
Tim Petersc5dc4da2003-01-02 17:55:03 +00006494Let
Tim Petersf3615152003-01-01 21:51:37 +00006495
Tim Peters4fede1a2003-01-04 00:26:59 +00006496 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00006497
Tim Peters4fede1a2003-01-04 00:26:59 +00006498and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00006499
Tim Peters8bb5ad22003-01-24 02:44:45 +00006500 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00006501
Tim Peters8bb5ad22003-01-24 02:44:45 +00006502If so, we're done. If not, the tzinfo class is insane, according to the
6503assumptions we've made. This also requires a bit of proof. As before, let's
6504compute the difference between the LHS and RHS of [8] (and skipping some of
6505the justifications for the kinds of substitutions we've done several times
6506already):
Tim Peters4fede1a2003-01-04 00:26:59 +00006507
Tim Peters8bb5ad22003-01-24 02:44:45 +00006508 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006509 x.n - (z.n + diff - z'.o) = replacing diff via [6]
6510 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
6511 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
6512 - z.n + z.n - z.o + z'.o = cancel z.n
6513 - z.o + z'.o = #1 twice
6514 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
6515 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00006516
6517So 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 +00006518we've found the UTC-equivalent so are done. In fact, we stop with [7] and
6519return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00006520
Tim Peters8bb5ad22003-01-24 02:44:45 +00006521How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
6522a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
6523would have to change the result dst() returns: we start in DST, and moving
6524a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00006525
Tim Peters8bb5ad22003-01-24 02:44:45 +00006526There isn't a sane case where this can happen. The closest it gets is at
6527the end of DST, where there's an hour in UTC with no spelling in a hybrid
6528tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
6529that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
6530UTC) because the docs insist on that, but 0:MM is taken as being in daylight
6531time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
6532clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
6533standard time. Since that's what the local clock *does*, we want to map both
6534UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00006535in local time, but so it goes -- it's the way the local clock works.
6536
Tim Peters8bb5ad22003-01-24 02:44:45 +00006537When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
6538so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
6539z' = 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 +00006540(correctly) concludes that z' is not UTC-equivalent to x.
6541
6542Because we know z.d said z was in daylight time (else [5] would have held and
6543we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006544and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00006545return in Eastern, it follows that z'.d must be 0 (which it is in the example,
6546but the reasoning doesn't depend on the example -- it depends on there being
6547two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00006548z' must be in standard time, and is the spelling we want in this case.
6549
6550Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
6551concerned (because it takes z' as being in standard time rather than the
6552daylight time we intend here), but returning it gives the real-life "local
6553clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
6554tz.
6555
6556When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
6557the 1:MM standard time spelling we want.
6558
6559So how can this break? One of the assumptions must be violated. Two
6560possibilities:
6561
65621) [2] effectively says that y.s is invariant across all y belong to a given
6563 time zone. This isn't true if, for political reasons or continental drift,
6564 a region decides to change its base offset from UTC.
6565
65662) There may be versions of "double daylight" time where the tail end of
6567 the analysis gives up a step too early. I haven't thought about that
6568 enough to say.
6569
6570In any case, it's clear that the default fromutc() is strong enough to handle
6571"almost all" time zones: so long as the standard offset is invariant, it
6572doesn't matter if daylight time transition points change from year to year, or
6573if daylight time is skipped in some years; it doesn't matter how large or
6574small dst() may get within its bounds; and it doesn't even matter if some
6575perverse time zone returns a negative dst()). So a breaking case must be
6576pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00006577--------------------------------------------------------------------------- */