blob: 1b68ff3b372c5b5b67389f71837546605b9ac23a [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/* ---------------------------------------------------------------------------
667 * Create various objects, mostly without range checking.
668 */
669
670/* Create a date instance with no range checking. */
671static PyObject *
672new_date_ex(int year, int month, int day, PyTypeObject *type)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000675
Victor Stinnerb67f0962017-02-10 10:34:02 +0100676 if (check_date_args(year, month, day) < 0) {
677 return NULL;
678 }
679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
681 if (self != NULL)
682 set_date_fields(self, year, month, day);
683 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000684}
685
686#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000688
689/* Create a datetime instance with no range checking. */
690static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400691new_datetime_ex2(int year, int month, int day, int hour, int minute,
692 int second, int usecond, PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyDateTime_DateTime *self;
695 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000696
Victor Stinnerb67f0962017-02-10 10:34:02 +0100697 if (check_date_args(year, month, day) < 0) {
698 return NULL;
699 }
700 if (check_time_args(hour, minute, second, usecond, fold) < 0) {
701 return NULL;
702 }
703 if (check_tzinfo_subclass(tzinfo) < 0) {
704 return NULL;
705 }
706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
708 if (self != NULL) {
709 self->hastzinfo = aware;
710 set_date_fields((PyDateTime_Date *)self, year, month, day);
711 DATE_SET_HOUR(self, hour);
712 DATE_SET_MINUTE(self, minute);
713 DATE_SET_SECOND(self, second);
714 DATE_SET_MICROSECOND(self, usecond);
715 if (aware) {
716 Py_INCREF(tzinfo);
717 self->tzinfo = tzinfo;
718 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400719 DATE_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 }
721 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000722}
723
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400724static PyObject *
725new_datetime_ex(int year, int month, int day, int hour, int minute,
726 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
727{
728 return new_datetime_ex2(year, month, day, hour, minute, second, usecond,
729 tzinfo, 0, type);
730}
731
732#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo, fold) \
733 new_datetime_ex2(y, m, d, hh, mm, ss, us, tzinfo, fold, \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000735
736/* Create a time instance with no range checking. */
737static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400738new_time_ex2(int hour, int minute, int second, int usecond,
739 PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyDateTime_Time *self;
742 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000743
Victor Stinnerb67f0962017-02-10 10:34:02 +0100744 if (check_time_args(hour, minute, second, usecond, fold) < 0) {
745 return NULL;
746 }
747 if (check_tzinfo_subclass(tzinfo) < 0) {
748 return NULL;
749 }
750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
752 if (self != NULL) {
753 self->hastzinfo = aware;
754 self->hashcode = -1;
755 TIME_SET_HOUR(self, hour);
756 TIME_SET_MINUTE(self, minute);
757 TIME_SET_SECOND(self, second);
758 TIME_SET_MICROSECOND(self, usecond);
759 if (aware) {
760 Py_INCREF(tzinfo);
761 self->tzinfo = tzinfo;
762 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400763 TIME_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 }
765 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000766}
767
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400768static PyObject *
769new_time_ex(int hour, int minute, int second, int usecond,
770 PyObject *tzinfo, PyTypeObject *type)
771{
772 return new_time_ex2(hour, minute, second, usecond, tzinfo, 0, type);
773}
774
775#define new_time(hh, mm, ss, us, tzinfo, fold) \
776 new_time_ex2(hh, mm, ss, us, tzinfo, fold, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000777
778/* Create a timedelta instance. Normalize the members iff normalize is
779 * true. Passing false is a speed optimization, if you know for sure
780 * that seconds and microseconds are already in their proper ranges. In any
781 * case, raises OverflowError and returns NULL if the normalized days is out
782 * of range).
783 */
784static PyObject *
785new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (normalize)
791 normalize_d_s_us(&days, &seconds, &microseconds);
792 assert(0 <= seconds && seconds < 24*3600);
793 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (check_delta_day_range(days) < 0)
796 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
799 if (self != NULL) {
800 self->hashcode = -1;
801 SET_TD_DAYS(self, days);
802 SET_TD_SECONDS(self, seconds);
803 SET_TD_MICROSECONDS(self, microseconds);
804 }
805 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000806}
807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808#define new_delta(d, s, us, normalize) \
809 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000810
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000811
812typedef struct
813{
814 PyObject_HEAD
815 PyObject *offset;
816 PyObject *name;
817} PyDateTime_TimeZone;
818
Victor Stinner6ced7c42011-03-21 18:15:42 +0100819/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000820static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya4415142012-06-08 12:33:09 -0400821/* The interned Epoch datetime instance */
822static PyObject *PyDateTime_Epoch;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +0000823
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000824/* Create new timezone instance checking offset range. This
825 function does not check the name argument. Caller must assure
826 that offset is a timedelta instance and name is either NULL
827 or a unicode object. */
828static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000829create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000830{
831 PyDateTime_TimeZone *self;
832 PyTypeObject *type = &PyDateTime_TimeZoneType;
833
834 assert(offset != NULL);
835 assert(PyDelta_Check(offset));
836 assert(name == NULL || PyUnicode_Check(name));
837
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000838 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
839 if (self == NULL) {
840 return NULL;
841 }
842 Py_INCREF(offset);
843 self->offset = offset;
844 Py_XINCREF(name);
845 self->name = name;
846 return (PyObject *)self;
847}
848
849static int delta_bool(PyDateTime_Delta *self);
850
851static PyObject *
852new_timezone(PyObject *offset, PyObject *name)
853{
854 assert(offset != NULL);
855 assert(PyDelta_Check(offset));
856 assert(name == NULL || PyUnicode_Check(name));
857
858 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
859 Py_INCREF(PyDateTime_TimeZone_UTC);
860 return PyDateTime_TimeZone_UTC;
861 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000862 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
863 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
864 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
865 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400866 " timedelta(hours=24),"
867 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000868 return NULL;
869 }
870
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000871 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000872}
873
Tim Petersb0c854d2003-05-17 15:57:00 +0000874/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000875 * tzinfo helpers.
876 */
877
Tim Peters855fe882002-12-22 03:43:39 +0000878/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
879 * raise TypeError and return -1.
880 */
881static int
882check_tzinfo_subclass(PyObject *p)
883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (p == Py_None || PyTZInfo_Check(p))
885 return 0;
886 PyErr_Format(PyExc_TypeError,
887 "tzinfo argument must be None or of a tzinfo subclass, "
888 "not type '%s'",
889 Py_TYPE(p)->tp_name);
890 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000891}
892
Tim Peters2a799bf2002-12-16 20:18:38 +0000893/* If self has a tzinfo member, return a BORROWED reference to it. Else
894 * return NULL, which is NOT AN ERROR. There are no error returns here,
895 * and the caller must not decref the result.
896 */
897static PyObject *
898get_tzinfo_member(PyObject *self)
899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (PyDateTime_Check(self) && HASTZINFO(self))
903 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
904 else if (PyTime_Check(self) && HASTZINFO(self))
905 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000908}
909
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000910/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
911 * be an instance of the tzinfo class. If the method returns None, this
912 * returns None. If the method doesn't return None or timedelta, TypeError is
913 * raised and this returns NULL. If it returns a timedelta and the value is
914 * out of range or isn't a whole number of minutes, ValueError is raised and
915 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000916 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000917static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200918call_tzinfo_method(PyObject *tzinfo, const char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000919{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000920 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000923 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000925
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000926 if (tzinfo == Py_None)
927 Py_RETURN_NONE;
928 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
929 if (offset == Py_None || offset == NULL)
930 return offset;
931 if (PyDelta_Check(offset)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000932 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
933 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
934 Py_DECREF(offset);
935 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
936 " strictly between -timedelta(hours=24) and"
937 " timedelta(hours=24).");
938 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 }
940 }
941 else {
942 PyErr_Format(PyExc_TypeError,
943 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000944 "timedelta, not '%.200s'",
945 name, Py_TYPE(offset)->tp_name);
Raymond Hettinger5a2146a2014-07-25 14:59:48 -0700946 Py_DECREF(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000947 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000949
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000950 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000951}
952
953/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
954 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
955 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000956 * doesn't return None or timedelta, TypeError is raised and this returns -1.
Alexander Belopolsky018d3532017-07-31 10:26:50 -0400957 * If utcoffset() returns an out of range timedelta,
958 * ValueError is raised and this returns -1. Else *none is
959 * set to 0 and the offset is returned (as timedelta, positive east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000960 */
Tim Peters855fe882002-12-22 03:43:39 +0000961static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000962call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
963{
964 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000965}
966
Tim Peters2a799bf2002-12-16 20:18:38 +0000967/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
968 * result. tzinfo must be an instance of the tzinfo class. If dst()
969 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Alexander Belopolsky018d3532017-07-31 10:26:50 -0400970 * doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000971 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000972 * ValueError is raised and this returns -1. Else *none is set to 0 and
Alexander Belopolsky018d3532017-07-31 10:26:50 -0400973 * the offset is returned (as timedelta, positive east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000974 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000975static PyObject *
976call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000977{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000978 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000979}
980
Tim Petersbad8ff02002-12-30 20:52:32 +0000981/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000982 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000983 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000984 * returns NULL. If the result is a string, we ensure it is a Unicode
985 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000986 */
987static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000988call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200991 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 assert(tzinfo != NULL);
994 assert(check_tzinfo_subclass(tzinfo) >= 0);
995 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000998 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +0000999
Victor Stinner20401de2016-12-09 15:24:31 +01001000 result = _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_tzname,
1001 tzinfoarg, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001002
1003 if (result == NULL || result == Py_None)
1004 return result;
1005
1006 if (!PyUnicode_Check(result)) {
1007 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
1008 "return None or a string, not '%s'",
1009 Py_TYPE(result)->tp_name);
1010 Py_DECREF(result);
1011 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001013
1014 return result;
Tim Peters00237032002-12-27 02:21:51 +00001015}
1016
Tim Peters2a799bf2002-12-16 20:18:38 +00001017/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1018 * stuff
1019 * ", tzinfo=" + repr(tzinfo)
1020 * before the closing ")".
1021 */
1022static PyObject *
1023append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 assert(PyUnicode_Check(repr));
1028 assert(tzinfo);
1029 if (tzinfo == Py_None)
1030 return repr;
1031 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001032 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1033 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 Py_DECREF(repr);
1035 if (temp == NULL)
1036 return NULL;
1037 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1038 Py_DECREF(temp);
1039 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001040}
1041
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001042/* repr is like "someclass(arg1, arg2)". If fold isn't 0,
1043 * stuff
1044 * ", fold=" + repr(tzinfo)
1045 * before the closing ")".
1046 */
1047static PyObject *
1048append_keyword_fold(PyObject *repr, int fold)
1049{
1050 PyObject *temp;
1051
1052 assert(PyUnicode_Check(repr));
1053 if (fold == 0)
1054 return repr;
1055 /* Get rid of the trailing ')'. */
1056 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1057 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
1058 Py_DECREF(repr);
1059 if (temp == NULL)
1060 return NULL;
1061 repr = PyUnicode_FromFormat("%U, fold=%d)", temp, fold);
1062 Py_DECREF(temp);
1063 return repr;
1064}
1065
Tim Peters2a799bf2002-12-16 20:18:38 +00001066/* ---------------------------------------------------------------------------
1067 * String format helpers.
1068 */
1069
1070static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001071format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001072{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001073 static const char * const DayNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1075 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001076 static const char * const MonthNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1078 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1079 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1084 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1085 GET_DAY(date), hours, minutes, seconds,
1086 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001087}
1088
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001089static PyObject *delta_negative(PyDateTime_Delta *self);
1090
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001091/* Add formatted UTC offset string to buf. buf has no more than
Tim Peters2a799bf2002-12-16 20:18:38 +00001092 * buflen bytes remaining. The UTC offset is gotten by calling
1093 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1094 * *buf, and that's all. Else the returned value is checked for sanity (an
1095 * integer in range), and if that's OK it's converted to an hours & minutes
1096 * string of the form
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001097 * sign HH sep MM [sep SS [. UUUUUU]]
Tim Peters2a799bf2002-12-16 20:18:38 +00001098 * Returns 0 if everything is OK. If the return value from utcoffset() is
1099 * bogus, an appropriate exception is set and -1 is returned.
1100 */
1101static int
Tim Peters328fff72002-12-20 01:31:27 +00001102format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001104{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001105 PyObject *offset;
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001106 int hours, minutes, seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001110
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001111 offset = call_utcoffset(tzinfo, tzinfoarg);
1112 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001114 if (offset == Py_None) {
1115 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 *buf = '\0';
1117 return 0;
1118 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001119 /* Offset is normalized, so it is negative if days < 0 */
1120 if (GET_TD_DAYS(offset) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 sign = '-';
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03001122 Py_SETREF(offset, delta_negative((PyDateTime_Delta *)offset));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001123 if (offset == NULL)
1124 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001126 else {
1127 sign = '+';
1128 }
1129 /* Offset is not negative here. */
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001130 microseconds = GET_TD_MICROSECONDS(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001131 seconds = GET_TD_SECONDS(offset);
1132 Py_DECREF(offset);
1133 minutes = divmod(seconds, 60, &seconds);
1134 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001135 if (microseconds) {
1136 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d.%06d", sign,
1137 hours, sep, minutes, sep, seconds, microseconds);
1138 return 0;
1139 }
1140 if (seconds) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001141 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d", sign, hours,
1142 sep, minutes, sep, seconds);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04001143 return 0;
1144 }
1145 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001147}
1148
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001149static PyObject *
1150make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 PyObject *temp;
1153 PyObject *tzinfo = get_tzinfo_member(object);
1154 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001155 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (Zreplacement == NULL)
1158 return NULL;
1159 if (tzinfo == Py_None || tzinfo == NULL)
1160 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 assert(tzinfoarg != NULL);
1163 temp = call_tzname(tzinfo, tzinfoarg);
1164 if (temp == NULL)
1165 goto Error;
1166 if (temp == Py_None) {
1167 Py_DECREF(temp);
1168 return Zreplacement;
1169 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 assert(PyUnicode_Check(temp));
1172 /* Since the tzname is getting stuffed into the
1173 * format, we have to double any % signs so that
1174 * strftime doesn't treat them as format codes.
1175 */
1176 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001177 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 Py_DECREF(temp);
1179 if (Zreplacement == NULL)
1180 return NULL;
1181 if (!PyUnicode_Check(Zreplacement)) {
1182 PyErr_SetString(PyExc_TypeError,
1183 "tzname.replace() did not return a string");
1184 goto Error;
1185 }
1186 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001187
1188 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 Py_DECREF(Zreplacement);
1190 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001191}
1192
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001193static PyObject *
1194make_freplacement(PyObject *object)
1195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 char freplacement[64];
1197 if (PyTime_Check(object))
1198 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1199 else if (PyDateTime_Check(object))
1200 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1201 else
1202 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001205}
1206
Tim Peters2a799bf2002-12-16 20:18:38 +00001207/* I sure don't want to reproduce the strftime code from the time module,
1208 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001209 * giving special meanings to the %z, %Z and %f format codes via a
1210 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001211 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1212 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001213 */
1214static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001215wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1221 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1222 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 const char *pin; /* pointer to next char in input format */
1225 Py_ssize_t flen; /* length of input format */
1226 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 PyObject *newfmt = NULL; /* py string, the output format */
1229 char *pnew; /* pointer to available byte in output format */
1230 size_t totalnew; /* number bytes total in output format buffer,
1231 exclusive of trailing \0 */
1232 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 const char *ptoappend; /* ptr to string to append to output buffer */
1235 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 assert(object && format && timetuple);
1238 assert(PyUnicode_Check(format));
1239 /* Convert the input format to a C string and size */
Serhiy Storchaka06515832016-11-20 09:13:07 +02001240 pin = PyUnicode_AsUTF8AndSize(format, &flen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (!pin)
1242 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 /* Scan the input format, looking for %z/%Z/%f escapes, building
1245 * a new format. Since computing the replacements for those codes
1246 * is expensive, don't unless they're actually used.
1247 */
1248 if (flen > INT_MAX - 1) {
1249 PyErr_NoMemory();
1250 goto Done;
1251 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 totalnew = flen + 1; /* realistic if no %z/%Z */
1254 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1255 if (newfmt == NULL) goto Done;
1256 pnew = PyBytes_AsString(newfmt);
1257 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 while ((ch = *pin++) != '\0') {
1260 if (ch != '%') {
1261 ptoappend = pin - 1;
1262 ntoappend = 1;
1263 }
1264 else if ((ch = *pin++) == '\0') {
1265 /* There's a lone trailing %; doesn't make sense. */
1266 PyErr_SetString(PyExc_ValueError, "strftime format "
1267 "ends with raw %");
1268 goto Done;
1269 }
1270 /* A % has been seen and ch is the character after it. */
1271 else if (ch == 'z') {
1272 if (zreplacement == NULL) {
1273 /* format utcoffset */
1274 char buf[100];
1275 PyObject *tzinfo = get_tzinfo_member(object);
1276 zreplacement = PyBytes_FromStringAndSize("", 0);
1277 if (zreplacement == NULL) goto Done;
1278 if (tzinfo != Py_None && tzinfo != NULL) {
1279 assert(tzinfoarg != NULL);
1280 if (format_utcoffset(buf,
1281 sizeof(buf),
1282 "",
1283 tzinfo,
1284 tzinfoarg) < 0)
1285 goto Done;
1286 Py_DECREF(zreplacement);
1287 zreplacement =
1288 PyBytes_FromStringAndSize(buf,
1289 strlen(buf));
1290 if (zreplacement == NULL)
1291 goto Done;
1292 }
1293 }
1294 assert(zreplacement != NULL);
1295 ptoappend = PyBytes_AS_STRING(zreplacement);
1296 ntoappend = PyBytes_GET_SIZE(zreplacement);
1297 }
1298 else if (ch == 'Z') {
1299 /* format tzname */
1300 if (Zreplacement == NULL) {
1301 Zreplacement = make_Zreplacement(object,
1302 tzinfoarg);
1303 if (Zreplacement == NULL)
1304 goto Done;
1305 }
1306 assert(Zreplacement != NULL);
1307 assert(PyUnicode_Check(Zreplacement));
Serhiy Storchaka06515832016-11-20 09:13:07 +02001308 ptoappend = PyUnicode_AsUTF8AndSize(Zreplacement,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001310 if (ptoappend == NULL)
1311 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 }
1313 else if (ch == 'f') {
1314 /* format microseconds */
1315 if (freplacement == NULL) {
1316 freplacement = make_freplacement(object);
1317 if (freplacement == NULL)
1318 goto Done;
1319 }
1320 assert(freplacement != NULL);
1321 assert(PyBytes_Check(freplacement));
1322 ptoappend = PyBytes_AS_STRING(freplacement);
1323 ntoappend = PyBytes_GET_SIZE(freplacement);
1324 }
1325 else {
1326 /* percent followed by neither z nor Z */
1327 ptoappend = pin - 2;
1328 ntoappend = 2;
1329 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* Append the ntoappend chars starting at ptoappend to
1332 * the new format.
1333 */
1334 if (ntoappend == 0)
1335 continue;
1336 assert(ptoappend != NULL);
1337 assert(ntoappend > 0);
1338 while (usednew + ntoappend > totalnew) {
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001339 if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 PyErr_NoMemory();
1341 goto Done;
1342 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001343 totalnew <<= 1;
1344 if (_PyBytes_Resize(&newfmt, totalnew) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 pnew = PyBytes_AsString(newfmt) + usednew;
1347 }
1348 memcpy(pnew, ptoappend, ntoappend);
1349 pnew += ntoappend;
1350 usednew += ntoappend;
1351 assert(usednew <= totalnew);
1352 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1355 goto Done;
1356 {
1357 PyObject *format;
1358 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (time == NULL)
1361 goto Done;
1362 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1363 if (format != NULL) {
Victor Stinner20401de2016-12-09 15:24:31 +01001364 result = _PyObject_CallMethodIdObjArgs(time, &PyId_strftime,
1365 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 Py_DECREF(format);
1367 }
1368 Py_DECREF(time);
1369 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001370 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 Py_XDECREF(freplacement);
1372 Py_XDECREF(zreplacement);
1373 Py_XDECREF(Zreplacement);
1374 Py_XDECREF(newfmt);
1375 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001376}
1377
Tim Peters2a799bf2002-12-16 20:18:38 +00001378/* ---------------------------------------------------------------------------
1379 * Wrap functions from the time module. These aren't directly available
1380 * from C. Perhaps they should be.
1381 */
1382
1383/* Call time.time() and return its result (a Python float). */
1384static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001385time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyObject *result = NULL;
1388 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001391 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001392
Victor Stinnerad8c83a2016-09-05 17:53:15 -07001393 result = _PyObject_CallMethodId(time, &PyId_time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 Py_DECREF(time);
1395 }
1396 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001397}
1398
1399/* Build a time.struct_time. The weekday and day number are automatically
1400 * computed from the y,m,d args.
1401 */
1402static PyObject *
1403build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyObject *time;
Victor Stinner2b635972016-12-09 00:38:16 +01001406 PyObject *result;
1407 _Py_IDENTIFIER(struct_time);
1408 PyObject *args;
1409
Tim Peters2a799bf2002-12-16 20:18:38 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 time = PyImport_ImportModuleNoBlock("time");
Victor Stinner2b635972016-12-09 00:38:16 +01001412 if (time == NULL) {
1413 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 }
Victor Stinner2b635972016-12-09 00:38:16 +01001415
1416 args = Py_BuildValue("iiiiiiiii",
1417 y, m, d,
1418 hh, mm, ss,
1419 weekday(y, m, d),
1420 days_before_month(y, m) + d,
1421 dstflag);
1422 if (args == NULL) {
1423 Py_DECREF(time);
1424 return NULL;
1425 }
1426
1427 result = _PyObject_CallMethodIdObjArgs(time, &PyId_struct_time,
1428 args, NULL);
1429 Py_DECREF(time);
Victor Stinnerddc120f2016-12-09 15:35:40 +01001430 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001432}
1433
1434/* ---------------------------------------------------------------------------
1435 * Miscellaneous helpers.
1436 */
1437
Mark Dickinsone94c6792009-02-02 20:36:42 +00001438/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001439 * The comparisons here all most naturally compute a cmp()-like result.
1440 * This little helper turns that into a bool result for rich comparisons.
1441 */
1442static PyObject *
1443diff_to_bool(int diff, int op)
1444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyObject *result;
1446 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 switch (op) {
1449 case Py_EQ: istrue = diff == 0; break;
1450 case Py_NE: istrue = diff != 0; break;
1451 case Py_LE: istrue = diff <= 0; break;
1452 case Py_GE: istrue = diff >= 0; break;
1453 case Py_LT: istrue = diff < 0; break;
1454 case Py_GT: istrue = diff > 0; break;
1455 default:
1456 assert(! "op unknown");
1457 istrue = 0; /* To shut up compiler */
1458 }
1459 result = istrue ? Py_True : Py_False;
1460 Py_INCREF(result);
1461 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001462}
1463
Tim Peters07534a62003-02-07 22:50:28 +00001464/* Raises a "can't compare" TypeError and returns NULL. */
1465static PyObject *
1466cmperror(PyObject *a, PyObject *b)
1467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyErr_Format(PyExc_TypeError,
1469 "can't compare %s to %s",
1470 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1471 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001472}
1473
Tim Peters2a799bf2002-12-16 20:18:38 +00001474/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001475 * Cached Python objects; these are set by the module init function.
1476 */
1477
1478/* Conversion factors. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479static PyObject *us_per_ms = NULL; /* 1000 */
1480static PyObject *us_per_second = NULL; /* 1000000 */
1481static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001482static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
1483static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
1484static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
Tim Peters2a799bf2002-12-16 20:18:38 +00001485static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1486
Tim Peters2a799bf2002-12-16 20:18:38 +00001487/* ---------------------------------------------------------------------------
1488 * Class implementations.
1489 */
1490
1491/*
1492 * PyDateTime_Delta implementation.
1493 */
1494
1495/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Serhiy Storchaka95949422013-08-27 19:40:23 +03001497 * as a Python int.
Tim Peters2a799bf2002-12-16 20:18:38 +00001498 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1499 * due to ubiquitous overflow possibilities.
1500 */
1501static PyObject *
1502delta_to_microseconds(PyDateTime_Delta *self)
1503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 PyObject *x1 = NULL;
1505 PyObject *x2 = NULL;
1506 PyObject *x3 = NULL;
1507 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1510 if (x1 == NULL)
1511 goto Done;
1512 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1513 if (x2 == NULL)
1514 goto Done;
1515 Py_DECREF(x1);
1516 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 /* x2 has days in seconds */
1519 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1520 if (x1 == NULL)
1521 goto Done;
1522 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1523 if (x3 == NULL)
1524 goto Done;
1525 Py_DECREF(x1);
1526 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001527 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 /* x3 has days+seconds in seconds */
1530 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1531 if (x1 == NULL)
1532 goto Done;
1533 Py_DECREF(x3);
1534 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 /* x1 has days+seconds in us */
1537 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1538 if (x2 == NULL)
1539 goto Done;
1540 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001541
1542Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 Py_XDECREF(x1);
1544 Py_XDECREF(x2);
1545 Py_XDECREF(x3);
1546 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001547}
1548
Serhiy Storchaka95949422013-08-27 19:40:23 +03001549/* Convert a number of us (as a Python int) to a timedelta.
Tim Peters2a799bf2002-12-16 20:18:38 +00001550 */
1551static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001552microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 int us;
1555 int s;
1556 int d;
1557 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyObject *tuple = NULL;
1560 PyObject *num = NULL;
1561 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 tuple = PyNumber_Divmod(pyus, us_per_second);
1564 if (tuple == NULL)
1565 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 num = PyTuple_GetItem(tuple, 1); /* us */
1568 if (num == NULL)
1569 goto Done;
1570 temp = PyLong_AsLong(num);
1571 num = NULL;
1572 if (temp == -1 && PyErr_Occurred())
1573 goto Done;
1574 assert(0 <= temp && temp < 1000000);
1575 us = (int)temp;
1576 if (us < 0) {
1577 /* The divisor was positive, so this must be an error. */
1578 assert(PyErr_Occurred());
1579 goto Done;
1580 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1583 if (num == NULL)
1584 goto Done;
1585 Py_INCREF(num);
1586 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 tuple = PyNumber_Divmod(num, seconds_per_day);
1589 if (tuple == NULL)
1590 goto Done;
1591 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 num = PyTuple_GetItem(tuple, 1); /* seconds */
1594 if (num == NULL)
1595 goto Done;
1596 temp = PyLong_AsLong(num);
1597 num = NULL;
1598 if (temp == -1 && PyErr_Occurred())
1599 goto Done;
1600 assert(0 <= temp && temp < 24*3600);
1601 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (s < 0) {
1604 /* The divisor was positive, so this must be an error. */
1605 assert(PyErr_Occurred());
1606 goto Done;
1607 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1610 if (num == NULL)
1611 goto Done;
1612 Py_INCREF(num);
1613 temp = PyLong_AsLong(num);
1614 if (temp == -1 && PyErr_Occurred())
1615 goto Done;
1616 d = (int)temp;
1617 if ((long)d != temp) {
1618 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1619 "large to fit in a C int");
1620 goto Done;
1621 }
1622 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001623
1624Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 Py_XDECREF(tuple);
1626 Py_XDECREF(num);
1627 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001628}
1629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630#define microseconds_to_delta(pymicros) \
1631 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001632
Tim Peters2a799bf2002-12-16 20:18:38 +00001633static PyObject *
1634multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 PyObject *pyus_in;
1637 PyObject *pyus_out;
1638 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 pyus_in = delta_to_microseconds(delta);
1641 if (pyus_in == NULL)
1642 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1645 Py_DECREF(pyus_in);
1646 if (pyus_out == NULL)
1647 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 result = microseconds_to_delta(pyus_out);
1650 Py_DECREF(pyus_out);
1651 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001652}
1653
1654static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001655multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1656{
1657 PyObject *result = NULL;
1658 PyObject *pyus_in = NULL, *temp, *pyus_out;
1659 PyObject *ratio = NULL;
1660
1661 pyus_in = delta_to_microseconds(delta);
1662 if (pyus_in == NULL)
1663 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001664 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001665 if (ratio == NULL)
1666 goto error;
1667 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1668 Py_DECREF(pyus_in);
1669 pyus_in = NULL;
1670 if (temp == NULL)
1671 goto error;
1672 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1673 Py_DECREF(temp);
1674 if (pyus_out == NULL)
1675 goto error;
1676 result = microseconds_to_delta(pyus_out);
1677 Py_DECREF(pyus_out);
1678 error:
1679 Py_XDECREF(pyus_in);
1680 Py_XDECREF(ratio);
1681
1682 return result;
1683}
1684
1685static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001686divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyObject *pyus_in;
1689 PyObject *pyus_out;
1690 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 pyus_in = delta_to_microseconds(delta);
1693 if (pyus_in == NULL)
1694 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1697 Py_DECREF(pyus_in);
1698 if (pyus_out == NULL)
1699 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 result = microseconds_to_delta(pyus_out);
1702 Py_DECREF(pyus_out);
1703 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001704}
1705
1706static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001707divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyObject *pyus_left;
1710 PyObject *pyus_right;
1711 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 pyus_left = delta_to_microseconds(left);
1714 if (pyus_left == NULL)
1715 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 pyus_right = delta_to_microseconds(right);
1718 if (pyus_right == NULL) {
1719 Py_DECREF(pyus_left);
1720 return NULL;
1721 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1724 Py_DECREF(pyus_left);
1725 Py_DECREF(pyus_right);
1726 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001727}
1728
1729static PyObject *
1730truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 PyObject *pyus_left;
1733 PyObject *pyus_right;
1734 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 pyus_left = delta_to_microseconds(left);
1737 if (pyus_left == NULL)
1738 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 pyus_right = delta_to_microseconds(right);
1741 if (pyus_right == NULL) {
1742 Py_DECREF(pyus_left);
1743 return NULL;
1744 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1747 Py_DECREF(pyus_left);
1748 Py_DECREF(pyus_right);
1749 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001750}
1751
1752static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001753truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1754{
1755 PyObject *result = NULL;
1756 PyObject *pyus_in = NULL, *temp, *pyus_out;
1757 PyObject *ratio = NULL;
1758
1759 pyus_in = delta_to_microseconds(delta);
1760 if (pyus_in == NULL)
1761 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001762 ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001763 if (ratio == NULL)
1764 goto error;
1765 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1766 Py_DECREF(pyus_in);
1767 pyus_in = NULL;
1768 if (temp == NULL)
1769 goto error;
1770 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1771 Py_DECREF(temp);
1772 if (pyus_out == NULL)
1773 goto error;
1774 result = microseconds_to_delta(pyus_out);
1775 Py_DECREF(pyus_out);
1776 error:
1777 Py_XDECREF(pyus_in);
1778 Py_XDECREF(ratio);
1779
1780 return result;
1781}
1782
1783static PyObject *
1784truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1785{
1786 PyObject *result;
1787 PyObject *pyus_in, *pyus_out;
1788 pyus_in = delta_to_microseconds(delta);
1789 if (pyus_in == NULL)
1790 return NULL;
1791 pyus_out = divide_nearest(pyus_in, i);
1792 Py_DECREF(pyus_in);
1793 if (pyus_out == NULL)
1794 return NULL;
1795 result = microseconds_to_delta(pyus_out);
1796 Py_DECREF(pyus_out);
1797
1798 return result;
1799}
1800
1801static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001802delta_add(PyObject *left, PyObject *right)
1803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1807 /* delta + delta */
1808 /* The C-level additions can't overflow because of the
1809 * invariant bounds.
1810 */
1811 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1812 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1813 int microseconds = GET_TD_MICROSECONDS(left) +
1814 GET_TD_MICROSECONDS(right);
1815 result = new_delta(days, seconds, microseconds, 1);
1816 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (result == Py_NotImplemented)
1819 Py_INCREF(result);
1820 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001821}
1822
1823static PyObject *
1824delta_negative(PyDateTime_Delta *self)
1825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 return new_delta(-GET_TD_DAYS(self),
1827 -GET_TD_SECONDS(self),
1828 -GET_TD_MICROSECONDS(self),
1829 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001830}
1831
1832static PyObject *
1833delta_positive(PyDateTime_Delta *self)
1834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 /* Could optimize this (by returning self) if this isn't a
1836 * subclass -- but who uses unary + ? Approximately nobody.
1837 */
1838 return new_delta(GET_TD_DAYS(self),
1839 GET_TD_SECONDS(self),
1840 GET_TD_MICROSECONDS(self),
1841 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001842}
1843
1844static PyObject *
1845delta_abs(PyDateTime_Delta *self)
1846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 assert(GET_TD_MICROSECONDS(self) >= 0);
1850 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (GET_TD_DAYS(self) < 0)
1853 result = delta_negative(self);
1854 else
1855 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001858}
1859
1860static PyObject *
1861delta_subtract(PyObject *left, PyObject *right)
1862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1866 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04001867 /* The C-level additions can't overflow because of the
1868 * invariant bounds.
1869 */
1870 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1871 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1872 int microseconds = GET_TD_MICROSECONDS(left) -
1873 GET_TD_MICROSECONDS(right);
1874 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (result == Py_NotImplemented)
1878 Py_INCREF(result);
1879 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001880}
1881
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001882static int
1883delta_cmp(PyObject *self, PyObject *other)
1884{
1885 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1886 if (diff == 0) {
1887 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1888 if (diff == 0)
1889 diff = GET_TD_MICROSECONDS(self) -
1890 GET_TD_MICROSECONDS(other);
1891 }
1892 return diff;
1893}
1894
Tim Peters2a799bf2002-12-16 20:18:38 +00001895static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001896delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001899 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 return diff_to_bool(diff, op);
1901 }
1902 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05001903 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001905}
1906
1907static PyObject *delta_getstate(PyDateTime_Delta *self);
1908
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001909static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001910delta_hash(PyDateTime_Delta *self)
1911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 if (self->hashcode == -1) {
1913 PyObject *temp = delta_getstate(self);
1914 if (temp != NULL) {
1915 self->hashcode = PyObject_Hash(temp);
1916 Py_DECREF(temp);
1917 }
1918 }
1919 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001920}
1921
1922static PyObject *
1923delta_multiply(PyObject *left, PyObject *right)
1924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 if (PyDelta_Check(left)) {
1928 /* delta * ??? */
1929 if (PyLong_Check(right))
1930 result = multiply_int_timedelta(right,
1931 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001932 else if (PyFloat_Check(right))
1933 result = multiply_float_timedelta(right,
1934 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 }
1936 else if (PyLong_Check(left))
1937 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001938 (PyDateTime_Delta *) right);
1939 else if (PyFloat_Check(left))
1940 result = multiply_float_timedelta(left,
1941 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 if (result == Py_NotImplemented)
1944 Py_INCREF(result);
1945 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001946}
1947
1948static PyObject *
1949delta_divide(PyObject *left, PyObject *right)
1950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 if (PyDelta_Check(left)) {
1954 /* delta * ??? */
1955 if (PyLong_Check(right))
1956 result = divide_timedelta_int(
1957 (PyDateTime_Delta *)left,
1958 right);
1959 else if (PyDelta_Check(right))
1960 result = divide_timedelta_timedelta(
1961 (PyDateTime_Delta *)left,
1962 (PyDateTime_Delta *)right);
1963 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (result == Py_NotImplemented)
1966 Py_INCREF(result);
1967 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001968}
1969
Mark Dickinson7c186e22010-04-20 22:32:49 +00001970static PyObject *
1971delta_truedivide(PyObject *left, PyObject *right)
1972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 if (PyDelta_Check(left)) {
1976 if (PyDelta_Check(right))
1977 result = truedivide_timedelta_timedelta(
1978 (PyDateTime_Delta *)left,
1979 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001980 else if (PyFloat_Check(right))
1981 result = truedivide_timedelta_float(
1982 (PyDateTime_Delta *)left, right);
1983 else if (PyLong_Check(right))
1984 result = truedivide_timedelta_int(
1985 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (result == Py_NotImplemented)
1989 Py_INCREF(result);
1990 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001991}
1992
1993static PyObject *
1994delta_remainder(PyObject *left, PyObject *right)
1995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 PyObject *pyus_left;
1997 PyObject *pyus_right;
1998 PyObject *pyus_remainder;
1999 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002000
Brian Curtindfc80e32011-08-10 20:28:54 -05002001 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2002 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2005 if (pyus_left == NULL)
2006 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2009 if (pyus_right == NULL) {
2010 Py_DECREF(pyus_left);
2011 return NULL;
2012 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
2015 Py_DECREF(pyus_left);
2016 Py_DECREF(pyus_right);
2017 if (pyus_remainder == NULL)
2018 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 remainder = microseconds_to_delta(pyus_remainder);
2021 Py_DECREF(pyus_remainder);
2022 if (remainder == NULL)
2023 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002026}
2027
2028static PyObject *
2029delta_divmod(PyObject *left, PyObject *right)
2030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 PyObject *pyus_left;
2032 PyObject *pyus_right;
2033 PyObject *divmod;
2034 PyObject *delta;
2035 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002036
Brian Curtindfc80e32011-08-10 20:28:54 -05002037 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2038 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2041 if (pyus_left == NULL)
2042 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2045 if (pyus_right == NULL) {
2046 Py_DECREF(pyus_left);
2047 return NULL;
2048 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 divmod = PyNumber_Divmod(pyus_left, pyus_right);
2051 Py_DECREF(pyus_left);
2052 Py_DECREF(pyus_right);
2053 if (divmod == NULL)
2054 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 assert(PyTuple_Size(divmod) == 2);
2057 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
2058 if (delta == NULL) {
2059 Py_DECREF(divmod);
2060 return NULL;
2061 }
2062 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
2063 Py_DECREF(delta);
2064 Py_DECREF(divmod);
2065 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002066}
2067
Tim Peters2a799bf2002-12-16 20:18:38 +00002068/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2069 * timedelta constructor. sofar is the # of microseconds accounted for
2070 * so far, and there are factor microseconds per current unit, the number
2071 * of which is given by num. num * factor is added to sofar in a
2072 * numerically careful way, and that's the result. Any fractional
2073 * microseconds left over (this can happen if num is a float type) are
2074 * added into *leftover.
2075 * Note that there are many ways this can give an error (NULL) return.
2076 */
2077static PyObject *
2078accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2079 double *leftover)
2080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 PyObject *prod;
2082 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 if (PyLong_Check(num)) {
2087 prod = PyNumber_Multiply(num, factor);
2088 if (prod == NULL)
2089 return NULL;
2090 sum = PyNumber_Add(sofar, prod);
2091 Py_DECREF(prod);
2092 return sum;
2093 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (PyFloat_Check(num)) {
2096 double dnum;
2097 double fracpart;
2098 double intpart;
2099 PyObject *x;
2100 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* The Plan: decompose num into an integer part and a
2103 * fractional part, num = intpart + fracpart.
2104 * Then num * factor ==
2105 * intpart * factor + fracpart * factor
2106 * and the LHS can be computed exactly in long arithmetic.
2107 * The RHS is again broken into an int part and frac part.
2108 * and the frac part is added into *leftover.
2109 */
2110 dnum = PyFloat_AsDouble(num);
2111 if (dnum == -1.0 && PyErr_Occurred())
2112 return NULL;
2113 fracpart = modf(dnum, &intpart);
2114 x = PyLong_FromDouble(intpart);
2115 if (x == NULL)
2116 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 prod = PyNumber_Multiply(x, factor);
2119 Py_DECREF(x);
2120 if (prod == NULL)
2121 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 sum = PyNumber_Add(sofar, prod);
2124 Py_DECREF(prod);
2125 if (sum == NULL)
2126 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (fracpart == 0.0)
2129 return sum;
2130 /* So far we've lost no information. Dealing with the
2131 * fractional part requires float arithmetic, and may
2132 * lose a little info.
2133 */
2134 assert(PyLong_Check(factor));
2135 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 dnum *= fracpart;
2138 fracpart = modf(dnum, &intpart);
2139 x = PyLong_FromDouble(intpart);
2140 if (x == NULL) {
2141 Py_DECREF(sum);
2142 return NULL;
2143 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 y = PyNumber_Add(sum, x);
2146 Py_DECREF(sum);
2147 Py_DECREF(x);
2148 *leftover += fracpart;
2149 return y;
2150 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyErr_Format(PyExc_TypeError,
2153 "unsupported type for timedelta %s component: %s",
2154 tag, Py_TYPE(num)->tp_name);
2155 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002156}
2157
2158static PyObject *
2159delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 /* Argument objects. */
2164 PyObject *day = NULL;
2165 PyObject *second = NULL;
2166 PyObject *us = NULL;
2167 PyObject *ms = NULL;
2168 PyObject *minute = NULL;
2169 PyObject *hour = NULL;
2170 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 PyObject *x = NULL; /* running sum of microseconds */
2173 PyObject *y = NULL; /* temp sum of microseconds */
2174 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 static char *keywords[] = {
2177 "days", "seconds", "microseconds", "milliseconds",
2178 "minutes", "hours", "weeks", NULL
2179 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2182 keywords,
2183 &day, &second, &us,
2184 &ms, &minute, &hour, &week) == 0)
2185 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 x = PyLong_FromLong(0);
2188 if (x == NULL)
2189 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191#define CLEANUP \
2192 Py_DECREF(x); \
2193 x = y; \
2194 if (x == NULL) \
2195 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (us) {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002198 y = accum("microseconds", x, us, _PyLong_One, &leftover_us);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 CLEANUP;
2200 }
2201 if (ms) {
2202 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2203 CLEANUP;
2204 }
2205 if (second) {
2206 y = accum("seconds", x, second, us_per_second, &leftover_us);
2207 CLEANUP;
2208 }
2209 if (minute) {
2210 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2211 CLEANUP;
2212 }
2213 if (hour) {
2214 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2215 CLEANUP;
2216 }
2217 if (day) {
2218 y = accum("days", x, day, us_per_day, &leftover_us);
2219 CLEANUP;
2220 }
2221 if (week) {
2222 y = accum("weeks", x, week, us_per_week, &leftover_us);
2223 CLEANUP;
2224 }
2225 if (leftover_us) {
2226 /* Round to nearest whole # of us, and add into x. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002227 double whole_us = round(leftover_us);
Victor Stinner69cc4872015-09-08 23:58:54 +02002228 int x_is_odd;
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002229 PyObject *temp;
2230
Victor Stinner69cc4872015-09-08 23:58:54 +02002231 whole_us = round(leftover_us);
2232 if (fabs(whole_us - leftover_us) == 0.5) {
2233 /* We're exactly halfway between two integers. In order
2234 * to do round-half-to-even, we must determine whether x
2235 * is odd. Note that x is odd when it's last bit is 1. The
2236 * code below uses bitwise and operation to check the last
2237 * bit. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002238 temp = PyNumber_And(x, _PyLong_One); /* temp <- x & 1 */
Victor Stinner69cc4872015-09-08 23:58:54 +02002239 if (temp == NULL) {
2240 Py_DECREF(x);
2241 goto Done;
2242 }
2243 x_is_odd = PyObject_IsTrue(temp);
2244 Py_DECREF(temp);
2245 if (x_is_odd == -1) {
2246 Py_DECREF(x);
2247 goto Done;
2248 }
2249 whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2250 }
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002251
Victor Stinner36a5a062013-08-28 01:53:39 +02002252 temp = PyLong_FromLong((long)whole_us);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (temp == NULL) {
2255 Py_DECREF(x);
2256 goto Done;
2257 }
2258 y = PyNumber_Add(x, temp);
2259 Py_DECREF(temp);
2260 CLEANUP;
2261 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 self = microseconds_to_delta_ex(x, type);
2264 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002265Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002267
2268#undef CLEANUP
2269}
2270
2271static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002272delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return (GET_TD_DAYS(self) != 0
2275 || GET_TD_SECONDS(self) != 0
2276 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002277}
2278
2279static PyObject *
2280delta_repr(PyDateTime_Delta *self)
2281{
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +02002282 PyObject *args = PyUnicode_FromString("");
Tim Peters2a799bf2002-12-16 20:18:38 +00002283
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +02002284 if (args == NULL) {
2285 return NULL;
2286 }
2287
2288 const char *sep = "";
2289
2290 if (GET_TD_DAYS(self) != 0) {
2291 Py_SETREF(args, PyUnicode_FromFormat("days=%d", GET_TD_DAYS(self)));
2292 if (args == NULL) {
2293 return NULL;
2294 }
2295 sep = ", ";
2296 }
2297
2298 if (GET_TD_SECONDS(self) != 0) {
2299 Py_SETREF(args, PyUnicode_FromFormat("%U%sseconds=%d", args, sep,
2300 GET_TD_SECONDS(self)));
2301 if (args == NULL) {
2302 return NULL;
2303 }
2304 sep = ", ";
2305 }
2306
2307 if (GET_TD_MICROSECONDS(self) != 0) {
2308 Py_SETREF(args, PyUnicode_FromFormat("%U%smicroseconds=%d", args, sep,
2309 GET_TD_MICROSECONDS(self)));
2310 if (args == NULL) {
2311 return NULL;
2312 }
2313 }
2314
2315 if (PyUnicode_GET_LENGTH(args) == 0) {
2316 Py_SETREF(args, PyUnicode_FromString("0"));
2317 if (args == NULL) {
2318 return NULL;
2319 }
2320 }
2321
2322 PyObject *repr = PyUnicode_FromFormat("%s(%S)", Py_TYPE(self)->tp_name,
2323 args);
2324 Py_DECREF(args);
2325 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00002326}
2327
2328static PyObject *
2329delta_str(PyDateTime_Delta *self)
2330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 int us = GET_TD_MICROSECONDS(self);
2332 int seconds = GET_TD_SECONDS(self);
2333 int minutes = divmod(seconds, 60, &seconds);
2334 int hours = divmod(minutes, 60, &minutes);
2335 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 if (days) {
2338 if (us)
2339 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2340 days, (days == 1 || days == -1) ? "" : "s",
2341 hours, minutes, seconds, us);
2342 else
2343 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2344 days, (days == 1 || days == -1) ? "" : "s",
2345 hours, minutes, seconds);
2346 } else {
2347 if (us)
2348 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2349 hours, minutes, seconds, us);
2350 else
2351 return PyUnicode_FromFormat("%d:%02d:%02d",
2352 hours, minutes, seconds);
2353 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002354
Tim Peters2a799bf2002-12-16 20:18:38 +00002355}
2356
Tim Peters371935f2003-02-01 01:52:50 +00002357/* Pickle support, a simple use of __reduce__. */
2358
Tim Petersb57f8f02003-02-01 02:54:15 +00002359/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002360static PyObject *
2361delta_getstate(PyDateTime_Delta *self)
2362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return Py_BuildValue("iii", GET_TD_DAYS(self),
2364 GET_TD_SECONDS(self),
2365 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002366}
2367
Tim Peters2a799bf2002-12-16 20:18:38 +00002368static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002369delta_total_seconds(PyObject *self)
2370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 PyObject *total_seconds;
2372 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2375 if (total_microseconds == NULL)
2376 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002377
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002378 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002382}
2383
2384static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002385delta_reduce(PyDateTime_Delta* self)
2386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002388}
2389
2390#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2391
2392static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 {"days", T_INT, OFFSET(days), READONLY,
2395 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 {"seconds", T_INT, OFFSET(seconds), READONLY,
2398 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2401 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2402 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002403};
2404
2405static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2407 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2410 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002413};
2414
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002415static const char delta_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00002416PyDoc_STR("Difference between two datetime values.");
2417
2418static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 delta_add, /* nb_add */
2420 delta_subtract, /* nb_subtract */
2421 delta_multiply, /* nb_multiply */
2422 delta_remainder, /* nb_remainder */
2423 delta_divmod, /* nb_divmod */
2424 0, /* nb_power */
2425 (unaryfunc)delta_negative, /* nb_negative */
2426 (unaryfunc)delta_positive, /* nb_positive */
2427 (unaryfunc)delta_abs, /* nb_absolute */
2428 (inquiry)delta_bool, /* nb_bool */
2429 0, /*nb_invert*/
2430 0, /*nb_lshift*/
2431 0, /*nb_rshift*/
2432 0, /*nb_and*/
2433 0, /*nb_xor*/
2434 0, /*nb_or*/
2435 0, /*nb_int*/
2436 0, /*nb_reserved*/
2437 0, /*nb_float*/
2438 0, /*nb_inplace_add*/
2439 0, /*nb_inplace_subtract*/
2440 0, /*nb_inplace_multiply*/
2441 0, /*nb_inplace_remainder*/
2442 0, /*nb_inplace_power*/
2443 0, /*nb_inplace_lshift*/
2444 0, /*nb_inplace_rshift*/
2445 0, /*nb_inplace_and*/
2446 0, /*nb_inplace_xor*/
2447 0, /*nb_inplace_or*/
2448 delta_divide, /* nb_floor_divide */
2449 delta_truedivide, /* nb_true_divide */
2450 0, /* nb_inplace_floor_divide */
2451 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002452};
2453
2454static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 PyVarObject_HEAD_INIT(NULL, 0)
2456 "datetime.timedelta", /* tp_name */
2457 sizeof(PyDateTime_Delta), /* tp_basicsize */
2458 0, /* tp_itemsize */
2459 0, /* tp_dealloc */
2460 0, /* tp_print */
2461 0, /* tp_getattr */
2462 0, /* tp_setattr */
2463 0, /* tp_reserved */
2464 (reprfunc)delta_repr, /* tp_repr */
2465 &delta_as_number, /* tp_as_number */
2466 0, /* tp_as_sequence */
2467 0, /* tp_as_mapping */
2468 (hashfunc)delta_hash, /* tp_hash */
2469 0, /* tp_call */
2470 (reprfunc)delta_str, /* tp_str */
2471 PyObject_GenericGetAttr, /* tp_getattro */
2472 0, /* tp_setattro */
2473 0, /* tp_as_buffer */
2474 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2475 delta_doc, /* tp_doc */
2476 0, /* tp_traverse */
2477 0, /* tp_clear */
2478 delta_richcompare, /* tp_richcompare */
2479 0, /* tp_weaklistoffset */
2480 0, /* tp_iter */
2481 0, /* tp_iternext */
2482 delta_methods, /* tp_methods */
2483 delta_members, /* tp_members */
2484 0, /* tp_getset */
2485 0, /* tp_base */
2486 0, /* tp_dict */
2487 0, /* tp_descr_get */
2488 0, /* tp_descr_set */
2489 0, /* tp_dictoffset */
2490 0, /* tp_init */
2491 0, /* tp_alloc */
2492 delta_new, /* tp_new */
2493 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002494};
2495
2496/*
2497 * PyDateTime_Date implementation.
2498 */
2499
2500/* Accessor properties. */
2501
2502static PyObject *
2503date_year(PyDateTime_Date *self, void *unused)
2504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002506}
2507
2508static PyObject *
2509date_month(PyDateTime_Date *self, void *unused)
2510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002512}
2513
2514static PyObject *
2515date_day(PyDateTime_Date *self, void *unused)
2516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002518}
2519
2520static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 {"year", (getter)date_year},
2522 {"month", (getter)date_month},
2523 {"day", (getter)date_day},
2524 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002525};
2526
2527/* Constructors. */
2528
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002529static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002530
Tim Peters2a799bf2002-12-16 20:18:38 +00002531static PyObject *
2532date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 PyObject *self = NULL;
2535 PyObject *state;
2536 int year;
2537 int month;
2538 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 /* Check for invocation from pickle with __getstate__ state */
2541 if (PyTuple_GET_SIZE(args) == 1 &&
2542 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2543 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2544 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2545 {
2546 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2549 if (me != NULL) {
2550 char *pdata = PyBytes_AS_STRING(state);
2551 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2552 me->hashcode = -1;
2553 }
2554 return (PyObject *)me;
2555 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2558 &year, &month, &day)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 self = new_date_ex(year, month, day, type);
2560 }
2561 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002562}
2563
2564/* Return new date from localtime(t). */
2565static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002566date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002567{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002568 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002570
Victor Stinnere4a994d2015-03-30 01:10:14 +02002571 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002573
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04002574 if (_PyTime_localtime(t, &tm) != 0)
Victor Stinner21f58932012-03-14 00:15:40 +01002575 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01002576
2577 return PyObject_CallFunction(cls, "iii",
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002578 tm.tm_year + 1900,
2579 tm.tm_mon + 1,
2580 tm.tm_mday);
Tim Peters2a799bf2002-12-16 20:18:38 +00002581}
2582
2583/* Return new date from current time.
2584 * We say this is equivalent to fromtimestamp(time.time()), and the
2585 * only way to be sure of that is to *call* time.time(). That's not
2586 * generally the same as calling C's time.
2587 */
2588static PyObject *
2589date_today(PyObject *cls, PyObject *dummy)
2590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 PyObject *time;
2592 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002593 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 time = time_time();
2596 if (time == NULL)
2597 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 /* Note well: today() is a class method, so this may not call
2600 * date.fromtimestamp. For example, it may call
2601 * datetime.fromtimestamp. That's why we need all the accuracy
2602 * time.time() delivers; if someone were gonzo about optimization,
2603 * date.today() could get away with plain C time().
2604 */
Victor Stinner20401de2016-12-09 15:24:31 +01002605 result = _PyObject_CallMethodIdObjArgs(cls, &PyId_fromtimestamp,
2606 time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 Py_DECREF(time);
2608 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002609}
2610
2611/* Return new date from given timestamp (Python timestamp -- a double). */
2612static PyObject *
2613date_fromtimestamp(PyObject *cls, PyObject *args)
2614{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002615 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002617
Victor Stinner5d272cc2012-03-13 13:35:55 +01002618 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2619 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002621}
2622
2623/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2624 * the ordinal is out of range.
2625 */
2626static PyObject *
2627date_fromordinal(PyObject *cls, PyObject *args)
2628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 PyObject *result = NULL;
2630 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2633 int year;
2634 int month;
2635 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (ordinal < 1)
2638 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2639 ">= 1");
2640 else {
2641 ord_to_ymd(ordinal, &year, &month, &day);
2642 result = PyObject_CallFunction(cls, "iii",
2643 year, month, day);
2644 }
2645 }
2646 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002647}
2648
2649/*
2650 * Date arithmetic.
2651 */
2652
2653/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2654 * instead.
2655 */
2656static PyObject *
2657add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 PyObject *result = NULL;
2660 int year = GET_YEAR(date);
2661 int month = GET_MONTH(date);
2662 int deltadays = GET_TD_DAYS(delta);
2663 /* C-level overflow is impossible because |deltadays| < 1e9. */
2664 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 if (normalize_date(&year, &month, &day) >= 0)
2667 result = new_date(year, month, day);
2668 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002669}
2670
2671static PyObject *
2672date_add(PyObject *left, PyObject *right)
2673{
Brian Curtindfc80e32011-08-10 20:28:54 -05002674 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2675 Py_RETURN_NOTIMPLEMENTED;
2676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 if (PyDate_Check(left)) {
2678 /* date + ??? */
2679 if (PyDelta_Check(right))
2680 /* date + delta */
2681 return add_date_timedelta((PyDateTime_Date *) left,
2682 (PyDateTime_Delta *) right,
2683 0);
2684 }
2685 else {
2686 /* ??? + date
2687 * 'right' must be one of us, or we wouldn't have been called
2688 */
2689 if (PyDelta_Check(left))
2690 /* delta + date */
2691 return add_date_timedelta((PyDateTime_Date *) right,
2692 (PyDateTime_Delta *) left,
2693 0);
2694 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002695 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002696}
2697
2698static PyObject *
2699date_subtract(PyObject *left, PyObject *right)
2700{
Brian Curtindfc80e32011-08-10 20:28:54 -05002701 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2702 Py_RETURN_NOTIMPLEMENTED;
2703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 if (PyDate_Check(left)) {
2705 if (PyDate_Check(right)) {
2706 /* date - date */
2707 int left_ord = ymd_to_ord(GET_YEAR(left),
2708 GET_MONTH(left),
2709 GET_DAY(left));
2710 int right_ord = ymd_to_ord(GET_YEAR(right),
2711 GET_MONTH(right),
2712 GET_DAY(right));
2713 return new_delta(left_ord - right_ord, 0, 0, 0);
2714 }
2715 if (PyDelta_Check(right)) {
2716 /* date - delta */
2717 return add_date_timedelta((PyDateTime_Date *) left,
2718 (PyDateTime_Delta *) right,
2719 1);
2720 }
2721 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002722 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002723}
2724
2725
2726/* Various ways to turn a date into a string. */
2727
2728static PyObject *
2729date_repr(PyDateTime_Date *self)
2730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2732 Py_TYPE(self)->tp_name,
2733 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002734}
2735
2736static PyObject *
2737date_isoformat(PyDateTime_Date *self)
2738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 return PyUnicode_FromFormat("%04d-%02d-%02d",
2740 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002741}
2742
Tim Peterse2df5ff2003-05-02 18:39:55 +00002743/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002744static PyObject *
2745date_str(PyDateTime_Date *self)
2746{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002747 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002748}
2749
2750
2751static PyObject *
2752date_ctime(PyDateTime_Date *self)
2753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002755}
2756
2757static PyObject *
2758date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 /* This method can be inherited, and needs to call the
2761 * timetuple() method appropriate to self's class.
2762 */
2763 PyObject *result;
2764 PyObject *tuple;
2765 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002766 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2770 &format))
2771 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002772
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002773 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (tuple == NULL)
2775 return NULL;
2776 result = wrap_strftime((PyObject *)self, format, tuple,
2777 (PyObject *)self);
2778 Py_DECREF(tuple);
2779 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002780}
2781
Eric Smith1ba31142007-09-11 18:06:02 +00002782static PyObject *
2783date_format(PyDateTime_Date *self, PyObject *args)
2784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2788 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002791 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002793
Victor Stinner20401de2016-12-09 15:24:31 +01002794 return _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_strftime,
2795 format, NULL);
Eric Smith1ba31142007-09-11 18:06:02 +00002796}
2797
Tim Peters2a799bf2002-12-16 20:18:38 +00002798/* ISO methods. */
2799
2800static PyObject *
2801date_isoweekday(PyDateTime_Date *self)
2802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002806}
2807
2808static PyObject *
2809date_isocalendar(PyDateTime_Date *self)
2810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 int year = GET_YEAR(self);
2812 int week1_monday = iso_week1_monday(year);
2813 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2814 int week;
2815 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 week = divmod(today - week1_monday, 7, &day);
2818 if (week < 0) {
2819 --year;
2820 week1_monday = iso_week1_monday(year);
2821 week = divmod(today - week1_monday, 7, &day);
2822 }
2823 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2824 ++year;
2825 week = 0;
2826 }
2827 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002828}
2829
2830/* Miscellaneous methods. */
2831
Tim Peters2a799bf2002-12-16 20:18:38 +00002832static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002833date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 if (PyDate_Check(other)) {
2836 int diff = memcmp(((PyDateTime_Date *)self)->data,
2837 ((PyDateTime_Date *)other)->data,
2838 _PyDateTime_DATE_DATASIZE);
2839 return diff_to_bool(diff, op);
2840 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002841 else
2842 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002843}
2844
2845static PyObject *
2846date_timetuple(PyDateTime_Date *self)
2847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 return build_struct_time(GET_YEAR(self),
2849 GET_MONTH(self),
2850 GET_DAY(self),
2851 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002852}
2853
Tim Peters12bf3392002-12-24 05:41:27 +00002854static PyObject *
2855date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 PyObject *clone;
2858 PyObject *tuple;
2859 int year = GET_YEAR(self);
2860 int month = GET_MONTH(self);
2861 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2864 &year, &month, &day))
2865 return NULL;
2866 tuple = Py_BuildValue("iii", year, month, day);
2867 if (tuple == NULL)
2868 return NULL;
2869 clone = date_new(Py_TYPE(self), tuple, NULL);
2870 Py_DECREF(tuple);
2871 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002872}
2873
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002874static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002875generic_hash(unsigned char *data, int len)
2876{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002877 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002878}
2879
2880
2881static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002882
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002883static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002884date_hash(PyDateTime_Date *self)
2885{
Benjamin Petersondec2df32016-09-09 17:46:24 -07002886 if (self->hashcode == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 self->hashcode = generic_hash(
2888 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Benjamin Petersondec2df32016-09-09 17:46:24 -07002889 }
Guido van Rossum254348e2007-11-21 19:29:53 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002892}
2893
2894static PyObject *
2895date_toordinal(PyDateTime_Date *self)
2896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2898 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002899}
2900
2901static PyObject *
2902date_weekday(PyDateTime_Date *self)
2903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002907}
2908
Tim Peters371935f2003-02-01 01:52:50 +00002909/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002910
Tim Petersb57f8f02003-02-01 02:54:15 +00002911/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002912static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002913date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 PyObject* field;
2916 field = PyBytes_FromStringAndSize((char*)self->data,
2917 _PyDateTime_DATE_DATASIZE);
2918 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002919}
2920
2921static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002922date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002925}
2926
2927static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2932 METH_CLASS,
2933 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2934 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2937 METH_CLASS,
2938 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2939 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2942 PyDoc_STR("Current date or datetime: same as "
2943 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2948 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2951 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2954 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2957 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2960 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2961 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2964 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2967 PyDoc_STR("Return the day of the week represented by the date.\n"
2968 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2971 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2972 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2975 PyDoc_STR("Return the day of the week represented by the date.\n"
2976 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2979 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2982 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002985};
2986
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002987static const char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002988PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002989
2990static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 date_add, /* nb_add */
2992 date_subtract, /* nb_subtract */
2993 0, /* nb_multiply */
2994 0, /* nb_remainder */
2995 0, /* nb_divmod */
2996 0, /* nb_power */
2997 0, /* nb_negative */
2998 0, /* nb_positive */
2999 0, /* nb_absolute */
3000 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003001};
3002
3003static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 PyVarObject_HEAD_INIT(NULL, 0)
3005 "datetime.date", /* tp_name */
3006 sizeof(PyDateTime_Date), /* tp_basicsize */
3007 0, /* tp_itemsize */
3008 0, /* tp_dealloc */
3009 0, /* tp_print */
3010 0, /* tp_getattr */
3011 0, /* tp_setattr */
3012 0, /* tp_reserved */
3013 (reprfunc)date_repr, /* tp_repr */
3014 &date_as_number, /* tp_as_number */
3015 0, /* tp_as_sequence */
3016 0, /* tp_as_mapping */
3017 (hashfunc)date_hash, /* tp_hash */
3018 0, /* tp_call */
3019 (reprfunc)date_str, /* tp_str */
3020 PyObject_GenericGetAttr, /* tp_getattro */
3021 0, /* tp_setattro */
3022 0, /* tp_as_buffer */
3023 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3024 date_doc, /* tp_doc */
3025 0, /* tp_traverse */
3026 0, /* tp_clear */
3027 date_richcompare, /* tp_richcompare */
3028 0, /* tp_weaklistoffset */
3029 0, /* tp_iter */
3030 0, /* tp_iternext */
3031 date_methods, /* tp_methods */
3032 0, /* tp_members */
3033 date_getset, /* tp_getset */
3034 0, /* tp_base */
3035 0, /* tp_dict */
3036 0, /* tp_descr_get */
3037 0, /* tp_descr_set */
3038 0, /* tp_dictoffset */
3039 0, /* tp_init */
3040 0, /* tp_alloc */
3041 date_new, /* tp_new */
3042 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003043};
3044
3045/*
Tim Peters2a799bf2002-12-16 20:18:38 +00003046 * PyDateTime_TZInfo implementation.
3047 */
3048
3049/* This is a pure abstract base class, so doesn't do anything beyond
3050 * raising NotImplemented exceptions. Real tzinfo classes need
3051 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00003052 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00003053 * be subclasses of this tzinfo class, which is easy and quick to check).
3054 *
3055 * Note: For reasons having to do with pickling of subclasses, we have
3056 * to allow tzinfo objects to be instantiated. This wasn't an issue
3057 * in the Python implementation (__init__() could raise NotImplementedError
3058 * there without ill effect), but doing so in the C implementation hit a
3059 * brick wall.
3060 */
3061
3062static PyObject *
3063tzinfo_nogo(const char* methodname)
3064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 PyErr_Format(PyExc_NotImplementedError,
3066 "a tzinfo subclass must implement %s()",
3067 methodname);
3068 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003069}
3070
3071/* Methods. A subclass must implement these. */
3072
Tim Peters52dcce22003-01-23 16:36:11 +00003073static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003074tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00003077}
3078
Tim Peters52dcce22003-01-23 16:36:11 +00003079static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003080tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00003083}
3084
Tim Peters52dcce22003-01-23 16:36:11 +00003085static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003086tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003089}
3090
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003091
3092static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
3093 PyDateTime_Delta *delta,
3094 int factor);
3095static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
3096static PyObject *datetime_dst(PyObject *self, PyObject *);
3097
Tim Peters52dcce22003-01-23 16:36:11 +00003098static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003099tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003100{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003101 PyObject *result = NULL;
3102 PyObject *off = NULL, *dst = NULL;
3103 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003104
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003105 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 PyErr_SetString(PyExc_TypeError,
3107 "fromutc: argument must be a datetime");
3108 return NULL;
3109 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003110 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3112 "is not self");
3113 return NULL;
3114 }
Tim Peters52dcce22003-01-23 16:36:11 +00003115
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003116 off = datetime_utcoffset(dt, NULL);
3117 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003119 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3121 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003122 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 }
Tim Peters52dcce22003-01-23 16:36:11 +00003124
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003125 dst = datetime_dst(dt, NULL);
3126 if (dst == NULL)
3127 goto Fail;
3128 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3130 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003131 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 }
Tim Peters52dcce22003-01-23 16:36:11 +00003133
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003134 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3135 if (delta == NULL)
3136 goto Fail;
3137 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003140
3141 Py_DECREF(dst);
3142 dst = call_dst(GET_DT_TZINFO(dt), result);
3143 if (dst == NULL)
3144 goto Fail;
3145 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 goto Inconsistent;
Alexander Belopolskyc79447b2015-09-27 21:41:55 -04003147 if (delta_bool((PyDateTime_Delta *)dst) != 0) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03003148 Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
Serhiy Storchaka576f1322016-01-05 21:27:54 +02003149 (PyDateTime_Delta *)dst, 1));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003150 if (result == NULL)
3151 goto Fail;
3152 }
3153 Py_DECREF(delta);
3154 Py_DECREF(dst);
3155 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003157
3158Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3160 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003163Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003164 Py_XDECREF(off);
3165 Py_XDECREF(dst);
3166 Py_XDECREF(delta);
3167 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003169}
3170
Tim Peters2a799bf2002-12-16 20:18:38 +00003171/*
3172 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003173 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003174 */
3175
Guido van Rossum177e41a2003-01-30 22:06:23 +00003176static PyObject *
3177tzinfo_reduce(PyObject *self)
3178{
Victor Stinnerd1584d32016-08-23 00:11:04 +02003179 PyObject *args, *state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003181 _Py_IDENTIFIER(__getinitargs__);
3182 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003183
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003184 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 if (getinitargs != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003186 args = _PyObject_CallNoArg(getinitargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 Py_DECREF(getinitargs);
3188 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 return NULL;
3190 }
3191 }
3192 else {
3193 PyErr_Clear();
Victor Stinnerd1584d32016-08-23 00:11:04 +02003194
3195 args = PyTuple_New(0);
3196 if (args == NULL) {
3197 return NULL;
3198 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003200
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003201 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 if (getstate != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003203 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 Py_DECREF(getstate);
3205 if (state == NULL) {
3206 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 return NULL;
3208 }
3209 }
3210 else {
3211 PyObject **dictptr;
3212 PyErr_Clear();
3213 state = Py_None;
3214 dictptr = _PyObject_GetDictPtr(self);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02003215 if (dictptr && *dictptr && PyDict_GET_SIZE(*dictptr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 state = *dictptr;
Victor Stinnerd1584d32016-08-23 00:11:04 +02003217 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 Py_INCREF(state);
3219 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 if (state == Py_None) {
3222 Py_DECREF(state);
3223 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3224 }
3225 else
3226 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003227}
Tim Peters2a799bf2002-12-16 20:18:38 +00003228
3229static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3232 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003235 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3236 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 {"dst", (PyCFunction)tzinfo_dst, METH_O,
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003239 PyDoc_STR("datetime -> DST offset as timedelta positive east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003242 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3245 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003248};
3249
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003250static const char tzinfo_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00003251PyDoc_STR("Abstract base class for time zone info objects.");
3252
Neal Norwitz227b5332006-03-22 09:28:35 +00003253static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 PyVarObject_HEAD_INIT(NULL, 0)
3255 "datetime.tzinfo", /* tp_name */
3256 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3257 0, /* tp_itemsize */
3258 0, /* tp_dealloc */
3259 0, /* tp_print */
3260 0, /* tp_getattr */
3261 0, /* tp_setattr */
3262 0, /* tp_reserved */
3263 0, /* tp_repr */
3264 0, /* tp_as_number */
3265 0, /* tp_as_sequence */
3266 0, /* tp_as_mapping */
3267 0, /* tp_hash */
3268 0, /* tp_call */
3269 0, /* tp_str */
3270 PyObject_GenericGetAttr, /* tp_getattro */
3271 0, /* tp_setattro */
3272 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003273 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 tzinfo_doc, /* tp_doc */
3275 0, /* tp_traverse */
3276 0, /* tp_clear */
3277 0, /* tp_richcompare */
3278 0, /* tp_weaklistoffset */
3279 0, /* tp_iter */
3280 0, /* tp_iternext */
3281 tzinfo_methods, /* tp_methods */
3282 0, /* tp_members */
3283 0, /* tp_getset */
3284 0, /* tp_base */
3285 0, /* tp_dict */
3286 0, /* tp_descr_get */
3287 0, /* tp_descr_set */
3288 0, /* tp_dictoffset */
3289 0, /* tp_init */
3290 0, /* tp_alloc */
3291 PyType_GenericNew, /* tp_new */
3292 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003293};
3294
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003295static char *timezone_kws[] = {"offset", "name", NULL};
3296
3297static PyObject *
3298timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3299{
3300 PyObject *offset;
3301 PyObject *name = NULL;
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03003302 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|U:timezone", timezone_kws,
3303 &PyDateTime_DeltaType, &offset, &name))
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003304 return new_timezone(offset, name);
3305
3306 return NULL;
3307}
3308
3309static void
3310timezone_dealloc(PyDateTime_TimeZone *self)
3311{
3312 Py_CLEAR(self->offset);
3313 Py_CLEAR(self->name);
3314 Py_TYPE(self)->tp_free((PyObject *)self);
3315}
3316
3317static PyObject *
3318timezone_richcompare(PyDateTime_TimeZone *self,
3319 PyDateTime_TimeZone *other, int op)
3320{
Brian Curtindfc80e32011-08-10 20:28:54 -05003321 if (op != Py_EQ && op != Py_NE)
3322 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003323 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003324 if (op == Py_EQ)
3325 Py_RETURN_FALSE;
3326 else
3327 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003328 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003329 return delta_richcompare(self->offset, other->offset, op);
3330}
3331
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003332static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003333timezone_hash(PyDateTime_TimeZone *self)
3334{
3335 return delta_hash((PyDateTime_Delta *)self->offset);
3336}
3337
3338/* Check argument type passed to tzname, utcoffset, or dst methods.
3339 Returns 0 for good argument. Returns -1 and sets exception info
3340 otherwise.
3341 */
3342static int
3343_timezone_check_argument(PyObject *dt, const char *meth)
3344{
3345 if (dt == Py_None || PyDateTime_Check(dt))
3346 return 0;
3347 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3348 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3349 return -1;
3350}
3351
3352static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003353timezone_repr(PyDateTime_TimeZone *self)
3354{
3355 /* Note that although timezone is not subclassable, it is convenient
3356 to use Py_TYPE(self)->tp_name here. */
3357 const char *type_name = Py_TYPE(self)->tp_name;
3358
3359 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3360 return PyUnicode_FromFormat("%s.utc", type_name);
3361
3362 if (self->name == NULL)
3363 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3364
3365 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3366 self->name);
3367}
3368
3369
3370static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003371timezone_str(PyDateTime_TimeZone *self)
3372{
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003373 int hours, minutes, seconds, microseconds;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003374 PyObject *offset;
3375 char sign;
3376
3377 if (self->name != NULL) {
3378 Py_INCREF(self->name);
3379 return self->name;
3380 }
Victor Stinner90fd8952015-09-08 00:12:49 +02003381 if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04003382 (GET_TD_DAYS(self->offset) == 0 &&
3383 GET_TD_SECONDS(self->offset) == 0 &&
3384 GET_TD_MICROSECONDS(self->offset) == 0))
3385 return PyUnicode_FromString("UTC");
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003386 /* Offset is normalized, so it is negative if days < 0 */
3387 if (GET_TD_DAYS(self->offset) < 0) {
3388 sign = '-';
3389 offset = delta_negative((PyDateTime_Delta *)self->offset);
3390 if (offset == NULL)
3391 return NULL;
3392 }
3393 else {
3394 sign = '+';
3395 offset = self->offset;
3396 Py_INCREF(offset);
3397 }
3398 /* Offset is not negative here. */
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003399 microseconds = GET_TD_MICROSECONDS(offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003400 seconds = GET_TD_SECONDS(offset);
3401 Py_DECREF(offset);
3402 minutes = divmod(seconds, 60, &seconds);
3403 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky018d3532017-07-31 10:26:50 -04003404 if (microseconds != 0) {
3405 return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d.%06d",
3406 sign, hours, minutes,
3407 seconds, microseconds);
3408 }
3409 if (seconds != 0) {
3410 return PyUnicode_FromFormat("UTC%c%02d:%02d:%02d",
3411 sign, hours, minutes, seconds);
3412 }
Victor Stinner6ced7c42011-03-21 18:15:42 +01003413 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003414}
3415
3416static PyObject *
3417timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3418{
3419 if (_timezone_check_argument(dt, "tzname") == -1)
3420 return NULL;
3421
3422 return timezone_str(self);
3423}
3424
3425static PyObject *
3426timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3427{
3428 if (_timezone_check_argument(dt, "utcoffset") == -1)
3429 return NULL;
3430
3431 Py_INCREF(self->offset);
3432 return self->offset;
3433}
3434
3435static PyObject *
3436timezone_dst(PyObject *self, PyObject *dt)
3437{
3438 if (_timezone_check_argument(dt, "dst") == -1)
3439 return NULL;
3440
3441 Py_RETURN_NONE;
3442}
3443
3444static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003445timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3446{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003447 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003448 PyErr_SetString(PyExc_TypeError,
3449 "fromutc: argument must be a datetime");
3450 return NULL;
3451 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003452 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003453 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3454 "is not self");
3455 return NULL;
3456 }
3457
3458 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3459}
3460
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003461static PyObject *
3462timezone_getinitargs(PyDateTime_TimeZone *self)
3463{
3464 if (self->name == NULL)
3465 return Py_BuildValue("(O)", self->offset);
3466 return Py_BuildValue("(OO)", self->offset, self->name);
3467}
3468
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003469static PyMethodDef timezone_methods[] = {
3470 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3471 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003472 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003473
3474 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003475 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003476
3477 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003478 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003479
3480 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3481 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3482
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003483 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3484 PyDoc_STR("pickle support")},
3485
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003486 {NULL, NULL}
3487};
3488
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003489static const char timezone_doc[] =
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003490PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3491
3492static PyTypeObject PyDateTime_TimeZoneType = {
3493 PyVarObject_HEAD_INIT(NULL, 0)
3494 "datetime.timezone", /* tp_name */
3495 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3496 0, /* tp_itemsize */
3497 (destructor)timezone_dealloc, /* tp_dealloc */
3498 0, /* tp_print */
3499 0, /* tp_getattr */
3500 0, /* tp_setattr */
3501 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003502 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003503 0, /* tp_as_number */
3504 0, /* tp_as_sequence */
3505 0, /* tp_as_mapping */
3506 (hashfunc)timezone_hash, /* tp_hash */
3507 0, /* tp_call */
3508 (reprfunc)timezone_str, /* tp_str */
3509 0, /* tp_getattro */
3510 0, /* tp_setattro */
3511 0, /* tp_as_buffer */
3512 Py_TPFLAGS_DEFAULT, /* tp_flags */
3513 timezone_doc, /* tp_doc */
3514 0, /* tp_traverse */
3515 0, /* tp_clear */
3516 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3517 0, /* tp_weaklistoffset */
3518 0, /* tp_iter */
3519 0, /* tp_iternext */
3520 timezone_methods, /* tp_methods */
3521 0, /* tp_members */
3522 0, /* tp_getset */
3523 &PyDateTime_TZInfoType, /* tp_base */
3524 0, /* tp_dict */
3525 0, /* tp_descr_get */
3526 0, /* tp_descr_set */
3527 0, /* tp_dictoffset */
3528 0, /* tp_init */
3529 0, /* tp_alloc */
3530 timezone_new, /* tp_new */
3531};
3532
Tim Peters2a799bf2002-12-16 20:18:38 +00003533/*
Tim Peters37f39822003-01-10 03:49:02 +00003534 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003535 */
3536
Tim Peters37f39822003-01-10 03:49:02 +00003537/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003538 */
3539
3540static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003541time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003544}
3545
Tim Peters37f39822003-01-10 03:49:02 +00003546static PyObject *
3547time_minute(PyDateTime_Time *self, void *unused)
3548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003550}
3551
3552/* The name time_second conflicted with some platform header file. */
3553static PyObject *
3554py_time_second(PyDateTime_Time *self, void *unused)
3555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003557}
3558
3559static PyObject *
3560time_microsecond(PyDateTime_Time *self, void *unused)
3561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003563}
3564
3565static PyObject *
3566time_tzinfo(PyDateTime_Time *self, void *unused)
3567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3569 Py_INCREF(result);
3570 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003571}
3572
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003573static PyObject *
3574time_fold(PyDateTime_Time *self, void *unused)
3575{
3576 return PyLong_FromLong(TIME_GET_FOLD(self));
3577}
3578
Tim Peters37f39822003-01-10 03:49:02 +00003579static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 {"hour", (getter)time_hour},
3581 {"minute", (getter)time_minute},
3582 {"second", (getter)py_time_second},
3583 {"microsecond", (getter)time_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003584 {"tzinfo", (getter)time_tzinfo},
3585 {"fold", (getter)time_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003587};
3588
3589/*
3590 * Constructors.
3591 */
3592
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003593static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003594 "tzinfo", "fold", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003595
Tim Peters2a799bf2002-12-16 20:18:38 +00003596static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003597time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 PyObject *self = NULL;
3600 PyObject *state;
3601 int hour = 0;
3602 int minute = 0;
3603 int second = 0;
3604 int usecond = 0;
3605 PyObject *tzinfo = Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003606 int fold = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* Check for invocation from pickle with __getstate__ state */
3609 if (PyTuple_GET_SIZE(args) >= 1 &&
3610 PyTuple_GET_SIZE(args) <= 2 &&
3611 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3612 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003613 (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 {
3615 PyDateTime_Time *me;
3616 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 if (PyTuple_GET_SIZE(args) == 2) {
3619 tzinfo = PyTuple_GET_ITEM(args, 1);
3620 if (check_tzinfo_subclass(tzinfo) < 0) {
3621 PyErr_SetString(PyExc_TypeError, "bad "
3622 "tzinfo state arg");
3623 return NULL;
3624 }
3625 }
3626 aware = (char)(tzinfo != Py_None);
3627 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3628 if (me != NULL) {
3629 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3632 me->hashcode = -1;
3633 me->hastzinfo = aware;
3634 if (aware) {
3635 Py_INCREF(tzinfo);
3636 me->tzinfo = tzinfo;
3637 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003638 if (pdata[0] & (1 << 7)) {
3639 me->data[0] -= 128;
3640 me->fold = 1;
3641 }
3642 else {
3643 me->fold = 0;
3644 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 }
3646 return (PyObject *)me;
3647 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003648
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003649 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 &hour, &minute, &second, &usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003651 &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003652 self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
3653 type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 }
3655 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003656}
3657
3658/*
3659 * Destructor.
3660 */
3661
3662static void
Tim Peters37f39822003-01-10 03:49:02 +00003663time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 if (HASTZINFO(self)) {
3666 Py_XDECREF(self->tzinfo);
3667 }
3668 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003669}
3670
3671/*
Tim Peters855fe882002-12-22 03:43:39 +00003672 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003673 */
3674
Tim Peters2a799bf2002-12-16 20:18:38 +00003675/* These are all METH_NOARGS, so don't need to check the arglist. */
3676static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003677time_utcoffset(PyObject *self, PyObject *unused) {
3678 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003679}
3680
3681static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003682time_dst(PyObject *self, PyObject *unused) {
3683 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003684}
3685
3686static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003687time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003688 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003689}
3690
3691/*
Tim Peters37f39822003-01-10 03:49:02 +00003692 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003693 */
3694
3695static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003696time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 const char *type_name = Py_TYPE(self)->tp_name;
3699 int h = TIME_GET_HOUR(self);
3700 int m = TIME_GET_MINUTE(self);
3701 int s = TIME_GET_SECOND(self);
3702 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003703 int fold = TIME_GET_FOLD(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 if (us)
3707 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3708 type_name, h, m, s, us);
3709 else if (s)
3710 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3711 type_name, h, m, s);
3712 else
3713 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3714 if (result != NULL && HASTZINFO(self))
3715 result = append_keyword_tzinfo(result, self->tzinfo);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003716 if (result != NULL && fold)
3717 result = append_keyword_fold(result, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003719}
3720
Tim Peters37f39822003-01-10 03:49:02 +00003721static PyObject *
3722time_str(PyDateTime_Time *self)
3723{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003724 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters37f39822003-01-10 03:49:02 +00003725}
Tim Peters2a799bf2002-12-16 20:18:38 +00003726
3727static PyObject *
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003728time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 char buf[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003731 char *timespec = NULL;
3732 static char *keywords[] = {"timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02003734 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003735 static char *specs[][2] = {
3736 {"hours", "%02d"},
3737 {"minutes", "%02d:%02d"},
3738 {"seconds", "%02d:%02d:%02d"},
3739 {"milliseconds", "%02d:%02d:%02d.%03d"},
3740 {"microseconds", "%02d:%02d:%02d.%06d"},
3741 };
3742 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00003743
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003744 if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
3745 return NULL;
3746
3747 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
3748 if (us == 0) {
3749 /* seconds */
3750 given_spec = 2;
3751 }
3752 else {
3753 /* microseconds */
3754 given_spec = 4;
3755 }
3756 }
3757 else {
3758 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
3759 if (strcmp(timespec, specs[given_spec][0]) == 0) {
3760 if (given_spec == 3) {
3761 /* milliseconds */
3762 us = us / 1000;
3763 }
3764 break;
3765 }
3766 }
3767 }
3768
3769 if (given_spec == Py_ARRAY_LENGTH(specs)) {
3770 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
3771 return NULL;
3772 }
3773 else {
3774 result = PyUnicode_FromFormat(specs[given_spec][1],
3775 TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
3776 TIME_GET_SECOND(self), us);
3777 }
Tim Peters37f39822003-01-10 03:49:02 +00003778
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003779 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 /* We need to append the UTC offset. */
3783 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3784 Py_None) < 0) {
3785 Py_DECREF(result);
3786 return NULL;
3787 }
3788 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3789 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003790}
3791
Tim Peters37f39822003-01-10 03:49:02 +00003792static PyObject *
3793time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 PyObject *result;
3796 PyObject *tuple;
3797 PyObject *format;
3798 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3801 &format))
3802 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 /* Python's strftime does insane things with the year part of the
3805 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003806 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 */
3808 tuple = Py_BuildValue("iiiiiiiii",
3809 1900, 1, 1, /* year, month, day */
3810 TIME_GET_HOUR(self),
3811 TIME_GET_MINUTE(self),
3812 TIME_GET_SECOND(self),
3813 0, 1, -1); /* weekday, daynum, dst */
3814 if (tuple == NULL)
3815 return NULL;
3816 assert(PyTuple_Size(tuple) == 9);
3817 result = wrap_strftime((PyObject *)self, format, tuple,
3818 Py_None);
3819 Py_DECREF(tuple);
3820 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003821}
Tim Peters2a799bf2002-12-16 20:18:38 +00003822
3823/*
3824 * Miscellaneous methods.
3825 */
3826
Tim Peters37f39822003-01-10 03:49:02 +00003827static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003828time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003829{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003830 PyObject *result = NULL;
3831 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003833
Brian Curtindfc80e32011-08-10 20:28:54 -05003834 if (! PyTime_Check(other))
3835 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003836
3837 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 diff = memcmp(((PyDateTime_Time *)self)->data,
3839 ((PyDateTime_Time *)other)->data,
3840 _PyDateTime_TIME_DATASIZE);
3841 return diff_to_bool(diff, op);
3842 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003843 offset1 = time_utcoffset(self, NULL);
3844 if (offset1 == NULL)
3845 return NULL;
3846 offset2 = time_utcoffset(other, NULL);
3847 if (offset2 == NULL)
3848 goto done;
3849 /* If they're both naive, or both aware and have the same offsets,
3850 * we get off cheap. Note that if they're both naive, offset1 ==
3851 * offset2 == Py_None at this point.
3852 */
3853 if ((offset1 == offset2) ||
3854 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3855 delta_cmp(offset1, offset2) == 0)) {
3856 diff = memcmp(((PyDateTime_Time *)self)->data,
3857 ((PyDateTime_Time *)other)->data,
3858 _PyDateTime_TIME_DATASIZE);
3859 result = diff_to_bool(diff, op);
3860 }
3861 /* The hard case: both aware with different UTC offsets */
3862 else if (offset1 != Py_None && offset2 != Py_None) {
3863 int offsecs1, offsecs2;
3864 assert(offset1 != offset2); /* else last "if" handled it */
3865 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3866 TIME_GET_MINUTE(self) * 60 +
3867 TIME_GET_SECOND(self) -
3868 GET_TD_DAYS(offset1) * 86400 -
3869 GET_TD_SECONDS(offset1);
3870 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3871 TIME_GET_MINUTE(other) * 60 +
3872 TIME_GET_SECOND(other) -
3873 GET_TD_DAYS(offset2) * 86400 -
3874 GET_TD_SECONDS(offset2);
3875 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003876 if (diff == 0)
3877 diff = TIME_GET_MICROSECOND(self) -
3878 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003879 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003881 else if (op == Py_EQ) {
3882 result = Py_False;
3883 Py_INCREF(result);
3884 }
3885 else if (op == Py_NE) {
3886 result = Py_True;
3887 Py_INCREF(result);
3888 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003889 else {
3890 PyErr_SetString(PyExc_TypeError,
3891 "can't compare offset-naive and "
3892 "offset-aware times");
3893 }
3894 done:
3895 Py_DECREF(offset1);
3896 Py_XDECREF(offset2);
3897 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003898}
3899
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003900static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003901time_hash(PyDateTime_Time *self)
3902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003904 PyObject *offset, *self0;
Victor Stinner423c16b2017-01-03 23:47:12 +01003905 if (TIME_GET_FOLD(self)) {
3906 self0 = new_time_ex2(TIME_GET_HOUR(self),
3907 TIME_GET_MINUTE(self),
3908 TIME_GET_SECOND(self),
3909 TIME_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003910 HASTZINFO(self) ? self->tzinfo : Py_None,
3911 0, Py_TYPE(self));
3912 if (self0 == NULL)
3913 return -1;
3914 }
3915 else {
3916 self0 = (PyObject *)self;
3917 Py_INCREF(self0);
3918 }
3919 offset = time_utcoffset(self0, NULL);
3920 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003921
3922 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003926 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 self->hashcode = generic_hash(
3928 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003930 PyObject *temp1, *temp2;
3931 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003933 seconds = TIME_GET_HOUR(self) * 3600 +
3934 TIME_GET_MINUTE(self) * 60 +
3935 TIME_GET_SECOND(self);
3936 microseconds = TIME_GET_MICROSECOND(self);
3937 temp1 = new_delta(0, seconds, microseconds, 1);
3938 if (temp1 == NULL) {
3939 Py_DECREF(offset);
3940 return -1;
3941 }
3942 temp2 = delta_subtract(temp1, offset);
3943 Py_DECREF(temp1);
3944 if (temp2 == NULL) {
3945 Py_DECREF(offset);
3946 return -1;
3947 }
3948 self->hashcode = PyObject_Hash(temp2);
3949 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003951 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 }
3953 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003954}
Tim Peters2a799bf2002-12-16 20:18:38 +00003955
Tim Peters12bf3392002-12-24 05:41:27 +00003956static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003957time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 PyObject *clone;
3960 PyObject *tuple;
3961 int hh = TIME_GET_HOUR(self);
3962 int mm = TIME_GET_MINUTE(self);
3963 int ss = TIME_GET_SECOND(self);
3964 int us = TIME_GET_MICROSECOND(self);
3965 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003966 int fold = TIME_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00003967
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003968 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 time_kws,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003970 &hh, &mm, &ss, &us, &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03003972 if (fold != 0 && fold != 1) {
3973 PyErr_SetString(PyExc_ValueError,
3974 "fold must be either 0 or 1");
3975 return NULL;
3976 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3978 if (tuple == NULL)
3979 return NULL;
3980 clone = time_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003981 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003982 TIME_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003983 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 Py_DECREF(tuple);
3985 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003986}
3987
Tim Peters371935f2003-02-01 01:52:50 +00003988/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003989
Tim Peters33e0f382003-01-10 02:05:14 +00003990/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003991 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3992 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003993 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003994 */
3995static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003996time_getstate(PyDateTime_Time *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00003997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 PyObject *basestate;
3999 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 basestate = PyBytes_FromStringAndSize((char *)self->data,
4002 _PyDateTime_TIME_DATASIZE);
4003 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004004 if (proto > 3 && TIME_GET_FOLD(self))
4005 /* Set the first bit of the first byte */
4006 PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4008 result = PyTuple_Pack(1, basestate);
4009 else
4010 result = PyTuple_Pack(2, basestate, self->tzinfo);
4011 Py_DECREF(basestate);
4012 }
4013 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004014}
4015
4016static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004017time_reduce_ex(PyDateTime_Time *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00004018{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004019 int proto;
4020 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004021 return NULL;
4022
4023 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00004024}
4025
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004026static PyObject *
4027time_reduce(PyDateTime_Time *self, PyObject *arg)
4028{
4029 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, 2));
4030}
4031
Tim Peters37f39822003-01-10 03:49:02 +00004032static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004033
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004034 {"isoformat", (PyCFunction)time_isoformat, METH_VARARGS | METH_KEYWORDS,
4035 PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
4036 "[+HH:MM].\n\n"
4037 "timespec specifies what components of the time to include.\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
4040 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 {"__format__", (PyCFunction)date_format, METH_VARARGS,
4043 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
4046 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
4049 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 {"dst", (PyCFunction)time_dst, METH_NOARGS,
4052 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
4055 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004056
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004057 {"__reduce_ex__", (PyCFunction)time_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004058 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004059
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004060 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
4061 PyDoc_STR("__reduce__() -> (cls, state)")},
4062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004064};
4065
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004066static const char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004067PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
4068\n\
4069All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03004070a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004071
Neal Norwitz227b5332006-03-22 09:28:35 +00004072static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 PyVarObject_HEAD_INIT(NULL, 0)
4074 "datetime.time", /* tp_name */
4075 sizeof(PyDateTime_Time), /* tp_basicsize */
4076 0, /* tp_itemsize */
4077 (destructor)time_dealloc, /* tp_dealloc */
4078 0, /* tp_print */
4079 0, /* tp_getattr */
4080 0, /* tp_setattr */
4081 0, /* tp_reserved */
4082 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05004083 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004084 0, /* tp_as_sequence */
4085 0, /* tp_as_mapping */
4086 (hashfunc)time_hash, /* tp_hash */
4087 0, /* tp_call */
4088 (reprfunc)time_str, /* tp_str */
4089 PyObject_GenericGetAttr, /* tp_getattro */
4090 0, /* tp_setattro */
4091 0, /* tp_as_buffer */
4092 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4093 time_doc, /* tp_doc */
4094 0, /* tp_traverse */
4095 0, /* tp_clear */
4096 time_richcompare, /* tp_richcompare */
4097 0, /* tp_weaklistoffset */
4098 0, /* tp_iter */
4099 0, /* tp_iternext */
4100 time_methods, /* tp_methods */
4101 0, /* tp_members */
4102 time_getset, /* tp_getset */
4103 0, /* tp_base */
4104 0, /* tp_dict */
4105 0, /* tp_descr_get */
4106 0, /* tp_descr_set */
4107 0, /* tp_dictoffset */
4108 0, /* tp_init */
4109 time_alloc, /* tp_alloc */
4110 time_new, /* tp_new */
4111 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004112};
4113
4114/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004115 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00004116 */
4117
Tim Petersa9bc1682003-01-11 03:39:11 +00004118/* Accessor properties. Properties for day, month, and year are inherited
4119 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004120 */
4121
4122static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004123datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00004124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004126}
4127
Tim Petersa9bc1682003-01-11 03:39:11 +00004128static PyObject *
4129datetime_minute(PyDateTime_DateTime *self, void *unused)
4130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004132}
4133
4134static PyObject *
4135datetime_second(PyDateTime_DateTime *self, void *unused)
4136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004138}
4139
4140static PyObject *
4141datetime_microsecond(PyDateTime_DateTime *self, void *unused)
4142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004144}
4145
4146static PyObject *
4147datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
4148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4150 Py_INCREF(result);
4151 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004152}
4153
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004154static PyObject *
4155datetime_fold(PyDateTime_DateTime *self, void *unused)
4156{
4157 return PyLong_FromLong(DATE_GET_FOLD(self));
4158}
4159
Tim Petersa9bc1682003-01-11 03:39:11 +00004160static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 {"hour", (getter)datetime_hour},
4162 {"minute", (getter)datetime_minute},
4163 {"second", (getter)datetime_second},
4164 {"microsecond", (getter)datetime_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004165 {"tzinfo", (getter)datetime_tzinfo},
4166 {"fold", (getter)datetime_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004168};
4169
4170/*
4171 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004172 */
4173
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004174static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 "year", "month", "day", "hour", "minute", "second",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004176 "microsecond", "tzinfo", "fold", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004177};
4178
Tim Peters2a799bf2002-12-16 20:18:38 +00004179static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004180datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 PyObject *self = NULL;
4183 PyObject *state;
4184 int year;
4185 int month;
4186 int day;
4187 int hour = 0;
4188 int minute = 0;
4189 int second = 0;
4190 int usecond = 0;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004191 int fold = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 /* Check for invocation from pickle with __getstate__ state */
4195 if (PyTuple_GET_SIZE(args) >= 1 &&
4196 PyTuple_GET_SIZE(args) <= 2 &&
4197 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4198 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004199 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 {
4201 PyDateTime_DateTime *me;
4202 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 if (PyTuple_GET_SIZE(args) == 2) {
4205 tzinfo = PyTuple_GET_ITEM(args, 1);
4206 if (check_tzinfo_subclass(tzinfo) < 0) {
4207 PyErr_SetString(PyExc_TypeError, "bad "
4208 "tzinfo state arg");
4209 return NULL;
4210 }
4211 }
4212 aware = (char)(tzinfo != Py_None);
4213 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4214 if (me != NULL) {
4215 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4218 me->hashcode = -1;
4219 me->hastzinfo = aware;
4220 if (aware) {
4221 Py_INCREF(tzinfo);
4222 me->tzinfo = tzinfo;
4223 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004224 if (pdata[2] & (1 << 7)) {
4225 me->data[2] -= 128;
4226 me->fold = 1;
4227 }
4228 else {
4229 me->fold = 0;
4230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 }
4232 return (PyObject *)me;
4233 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004234
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004235 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 &year, &month, &day, &hour, &minute,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004237 &second, &usecond, &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004238 self = new_datetime_ex2(year, month, day,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 hour, minute, second, usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004240 tzinfo, fold, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 }
4242 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004243}
4244
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004245/* TM_FUNC is the shared type of _PyTime_localtime() and
4246 * _PyTime_gmtime(). */
4247typedef int (*TM_FUNC)(time_t timer, struct tm*);
Tim Petersa9bc1682003-01-11 03:39:11 +00004248
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004249/* As of version 2015f max fold in IANA database is
4250 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004251static long long max_fold_seconds = 24 * 3600;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004252/* NB: date(1970,1,1).toordinal() == 719163 */
Benjamin Petersonac965ca2016-09-18 18:12:21 -07004253static long long epoch = 719163LL * 24 * 60 * 60;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004254
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004255static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004256utc_to_seconds(int year, int month, int day,
4257 int hour, int minute, int second)
4258{
Victor Stinnerb67f0962017-02-10 10:34:02 +01004259 long long ordinal;
4260
4261 /* ymd_to_ord() doesn't support year <= 0 */
4262 if (year < MINYEAR || year > MAXYEAR) {
4263 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
4264 return -1;
4265 }
4266
4267 ordinal = ymd_to_ord(year, month, day);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004268 return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
4269}
4270
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004271static long long
4272local(long long u)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004273{
4274 struct tm local_time;
Alexander Belopolsky8e1d3a22016-07-25 13:54:51 -04004275 time_t t;
4276 u -= epoch;
4277 t = u;
4278 if (t != u) {
4279 PyErr_SetString(PyExc_OverflowError,
4280 "timestamp out of range for platform time_t");
4281 return -1;
4282 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004283 if (_PyTime_localtime(t, &local_time) != 0)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004284 return -1;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004285 return utc_to_seconds(local_time.tm_year + 1900,
4286 local_time.tm_mon + 1,
4287 local_time.tm_mday,
4288 local_time.tm_hour,
4289 local_time.tm_min,
4290 local_time.tm_sec);
4291}
4292
Tim Petersa9bc1682003-01-11 03:39:11 +00004293/* Internal helper.
4294 * Build datetime from a time_t and a distinct count of microseconds.
4295 * Pass localtime or gmtime for f, to control the interpretation of timet.
4296 */
4297static PyObject *
4298datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004299 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004300{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004301 struct tm tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004302 int year, month, day, hour, minute, second, fold = 0;
Tim Petersa9bc1682003-01-11 03:39:11 +00004303
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004304 if (f(timet, &tm) != 0)
4305 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01004306
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004307 year = tm.tm_year + 1900;
4308 month = tm.tm_mon + 1;
4309 day = tm.tm_mday;
4310 hour = tm.tm_hour;
4311 minute = tm.tm_min;
Victor Stinner21f58932012-03-14 00:15:40 +01004312 /* The platform localtime/gmtime may insert leap seconds,
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004313 * indicated by tm.tm_sec > 59. We don't care about them,
Victor Stinner21f58932012-03-14 00:15:40 +01004314 * except to the extent that passing them on to the datetime
4315 * constructor would raise ValueError for a reason that
4316 * made no sense to the user.
4317 */
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004318 second = Py_MIN(59, tm.tm_sec);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004319
Victor Stinnerb67f0962017-02-10 10:34:02 +01004320 /* local timezone requires to compute fold */
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004321 if (tzinfo == Py_None && f == _PyTime_localtime) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004322 long long probe_seconds, result_seconds, transition;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004323
4324 result_seconds = utc_to_seconds(year, month, day,
4325 hour, minute, second);
4326 /* Probe max_fold_seconds to detect a fold. */
4327 probe_seconds = local(epoch + timet - max_fold_seconds);
4328 if (probe_seconds == -1)
4329 return NULL;
4330 transition = result_seconds - probe_seconds - max_fold_seconds;
4331 if (transition < 0) {
4332 probe_seconds = local(epoch + timet + transition);
4333 if (probe_seconds == -1)
4334 return NULL;
4335 if (probe_seconds == result_seconds)
4336 fold = 1;
4337 }
4338 }
4339 return new_datetime_ex2(year, month, day, hour,
4340 minute, second, us, tzinfo, fold,
4341 (PyTypeObject *)cls);
Tim Petersa9bc1682003-01-11 03:39:11 +00004342}
4343
4344/* Internal helper.
4345 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4346 * to control the interpretation of the timestamp. Since a double doesn't
4347 * have enough bits to cover a datetime's full range of precision, it's
4348 * better to call datetime_from_timet_and_us provided you have a way
4349 * to get that much precision (e.g., C time() isn't good enough).
4350 */
4351static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004352datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004356 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004357
Victor Stinnere4a994d2015-03-30 01:10:14 +02004358 if (_PyTime_ObjectToTimeval(timestamp,
Victor Stinner7667f582015-09-09 01:02:23 +02004359 &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004361
Victor Stinner21f58932012-03-14 00:15:40 +01004362 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004363}
4364
4365/* Internal helper.
4366 * Build most accurate possible datetime for current time. Pass localtime or
4367 * gmtime for f as appropriate.
4368 */
4369static PyObject *
4370datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4371{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004372 _PyTime_t ts = _PyTime_GetSystemClock();
Victor Stinner1e2b6882015-09-18 13:23:02 +02004373 time_t secs;
4374 int us;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004375
Victor Stinner1e2b6882015-09-18 13:23:02 +02004376 if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner09e5cf22015-03-30 00:09:18 +02004377 return NULL;
Victor Stinner1e2b6882015-09-18 13:23:02 +02004378 assert(0 <= us && us <= 999999);
Victor Stinner09e5cf22015-03-30 00:09:18 +02004379
Victor Stinner1e2b6882015-09-18 13:23:02 +02004380 return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004381}
4382
Larry Hastings61272b72014-01-07 12:41:53 -08004383/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004384
4385@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004386datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004387
4388 tz: object = None
4389 Timezone object.
4390
4391Returns new datetime object representing current time local to tz.
4392
4393If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004394[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004395
Larry Hastings31826802013-10-19 00:09:25 -07004396static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004397datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03004398/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004401
Larry Hastings31826802013-10-19 00:09:25 -07004402 /* Return best possible local time -- this isn't constrained by the
4403 * precision of a timestamp.
4404 */
4405 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004407
Larry Hastings5c661892014-01-24 06:17:25 -08004408 self = datetime_best_possible((PyObject *)type,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004409 tz == Py_None ? _PyTime_localtime :
4410 _PyTime_gmtime,
Larry Hastings31826802013-10-19 00:09:25 -07004411 tz);
4412 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004414 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 }
4416 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004417}
4418
Tim Petersa9bc1682003-01-11 03:39:11 +00004419/* Return best possible UTC time -- this isn't constrained by the
4420 * precision of a timestamp.
4421 */
4422static PyObject *
4423datetime_utcnow(PyObject *cls, PyObject *dummy)
4424{
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004425 return datetime_best_possible(cls, _PyTime_gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004426}
4427
Tim Peters2a799bf2002-12-16 20:18:38 +00004428/* Return new local datetime from timestamp (Python timestamp -- a double). */
4429static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004430datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004433 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 PyObject *tzinfo = Py_None;
4435 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004436
Victor Stinner5d272cc2012-03-13 13:35:55 +01004437 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 keywords, &timestamp, &tzinfo))
4439 return NULL;
4440 if (check_tzinfo_subclass(tzinfo) < 0)
4441 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 self = datetime_from_timestamp(cls,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004444 tzinfo == Py_None ? _PyTime_localtime :
4445 _PyTime_gmtime,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 timestamp,
4447 tzinfo);
4448 if (self != NULL && tzinfo != Py_None) {
4449 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004450 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 }
4452 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004453}
4454
Tim Petersa9bc1682003-01-11 03:39:11 +00004455/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4456static PyObject *
4457datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4458{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004459 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004461
Victor Stinner5d272cc2012-03-13 13:35:55 +01004462 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004463 result = datetime_from_timestamp(cls, _PyTime_gmtime, timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 Py_None);
4465 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004466}
4467
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004468/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004469static PyObject *
4470datetime_strptime(PyObject *cls, PyObject *args)
4471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004473 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004474 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004476 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004478
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004479 if (module == NULL) {
4480 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004481 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004482 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 }
Victor Stinner20401de2016-12-09 15:24:31 +01004484 return _PyObject_CallMethodIdObjArgs(module, &PyId__strptime_datetime,
4485 cls, string, format, NULL);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004486}
4487
Tim Petersa9bc1682003-01-11 03:39:11 +00004488/* Return new datetime from date/datetime and time arguments. */
4489static PyObject *
4490datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4491{
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004492 static char *keywords[] = {"date", "time", "tzinfo", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 PyObject *date;
4494 PyObject *time;
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004495 PyObject *tzinfo = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004497
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004498 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 &PyDateTime_DateType, &date,
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004500 &PyDateTime_TimeType, &time, &tzinfo)) {
4501 if (tzinfo == NULL) {
4502 if (HASTZINFO(time))
4503 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4504 else
4505 tzinfo = Py_None;
4506 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 result = PyObject_CallFunction(cls, "iiiiiiiO",
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004508 GET_YEAR(date),
4509 GET_MONTH(date),
4510 GET_DAY(date),
4511 TIME_GET_HOUR(time),
4512 TIME_GET_MINUTE(time),
4513 TIME_GET_SECOND(time),
4514 TIME_GET_MICROSECOND(time),
4515 tzinfo);
4516 if (result)
4517 DATE_SET_FOLD(result, TIME_GET_FOLD(time));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 }
4519 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004520}
Tim Peters2a799bf2002-12-16 20:18:38 +00004521
4522/*
4523 * Destructor.
4524 */
4525
4526static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004527datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 if (HASTZINFO(self)) {
4530 Py_XDECREF(self->tzinfo);
4531 }
4532 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004533}
4534
4535/*
4536 * Indirect access to tzinfo methods.
4537 */
4538
Tim Peters2a799bf2002-12-16 20:18:38 +00004539/* These are all METH_NOARGS, so don't need to check the arglist. */
4540static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004541datetime_utcoffset(PyObject *self, PyObject *unused) {
4542 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004543}
4544
4545static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004546datetime_dst(PyObject *self, PyObject *unused) {
4547 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004548}
4549
4550static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004551datetime_tzname(PyObject *self, PyObject *unused) {
4552 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004553}
4554
4555/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004556 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004557 */
4558
Tim Petersa9bc1682003-01-11 03:39:11 +00004559/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4560 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004561 */
4562static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004563add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 /* Note that the C-level additions can't overflow, because of
4567 * invariant bounds on the member values.
4568 */
4569 int year = GET_YEAR(date);
4570 int month = GET_MONTH(date);
4571 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4572 int hour = DATE_GET_HOUR(date);
4573 int minute = DATE_GET_MINUTE(date);
4574 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4575 int microsecond = DATE_GET_MICROSECOND(date) +
4576 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 assert(factor == 1 || factor == -1);
4579 if (normalize_datetime(&year, &month, &day,
Victor Stinnerb67f0962017-02-10 10:34:02 +01004580 &hour, &minute, &second, &microsecond) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 return NULL;
Victor Stinnerb67f0962017-02-10 10:34:02 +01004582 }
4583
4584 return new_datetime(year, month, day,
4585 hour, minute, second, microsecond,
4586 HASTZINFO(date) ? date->tzinfo : Py_None, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004587}
4588
4589static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004590datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 if (PyDateTime_Check(left)) {
4593 /* datetime + ??? */
4594 if (PyDelta_Check(right))
4595 /* datetime + delta */
4596 return add_datetime_timedelta(
4597 (PyDateTime_DateTime *)left,
4598 (PyDateTime_Delta *)right,
4599 1);
4600 }
4601 else if (PyDelta_Check(left)) {
4602 /* delta + datetime */
4603 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4604 (PyDateTime_Delta *) left,
4605 1);
4606 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004607 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004608}
4609
4610static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004611datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 if (PyDateTime_Check(left)) {
4616 /* datetime - ??? */
4617 if (PyDateTime_Check(right)) {
4618 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004619 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004621
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004622 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4623 offset2 = offset1 = Py_None;
4624 Py_INCREF(offset1);
4625 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004627 else {
4628 offset1 = datetime_utcoffset(left, NULL);
4629 if (offset1 == NULL)
4630 return NULL;
4631 offset2 = datetime_utcoffset(right, NULL);
4632 if (offset2 == NULL) {
4633 Py_DECREF(offset1);
4634 return NULL;
4635 }
4636 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4637 PyErr_SetString(PyExc_TypeError,
4638 "can't subtract offset-naive and "
4639 "offset-aware datetimes");
4640 Py_DECREF(offset1);
4641 Py_DECREF(offset2);
4642 return NULL;
4643 }
4644 }
4645 if ((offset1 != offset2) &&
4646 delta_cmp(offset1, offset2) != 0) {
4647 offdiff = delta_subtract(offset1, offset2);
4648 if (offdiff == NULL) {
4649 Py_DECREF(offset1);
4650 Py_DECREF(offset2);
4651 return NULL;
4652 }
4653 }
4654 Py_DECREF(offset1);
4655 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 delta_d = ymd_to_ord(GET_YEAR(left),
4657 GET_MONTH(left),
4658 GET_DAY(left)) -
4659 ymd_to_ord(GET_YEAR(right),
4660 GET_MONTH(right),
4661 GET_DAY(right));
4662 /* These can't overflow, since the values are
4663 * normalized. At most this gives the number of
4664 * seconds in one day.
4665 */
4666 delta_s = (DATE_GET_HOUR(left) -
4667 DATE_GET_HOUR(right)) * 3600 +
4668 (DATE_GET_MINUTE(left) -
4669 DATE_GET_MINUTE(right)) * 60 +
4670 (DATE_GET_SECOND(left) -
4671 DATE_GET_SECOND(right));
4672 delta_us = DATE_GET_MICROSECOND(left) -
4673 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004675 if (result == NULL)
4676 return NULL;
4677
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004678 if (offdiff != NULL) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03004679 Py_SETREF(result, delta_subtract(result, offdiff));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004680 Py_DECREF(offdiff);
4681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 }
4683 else if (PyDelta_Check(right)) {
4684 /* datetime - delta */
4685 result = add_datetime_timedelta(
4686 (PyDateTime_DateTime *)left,
4687 (PyDateTime_Delta *)right,
4688 -1);
4689 }
4690 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 if (result == Py_NotImplemented)
4693 Py_INCREF(result);
4694 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004695}
4696
4697/* Various ways to turn a datetime into a string. */
4698
4699static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004700datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 const char *type_name = Py_TYPE(self)->tp_name;
4703 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 if (DATE_GET_MICROSECOND(self)) {
4706 baserepr = PyUnicode_FromFormat(
4707 "%s(%d, %d, %d, %d, %d, %d, %d)",
4708 type_name,
4709 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4710 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4711 DATE_GET_SECOND(self),
4712 DATE_GET_MICROSECOND(self));
4713 }
4714 else if (DATE_GET_SECOND(self)) {
4715 baserepr = PyUnicode_FromFormat(
4716 "%s(%d, %d, %d, %d, %d, %d)",
4717 type_name,
4718 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4719 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4720 DATE_GET_SECOND(self));
4721 }
4722 else {
4723 baserepr = PyUnicode_FromFormat(
4724 "%s(%d, %d, %d, %d, %d)",
4725 type_name,
4726 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4727 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4728 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004729 if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
4730 baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 if (baserepr == NULL || ! HASTZINFO(self))
4732 return baserepr;
4733 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004734}
4735
Tim Petersa9bc1682003-01-11 03:39:11 +00004736static PyObject *
4737datetime_str(PyDateTime_DateTime *self)
4738{
Victor Stinner4c381542016-12-09 00:33:39 +01004739 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "s", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004740}
Tim Peters2a799bf2002-12-16 20:18:38 +00004741
4742static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004743datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 int sep = 'T';
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004746 char *timespec = NULL;
4747 static char *keywords[] = {"sep", "timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 char buffer[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004749 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 int us = DATE_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004751 static char *specs[][2] = {
4752 {"hours", "%04d-%02d-%02d%c%02d"},
4753 {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
4754 {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
4755 {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
4756 {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
4757 };
4758 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00004759
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004760 if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 return NULL;
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004762
4763 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4764 if (us == 0) {
4765 /* seconds */
4766 given_spec = 2;
4767 }
4768 else {
4769 /* microseconds */
4770 given_spec = 4;
4771 }
4772 }
4773 else {
4774 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4775 if (strcmp(timespec, specs[given_spec][0]) == 0) {
4776 if (given_spec == 3) {
4777 us = us / 1000;
4778 }
4779 break;
4780 }
4781 }
4782 }
4783
4784 if (given_spec == Py_ARRAY_LENGTH(specs)) {
4785 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4786 return NULL;
4787 }
4788 else {
4789 result = PyUnicode_FromFormat(specs[given_spec][1],
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 GET_YEAR(self), GET_MONTH(self),
4791 GET_DAY(self), (int)sep,
4792 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4793 DATE_GET_SECOND(self), us);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004794 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 if (!result || !HASTZINFO(self))
4797 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 /* We need to append the UTC offset. */
4800 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4801 (PyObject *)self) < 0) {
4802 Py_DECREF(result);
4803 return NULL;
4804 }
4805 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4806 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004807}
4808
Tim Petersa9bc1682003-01-11 03:39:11 +00004809static PyObject *
4810datetime_ctime(PyDateTime_DateTime *self)
4811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 return format_ctime((PyDateTime_Date *)self,
4813 DATE_GET_HOUR(self),
4814 DATE_GET_MINUTE(self),
4815 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004816}
4817
Tim Peters2a799bf2002-12-16 20:18:38 +00004818/* Miscellaneous methods. */
4819
Tim Petersa9bc1682003-01-11 03:39:11 +00004820static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004821flip_fold(PyObject *dt)
4822{
4823 return new_datetime_ex2(GET_YEAR(dt),
4824 GET_MONTH(dt),
4825 GET_DAY(dt),
4826 DATE_GET_HOUR(dt),
4827 DATE_GET_MINUTE(dt),
4828 DATE_GET_SECOND(dt),
4829 DATE_GET_MICROSECOND(dt),
4830 HASTZINFO(dt) ?
4831 ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
4832 !DATE_GET_FOLD(dt),
4833 Py_TYPE(dt));
4834}
4835
4836static PyObject *
4837get_flip_fold_offset(PyObject *dt)
4838{
4839 PyObject *result, *flip_dt;
4840
4841 flip_dt = flip_fold(dt);
4842 if (flip_dt == NULL)
4843 return NULL;
4844 result = datetime_utcoffset(flip_dt, NULL);
4845 Py_DECREF(flip_dt);
4846 return result;
4847}
4848
4849/* PEP 495 exception: Whenever one or both of the operands in
4850 * inter-zone comparison is such that its utcoffset() depends
4851 * on the value of its fold fold attribute, the result is False.
4852 *
4853 * Return 1 if exception applies, 0 if not, and -1 on error.
4854 */
4855static int
4856pep495_eq_exception(PyObject *self, PyObject *other,
4857 PyObject *offset_self, PyObject *offset_other)
4858{
4859 int result = 0;
4860 PyObject *flip_offset;
4861
4862 flip_offset = get_flip_fold_offset(self);
4863 if (flip_offset == NULL)
4864 return -1;
4865 if (flip_offset != offset_self &&
4866 delta_cmp(flip_offset, offset_self))
4867 {
4868 result = 1;
4869 goto done;
4870 }
4871 Py_DECREF(flip_offset);
4872
4873 flip_offset = get_flip_fold_offset(other);
4874 if (flip_offset == NULL)
4875 return -1;
4876 if (flip_offset != offset_other &&
4877 delta_cmp(flip_offset, offset_other))
4878 result = 1;
4879 done:
4880 Py_DECREF(flip_offset);
4881 return result;
4882}
4883
4884static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004885datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004886{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004887 PyObject *result = NULL;
4888 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 if (! PyDateTime_Check(other)) {
4892 if (PyDate_Check(other)) {
4893 /* Prevent invocation of date_richcompare. We want to
4894 return NotImplemented here to give the other object
4895 a chance. But since DateTime is a subclass of
4896 Date, if the other object is a Date, it would
4897 compute an ordering based on the date part alone,
4898 and we don't want that. So force unequal or
4899 uncomparable here in that case. */
4900 if (op == Py_EQ)
4901 Py_RETURN_FALSE;
4902 if (op == Py_NE)
4903 Py_RETURN_TRUE;
4904 return cmperror(self, other);
4905 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004906 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004908
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004909 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4911 ((PyDateTime_DateTime *)other)->data,
4912 _PyDateTime_DATETIME_DATASIZE);
4913 return diff_to_bool(diff, op);
4914 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004915 offset1 = datetime_utcoffset(self, NULL);
4916 if (offset1 == NULL)
4917 return NULL;
4918 offset2 = datetime_utcoffset(other, NULL);
4919 if (offset2 == NULL)
4920 goto done;
4921 /* If they're both naive, or both aware and have the same offsets,
4922 * we get off cheap. Note that if they're both naive, offset1 ==
4923 * offset2 == Py_None at this point.
4924 */
4925 if ((offset1 == offset2) ||
4926 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4927 delta_cmp(offset1, offset2) == 0)) {
4928 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4929 ((PyDateTime_DateTime *)other)->data,
4930 _PyDateTime_DATETIME_DATASIZE);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004931 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4932 int ex = pep495_eq_exception(self, other, offset1, offset2);
4933 if (ex == -1)
4934 goto done;
4935 if (ex)
4936 diff = 1;
4937 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004938 result = diff_to_bool(diff, op);
4939 }
4940 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004942
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004943 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004944 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4945 other);
4946 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004947 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 diff = GET_TD_DAYS(delta);
4949 if (diff == 0)
4950 diff = GET_TD_SECONDS(delta) |
4951 GET_TD_MICROSECONDS(delta);
4952 Py_DECREF(delta);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004953 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4954 int ex = pep495_eq_exception(self, other, offset1, offset2);
4955 if (ex == -1)
4956 goto done;
4957 if (ex)
4958 diff = 1;
4959 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004960 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004961 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004962 else if (op == Py_EQ) {
4963 result = Py_False;
4964 Py_INCREF(result);
4965 }
4966 else if (op == Py_NE) {
4967 result = Py_True;
4968 Py_INCREF(result);
4969 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004970 else {
4971 PyErr_SetString(PyExc_TypeError,
4972 "can't compare offset-naive and "
4973 "offset-aware datetimes");
4974 }
4975 done:
4976 Py_DECREF(offset1);
4977 Py_XDECREF(offset2);
4978 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004979}
4980
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004981static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004982datetime_hash(PyDateTime_DateTime *self)
4983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004985 PyObject *offset, *self0;
4986 if (DATE_GET_FOLD(self)) {
4987 self0 = new_datetime_ex2(GET_YEAR(self),
4988 GET_MONTH(self),
4989 GET_DAY(self),
4990 DATE_GET_HOUR(self),
4991 DATE_GET_MINUTE(self),
4992 DATE_GET_SECOND(self),
4993 DATE_GET_MICROSECOND(self),
4994 HASTZINFO(self) ? self->tzinfo : Py_None,
4995 0, Py_TYPE(self));
4996 if (self0 == NULL)
4997 return -1;
4998 }
4999 else {
5000 self0 = (PyObject *)self;
5001 Py_INCREF(self0);
5002 }
5003 offset = datetime_utcoffset(self0, NULL);
5004 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005005
5006 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00005008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005010 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 self->hashcode = generic_hash(
5012 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005014 PyObject *temp1, *temp2;
5015 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00005016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 assert(HASTZINFO(self));
5018 days = ymd_to_ord(GET_YEAR(self),
5019 GET_MONTH(self),
5020 GET_DAY(self));
5021 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005022 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005024 temp1 = new_delta(days, seconds,
5025 DATE_GET_MICROSECOND(self),
5026 1);
5027 if (temp1 == NULL) {
5028 Py_DECREF(offset);
5029 return -1;
5030 }
5031 temp2 = delta_subtract(temp1, offset);
5032 Py_DECREF(temp1);
5033 if (temp2 == NULL) {
5034 Py_DECREF(offset);
5035 return -1;
5036 }
5037 self->hashcode = PyObject_Hash(temp2);
5038 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005040 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 }
5042 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00005043}
Tim Peters2a799bf2002-12-16 20:18:38 +00005044
5045static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005046datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00005047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 PyObject *clone;
5049 PyObject *tuple;
5050 int y = GET_YEAR(self);
5051 int m = GET_MONTH(self);
5052 int d = GET_DAY(self);
5053 int hh = DATE_GET_HOUR(self);
5054 int mm = DATE_GET_MINUTE(self);
5055 int ss = DATE_GET_SECOND(self);
5056 int us = DATE_GET_MICROSECOND(self);
5057 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005058 int fold = DATE_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00005059
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005060 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 datetime_kws,
5062 &y, &m, &d, &hh, &mm, &ss, &us,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005063 &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03005065 if (fold != 0 && fold != 1) {
5066 PyErr_SetString(PyExc_ValueError,
5067 "fold must be either 0 or 1");
5068 return NULL;
5069 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
5071 if (tuple == NULL)
5072 return NULL;
5073 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005074 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005075 DATE_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 Py_DECREF(tuple);
5078 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00005079}
5080
5081static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005082local_timezone_from_timestamp(time_t timestamp)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005083{
5084 PyObject *result = NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005085 PyObject *delta;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005086 struct tm local_time_tm;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005087 PyObject *nameo = NULL;
5088 const char *zone = NULL;
5089
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005090 if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005091 return NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005092#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005093 zone = local_time_tm.tm_zone;
5094 delta = new_delta(0, local_time_tm.tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005095#else /* HAVE_STRUCT_TM_TM_ZONE */
5096 {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005097 PyObject *local_time, *utc_time;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005098 struct tm utc_time_tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005099 char buf[100];
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005100 strftime(buf, sizeof(buf), "%Z", &local_time_tm);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005101 zone = buf;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005102 local_time = new_datetime(local_time_tm.tm_year + 1900,
5103 local_time_tm.tm_mon + 1,
5104 local_time_tm.tm_mday,
5105 local_time_tm.tm_hour,
5106 local_time_tm.tm_min,
5107 local_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005108 if (local_time == NULL) {
5109 return NULL;
5110 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005111 if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005112 return NULL;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005113 utc_time = new_datetime(utc_time_tm.tm_year + 1900,
5114 utc_time_tm.tm_mon + 1,
5115 utc_time_tm.tm_mday,
5116 utc_time_tm.tm_hour,
5117 utc_time_tm.tm_min,
5118 utc_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005119 if (utc_time == NULL) {
5120 Py_DECREF(local_time);
5121 return NULL;
5122 }
5123 delta = datetime_subtract(local_time, utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005124 Py_DECREF(local_time);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005125 Py_DECREF(utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005126 }
5127#endif /* HAVE_STRUCT_TM_TM_ZONE */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005128 if (delta == NULL) {
5129 return NULL;
5130 }
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005131 if (zone != NULL) {
5132 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
5133 if (nameo == NULL)
5134 goto error;
5135 }
5136 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02005137 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005138 error:
5139 Py_DECREF(delta);
5140 return result;
5141}
5142
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005143static PyObject *
5144local_timezone(PyDateTime_DateTime *utc_time)
5145{
5146 time_t timestamp;
5147 PyObject *delta;
5148 PyObject *one_second;
5149 PyObject *seconds;
5150
5151 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
5152 if (delta == NULL)
5153 return NULL;
5154 one_second = new_delta(0, 1, 0, 0);
5155 if (one_second == NULL) {
5156 Py_DECREF(delta);
5157 return NULL;
5158 }
5159 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
5160 (PyDateTime_Delta *)one_second);
5161 Py_DECREF(one_second);
5162 Py_DECREF(delta);
5163 if (seconds == NULL)
5164 return NULL;
5165 timestamp = _PyLong_AsTime_t(seconds);
5166 Py_DECREF(seconds);
5167 if (timestamp == -1 && PyErr_Occurred())
5168 return NULL;
5169 return local_timezone_from_timestamp(timestamp);
5170}
5171
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005172static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005173local_to_seconds(int year, int month, int day,
5174 int hour, int minute, int second, int fold);
5175
5176static PyObject *
5177local_timezone_from_local(PyDateTime_DateTime *local_dt)
5178{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005179 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005180 time_t timestamp;
5181 seconds = local_to_seconds(GET_YEAR(local_dt),
5182 GET_MONTH(local_dt),
5183 GET_DAY(local_dt),
5184 DATE_GET_HOUR(local_dt),
5185 DATE_GET_MINUTE(local_dt),
5186 DATE_GET_SECOND(local_dt),
5187 DATE_GET_FOLD(local_dt));
5188 if (seconds == -1)
5189 return NULL;
5190 /* XXX: add bounds check */
5191 timestamp = seconds - epoch;
5192 return local_timezone_from_timestamp(timestamp);
5193}
5194
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005195static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00005196datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00005197{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005198 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005199 PyObject *offset;
5200 PyObject *temp;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005201 PyObject *self_tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005202 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00005204
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005205 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07005206 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005207 return NULL;
5208
5209 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005210 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00005211
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005212 if (!HASTZINFO(self) || self->tzinfo == Py_None) {
5213 self_tzinfo = local_timezone_from_local(self);
5214 if (self_tzinfo == NULL)
5215 return NULL;
5216 } else {
5217 self_tzinfo = self->tzinfo;
5218 Py_INCREF(self_tzinfo);
5219 }
Tim Peters521fc152002-12-31 17:36:56 +00005220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 /* Conversion to self's own time zone is a NOP. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005222 if (self_tzinfo == tzinfo) {
5223 Py_DECREF(self_tzinfo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005224 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005225 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005226 }
Tim Peters521fc152002-12-31 17:36:56 +00005227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 /* Convert self to UTC. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005229 offset = call_utcoffset(self_tzinfo, (PyObject *)self);
5230 Py_DECREF(self_tzinfo);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005231 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005233 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005234 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5235 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005236 Py_DECREF(offset);
5237 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00005239
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005240 /* Make sure result is aware and UTC. */
5241 if (!HASTZINFO(result)) {
5242 temp = (PyObject *)result;
5243 result = (PyDateTime_DateTime *)
5244 new_datetime_ex2(GET_YEAR(result),
5245 GET_MONTH(result),
5246 GET_DAY(result),
5247 DATE_GET_HOUR(result),
5248 DATE_GET_MINUTE(result),
5249 DATE_GET_SECOND(result),
5250 DATE_GET_MICROSECOND(result),
5251 PyDateTime_TimeZone_UTC,
5252 DATE_GET_FOLD(result),
5253 Py_TYPE(result));
5254 Py_DECREF(temp);
5255 if (result == NULL)
5256 return NULL;
5257 }
5258 else {
5259 /* Result is already aware - just replace tzinfo. */
5260 temp = result->tzinfo;
5261 result->tzinfo = PyDateTime_TimeZone_UTC;
5262 Py_INCREF(result->tzinfo);
5263 Py_DECREF(temp);
5264 }
5265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005267 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005268 if (tzinfo == Py_None) {
5269 tzinfo = local_timezone(result);
5270 if (tzinfo == NULL) {
5271 Py_DECREF(result);
5272 return NULL;
5273 }
5274 }
5275 else
5276 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005277 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005278 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00005279
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005280 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005281 result = (PyDateTime_DateTime *)
Victor Stinner20401de2016-12-09 15:24:31 +01005282 _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_fromutc, temp, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005283 Py_DECREF(temp);
5284
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005285 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00005286}
5287
5288static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005289datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00005292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005294 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00005295
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005296 dst = call_dst(self->tzinfo, (PyObject *)self);
5297 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005299
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005300 if (dst != Py_None)
5301 dstflag = delta_bool((PyDateTime_Delta *)dst);
5302 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 }
5304 return build_struct_time(GET_YEAR(self),
5305 GET_MONTH(self),
5306 GET_DAY(self),
5307 DATE_GET_HOUR(self),
5308 DATE_GET_MINUTE(self),
5309 DATE_GET_SECOND(self),
5310 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00005311}
5312
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005313static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005314local_to_seconds(int year, int month, int day,
5315 int hour, int minute, int second, int fold)
5316{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005317 long long t, a, b, u1, u2, t1, t2, lt;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005318 t = utc_to_seconds(year, month, day, hour, minute, second);
5319 /* Our goal is to solve t = local(u) for u. */
5320 lt = local(t);
5321 if (lt == -1)
5322 return -1;
5323 a = lt - t;
5324 u1 = t - a;
5325 t1 = local(u1);
5326 if (t1 == -1)
5327 return -1;
5328 if (t1 == t) {
5329 /* We found one solution, but it may not be the one we need.
5330 * Look for an earlier solution (if `fold` is 0), or a
5331 * later one (if `fold` is 1). */
5332 if (fold)
5333 u2 = u1 + max_fold_seconds;
5334 else
5335 u2 = u1 - max_fold_seconds;
5336 lt = local(u2);
5337 if (lt == -1)
5338 return -1;
5339 b = lt - u2;
5340 if (a == b)
5341 return u1;
5342 }
5343 else {
5344 b = t1 - u1;
5345 assert(a != b);
5346 }
5347 u2 = t - b;
5348 t2 = local(u2);
5349 if (t2 == -1)
5350 return -1;
5351 if (t2 == t)
5352 return u2;
5353 if (t1 == t)
5354 return u1;
5355 /* We have found both offsets a and b, but neither t - a nor t - b is
5356 * a solution. This means t is in the gap. */
5357 return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
5358}
5359
5360/* date(1970,1,1).toordinal() == 719163 */
5361#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
5362
Tim Peters2a799bf2002-12-16 20:18:38 +00005363static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04005364datetime_timestamp(PyDateTime_DateTime *self)
5365{
5366 PyObject *result;
5367
5368 if (HASTZINFO(self) && self->tzinfo != Py_None) {
5369 PyObject *delta;
5370 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
5371 if (delta == NULL)
5372 return NULL;
5373 result = delta_total_seconds(delta);
5374 Py_DECREF(delta);
5375 }
5376 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005377 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005378 seconds = local_to_seconds(GET_YEAR(self),
5379 GET_MONTH(self),
5380 GET_DAY(self),
5381 DATE_GET_HOUR(self),
5382 DATE_GET_MINUTE(self),
5383 DATE_GET_SECOND(self),
5384 DATE_GET_FOLD(self));
5385 if (seconds == -1)
Alexander Belopolskya4415142012-06-08 12:33:09 -04005386 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005387 result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
5388 DATE_GET_MICROSECOND(self) / 1e6);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005389 }
5390 return result;
5391}
5392
5393static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005394datetime_getdate(PyDateTime_DateTime *self)
5395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 return new_date(GET_YEAR(self),
5397 GET_MONTH(self),
5398 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005399}
5400
5401static PyObject *
5402datetime_gettime(PyDateTime_DateTime *self)
5403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 return new_time(DATE_GET_HOUR(self),
5405 DATE_GET_MINUTE(self),
5406 DATE_GET_SECOND(self),
5407 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005408 Py_None,
5409 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005410}
5411
5412static PyObject *
5413datetime_gettimetz(PyDateTime_DateTime *self)
5414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005415 return new_time(DATE_GET_HOUR(self),
5416 DATE_GET_MINUTE(self),
5417 DATE_GET_SECOND(self),
5418 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005419 GET_DT_TZINFO(self),
5420 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005421}
5422
5423static PyObject *
5424datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005425{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005426 int y, m, d, hh, mm, ss;
5427 PyObject *tzinfo;
5428 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00005429
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005430 tzinfo = GET_DT_TZINFO(self);
5431 if (tzinfo == Py_None) {
5432 utcself = self;
5433 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005434 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005435 else {
5436 PyObject *offset;
5437 offset = call_utcoffset(tzinfo, (PyObject *)self);
5438 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00005439 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005440 if (offset == Py_None) {
5441 Py_DECREF(offset);
5442 utcself = self;
5443 Py_INCREF(utcself);
5444 }
5445 else {
5446 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5447 (PyDateTime_Delta *)offset, -1);
5448 Py_DECREF(offset);
5449 if (utcself == NULL)
5450 return NULL;
5451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005453 y = GET_YEAR(utcself);
5454 m = GET_MONTH(utcself);
5455 d = GET_DAY(utcself);
5456 hh = DATE_GET_HOUR(utcself);
5457 mm = DATE_GET_MINUTE(utcself);
5458 ss = DATE_GET_SECOND(utcself);
5459
5460 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005461 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005462}
5463
Tim Peters371935f2003-02-01 01:52:50 +00005464/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00005465
Tim Petersa9bc1682003-01-11 03:39:11 +00005466/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00005467 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5468 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00005469 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00005470 */
5471static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005472datetime_getstate(PyDateTime_DateTime *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00005473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 PyObject *basestate;
5475 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 basestate = PyBytes_FromStringAndSize((char *)self->data,
5478 _PyDateTime_DATETIME_DATASIZE);
5479 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005480 if (proto > 3 && DATE_GET_FOLD(self))
5481 /* Set the first bit of the third byte */
5482 PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5484 result = PyTuple_Pack(1, basestate);
5485 else
5486 result = PyTuple_Pack(2, basestate, self->tzinfo);
5487 Py_DECREF(basestate);
5488 }
5489 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005490}
5491
5492static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005493datetime_reduce_ex(PyDateTime_DateTime *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00005494{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005495 int proto;
5496 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005497 return NULL;
5498
5499 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00005500}
5501
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005502static PyObject *
5503datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
5504{
5505 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, 2));
5506}
5507
Tim Petersa9bc1682003-01-11 03:39:11 +00005508static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005511
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005512 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 {"utcnow", (PyCFunction)datetime_utcnow,
5515 METH_NOARGS | METH_CLASS,
5516 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5519 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5520 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5523 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05005524 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005526 {"strptime", (PyCFunction)datetime_strptime,
5527 METH_VARARGS | METH_CLASS,
5528 PyDoc_STR("string, format -> new datetime parsed from a string "
5529 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 {"combine", (PyCFunction)datetime_combine,
5532 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5533 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5538 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5541 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5544 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5547 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5550 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005551
Alexander Belopolskya4415142012-06-08 12:33:09 -04005552 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5553 PyDoc_STR("Return POSIX timestamp as float.")},
5554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5556 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5559 PyDoc_STR("[sep] -> string in ISO 8601 format, "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005560 "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 "sep is used to separate the year from the time, and "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005562 "defaults to 'T'.\n"
5563 "timespec specifies what components of the time to include"
5564 " (allowed values are 'auto', 'hours', 'minutes', 'seconds',"
5565 " 'milliseconds', and 'microseconds').\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5568 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5571 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005573 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5574 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5577 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5580 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005581
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005582 {"__reduce_ex__", (PyCFunction)datetime_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005583 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005584
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005585 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
5586 PyDoc_STR("__reduce__() -> (cls, state)")},
5587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005589};
5590
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02005591static const char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005592PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5593\n\
5594The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005595instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005596
Tim Petersa9bc1682003-01-11 03:39:11 +00005597static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 datetime_add, /* nb_add */
5599 datetime_subtract, /* nb_subtract */
5600 0, /* nb_multiply */
5601 0, /* nb_remainder */
5602 0, /* nb_divmod */
5603 0, /* nb_power */
5604 0, /* nb_negative */
5605 0, /* nb_positive */
5606 0, /* nb_absolute */
5607 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005608};
5609
Neal Norwitz227b5332006-03-22 09:28:35 +00005610static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 PyVarObject_HEAD_INIT(NULL, 0)
5612 "datetime.datetime", /* tp_name */
5613 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5614 0, /* tp_itemsize */
5615 (destructor)datetime_dealloc, /* tp_dealloc */
5616 0, /* tp_print */
5617 0, /* tp_getattr */
5618 0, /* tp_setattr */
5619 0, /* tp_reserved */
5620 (reprfunc)datetime_repr, /* tp_repr */
5621 &datetime_as_number, /* tp_as_number */
5622 0, /* tp_as_sequence */
5623 0, /* tp_as_mapping */
5624 (hashfunc)datetime_hash, /* tp_hash */
5625 0, /* tp_call */
5626 (reprfunc)datetime_str, /* tp_str */
5627 PyObject_GenericGetAttr, /* tp_getattro */
5628 0, /* tp_setattro */
5629 0, /* tp_as_buffer */
5630 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5631 datetime_doc, /* tp_doc */
5632 0, /* tp_traverse */
5633 0, /* tp_clear */
5634 datetime_richcompare, /* tp_richcompare */
5635 0, /* tp_weaklistoffset */
5636 0, /* tp_iter */
5637 0, /* tp_iternext */
5638 datetime_methods, /* tp_methods */
5639 0, /* tp_members */
5640 datetime_getset, /* tp_getset */
5641 &PyDateTime_DateType, /* tp_base */
5642 0, /* tp_dict */
5643 0, /* tp_descr_get */
5644 0, /* tp_descr_set */
5645 0, /* tp_dictoffset */
5646 0, /* tp_init */
5647 datetime_alloc, /* tp_alloc */
5648 datetime_new, /* tp_new */
5649 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005650};
5651
5652/* ---------------------------------------------------------------------------
5653 * Module methods and initialization.
5654 */
5655
5656static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005657 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005658};
5659
Tim Peters9ddf40b2004-06-20 22:41:32 +00005660/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5661 * datetime.h.
5662 */
5663static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 &PyDateTime_DateType,
5665 &PyDateTime_DateTimeType,
5666 &PyDateTime_TimeType,
5667 &PyDateTime_DeltaType,
5668 &PyDateTime_TZInfoType,
5669 new_date_ex,
5670 new_datetime_ex,
5671 new_time_ex,
5672 new_delta_ex,
5673 datetime_fromtimestamp,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005674 date_fromtimestamp,
5675 new_datetime_ex2,
5676 new_time_ex2
Tim Peters9ddf40b2004-06-20 22:41:32 +00005677};
5678
5679
Martin v. Löwis1a214512008-06-11 05:26:20 +00005680
5681static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005683 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 "Fast implementation of the datetime type.",
5685 -1,
5686 module_methods,
5687 NULL,
5688 NULL,
5689 NULL,
5690 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005691};
5692
Tim Peters2a799bf2002-12-16 20:18:38 +00005693PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005694PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 PyObject *m; /* a module object */
5697 PyObject *d; /* its dict */
5698 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005699 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 m = PyModule_Create(&datetimemodule);
5702 if (m == NULL)
5703 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 if (PyType_Ready(&PyDateTime_DateType) < 0)
5706 return NULL;
5707 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5708 return NULL;
5709 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5710 return NULL;
5711 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5712 return NULL;
5713 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5714 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005715 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5716 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 /* timedelta values */
5719 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 x = new_delta(0, 0, 1, 0);
5722 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5723 return NULL;
5724 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5727 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5728 return NULL;
5729 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5732 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5733 return NULL;
5734 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 /* date values */
5737 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 x = new_date(1, 1, 1);
5740 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5741 return NULL;
5742 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005744 x = new_date(MAXYEAR, 12, 31);
5745 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5746 return NULL;
5747 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 x = new_delta(1, 0, 0, 0);
5750 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5751 return NULL;
5752 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 /* time values */
5755 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005756
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005757 x = new_time(0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5759 return NULL;
5760 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005761
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005762 x = new_time(23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5764 return NULL;
5765 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005767 x = new_delta(0, 0, 1, 0);
5768 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5769 return NULL;
5770 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 /* datetime values */
5773 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005774
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005775 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005776 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5777 return NULL;
5778 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005779
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005780 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5782 return NULL;
5783 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 x = new_delta(0, 0, 1, 0);
5786 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5787 return NULL;
5788 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005789
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005790 /* timezone values */
5791 d = PyDateTime_TimeZoneType.tp_dict;
5792
5793 delta = new_delta(0, 0, 0, 0);
5794 if (delta == NULL)
5795 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005796 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005797 Py_DECREF(delta);
5798 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5799 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005800 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005801
5802 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5803 if (delta == NULL)
5804 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005805 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005806 Py_DECREF(delta);
5807 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5808 return NULL;
5809 Py_DECREF(x);
5810
5811 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5812 if (delta == NULL)
5813 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005814 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005815 Py_DECREF(delta);
5816 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5817 return NULL;
5818 Py_DECREF(x);
5819
Alexander Belopolskya4415142012-06-08 12:33:09 -04005820 /* Epoch */
5821 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005822 PyDateTime_TimeZone_UTC, 0);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005823 if (PyDateTime_Epoch == NULL)
5824 return NULL;
5825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005827 PyModule_AddIntMacro(m, MINYEAR);
5828 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 Py_INCREF(&PyDateTime_DateType);
5831 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 Py_INCREF(&PyDateTime_DateTimeType);
5834 PyModule_AddObject(m, "datetime",
5835 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 Py_INCREF(&PyDateTime_TimeType);
5838 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005840 Py_INCREF(&PyDateTime_DeltaType);
5841 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 Py_INCREF(&PyDateTime_TZInfoType);
5844 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005845
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005846 Py_INCREF(&PyDateTime_TimeZoneType);
5847 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005849 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5850 if (x == NULL)
5851 return NULL;
5852 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005854 /* A 4-year cycle has an extra leap day over what we'd get from
5855 * pasting together 4 single years.
5856 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005857 Py_BUILD_ASSERT(DI4Y == 4 * 365 + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005858 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005860 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5861 * get from pasting together 4 100-year cycles.
5862 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005863 Py_BUILD_ASSERT(DI400Y == 4 * DI100Y + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5867 * pasting together 25 4-year cycles.
5868 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005869 Py_BUILD_ASSERT(DI100Y == 25 * DI4Y - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005870 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005872 us_per_ms = PyLong_FromLong(1000);
5873 us_per_second = PyLong_FromLong(1000000);
5874 us_per_minute = PyLong_FromLong(60000000);
5875 seconds_per_day = PyLong_FromLong(24 * 3600);
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005876 if (us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 us_per_minute == NULL || seconds_per_day == NULL)
5878 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 /* The rest are too big for 32-bit ints, but even
5881 * us_per_week fits in 40 bits, so doubles should be exact.
5882 */
5883 us_per_hour = PyLong_FromDouble(3600000000.0);
5884 us_per_day = PyLong_FromDouble(86400000000.0);
5885 us_per_week = PyLong_FromDouble(604800000000.0);
5886 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5887 return NULL;
5888 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005889}
Tim Petersf3615152003-01-01 21:51:37 +00005890
5891/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005892Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005893 x.n = x stripped of its timezone -- its naive time.
5894 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 return None
Tim Petersf3615152003-01-01 21:51:37 +00005896 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005897 return None
Tim Petersf3615152003-01-01 21:51:37 +00005898 x.s = x's standard offset, x.o - x.d
5899
5900Now some derived rules, where k is a duration (timedelta).
5901
59021. x.o = x.s + x.d
5903 This follows from the definition of x.s.
5904
Tim Petersc5dc4da2003-01-02 17:55:03 +000059052. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005906 This is actually a requirement, an assumption we need to make about
5907 sane tzinfo classes.
5908
59093. The naive UTC time corresponding to x is x.n - x.o.
5910 This is again a requirement for a sane tzinfo class.
5911
59124. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005913 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005914
Tim Petersc5dc4da2003-01-02 17:55:03 +000059155. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005916 Again follows from how arithmetic is defined.
5917
Tim Peters8bb5ad22003-01-24 02:44:45 +00005918Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005919(meaning that the various tzinfo methods exist, and don't blow up or return
5920None when called).
5921
Tim Petersa9bc1682003-01-11 03:39:11 +00005922The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005923x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005924
5925By #3, we want
5926
Tim Peters8bb5ad22003-01-24 02:44:45 +00005927 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005928
5929The algorithm starts by attaching tz to x.n, and calling that y. So
5930x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5931becomes true; in effect, we want to solve [2] for k:
5932
Tim Peters8bb5ad22003-01-24 02:44:45 +00005933 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005934
5935By #1, this is the same as
5936
Tim Peters8bb5ad22003-01-24 02:44:45 +00005937 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005938
5939By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5940Substituting that into [3],
5941
Tim Peters8bb5ad22003-01-24 02:44:45 +00005942 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5943 k - (y+k).s - (y+k).d = 0; rearranging,
5944 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5945 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005946
Tim Peters8bb5ad22003-01-24 02:44:45 +00005947On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5948approximate k by ignoring the (y+k).d term at first. Note that k can't be
5949very large, since all offset-returning methods return a duration of magnitude
5950less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5951be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005952
5953In any case, the new value is
5954
Tim Peters8bb5ad22003-01-24 02:44:45 +00005955 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005956
Tim Peters8bb5ad22003-01-24 02:44:45 +00005957It's helpful to step back at look at [4] from a higher level: it's simply
5958mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005959
5960At this point, if
5961
Tim Peters8bb5ad22003-01-24 02:44:45 +00005962 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005963
5964we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005965at the start of daylight time. Picture US Eastern for concreteness. The wall
5966time 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 +00005967sense then. The docs ask that an Eastern tzinfo class consider such a time to
5968be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5969on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005970the only spelling that makes sense on the local wall clock.
5971
Tim Petersc5dc4da2003-01-02 17:55:03 +00005972In fact, if [5] holds at this point, we do have the standard-time spelling,
5973but that takes a bit of proof. We first prove a stronger result. What's the
5974difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005975
Tim Peters8bb5ad22003-01-24 02:44:45 +00005976 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005977
Tim Petersc5dc4da2003-01-02 17:55:03 +00005978Now
5979 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005980 (y + y.s).n = by #5
5981 y.n + y.s = since y.n = x.n
5982 x.n + y.s = since z and y are have the same tzinfo member,
5983 y.s = z.s by #2
5984 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005985
Tim Petersc5dc4da2003-01-02 17:55:03 +00005986Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005987
Tim Petersc5dc4da2003-01-02 17:55:03 +00005988 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005989 x.n - ((x.n + z.s) - z.o) = expanding
5990 x.n - x.n - z.s + z.o = cancelling
5991 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005992 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005993
Tim Petersc5dc4da2003-01-02 17:55:03 +00005994So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005995
Tim Petersc5dc4da2003-01-02 17:55:03 +00005996If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005997spelling we wanted in the endcase described above. We're done. Contrarily,
5998if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005999
Tim Petersc5dc4da2003-01-02 17:55:03 +00006000If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
6001add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00006002local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00006003
Tim Petersc5dc4da2003-01-02 17:55:03 +00006004Let
Tim Petersf3615152003-01-01 21:51:37 +00006005
Tim Peters4fede1a2003-01-04 00:26:59 +00006006 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00006007
Tim Peters4fede1a2003-01-04 00:26:59 +00006008and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00006009
Tim Peters8bb5ad22003-01-24 02:44:45 +00006010 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00006011
Tim Peters8bb5ad22003-01-24 02:44:45 +00006012If so, we're done. If not, the tzinfo class is insane, according to the
6013assumptions we've made. This also requires a bit of proof. As before, let's
6014compute the difference between the LHS and RHS of [8] (and skipping some of
6015the justifications for the kinds of substitutions we've done several times
6016already):
Tim Peters4fede1a2003-01-04 00:26:59 +00006017
Tim Peters8bb5ad22003-01-24 02:44:45 +00006018 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 x.n - (z.n + diff - z'.o) = replacing diff via [6]
6020 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
6021 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
6022 - z.n + z.n - z.o + z'.o = cancel z.n
6023 - z.o + z'.o = #1 twice
6024 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
6025 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00006026
6027So 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 +00006028we've found the UTC-equivalent so are done. In fact, we stop with [7] and
6029return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00006030
Tim Peters8bb5ad22003-01-24 02:44:45 +00006031How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
6032a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
6033would have to change the result dst() returns: we start in DST, and moving
6034a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00006035
Tim Peters8bb5ad22003-01-24 02:44:45 +00006036There isn't a sane case where this can happen. The closest it gets is at
6037the end of DST, where there's an hour in UTC with no spelling in a hybrid
6038tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
6039that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
6040UTC) because the docs insist on that, but 0:MM is taken as being in daylight
6041time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
6042clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
6043standard time. Since that's what the local clock *does*, we want to map both
6044UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00006045in local time, but so it goes -- it's the way the local clock works.
6046
Tim Peters8bb5ad22003-01-24 02:44:45 +00006047When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
6048so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
6049z' = 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 +00006050(correctly) concludes that z' is not UTC-equivalent to x.
6051
6052Because we know z.d said z was in daylight time (else [5] would have held and
6053we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006054and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00006055return in Eastern, it follows that z'.d must be 0 (which it is in the example,
6056but the reasoning doesn't depend on the example -- it depends on there being
6057two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00006058z' must be in standard time, and is the spelling we want in this case.
6059
6060Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
6061concerned (because it takes z' as being in standard time rather than the
6062daylight time we intend here), but returning it gives the real-life "local
6063clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
6064tz.
6065
6066When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
6067the 1:MM standard time spelling we want.
6068
6069So how can this break? One of the assumptions must be violated. Two
6070possibilities:
6071
60721) [2] effectively says that y.s is invariant across all y belong to a given
6073 time zone. This isn't true if, for political reasons or continental drift,
6074 a region decides to change its base offset from UTC.
6075
60762) There may be versions of "double daylight" time where the tail end of
6077 the analysis gives up a step too early. I haven't thought about that
6078 enough to say.
6079
6080In any case, it's clear that the default fromutc() is strong enough to handle
6081"almost all" time zones: so long as the standard offset is invariant, it
6082doesn't matter if daylight time transition points change from year to year, or
6083if daylight time is skipped in some years; it doesn't matter how large or
6084small dst() may get within its bounds; and it doesn't even matter if some
6085perverse time zone returns a negative dst()). So a breaking case must be
6086pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00006087--------------------------------------------------------------------------- */