blob: 28805d18da8eee59a558381977a5234a2711feb7 [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_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
863 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400864 " representing a whole number of minutes,"
865 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000866 return NULL;
867 }
868 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
869 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
870 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
871 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400872 " timedelta(hours=24),"
873 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000874 return NULL;
875 }
876
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000877 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000878}
879
Tim Petersb0c854d2003-05-17 15:57:00 +0000880/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000881 * tzinfo helpers.
882 */
883
Tim Peters855fe882002-12-22 03:43:39 +0000884/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
885 * raise TypeError and return -1.
886 */
887static int
888check_tzinfo_subclass(PyObject *p)
889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 if (p == Py_None || PyTZInfo_Check(p))
891 return 0;
892 PyErr_Format(PyExc_TypeError,
893 "tzinfo argument must be None or of a tzinfo subclass, "
894 "not type '%s'",
895 Py_TYPE(p)->tp_name);
896 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000897}
898
Tim Peters2a799bf2002-12-16 20:18:38 +0000899/* If self has a tzinfo member, return a BORROWED reference to it. Else
900 * return NULL, which is NOT AN ERROR. There are no error returns here,
901 * and the caller must not decref the result.
902 */
903static PyObject *
904get_tzinfo_member(PyObject *self)
905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (PyDateTime_Check(self) && HASTZINFO(self))
909 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
910 else if (PyTime_Check(self) && HASTZINFO(self))
911 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000914}
915
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000916/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
917 * be an instance of the tzinfo class. If the method returns None, this
918 * returns None. If the method doesn't return None or timedelta, TypeError is
919 * raised and this returns NULL. If it returns a timedelta and the value is
920 * out of range or isn't a whole number of minutes, ValueError is raised and
921 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000922 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000923static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200924call_tzinfo_method(PyObject *tzinfo, const char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000925{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000926 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000929 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000931
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000932 if (tzinfo == Py_None)
933 Py_RETURN_NONE;
934 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
935 if (offset == Py_None || offset == NULL)
936 return offset;
937 if (PyDelta_Check(offset)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400938 if (GET_TD_MICROSECONDS(offset) != 0) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000939 Py_DECREF(offset);
940 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400941 " representing a whole number of seconds");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000942 return NULL;
943 }
944 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
945 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
946 Py_DECREF(offset);
947 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
948 " strictly between -timedelta(hours=24) and"
949 " timedelta(hours=24).");
950 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 }
952 }
953 else {
954 PyErr_Format(PyExc_TypeError,
955 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000956 "timedelta, not '%.200s'",
957 name, Py_TYPE(offset)->tp_name);
Raymond Hettinger5a2146a2014-07-25 14:59:48 -0700958 Py_DECREF(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000959 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000961
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000962 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000963}
964
965/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
966 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
967 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000968 * doesn't return None or timedelta, TypeError is raised and this returns -1.
969 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
970 * # of minutes), ValueError is raised and this returns -1. Else *none is
971 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000972 */
Tim Peters855fe882002-12-22 03:43:39 +0000973static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000974call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
975{
976 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000977}
978
Tim Peters2a799bf2002-12-16 20:18:38 +0000979/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
980 * result. tzinfo must be an instance of the tzinfo class. If dst()
981 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000982 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000983 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000984 * ValueError is raised and this returns -1. Else *none is set to 0 and
985 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000986 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000987static PyObject *
988call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000989{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000990 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000991}
992
Tim Petersbad8ff02002-12-30 20:52:32 +0000993/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000994 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000995 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000996 * returns NULL. If the result is a string, we ensure it is a Unicode
997 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000998 */
999static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001000call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001003 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 assert(tzinfo != NULL);
1006 assert(check_tzinfo_subclass(tzinfo) >= 0);
1007 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001010 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001011
Victor Stinner20401de2016-12-09 15:24:31 +01001012 result = _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_tzname,
1013 tzinfoarg, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001014
1015 if (result == NULL || result == Py_None)
1016 return result;
1017
1018 if (!PyUnicode_Check(result)) {
1019 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
1020 "return None or a string, not '%s'",
1021 Py_TYPE(result)->tp_name);
1022 Py_DECREF(result);
1023 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001025
1026 return result;
Tim Peters00237032002-12-27 02:21:51 +00001027}
1028
Tim Peters2a799bf2002-12-16 20:18:38 +00001029/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1030 * stuff
1031 * ", tzinfo=" + repr(tzinfo)
1032 * before the closing ")".
1033 */
1034static PyObject *
1035append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 assert(PyUnicode_Check(repr));
1040 assert(tzinfo);
1041 if (tzinfo == Py_None)
1042 return repr;
1043 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1045 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 Py_DECREF(repr);
1047 if (temp == NULL)
1048 return NULL;
1049 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1050 Py_DECREF(temp);
1051 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001052}
1053
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001054/* repr is like "someclass(arg1, arg2)". If fold isn't 0,
1055 * stuff
1056 * ", fold=" + repr(tzinfo)
1057 * before the closing ")".
1058 */
1059static PyObject *
1060append_keyword_fold(PyObject *repr, int fold)
1061{
1062 PyObject *temp;
1063
1064 assert(PyUnicode_Check(repr));
1065 if (fold == 0)
1066 return repr;
1067 /* Get rid of the trailing ')'. */
1068 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1069 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
1070 Py_DECREF(repr);
1071 if (temp == NULL)
1072 return NULL;
1073 repr = PyUnicode_FromFormat("%U, fold=%d)", temp, fold);
1074 Py_DECREF(temp);
1075 return repr;
1076}
1077
Tim Peters2a799bf2002-12-16 20:18:38 +00001078/* ---------------------------------------------------------------------------
1079 * String format helpers.
1080 */
1081
1082static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001083format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001084{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001085 static const char * const DayNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1087 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001088 static const char * const MonthNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1090 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1091 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1096 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1097 GET_DAY(date), hours, minutes, seconds,
1098 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001099}
1100
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001101static PyObject *delta_negative(PyDateTime_Delta *self);
1102
Tim Peters2a799bf2002-12-16 20:18:38 +00001103/* Add an hours & minutes UTC offset string to buf. buf has no more than
1104 * buflen bytes remaining. The UTC offset is gotten by calling
1105 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1106 * *buf, and that's all. Else the returned value is checked for sanity (an
1107 * integer in range), and if that's OK it's converted to an hours & minutes
1108 * string of the form
1109 * sign HH sep MM
1110 * Returns 0 if everything is OK. If the return value from utcoffset() is
1111 * bogus, an appropriate exception is set and -1 is returned.
1112 */
1113static int
Tim Peters328fff72002-12-20 01:31:27 +00001114format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001116{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001117 PyObject *offset;
1118 int hours, minutes, seconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001122
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001123 offset = call_utcoffset(tzinfo, tzinfoarg);
1124 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001126 if (offset == Py_None) {
1127 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 *buf = '\0';
1129 return 0;
1130 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001131 /* Offset is normalized, so it is negative if days < 0 */
1132 if (GET_TD_DAYS(offset) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 sign = '-';
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03001134 Py_SETREF(offset, delta_negative((PyDateTime_Delta *)offset));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001135 if (offset == NULL)
1136 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001138 else {
1139 sign = '+';
1140 }
1141 /* Offset is not negative here. */
1142 seconds = GET_TD_SECONDS(offset);
1143 Py_DECREF(offset);
1144 minutes = divmod(seconds, 60, &seconds);
1145 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001146 if (seconds == 0)
1147 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1148 else
1149 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d", sign, hours,
1150 sep, minutes, sep, seconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001152}
1153
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001154static PyObject *
1155make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 PyObject *temp;
1158 PyObject *tzinfo = get_tzinfo_member(object);
1159 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001160 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (Zreplacement == NULL)
1163 return NULL;
1164 if (tzinfo == Py_None || tzinfo == NULL)
1165 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 assert(tzinfoarg != NULL);
1168 temp = call_tzname(tzinfo, tzinfoarg);
1169 if (temp == NULL)
1170 goto Error;
1171 if (temp == Py_None) {
1172 Py_DECREF(temp);
1173 return Zreplacement;
1174 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 assert(PyUnicode_Check(temp));
1177 /* Since the tzname is getting stuffed into the
1178 * format, we have to double any % signs so that
1179 * strftime doesn't treat them as format codes.
1180 */
1181 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001182 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(temp);
1184 if (Zreplacement == NULL)
1185 return NULL;
1186 if (!PyUnicode_Check(Zreplacement)) {
1187 PyErr_SetString(PyExc_TypeError,
1188 "tzname.replace() did not return a string");
1189 goto Error;
1190 }
1191 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001192
1193 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 Py_DECREF(Zreplacement);
1195 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001196}
1197
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001198static PyObject *
1199make_freplacement(PyObject *object)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 char freplacement[64];
1202 if (PyTime_Check(object))
1203 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1204 else if (PyDateTime_Check(object))
1205 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1206 else
1207 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001210}
1211
Tim Peters2a799bf2002-12-16 20:18:38 +00001212/* I sure don't want to reproduce the strftime code from the time module,
1213 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001214 * giving special meanings to the %z, %Z and %f format codes via a
1215 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001216 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1217 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001218 */
1219static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001220wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1226 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1227 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 const char *pin; /* pointer to next char in input format */
1230 Py_ssize_t flen; /* length of input format */
1231 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 PyObject *newfmt = NULL; /* py string, the output format */
1234 char *pnew; /* pointer to available byte in output format */
1235 size_t totalnew; /* number bytes total in output format buffer,
1236 exclusive of trailing \0 */
1237 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 const char *ptoappend; /* ptr to string to append to output buffer */
1240 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 assert(object && format && timetuple);
1243 assert(PyUnicode_Check(format));
1244 /* Convert the input format to a C string and size */
Serhiy Storchaka06515832016-11-20 09:13:07 +02001245 pin = PyUnicode_AsUTF8AndSize(format, &flen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (!pin)
1247 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 /* Scan the input format, looking for %z/%Z/%f escapes, building
1250 * a new format. Since computing the replacements for those codes
1251 * is expensive, don't unless they're actually used.
1252 */
1253 if (flen > INT_MAX - 1) {
1254 PyErr_NoMemory();
1255 goto Done;
1256 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 totalnew = flen + 1; /* realistic if no %z/%Z */
1259 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1260 if (newfmt == NULL) goto Done;
1261 pnew = PyBytes_AsString(newfmt);
1262 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 while ((ch = *pin++) != '\0') {
1265 if (ch != '%') {
1266 ptoappend = pin - 1;
1267 ntoappend = 1;
1268 }
1269 else if ((ch = *pin++) == '\0') {
1270 /* There's a lone trailing %; doesn't make sense. */
1271 PyErr_SetString(PyExc_ValueError, "strftime format "
1272 "ends with raw %");
1273 goto Done;
1274 }
1275 /* A % has been seen and ch is the character after it. */
1276 else if (ch == 'z') {
1277 if (zreplacement == NULL) {
1278 /* format utcoffset */
1279 char buf[100];
1280 PyObject *tzinfo = get_tzinfo_member(object);
1281 zreplacement = PyBytes_FromStringAndSize("", 0);
1282 if (zreplacement == NULL) goto Done;
1283 if (tzinfo != Py_None && tzinfo != NULL) {
1284 assert(tzinfoarg != NULL);
1285 if (format_utcoffset(buf,
1286 sizeof(buf),
1287 "",
1288 tzinfo,
1289 tzinfoarg) < 0)
1290 goto Done;
1291 Py_DECREF(zreplacement);
1292 zreplacement =
1293 PyBytes_FromStringAndSize(buf,
1294 strlen(buf));
1295 if (zreplacement == NULL)
1296 goto Done;
1297 }
1298 }
1299 assert(zreplacement != NULL);
1300 ptoappend = PyBytes_AS_STRING(zreplacement);
1301 ntoappend = PyBytes_GET_SIZE(zreplacement);
1302 }
1303 else if (ch == 'Z') {
1304 /* format tzname */
1305 if (Zreplacement == NULL) {
1306 Zreplacement = make_Zreplacement(object,
1307 tzinfoarg);
1308 if (Zreplacement == NULL)
1309 goto Done;
1310 }
1311 assert(Zreplacement != NULL);
1312 assert(PyUnicode_Check(Zreplacement));
Serhiy Storchaka06515832016-11-20 09:13:07 +02001313 ptoappend = PyUnicode_AsUTF8AndSize(Zreplacement,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001315 if (ptoappend == NULL)
1316 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 }
1318 else if (ch == 'f') {
1319 /* format microseconds */
1320 if (freplacement == NULL) {
1321 freplacement = make_freplacement(object);
1322 if (freplacement == NULL)
1323 goto Done;
1324 }
1325 assert(freplacement != NULL);
1326 assert(PyBytes_Check(freplacement));
1327 ptoappend = PyBytes_AS_STRING(freplacement);
1328 ntoappend = PyBytes_GET_SIZE(freplacement);
1329 }
1330 else {
1331 /* percent followed by neither z nor Z */
1332 ptoappend = pin - 2;
1333 ntoappend = 2;
1334 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /* Append the ntoappend chars starting at ptoappend to
1337 * the new format.
1338 */
1339 if (ntoappend == 0)
1340 continue;
1341 assert(ptoappend != NULL);
1342 assert(ntoappend > 0);
1343 while (usednew + ntoappend > totalnew) {
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001344 if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 PyErr_NoMemory();
1346 goto Done;
1347 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001348 totalnew <<= 1;
1349 if (_PyBytes_Resize(&newfmt, totalnew) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 pnew = PyBytes_AsString(newfmt) + usednew;
1352 }
1353 memcpy(pnew, ptoappend, ntoappend);
1354 pnew += ntoappend;
1355 usednew += ntoappend;
1356 assert(usednew <= totalnew);
1357 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1360 goto Done;
1361 {
1362 PyObject *format;
1363 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 if (time == NULL)
1366 goto Done;
1367 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1368 if (format != NULL) {
Victor Stinner20401de2016-12-09 15:24:31 +01001369 result = _PyObject_CallMethodIdObjArgs(time, &PyId_strftime,
1370 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 Py_DECREF(format);
1372 }
1373 Py_DECREF(time);
1374 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001375 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 Py_XDECREF(freplacement);
1377 Py_XDECREF(zreplacement);
1378 Py_XDECREF(Zreplacement);
1379 Py_XDECREF(newfmt);
1380 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001381}
1382
Tim Peters2a799bf2002-12-16 20:18:38 +00001383/* ---------------------------------------------------------------------------
1384 * Wrap functions from the time module. These aren't directly available
1385 * from C. Perhaps they should be.
1386 */
1387
1388/* Call time.time() and return its result (a Python float). */
1389static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001390time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 PyObject *result = NULL;
1393 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001396 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001397
Victor Stinnerad8c83a2016-09-05 17:53:15 -07001398 result = _PyObject_CallMethodId(time, &PyId_time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_DECREF(time);
1400 }
1401 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001402}
1403
1404/* Build a time.struct_time. The weekday and day number are automatically
1405 * computed from the y,m,d args.
1406 */
1407static PyObject *
1408build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyObject *time;
Victor Stinner2b635972016-12-09 00:38:16 +01001411 PyObject *result;
1412 _Py_IDENTIFIER(struct_time);
1413 PyObject *args;
1414
Tim Peters2a799bf2002-12-16 20:18:38 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 time = PyImport_ImportModuleNoBlock("time");
Victor Stinner2b635972016-12-09 00:38:16 +01001417 if (time == NULL) {
1418 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 }
Victor Stinner2b635972016-12-09 00:38:16 +01001420
1421 args = Py_BuildValue("iiiiiiiii",
1422 y, m, d,
1423 hh, mm, ss,
1424 weekday(y, m, d),
1425 days_before_month(y, m) + d,
1426 dstflag);
1427 if (args == NULL) {
1428 Py_DECREF(time);
1429 return NULL;
1430 }
1431
1432 result = _PyObject_CallMethodIdObjArgs(time, &PyId_struct_time,
1433 args, NULL);
1434 Py_DECREF(time);
Victor Stinnerddc120f2016-12-09 15:35:40 +01001435 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001437}
1438
1439/* ---------------------------------------------------------------------------
1440 * Miscellaneous helpers.
1441 */
1442
Mark Dickinsone94c6792009-02-02 20:36:42 +00001443/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001444 * The comparisons here all most naturally compute a cmp()-like result.
1445 * This little helper turns that into a bool result for rich comparisons.
1446 */
1447static PyObject *
1448diff_to_bool(int diff, int op)
1449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 PyObject *result;
1451 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 switch (op) {
1454 case Py_EQ: istrue = diff == 0; break;
1455 case Py_NE: istrue = diff != 0; break;
1456 case Py_LE: istrue = diff <= 0; break;
1457 case Py_GE: istrue = diff >= 0; break;
1458 case Py_LT: istrue = diff < 0; break;
1459 case Py_GT: istrue = diff > 0; break;
1460 default:
1461 assert(! "op unknown");
1462 istrue = 0; /* To shut up compiler */
1463 }
1464 result = istrue ? Py_True : Py_False;
1465 Py_INCREF(result);
1466 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001467}
1468
Tim Peters07534a62003-02-07 22:50:28 +00001469/* Raises a "can't compare" TypeError and returns NULL. */
1470static PyObject *
1471cmperror(PyObject *a, PyObject *b)
1472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 PyErr_Format(PyExc_TypeError,
1474 "can't compare %s to %s",
1475 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1476 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001477}
1478
Tim Peters2a799bf2002-12-16 20:18:38 +00001479/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001480 * Cached Python objects; these are set by the module init function.
1481 */
1482
1483/* Conversion factors. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484static PyObject *us_per_ms = NULL; /* 1000 */
1485static PyObject *us_per_second = NULL; /* 1000000 */
1486static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001487static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
1488static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
1489static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
Tim Peters2a799bf2002-12-16 20:18:38 +00001490static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1491
Tim Peters2a799bf2002-12-16 20:18:38 +00001492/* ---------------------------------------------------------------------------
1493 * Class implementations.
1494 */
1495
1496/*
1497 * PyDateTime_Delta implementation.
1498 */
1499
1500/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Serhiy Storchaka95949422013-08-27 19:40:23 +03001502 * as a Python int.
Tim Peters2a799bf2002-12-16 20:18:38 +00001503 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1504 * due to ubiquitous overflow possibilities.
1505 */
1506static PyObject *
1507delta_to_microseconds(PyDateTime_Delta *self)
1508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 PyObject *x1 = NULL;
1510 PyObject *x2 = NULL;
1511 PyObject *x3 = NULL;
1512 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1515 if (x1 == NULL)
1516 goto Done;
1517 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1518 if (x2 == NULL)
1519 goto Done;
1520 Py_DECREF(x1);
1521 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 /* x2 has days in seconds */
1524 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1525 if (x1 == NULL)
1526 goto Done;
1527 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1528 if (x3 == NULL)
1529 goto Done;
1530 Py_DECREF(x1);
1531 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001532 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 /* x3 has days+seconds in seconds */
1535 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1536 if (x1 == NULL)
1537 goto Done;
1538 Py_DECREF(x3);
1539 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 /* x1 has days+seconds in us */
1542 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1543 if (x2 == NULL)
1544 goto Done;
1545 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001546
1547Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 Py_XDECREF(x1);
1549 Py_XDECREF(x2);
1550 Py_XDECREF(x3);
1551 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001552}
1553
Serhiy Storchaka95949422013-08-27 19:40:23 +03001554/* Convert a number of us (as a Python int) to a timedelta.
Tim Peters2a799bf2002-12-16 20:18:38 +00001555 */
1556static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001557microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 int us;
1560 int s;
1561 int d;
1562 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 PyObject *tuple = NULL;
1565 PyObject *num = NULL;
1566 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 tuple = PyNumber_Divmod(pyus, us_per_second);
1569 if (tuple == NULL)
1570 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 num = PyTuple_GetItem(tuple, 1); /* us */
1573 if (num == NULL)
1574 goto Done;
1575 temp = PyLong_AsLong(num);
1576 num = NULL;
1577 if (temp == -1 && PyErr_Occurred())
1578 goto Done;
1579 assert(0 <= temp && temp < 1000000);
1580 us = (int)temp;
1581 if (us < 0) {
1582 /* The divisor was positive, so this must be an error. */
1583 assert(PyErr_Occurred());
1584 goto Done;
1585 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1588 if (num == NULL)
1589 goto Done;
1590 Py_INCREF(num);
1591 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 tuple = PyNumber_Divmod(num, seconds_per_day);
1594 if (tuple == NULL)
1595 goto Done;
1596 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 num = PyTuple_GetItem(tuple, 1); /* seconds */
1599 if (num == NULL)
1600 goto Done;
1601 temp = PyLong_AsLong(num);
1602 num = NULL;
1603 if (temp == -1 && PyErr_Occurred())
1604 goto Done;
1605 assert(0 <= temp && temp < 24*3600);
1606 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 if (s < 0) {
1609 /* The divisor was positive, so this must be an error. */
1610 assert(PyErr_Occurred());
1611 goto Done;
1612 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1615 if (num == NULL)
1616 goto Done;
1617 Py_INCREF(num);
1618 temp = PyLong_AsLong(num);
1619 if (temp == -1 && PyErr_Occurred())
1620 goto Done;
1621 d = (int)temp;
1622 if ((long)d != temp) {
1623 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1624 "large to fit in a C int");
1625 goto Done;
1626 }
1627 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001628
1629Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 Py_XDECREF(tuple);
1631 Py_XDECREF(num);
1632 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001633}
1634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635#define microseconds_to_delta(pymicros) \
1636 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001637
Tim Peters2a799bf2002-12-16 20:18:38 +00001638static PyObject *
1639multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 PyObject *pyus_in;
1642 PyObject *pyus_out;
1643 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 pyus_in = delta_to_microseconds(delta);
1646 if (pyus_in == NULL)
1647 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1650 Py_DECREF(pyus_in);
1651 if (pyus_out == NULL)
1652 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 result = microseconds_to_delta(pyus_out);
1655 Py_DECREF(pyus_out);
1656 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001657}
1658
1659static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001660multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1661{
1662 PyObject *result = NULL;
1663 PyObject *pyus_in = NULL, *temp, *pyus_out;
1664 PyObject *ratio = NULL;
1665
1666 pyus_in = delta_to_microseconds(delta);
1667 if (pyus_in == NULL)
1668 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001669 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001670 if (ratio == NULL)
1671 goto error;
1672 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1673 Py_DECREF(pyus_in);
1674 pyus_in = NULL;
1675 if (temp == NULL)
1676 goto error;
1677 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1678 Py_DECREF(temp);
1679 if (pyus_out == NULL)
1680 goto error;
1681 result = microseconds_to_delta(pyus_out);
1682 Py_DECREF(pyus_out);
1683 error:
1684 Py_XDECREF(pyus_in);
1685 Py_XDECREF(ratio);
1686
1687 return result;
1688}
1689
1690static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001691divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 PyObject *pyus_in;
1694 PyObject *pyus_out;
1695 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 pyus_in = delta_to_microseconds(delta);
1698 if (pyus_in == NULL)
1699 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1702 Py_DECREF(pyus_in);
1703 if (pyus_out == NULL)
1704 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 result = microseconds_to_delta(pyus_out);
1707 Py_DECREF(pyus_out);
1708 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001709}
1710
1711static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001712divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 PyObject *pyus_left;
1715 PyObject *pyus_right;
1716 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 pyus_left = delta_to_microseconds(left);
1719 if (pyus_left == NULL)
1720 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 pyus_right = delta_to_microseconds(right);
1723 if (pyus_right == NULL) {
1724 Py_DECREF(pyus_left);
1725 return NULL;
1726 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1729 Py_DECREF(pyus_left);
1730 Py_DECREF(pyus_right);
1731 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001732}
1733
1734static PyObject *
1735truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyObject *pyus_left;
1738 PyObject *pyus_right;
1739 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 pyus_left = delta_to_microseconds(left);
1742 if (pyus_left == NULL)
1743 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 pyus_right = delta_to_microseconds(right);
1746 if (pyus_right == NULL) {
1747 Py_DECREF(pyus_left);
1748 return NULL;
1749 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1752 Py_DECREF(pyus_left);
1753 Py_DECREF(pyus_right);
1754 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001755}
1756
1757static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001758truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1759{
1760 PyObject *result = NULL;
1761 PyObject *pyus_in = NULL, *temp, *pyus_out;
1762 PyObject *ratio = NULL;
1763
1764 pyus_in = delta_to_microseconds(delta);
1765 if (pyus_in == NULL)
1766 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001767 ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001768 if (ratio == NULL)
1769 goto error;
1770 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1771 Py_DECREF(pyus_in);
1772 pyus_in = NULL;
1773 if (temp == NULL)
1774 goto error;
1775 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1776 Py_DECREF(temp);
1777 if (pyus_out == NULL)
1778 goto error;
1779 result = microseconds_to_delta(pyus_out);
1780 Py_DECREF(pyus_out);
1781 error:
1782 Py_XDECREF(pyus_in);
1783 Py_XDECREF(ratio);
1784
1785 return result;
1786}
1787
1788static PyObject *
1789truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1790{
1791 PyObject *result;
1792 PyObject *pyus_in, *pyus_out;
1793 pyus_in = delta_to_microseconds(delta);
1794 if (pyus_in == NULL)
1795 return NULL;
1796 pyus_out = divide_nearest(pyus_in, i);
1797 Py_DECREF(pyus_in);
1798 if (pyus_out == NULL)
1799 return NULL;
1800 result = microseconds_to_delta(pyus_out);
1801 Py_DECREF(pyus_out);
1802
1803 return result;
1804}
1805
1806static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001807delta_add(PyObject *left, PyObject *right)
1808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1812 /* delta + delta */
1813 /* The C-level additions can't overflow because of the
1814 * invariant bounds.
1815 */
1816 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1817 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1818 int microseconds = GET_TD_MICROSECONDS(left) +
1819 GET_TD_MICROSECONDS(right);
1820 result = new_delta(days, seconds, microseconds, 1);
1821 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (result == Py_NotImplemented)
1824 Py_INCREF(result);
1825 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001826}
1827
1828static PyObject *
1829delta_negative(PyDateTime_Delta *self)
1830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 return new_delta(-GET_TD_DAYS(self),
1832 -GET_TD_SECONDS(self),
1833 -GET_TD_MICROSECONDS(self),
1834 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001835}
1836
1837static PyObject *
1838delta_positive(PyDateTime_Delta *self)
1839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 /* Could optimize this (by returning self) if this isn't a
1841 * subclass -- but who uses unary + ? Approximately nobody.
1842 */
1843 return new_delta(GET_TD_DAYS(self),
1844 GET_TD_SECONDS(self),
1845 GET_TD_MICROSECONDS(self),
1846 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001847}
1848
1849static PyObject *
1850delta_abs(PyDateTime_Delta *self)
1851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 assert(GET_TD_MICROSECONDS(self) >= 0);
1855 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 if (GET_TD_DAYS(self) < 0)
1858 result = delta_negative(self);
1859 else
1860 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001863}
1864
1865static PyObject *
1866delta_subtract(PyObject *left, PyObject *right)
1867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1871 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04001872 /* The C-level additions can't overflow because of the
1873 * invariant bounds.
1874 */
1875 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1876 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1877 int microseconds = GET_TD_MICROSECONDS(left) -
1878 GET_TD_MICROSECONDS(right);
1879 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (result == Py_NotImplemented)
1883 Py_INCREF(result);
1884 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001885}
1886
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001887static int
1888delta_cmp(PyObject *self, PyObject *other)
1889{
1890 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1891 if (diff == 0) {
1892 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1893 if (diff == 0)
1894 diff = GET_TD_MICROSECONDS(self) -
1895 GET_TD_MICROSECONDS(other);
1896 }
1897 return diff;
1898}
1899
Tim Peters2a799bf2002-12-16 20:18:38 +00001900static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001901delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001904 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 return diff_to_bool(diff, op);
1906 }
1907 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05001908 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001910}
1911
1912static PyObject *delta_getstate(PyDateTime_Delta *self);
1913
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001914static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001915delta_hash(PyDateTime_Delta *self)
1916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 if (self->hashcode == -1) {
1918 PyObject *temp = delta_getstate(self);
1919 if (temp != NULL) {
1920 self->hashcode = PyObject_Hash(temp);
1921 Py_DECREF(temp);
1922 }
1923 }
1924 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001925}
1926
1927static PyObject *
1928delta_multiply(PyObject *left, PyObject *right)
1929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 if (PyDelta_Check(left)) {
1933 /* delta * ??? */
1934 if (PyLong_Check(right))
1935 result = multiply_int_timedelta(right,
1936 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001937 else if (PyFloat_Check(right))
1938 result = multiply_float_timedelta(right,
1939 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 }
1941 else if (PyLong_Check(left))
1942 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001943 (PyDateTime_Delta *) right);
1944 else if (PyFloat_Check(left))
1945 result = multiply_float_timedelta(left,
1946 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 if (result == Py_NotImplemented)
1949 Py_INCREF(result);
1950 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001951}
1952
1953static PyObject *
1954delta_divide(PyObject *left, PyObject *right)
1955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 if (PyDelta_Check(left)) {
1959 /* delta * ??? */
1960 if (PyLong_Check(right))
1961 result = divide_timedelta_int(
1962 (PyDateTime_Delta *)left,
1963 right);
1964 else if (PyDelta_Check(right))
1965 result = divide_timedelta_timedelta(
1966 (PyDateTime_Delta *)left,
1967 (PyDateTime_Delta *)right);
1968 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (result == Py_NotImplemented)
1971 Py_INCREF(result);
1972 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001973}
1974
Mark Dickinson7c186e22010-04-20 22:32:49 +00001975static PyObject *
1976delta_truedivide(PyObject *left, PyObject *right)
1977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 if (PyDelta_Check(left)) {
1981 if (PyDelta_Check(right))
1982 result = truedivide_timedelta_timedelta(
1983 (PyDateTime_Delta *)left,
1984 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001985 else if (PyFloat_Check(right))
1986 result = truedivide_timedelta_float(
1987 (PyDateTime_Delta *)left, right);
1988 else if (PyLong_Check(right))
1989 result = truedivide_timedelta_int(
1990 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 if (result == Py_NotImplemented)
1994 Py_INCREF(result);
1995 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001996}
1997
1998static PyObject *
1999delta_remainder(PyObject *left, PyObject *right)
2000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 PyObject *pyus_left;
2002 PyObject *pyus_right;
2003 PyObject *pyus_remainder;
2004 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002005
Brian Curtindfc80e32011-08-10 20:28:54 -05002006 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2007 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2010 if (pyus_left == NULL)
2011 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2014 if (pyus_right == NULL) {
2015 Py_DECREF(pyus_left);
2016 return NULL;
2017 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
2020 Py_DECREF(pyus_left);
2021 Py_DECREF(pyus_right);
2022 if (pyus_remainder == NULL)
2023 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 remainder = microseconds_to_delta(pyus_remainder);
2026 Py_DECREF(pyus_remainder);
2027 if (remainder == NULL)
2028 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002031}
2032
2033static PyObject *
2034delta_divmod(PyObject *left, PyObject *right)
2035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 PyObject *pyus_left;
2037 PyObject *pyus_right;
2038 PyObject *divmod;
2039 PyObject *delta;
2040 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002041
Brian Curtindfc80e32011-08-10 20:28:54 -05002042 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2043 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2046 if (pyus_left == NULL)
2047 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2050 if (pyus_right == NULL) {
2051 Py_DECREF(pyus_left);
2052 return NULL;
2053 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 divmod = PyNumber_Divmod(pyus_left, pyus_right);
2056 Py_DECREF(pyus_left);
2057 Py_DECREF(pyus_right);
2058 if (divmod == NULL)
2059 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 assert(PyTuple_Size(divmod) == 2);
2062 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
2063 if (delta == NULL) {
2064 Py_DECREF(divmod);
2065 return NULL;
2066 }
2067 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
2068 Py_DECREF(delta);
2069 Py_DECREF(divmod);
2070 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002071}
2072
Tim Peters2a799bf2002-12-16 20:18:38 +00002073/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2074 * timedelta constructor. sofar is the # of microseconds accounted for
2075 * so far, and there are factor microseconds per current unit, the number
2076 * of which is given by num. num * factor is added to sofar in a
2077 * numerically careful way, and that's the result. Any fractional
2078 * microseconds left over (this can happen if num is a float type) are
2079 * added into *leftover.
2080 * Note that there are many ways this can give an error (NULL) return.
2081 */
2082static PyObject *
2083accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2084 double *leftover)
2085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 PyObject *prod;
2087 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 if (PyLong_Check(num)) {
2092 prod = PyNumber_Multiply(num, factor);
2093 if (prod == NULL)
2094 return NULL;
2095 sum = PyNumber_Add(sofar, prod);
2096 Py_DECREF(prod);
2097 return sum;
2098 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (PyFloat_Check(num)) {
2101 double dnum;
2102 double fracpart;
2103 double intpart;
2104 PyObject *x;
2105 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 /* The Plan: decompose num into an integer part and a
2108 * fractional part, num = intpart + fracpart.
2109 * Then num * factor ==
2110 * intpart * factor + fracpart * factor
2111 * and the LHS can be computed exactly in long arithmetic.
2112 * The RHS is again broken into an int part and frac part.
2113 * and the frac part is added into *leftover.
2114 */
2115 dnum = PyFloat_AsDouble(num);
2116 if (dnum == -1.0 && PyErr_Occurred())
2117 return NULL;
2118 fracpart = modf(dnum, &intpart);
2119 x = PyLong_FromDouble(intpart);
2120 if (x == NULL)
2121 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 prod = PyNumber_Multiply(x, factor);
2124 Py_DECREF(x);
2125 if (prod == NULL)
2126 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 sum = PyNumber_Add(sofar, prod);
2129 Py_DECREF(prod);
2130 if (sum == NULL)
2131 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if (fracpart == 0.0)
2134 return sum;
2135 /* So far we've lost no information. Dealing with the
2136 * fractional part requires float arithmetic, and may
2137 * lose a little info.
2138 */
2139 assert(PyLong_Check(factor));
2140 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 dnum *= fracpart;
2143 fracpart = modf(dnum, &intpart);
2144 x = PyLong_FromDouble(intpart);
2145 if (x == NULL) {
2146 Py_DECREF(sum);
2147 return NULL;
2148 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 y = PyNumber_Add(sum, x);
2151 Py_DECREF(sum);
2152 Py_DECREF(x);
2153 *leftover += fracpart;
2154 return y;
2155 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 PyErr_Format(PyExc_TypeError,
2158 "unsupported type for timedelta %s component: %s",
2159 tag, Py_TYPE(num)->tp_name);
2160 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002161}
2162
2163static PyObject *
2164delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 /* Argument objects. */
2169 PyObject *day = NULL;
2170 PyObject *second = NULL;
2171 PyObject *us = NULL;
2172 PyObject *ms = NULL;
2173 PyObject *minute = NULL;
2174 PyObject *hour = NULL;
2175 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 PyObject *x = NULL; /* running sum of microseconds */
2178 PyObject *y = NULL; /* temp sum of microseconds */
2179 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 static char *keywords[] = {
2182 "days", "seconds", "microseconds", "milliseconds",
2183 "minutes", "hours", "weeks", NULL
2184 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2187 keywords,
2188 &day, &second, &us,
2189 &ms, &minute, &hour, &week) == 0)
2190 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 x = PyLong_FromLong(0);
2193 if (x == NULL)
2194 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196#define CLEANUP \
2197 Py_DECREF(x); \
2198 x = y; \
2199 if (x == NULL) \
2200 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (us) {
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002203 y = accum("microseconds", x, us, _PyLong_One, &leftover_us);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 CLEANUP;
2205 }
2206 if (ms) {
2207 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2208 CLEANUP;
2209 }
2210 if (second) {
2211 y = accum("seconds", x, second, us_per_second, &leftover_us);
2212 CLEANUP;
2213 }
2214 if (minute) {
2215 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2216 CLEANUP;
2217 }
2218 if (hour) {
2219 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2220 CLEANUP;
2221 }
2222 if (day) {
2223 y = accum("days", x, day, us_per_day, &leftover_us);
2224 CLEANUP;
2225 }
2226 if (week) {
2227 y = accum("weeks", x, week, us_per_week, &leftover_us);
2228 CLEANUP;
2229 }
2230 if (leftover_us) {
2231 /* Round to nearest whole # of us, and add into x. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002232 double whole_us = round(leftover_us);
Victor Stinner69cc4872015-09-08 23:58:54 +02002233 int x_is_odd;
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002234 PyObject *temp;
2235
Victor Stinner69cc4872015-09-08 23:58:54 +02002236 whole_us = round(leftover_us);
2237 if (fabs(whole_us - leftover_us) == 0.5) {
2238 /* We're exactly halfway between two integers. In order
2239 * to do round-half-to-even, we must determine whether x
2240 * is odd. Note that x is odd when it's last bit is 1. The
2241 * code below uses bitwise and operation to check the last
2242 * bit. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002243 temp = PyNumber_And(x, _PyLong_One); /* temp <- x & 1 */
Victor Stinner69cc4872015-09-08 23:58:54 +02002244 if (temp == NULL) {
2245 Py_DECREF(x);
2246 goto Done;
2247 }
2248 x_is_odd = PyObject_IsTrue(temp);
2249 Py_DECREF(temp);
2250 if (x_is_odd == -1) {
2251 Py_DECREF(x);
2252 goto Done;
2253 }
2254 whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2255 }
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002256
Victor Stinner36a5a062013-08-28 01:53:39 +02002257 temp = PyLong_FromLong((long)whole_us);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 if (temp == NULL) {
2260 Py_DECREF(x);
2261 goto Done;
2262 }
2263 y = PyNumber_Add(x, temp);
2264 Py_DECREF(temp);
2265 CLEANUP;
2266 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 self = microseconds_to_delta_ex(x, type);
2269 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002270Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002272
2273#undef CLEANUP
2274}
2275
2276static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002277delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 return (GET_TD_DAYS(self) != 0
2280 || GET_TD_SECONDS(self) != 0
2281 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002282}
2283
2284static PyObject *
2285delta_repr(PyDateTime_Delta *self)
2286{
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +02002287 PyObject *args = PyUnicode_FromString("");
Tim Peters2a799bf2002-12-16 20:18:38 +00002288
Utkarsh Upadhyaycc5a65c2017-07-25 23:51:33 +02002289 if (args == NULL) {
2290 return NULL;
2291 }
2292
2293 const char *sep = "";
2294
2295 if (GET_TD_DAYS(self) != 0) {
2296 Py_SETREF(args, PyUnicode_FromFormat("days=%d", GET_TD_DAYS(self)));
2297 if (args == NULL) {
2298 return NULL;
2299 }
2300 sep = ", ";
2301 }
2302
2303 if (GET_TD_SECONDS(self) != 0) {
2304 Py_SETREF(args, PyUnicode_FromFormat("%U%sseconds=%d", args, sep,
2305 GET_TD_SECONDS(self)));
2306 if (args == NULL) {
2307 return NULL;
2308 }
2309 sep = ", ";
2310 }
2311
2312 if (GET_TD_MICROSECONDS(self) != 0) {
2313 Py_SETREF(args, PyUnicode_FromFormat("%U%smicroseconds=%d", args, sep,
2314 GET_TD_MICROSECONDS(self)));
2315 if (args == NULL) {
2316 return NULL;
2317 }
2318 }
2319
2320 if (PyUnicode_GET_LENGTH(args) == 0) {
2321 Py_SETREF(args, PyUnicode_FromString("0"));
2322 if (args == NULL) {
2323 return NULL;
2324 }
2325 }
2326
2327 PyObject *repr = PyUnicode_FromFormat("%s(%S)", Py_TYPE(self)->tp_name,
2328 args);
2329 Py_DECREF(args);
2330 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00002331}
2332
2333static PyObject *
2334delta_str(PyDateTime_Delta *self)
2335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 int us = GET_TD_MICROSECONDS(self);
2337 int seconds = GET_TD_SECONDS(self);
2338 int minutes = divmod(seconds, 60, &seconds);
2339 int hours = divmod(minutes, 60, &minutes);
2340 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 if (days) {
2343 if (us)
2344 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2345 days, (days == 1 || days == -1) ? "" : "s",
2346 hours, minutes, seconds, us);
2347 else
2348 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2349 days, (days == 1 || days == -1) ? "" : "s",
2350 hours, minutes, seconds);
2351 } else {
2352 if (us)
2353 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2354 hours, minutes, seconds, us);
2355 else
2356 return PyUnicode_FromFormat("%d:%02d:%02d",
2357 hours, minutes, seconds);
2358 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002359
Tim Peters2a799bf2002-12-16 20:18:38 +00002360}
2361
Tim Peters371935f2003-02-01 01:52:50 +00002362/* Pickle support, a simple use of __reduce__. */
2363
Tim Petersb57f8f02003-02-01 02:54:15 +00002364/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002365static PyObject *
2366delta_getstate(PyDateTime_Delta *self)
2367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 return Py_BuildValue("iii", GET_TD_DAYS(self),
2369 GET_TD_SECONDS(self),
2370 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002371}
2372
Tim Peters2a799bf2002-12-16 20:18:38 +00002373static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002374delta_total_seconds(PyObject *self)
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 PyObject *total_seconds;
2377 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2380 if (total_microseconds == NULL)
2381 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002382
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002383 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002387}
2388
2389static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002390delta_reduce(PyDateTime_Delta* self)
2391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002393}
2394
2395#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2396
2397static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 {"days", T_INT, OFFSET(days), READONLY,
2400 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 {"seconds", T_INT, OFFSET(seconds), READONLY,
2403 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2406 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2407 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002408};
2409
2410static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2412 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2415 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002418};
2419
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002420static const char delta_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00002421PyDoc_STR("Difference between two datetime values.");
2422
2423static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 delta_add, /* nb_add */
2425 delta_subtract, /* nb_subtract */
2426 delta_multiply, /* nb_multiply */
2427 delta_remainder, /* nb_remainder */
2428 delta_divmod, /* nb_divmod */
2429 0, /* nb_power */
2430 (unaryfunc)delta_negative, /* nb_negative */
2431 (unaryfunc)delta_positive, /* nb_positive */
2432 (unaryfunc)delta_abs, /* nb_absolute */
2433 (inquiry)delta_bool, /* nb_bool */
2434 0, /*nb_invert*/
2435 0, /*nb_lshift*/
2436 0, /*nb_rshift*/
2437 0, /*nb_and*/
2438 0, /*nb_xor*/
2439 0, /*nb_or*/
2440 0, /*nb_int*/
2441 0, /*nb_reserved*/
2442 0, /*nb_float*/
2443 0, /*nb_inplace_add*/
2444 0, /*nb_inplace_subtract*/
2445 0, /*nb_inplace_multiply*/
2446 0, /*nb_inplace_remainder*/
2447 0, /*nb_inplace_power*/
2448 0, /*nb_inplace_lshift*/
2449 0, /*nb_inplace_rshift*/
2450 0, /*nb_inplace_and*/
2451 0, /*nb_inplace_xor*/
2452 0, /*nb_inplace_or*/
2453 delta_divide, /* nb_floor_divide */
2454 delta_truedivide, /* nb_true_divide */
2455 0, /* nb_inplace_floor_divide */
2456 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002457};
2458
2459static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 PyVarObject_HEAD_INIT(NULL, 0)
2461 "datetime.timedelta", /* tp_name */
2462 sizeof(PyDateTime_Delta), /* tp_basicsize */
2463 0, /* tp_itemsize */
2464 0, /* tp_dealloc */
2465 0, /* tp_print */
2466 0, /* tp_getattr */
2467 0, /* tp_setattr */
2468 0, /* tp_reserved */
2469 (reprfunc)delta_repr, /* tp_repr */
2470 &delta_as_number, /* tp_as_number */
2471 0, /* tp_as_sequence */
2472 0, /* tp_as_mapping */
2473 (hashfunc)delta_hash, /* tp_hash */
2474 0, /* tp_call */
2475 (reprfunc)delta_str, /* tp_str */
2476 PyObject_GenericGetAttr, /* tp_getattro */
2477 0, /* tp_setattro */
2478 0, /* tp_as_buffer */
2479 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2480 delta_doc, /* tp_doc */
2481 0, /* tp_traverse */
2482 0, /* tp_clear */
2483 delta_richcompare, /* tp_richcompare */
2484 0, /* tp_weaklistoffset */
2485 0, /* tp_iter */
2486 0, /* tp_iternext */
2487 delta_methods, /* tp_methods */
2488 delta_members, /* tp_members */
2489 0, /* tp_getset */
2490 0, /* tp_base */
2491 0, /* tp_dict */
2492 0, /* tp_descr_get */
2493 0, /* tp_descr_set */
2494 0, /* tp_dictoffset */
2495 0, /* tp_init */
2496 0, /* tp_alloc */
2497 delta_new, /* tp_new */
2498 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002499};
2500
2501/*
2502 * PyDateTime_Date implementation.
2503 */
2504
2505/* Accessor properties. */
2506
2507static PyObject *
2508date_year(PyDateTime_Date *self, void *unused)
2509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002511}
2512
2513static PyObject *
2514date_month(PyDateTime_Date *self, void *unused)
2515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002517}
2518
2519static PyObject *
2520date_day(PyDateTime_Date *self, void *unused)
2521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002523}
2524
2525static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 {"year", (getter)date_year},
2527 {"month", (getter)date_month},
2528 {"day", (getter)date_day},
2529 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002530};
2531
2532/* Constructors. */
2533
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002534static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002535
Tim Peters2a799bf2002-12-16 20:18:38 +00002536static PyObject *
2537date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 PyObject *self = NULL;
2540 PyObject *state;
2541 int year;
2542 int month;
2543 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 /* Check for invocation from pickle with __getstate__ state */
2546 if (PyTuple_GET_SIZE(args) == 1 &&
2547 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2548 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2549 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2550 {
2551 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2554 if (me != NULL) {
2555 char *pdata = PyBytes_AS_STRING(state);
2556 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2557 me->hashcode = -1;
2558 }
2559 return (PyObject *)me;
2560 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2563 &year, &month, &day)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 self = new_date_ex(year, month, day, type);
2565 }
2566 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002567}
2568
2569/* Return new date from localtime(t). */
2570static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002571date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002572{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002573 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002575
Victor Stinnere4a994d2015-03-30 01:10:14 +02002576 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002578
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04002579 if (_PyTime_localtime(t, &tm) != 0)
Victor Stinner21f58932012-03-14 00:15:40 +01002580 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01002581
2582 return PyObject_CallFunction(cls, "iii",
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002583 tm.tm_year + 1900,
2584 tm.tm_mon + 1,
2585 tm.tm_mday);
Tim Peters2a799bf2002-12-16 20:18:38 +00002586}
2587
2588/* Return new date from current time.
2589 * We say this is equivalent to fromtimestamp(time.time()), and the
2590 * only way to be sure of that is to *call* time.time(). That's not
2591 * generally the same as calling C's time.
2592 */
2593static PyObject *
2594date_today(PyObject *cls, PyObject *dummy)
2595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 PyObject *time;
2597 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002598 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 time = time_time();
2601 if (time == NULL)
2602 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 /* Note well: today() is a class method, so this may not call
2605 * date.fromtimestamp. For example, it may call
2606 * datetime.fromtimestamp. That's why we need all the accuracy
2607 * time.time() delivers; if someone were gonzo about optimization,
2608 * date.today() could get away with plain C time().
2609 */
Victor Stinner20401de2016-12-09 15:24:31 +01002610 result = _PyObject_CallMethodIdObjArgs(cls, &PyId_fromtimestamp,
2611 time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 Py_DECREF(time);
2613 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002614}
2615
2616/* Return new date from given timestamp (Python timestamp -- a double). */
2617static PyObject *
2618date_fromtimestamp(PyObject *cls, PyObject *args)
2619{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002620 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002622
Victor Stinner5d272cc2012-03-13 13:35:55 +01002623 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2624 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002626}
2627
2628/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2629 * the ordinal is out of range.
2630 */
2631static PyObject *
2632date_fromordinal(PyObject *cls, PyObject *args)
2633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 PyObject *result = NULL;
2635 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2638 int year;
2639 int month;
2640 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 if (ordinal < 1)
2643 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2644 ">= 1");
2645 else {
2646 ord_to_ymd(ordinal, &year, &month, &day);
2647 result = PyObject_CallFunction(cls, "iii",
2648 year, month, day);
2649 }
2650 }
2651 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002652}
2653
2654/*
2655 * Date arithmetic.
2656 */
2657
2658/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2659 * instead.
2660 */
2661static PyObject *
2662add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 PyObject *result = NULL;
2665 int year = GET_YEAR(date);
2666 int month = GET_MONTH(date);
2667 int deltadays = GET_TD_DAYS(delta);
2668 /* C-level overflow is impossible because |deltadays| < 1e9. */
2669 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 if (normalize_date(&year, &month, &day) >= 0)
2672 result = new_date(year, month, day);
2673 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002674}
2675
2676static PyObject *
2677date_add(PyObject *left, PyObject *right)
2678{
Brian Curtindfc80e32011-08-10 20:28:54 -05002679 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2680 Py_RETURN_NOTIMPLEMENTED;
2681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 if (PyDate_Check(left)) {
2683 /* date + ??? */
2684 if (PyDelta_Check(right))
2685 /* date + delta */
2686 return add_date_timedelta((PyDateTime_Date *) left,
2687 (PyDateTime_Delta *) right,
2688 0);
2689 }
2690 else {
2691 /* ??? + date
2692 * 'right' must be one of us, or we wouldn't have been called
2693 */
2694 if (PyDelta_Check(left))
2695 /* delta + date */
2696 return add_date_timedelta((PyDateTime_Date *) right,
2697 (PyDateTime_Delta *) left,
2698 0);
2699 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002700 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002701}
2702
2703static PyObject *
2704date_subtract(PyObject *left, PyObject *right)
2705{
Brian Curtindfc80e32011-08-10 20:28:54 -05002706 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2707 Py_RETURN_NOTIMPLEMENTED;
2708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 if (PyDate_Check(left)) {
2710 if (PyDate_Check(right)) {
2711 /* date - date */
2712 int left_ord = ymd_to_ord(GET_YEAR(left),
2713 GET_MONTH(left),
2714 GET_DAY(left));
2715 int right_ord = ymd_to_ord(GET_YEAR(right),
2716 GET_MONTH(right),
2717 GET_DAY(right));
2718 return new_delta(left_ord - right_ord, 0, 0, 0);
2719 }
2720 if (PyDelta_Check(right)) {
2721 /* date - delta */
2722 return add_date_timedelta((PyDateTime_Date *) left,
2723 (PyDateTime_Delta *) right,
2724 1);
2725 }
2726 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002727 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002728}
2729
2730
2731/* Various ways to turn a date into a string. */
2732
2733static PyObject *
2734date_repr(PyDateTime_Date *self)
2735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2737 Py_TYPE(self)->tp_name,
2738 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002739}
2740
2741static PyObject *
2742date_isoformat(PyDateTime_Date *self)
2743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 return PyUnicode_FromFormat("%04d-%02d-%02d",
2745 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002746}
2747
Tim Peterse2df5ff2003-05-02 18:39:55 +00002748/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002749static PyObject *
2750date_str(PyDateTime_Date *self)
2751{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002752 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002753}
2754
2755
2756static PyObject *
2757date_ctime(PyDateTime_Date *self)
2758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002760}
2761
2762static PyObject *
2763date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 /* This method can be inherited, and needs to call the
2766 * timetuple() method appropriate to self's class.
2767 */
2768 PyObject *result;
2769 PyObject *tuple;
2770 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002771 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2775 &format))
2776 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002777
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002778 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 if (tuple == NULL)
2780 return NULL;
2781 result = wrap_strftime((PyObject *)self, format, tuple,
2782 (PyObject *)self);
2783 Py_DECREF(tuple);
2784 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002785}
2786
Eric Smith1ba31142007-09-11 18:06:02 +00002787static PyObject *
2788date_format(PyDateTime_Date *self, PyObject *args)
2789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2793 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002796 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002798
Victor Stinner20401de2016-12-09 15:24:31 +01002799 return _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_strftime,
2800 format, NULL);
Eric Smith1ba31142007-09-11 18:06:02 +00002801}
2802
Tim Peters2a799bf2002-12-16 20:18:38 +00002803/* ISO methods. */
2804
2805static PyObject *
2806date_isoweekday(PyDateTime_Date *self)
2807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002811}
2812
2813static PyObject *
2814date_isocalendar(PyDateTime_Date *self)
2815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 int year = GET_YEAR(self);
2817 int week1_monday = iso_week1_monday(year);
2818 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2819 int week;
2820 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 week = divmod(today - week1_monday, 7, &day);
2823 if (week < 0) {
2824 --year;
2825 week1_monday = iso_week1_monday(year);
2826 week = divmod(today - week1_monday, 7, &day);
2827 }
2828 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2829 ++year;
2830 week = 0;
2831 }
2832 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002833}
2834
2835/* Miscellaneous methods. */
2836
Tim Peters2a799bf2002-12-16 20:18:38 +00002837static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002838date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 if (PyDate_Check(other)) {
2841 int diff = memcmp(((PyDateTime_Date *)self)->data,
2842 ((PyDateTime_Date *)other)->data,
2843 _PyDateTime_DATE_DATASIZE);
2844 return diff_to_bool(diff, op);
2845 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002846 else
2847 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002848}
2849
2850static PyObject *
2851date_timetuple(PyDateTime_Date *self)
2852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 return build_struct_time(GET_YEAR(self),
2854 GET_MONTH(self),
2855 GET_DAY(self),
2856 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002857}
2858
Tim Peters12bf3392002-12-24 05:41:27 +00002859static PyObject *
2860date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 PyObject *clone;
2863 PyObject *tuple;
2864 int year = GET_YEAR(self);
2865 int month = GET_MONTH(self);
2866 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2869 &year, &month, &day))
2870 return NULL;
2871 tuple = Py_BuildValue("iii", year, month, day);
2872 if (tuple == NULL)
2873 return NULL;
2874 clone = date_new(Py_TYPE(self), tuple, NULL);
2875 Py_DECREF(tuple);
2876 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002877}
2878
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002879static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002880generic_hash(unsigned char *data, int len)
2881{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002882 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002883}
2884
2885
2886static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002887
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002888static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002889date_hash(PyDateTime_Date *self)
2890{
Benjamin Petersondec2df32016-09-09 17:46:24 -07002891 if (self->hashcode == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 self->hashcode = generic_hash(
2893 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Benjamin Petersondec2df32016-09-09 17:46:24 -07002894 }
Guido van Rossum254348e2007-11-21 19:29:53 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002897}
2898
2899static PyObject *
2900date_toordinal(PyDateTime_Date *self)
2901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2903 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002904}
2905
2906static PyObject *
2907date_weekday(PyDateTime_Date *self)
2908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002912}
2913
Tim Peters371935f2003-02-01 01:52:50 +00002914/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002915
Tim Petersb57f8f02003-02-01 02:54:15 +00002916/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002917static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002918date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 PyObject* field;
2921 field = PyBytes_FromStringAndSize((char*)self->data,
2922 _PyDateTime_DATE_DATASIZE);
2923 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002924}
2925
2926static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002927date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002930}
2931
2932static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2937 METH_CLASS,
2938 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2939 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2942 METH_CLASS,
2943 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2944 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2947 PyDoc_STR("Current date or datetime: same as "
2948 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2953 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2956 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2959 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2962 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2965 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2966 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2969 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2972 PyDoc_STR("Return the day of the week represented by the date.\n"
2973 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2976 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2977 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2980 PyDoc_STR("Return the day of the week represented by the date.\n"
2981 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2984 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2987 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002990};
2991
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002992static const char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002993PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002994
2995static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 date_add, /* nb_add */
2997 date_subtract, /* nb_subtract */
2998 0, /* nb_multiply */
2999 0, /* nb_remainder */
3000 0, /* nb_divmod */
3001 0, /* nb_power */
3002 0, /* nb_negative */
3003 0, /* nb_positive */
3004 0, /* nb_absolute */
3005 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003006};
3007
3008static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 PyVarObject_HEAD_INIT(NULL, 0)
3010 "datetime.date", /* tp_name */
3011 sizeof(PyDateTime_Date), /* tp_basicsize */
3012 0, /* tp_itemsize */
3013 0, /* tp_dealloc */
3014 0, /* tp_print */
3015 0, /* tp_getattr */
3016 0, /* tp_setattr */
3017 0, /* tp_reserved */
3018 (reprfunc)date_repr, /* tp_repr */
3019 &date_as_number, /* tp_as_number */
3020 0, /* tp_as_sequence */
3021 0, /* tp_as_mapping */
3022 (hashfunc)date_hash, /* tp_hash */
3023 0, /* tp_call */
3024 (reprfunc)date_str, /* tp_str */
3025 PyObject_GenericGetAttr, /* tp_getattro */
3026 0, /* tp_setattro */
3027 0, /* tp_as_buffer */
3028 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3029 date_doc, /* tp_doc */
3030 0, /* tp_traverse */
3031 0, /* tp_clear */
3032 date_richcompare, /* tp_richcompare */
3033 0, /* tp_weaklistoffset */
3034 0, /* tp_iter */
3035 0, /* tp_iternext */
3036 date_methods, /* tp_methods */
3037 0, /* tp_members */
3038 date_getset, /* tp_getset */
3039 0, /* tp_base */
3040 0, /* tp_dict */
3041 0, /* tp_descr_get */
3042 0, /* tp_descr_set */
3043 0, /* tp_dictoffset */
3044 0, /* tp_init */
3045 0, /* tp_alloc */
3046 date_new, /* tp_new */
3047 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003048};
3049
3050/*
Tim Peters2a799bf2002-12-16 20:18:38 +00003051 * PyDateTime_TZInfo implementation.
3052 */
3053
3054/* This is a pure abstract base class, so doesn't do anything beyond
3055 * raising NotImplemented exceptions. Real tzinfo classes need
3056 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00003057 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00003058 * be subclasses of this tzinfo class, which is easy and quick to check).
3059 *
3060 * Note: For reasons having to do with pickling of subclasses, we have
3061 * to allow tzinfo objects to be instantiated. This wasn't an issue
3062 * in the Python implementation (__init__() could raise NotImplementedError
3063 * there without ill effect), but doing so in the C implementation hit a
3064 * brick wall.
3065 */
3066
3067static PyObject *
3068tzinfo_nogo(const char* methodname)
3069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 PyErr_Format(PyExc_NotImplementedError,
3071 "a tzinfo subclass must implement %s()",
3072 methodname);
3073 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003074}
3075
3076/* Methods. A subclass must implement these. */
3077
Tim Peters52dcce22003-01-23 16:36:11 +00003078static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003079tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00003082}
3083
Tim Peters52dcce22003-01-23 16:36:11 +00003084static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003085tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00003088}
3089
Tim Peters52dcce22003-01-23 16:36:11 +00003090static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003091tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003094}
3095
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003096
3097static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
3098 PyDateTime_Delta *delta,
3099 int factor);
3100static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
3101static PyObject *datetime_dst(PyObject *self, PyObject *);
3102
Tim Peters52dcce22003-01-23 16:36:11 +00003103static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003104tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003105{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003106 PyObject *result = NULL;
3107 PyObject *off = NULL, *dst = NULL;
3108 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003109
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003110 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 PyErr_SetString(PyExc_TypeError,
3112 "fromutc: argument must be a datetime");
3113 return NULL;
3114 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003115 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3117 "is not self");
3118 return NULL;
3119 }
Tim Peters52dcce22003-01-23 16:36:11 +00003120
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003121 off = datetime_utcoffset(dt, NULL);
3122 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003124 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3126 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003127 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 }
Tim Peters52dcce22003-01-23 16:36:11 +00003129
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003130 dst = datetime_dst(dt, NULL);
3131 if (dst == NULL)
3132 goto Fail;
3133 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3135 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003136 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 }
Tim Peters52dcce22003-01-23 16:36:11 +00003138
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003139 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3140 if (delta == NULL)
3141 goto Fail;
3142 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003145
3146 Py_DECREF(dst);
3147 dst = call_dst(GET_DT_TZINFO(dt), result);
3148 if (dst == NULL)
3149 goto Fail;
3150 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 goto Inconsistent;
Alexander Belopolskyc79447b2015-09-27 21:41:55 -04003152 if (delta_bool((PyDateTime_Delta *)dst) != 0) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03003153 Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
Serhiy Storchaka576f1322016-01-05 21:27:54 +02003154 (PyDateTime_Delta *)dst, 1));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003155 if (result == NULL)
3156 goto Fail;
3157 }
3158 Py_DECREF(delta);
3159 Py_DECREF(dst);
3160 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003162
3163Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3165 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003168Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003169 Py_XDECREF(off);
3170 Py_XDECREF(dst);
3171 Py_XDECREF(delta);
3172 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003174}
3175
Tim Peters2a799bf2002-12-16 20:18:38 +00003176/*
3177 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003178 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003179 */
3180
Guido van Rossum177e41a2003-01-30 22:06:23 +00003181static PyObject *
3182tzinfo_reduce(PyObject *self)
3183{
Victor Stinnerd1584d32016-08-23 00:11:04 +02003184 PyObject *args, *state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003186 _Py_IDENTIFIER(__getinitargs__);
3187 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003188
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003189 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 if (getinitargs != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003191 args = _PyObject_CallNoArg(getinitargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 Py_DECREF(getinitargs);
3193 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 return NULL;
3195 }
3196 }
3197 else {
3198 PyErr_Clear();
Victor Stinnerd1584d32016-08-23 00:11:04 +02003199
3200 args = PyTuple_New(0);
3201 if (args == NULL) {
3202 return NULL;
3203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003205
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003206 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 if (getstate != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003208 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 Py_DECREF(getstate);
3210 if (state == NULL) {
3211 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 return NULL;
3213 }
3214 }
3215 else {
3216 PyObject **dictptr;
3217 PyErr_Clear();
3218 state = Py_None;
3219 dictptr = _PyObject_GetDictPtr(self);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02003220 if (dictptr && *dictptr && PyDict_GET_SIZE(*dictptr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 state = *dictptr;
Victor Stinnerd1584d32016-08-23 00:11:04 +02003222 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 Py_INCREF(state);
3224 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 if (state == Py_None) {
3227 Py_DECREF(state);
3228 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3229 }
3230 else
3231 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003232}
Tim Peters2a799bf2002-12-16 20:18:38 +00003233
3234static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3237 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003240 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3241 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3244 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003247 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3250 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003253};
3254
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003255static const char tzinfo_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00003256PyDoc_STR("Abstract base class for time zone info objects.");
3257
Neal Norwitz227b5332006-03-22 09:28:35 +00003258static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 PyVarObject_HEAD_INIT(NULL, 0)
3260 "datetime.tzinfo", /* tp_name */
3261 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3262 0, /* tp_itemsize */
3263 0, /* tp_dealloc */
3264 0, /* tp_print */
3265 0, /* tp_getattr */
3266 0, /* tp_setattr */
3267 0, /* tp_reserved */
3268 0, /* tp_repr */
3269 0, /* tp_as_number */
3270 0, /* tp_as_sequence */
3271 0, /* tp_as_mapping */
3272 0, /* tp_hash */
3273 0, /* tp_call */
3274 0, /* tp_str */
3275 PyObject_GenericGetAttr, /* tp_getattro */
3276 0, /* tp_setattro */
3277 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003278 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 tzinfo_doc, /* tp_doc */
3280 0, /* tp_traverse */
3281 0, /* tp_clear */
3282 0, /* tp_richcompare */
3283 0, /* tp_weaklistoffset */
3284 0, /* tp_iter */
3285 0, /* tp_iternext */
3286 tzinfo_methods, /* tp_methods */
3287 0, /* tp_members */
3288 0, /* tp_getset */
3289 0, /* tp_base */
3290 0, /* tp_dict */
3291 0, /* tp_descr_get */
3292 0, /* tp_descr_set */
3293 0, /* tp_dictoffset */
3294 0, /* tp_init */
3295 0, /* tp_alloc */
3296 PyType_GenericNew, /* tp_new */
3297 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003298};
3299
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003300static char *timezone_kws[] = {"offset", "name", NULL};
3301
3302static PyObject *
3303timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3304{
3305 PyObject *offset;
3306 PyObject *name = NULL;
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03003307 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|U:timezone", timezone_kws,
3308 &PyDateTime_DeltaType, &offset, &name))
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003309 return new_timezone(offset, name);
3310
3311 return NULL;
3312}
3313
3314static void
3315timezone_dealloc(PyDateTime_TimeZone *self)
3316{
3317 Py_CLEAR(self->offset);
3318 Py_CLEAR(self->name);
3319 Py_TYPE(self)->tp_free((PyObject *)self);
3320}
3321
3322static PyObject *
3323timezone_richcompare(PyDateTime_TimeZone *self,
3324 PyDateTime_TimeZone *other, int op)
3325{
Brian Curtindfc80e32011-08-10 20:28:54 -05003326 if (op != Py_EQ && op != Py_NE)
3327 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003328 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003329 if (op == Py_EQ)
3330 Py_RETURN_FALSE;
3331 else
3332 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003333 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003334 return delta_richcompare(self->offset, other->offset, op);
3335}
3336
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003337static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003338timezone_hash(PyDateTime_TimeZone *self)
3339{
3340 return delta_hash((PyDateTime_Delta *)self->offset);
3341}
3342
3343/* Check argument type passed to tzname, utcoffset, or dst methods.
3344 Returns 0 for good argument. Returns -1 and sets exception info
3345 otherwise.
3346 */
3347static int
3348_timezone_check_argument(PyObject *dt, const char *meth)
3349{
3350 if (dt == Py_None || PyDateTime_Check(dt))
3351 return 0;
3352 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3353 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3354 return -1;
3355}
3356
3357static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003358timezone_repr(PyDateTime_TimeZone *self)
3359{
3360 /* Note that although timezone is not subclassable, it is convenient
3361 to use Py_TYPE(self)->tp_name here. */
3362 const char *type_name = Py_TYPE(self)->tp_name;
3363
3364 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3365 return PyUnicode_FromFormat("%s.utc", type_name);
3366
3367 if (self->name == NULL)
3368 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3369
3370 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3371 self->name);
3372}
3373
3374
3375static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003376timezone_str(PyDateTime_TimeZone *self)
3377{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003378 int hours, minutes, seconds;
3379 PyObject *offset;
3380 char sign;
3381
3382 if (self->name != NULL) {
3383 Py_INCREF(self->name);
3384 return self->name;
3385 }
Victor Stinner90fd8952015-09-08 00:12:49 +02003386 if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04003387 (GET_TD_DAYS(self->offset) == 0 &&
3388 GET_TD_SECONDS(self->offset) == 0 &&
3389 GET_TD_MICROSECONDS(self->offset) == 0))
3390 return PyUnicode_FromString("UTC");
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003391 /* Offset is normalized, so it is negative if days < 0 */
3392 if (GET_TD_DAYS(self->offset) < 0) {
3393 sign = '-';
3394 offset = delta_negative((PyDateTime_Delta *)self->offset);
3395 if (offset == NULL)
3396 return NULL;
3397 }
3398 else {
3399 sign = '+';
3400 offset = self->offset;
3401 Py_INCREF(offset);
3402 }
3403 /* Offset is not negative here. */
3404 seconds = GET_TD_SECONDS(offset);
3405 Py_DECREF(offset);
3406 minutes = divmod(seconds, 60, &seconds);
3407 hours = divmod(minutes, 60, &minutes);
Martin Pantere26da7c2016-06-02 10:07:09 +00003408 /* XXX ignore sub-minute data, currently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003409 assert(seconds == 0);
3410 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003411}
3412
3413static PyObject *
3414timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3415{
3416 if (_timezone_check_argument(dt, "tzname") == -1)
3417 return NULL;
3418
3419 return timezone_str(self);
3420}
3421
3422static PyObject *
3423timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3424{
3425 if (_timezone_check_argument(dt, "utcoffset") == -1)
3426 return NULL;
3427
3428 Py_INCREF(self->offset);
3429 return self->offset;
3430}
3431
3432static PyObject *
3433timezone_dst(PyObject *self, PyObject *dt)
3434{
3435 if (_timezone_check_argument(dt, "dst") == -1)
3436 return NULL;
3437
3438 Py_RETURN_NONE;
3439}
3440
3441static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003442timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3443{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003444 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003445 PyErr_SetString(PyExc_TypeError,
3446 "fromutc: argument must be a datetime");
3447 return NULL;
3448 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003449 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003450 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3451 "is not self");
3452 return NULL;
3453 }
3454
3455 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3456}
3457
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003458static PyObject *
3459timezone_getinitargs(PyDateTime_TimeZone *self)
3460{
3461 if (self->name == NULL)
3462 return Py_BuildValue("(O)", self->offset);
3463 return Py_BuildValue("(OO)", self->offset, self->name);
3464}
3465
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003466static PyMethodDef timezone_methods[] = {
3467 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3468 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003469 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003470
3471 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003472 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003473
3474 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003475 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003476
3477 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3478 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3479
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003480 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3481 PyDoc_STR("pickle support")},
3482
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003483 {NULL, NULL}
3484};
3485
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003486static const char timezone_doc[] =
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003487PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3488
3489static PyTypeObject PyDateTime_TimeZoneType = {
3490 PyVarObject_HEAD_INIT(NULL, 0)
3491 "datetime.timezone", /* tp_name */
3492 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3493 0, /* tp_itemsize */
3494 (destructor)timezone_dealloc, /* tp_dealloc */
3495 0, /* tp_print */
3496 0, /* tp_getattr */
3497 0, /* tp_setattr */
3498 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003499 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003500 0, /* tp_as_number */
3501 0, /* tp_as_sequence */
3502 0, /* tp_as_mapping */
3503 (hashfunc)timezone_hash, /* tp_hash */
3504 0, /* tp_call */
3505 (reprfunc)timezone_str, /* tp_str */
3506 0, /* tp_getattro */
3507 0, /* tp_setattro */
3508 0, /* tp_as_buffer */
3509 Py_TPFLAGS_DEFAULT, /* tp_flags */
3510 timezone_doc, /* tp_doc */
3511 0, /* tp_traverse */
3512 0, /* tp_clear */
3513 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3514 0, /* tp_weaklistoffset */
3515 0, /* tp_iter */
3516 0, /* tp_iternext */
3517 timezone_methods, /* tp_methods */
3518 0, /* tp_members */
3519 0, /* tp_getset */
3520 &PyDateTime_TZInfoType, /* tp_base */
3521 0, /* tp_dict */
3522 0, /* tp_descr_get */
3523 0, /* tp_descr_set */
3524 0, /* tp_dictoffset */
3525 0, /* tp_init */
3526 0, /* tp_alloc */
3527 timezone_new, /* tp_new */
3528};
3529
Tim Peters2a799bf2002-12-16 20:18:38 +00003530/*
Tim Peters37f39822003-01-10 03:49:02 +00003531 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003532 */
3533
Tim Peters37f39822003-01-10 03:49:02 +00003534/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003535 */
3536
3537static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003538time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003541}
3542
Tim Peters37f39822003-01-10 03:49:02 +00003543static PyObject *
3544time_minute(PyDateTime_Time *self, void *unused)
3545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003547}
3548
3549/* The name time_second conflicted with some platform header file. */
3550static PyObject *
3551py_time_second(PyDateTime_Time *self, void *unused)
3552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003554}
3555
3556static PyObject *
3557time_microsecond(PyDateTime_Time *self, void *unused)
3558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003560}
3561
3562static PyObject *
3563time_tzinfo(PyDateTime_Time *self, void *unused)
3564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3566 Py_INCREF(result);
3567 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003568}
3569
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003570static PyObject *
3571time_fold(PyDateTime_Time *self, void *unused)
3572{
3573 return PyLong_FromLong(TIME_GET_FOLD(self));
3574}
3575
Tim Peters37f39822003-01-10 03:49:02 +00003576static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 {"hour", (getter)time_hour},
3578 {"minute", (getter)time_minute},
3579 {"second", (getter)py_time_second},
3580 {"microsecond", (getter)time_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003581 {"tzinfo", (getter)time_tzinfo},
3582 {"fold", (getter)time_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003584};
3585
3586/*
3587 * Constructors.
3588 */
3589
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003590static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003591 "tzinfo", "fold", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003592
Tim Peters2a799bf2002-12-16 20:18:38 +00003593static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003594time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 PyObject *self = NULL;
3597 PyObject *state;
3598 int hour = 0;
3599 int minute = 0;
3600 int second = 0;
3601 int usecond = 0;
3602 PyObject *tzinfo = Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003603 int fold = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 /* Check for invocation from pickle with __getstate__ state */
3606 if (PyTuple_GET_SIZE(args) >= 1 &&
3607 PyTuple_GET_SIZE(args) <= 2 &&
3608 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3609 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003610 (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 {
3612 PyDateTime_Time *me;
3613 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 if (PyTuple_GET_SIZE(args) == 2) {
3616 tzinfo = PyTuple_GET_ITEM(args, 1);
3617 if (check_tzinfo_subclass(tzinfo) < 0) {
3618 PyErr_SetString(PyExc_TypeError, "bad "
3619 "tzinfo state arg");
3620 return NULL;
3621 }
3622 }
3623 aware = (char)(tzinfo != Py_None);
3624 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3625 if (me != NULL) {
3626 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3629 me->hashcode = -1;
3630 me->hastzinfo = aware;
3631 if (aware) {
3632 Py_INCREF(tzinfo);
3633 me->tzinfo = tzinfo;
3634 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003635 if (pdata[0] & (1 << 7)) {
3636 me->data[0] -= 128;
3637 me->fold = 1;
3638 }
3639 else {
3640 me->fold = 0;
3641 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 }
3643 return (PyObject *)me;
3644 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003645
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003646 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 &hour, &minute, &second, &usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003648 &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003649 self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
3650 type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 }
3652 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003653}
3654
3655/*
3656 * Destructor.
3657 */
3658
3659static void
Tim Peters37f39822003-01-10 03:49:02 +00003660time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 if (HASTZINFO(self)) {
3663 Py_XDECREF(self->tzinfo);
3664 }
3665 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003666}
3667
3668/*
Tim Peters855fe882002-12-22 03:43:39 +00003669 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003670 */
3671
Tim Peters2a799bf2002-12-16 20:18:38 +00003672/* These are all METH_NOARGS, so don't need to check the arglist. */
3673static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003674time_utcoffset(PyObject *self, PyObject *unused) {
3675 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003676}
3677
3678static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003679time_dst(PyObject *self, PyObject *unused) {
3680 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003681}
3682
3683static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003684time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003685 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003686}
3687
3688/*
Tim Peters37f39822003-01-10 03:49:02 +00003689 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003690 */
3691
3692static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003693time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 const char *type_name = Py_TYPE(self)->tp_name;
3696 int h = TIME_GET_HOUR(self);
3697 int m = TIME_GET_MINUTE(self);
3698 int s = TIME_GET_SECOND(self);
3699 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003700 int fold = TIME_GET_FOLD(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 if (us)
3704 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3705 type_name, h, m, s, us);
3706 else if (s)
3707 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3708 type_name, h, m, s);
3709 else
3710 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3711 if (result != NULL && HASTZINFO(self))
3712 result = append_keyword_tzinfo(result, self->tzinfo);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003713 if (result != NULL && fold)
3714 result = append_keyword_fold(result, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003716}
3717
Tim Peters37f39822003-01-10 03:49:02 +00003718static PyObject *
3719time_str(PyDateTime_Time *self)
3720{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003721 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters37f39822003-01-10 03:49:02 +00003722}
Tim Peters2a799bf2002-12-16 20:18:38 +00003723
3724static PyObject *
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003725time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 char buf[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003728 char *timespec = NULL;
3729 static char *keywords[] = {"timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02003731 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003732 static char *specs[][2] = {
3733 {"hours", "%02d"},
3734 {"minutes", "%02d:%02d"},
3735 {"seconds", "%02d:%02d:%02d"},
3736 {"milliseconds", "%02d:%02d:%02d.%03d"},
3737 {"microseconds", "%02d:%02d:%02d.%06d"},
3738 };
3739 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00003740
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003741 if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
3742 return NULL;
3743
3744 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
3745 if (us == 0) {
3746 /* seconds */
3747 given_spec = 2;
3748 }
3749 else {
3750 /* microseconds */
3751 given_spec = 4;
3752 }
3753 }
3754 else {
3755 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
3756 if (strcmp(timespec, specs[given_spec][0]) == 0) {
3757 if (given_spec == 3) {
3758 /* milliseconds */
3759 us = us / 1000;
3760 }
3761 break;
3762 }
3763 }
3764 }
3765
3766 if (given_spec == Py_ARRAY_LENGTH(specs)) {
3767 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
3768 return NULL;
3769 }
3770 else {
3771 result = PyUnicode_FromFormat(specs[given_spec][1],
3772 TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
3773 TIME_GET_SECOND(self), us);
3774 }
Tim Peters37f39822003-01-10 03:49:02 +00003775
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003776 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 /* We need to append the UTC offset. */
3780 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3781 Py_None) < 0) {
3782 Py_DECREF(result);
3783 return NULL;
3784 }
3785 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3786 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003787}
3788
Tim Peters37f39822003-01-10 03:49:02 +00003789static PyObject *
3790time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 PyObject *result;
3793 PyObject *tuple;
3794 PyObject *format;
3795 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3798 &format))
3799 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 /* Python's strftime does insane things with the year part of the
3802 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003803 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 */
3805 tuple = Py_BuildValue("iiiiiiiii",
3806 1900, 1, 1, /* year, month, day */
3807 TIME_GET_HOUR(self),
3808 TIME_GET_MINUTE(self),
3809 TIME_GET_SECOND(self),
3810 0, 1, -1); /* weekday, daynum, dst */
3811 if (tuple == NULL)
3812 return NULL;
3813 assert(PyTuple_Size(tuple) == 9);
3814 result = wrap_strftime((PyObject *)self, format, tuple,
3815 Py_None);
3816 Py_DECREF(tuple);
3817 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003818}
Tim Peters2a799bf2002-12-16 20:18:38 +00003819
3820/*
3821 * Miscellaneous methods.
3822 */
3823
Tim Peters37f39822003-01-10 03:49:02 +00003824static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003825time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003826{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003827 PyObject *result = NULL;
3828 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003830
Brian Curtindfc80e32011-08-10 20:28:54 -05003831 if (! PyTime_Check(other))
3832 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003833
3834 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 diff = memcmp(((PyDateTime_Time *)self)->data,
3836 ((PyDateTime_Time *)other)->data,
3837 _PyDateTime_TIME_DATASIZE);
3838 return diff_to_bool(diff, op);
3839 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003840 offset1 = time_utcoffset(self, NULL);
3841 if (offset1 == NULL)
3842 return NULL;
3843 offset2 = time_utcoffset(other, NULL);
3844 if (offset2 == NULL)
3845 goto done;
3846 /* If they're both naive, or both aware and have the same offsets,
3847 * we get off cheap. Note that if they're both naive, offset1 ==
3848 * offset2 == Py_None at this point.
3849 */
3850 if ((offset1 == offset2) ||
3851 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3852 delta_cmp(offset1, offset2) == 0)) {
3853 diff = memcmp(((PyDateTime_Time *)self)->data,
3854 ((PyDateTime_Time *)other)->data,
3855 _PyDateTime_TIME_DATASIZE);
3856 result = diff_to_bool(diff, op);
3857 }
3858 /* The hard case: both aware with different UTC offsets */
3859 else if (offset1 != Py_None && offset2 != Py_None) {
3860 int offsecs1, offsecs2;
3861 assert(offset1 != offset2); /* else last "if" handled it */
3862 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3863 TIME_GET_MINUTE(self) * 60 +
3864 TIME_GET_SECOND(self) -
3865 GET_TD_DAYS(offset1) * 86400 -
3866 GET_TD_SECONDS(offset1);
3867 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3868 TIME_GET_MINUTE(other) * 60 +
3869 TIME_GET_SECOND(other) -
3870 GET_TD_DAYS(offset2) * 86400 -
3871 GET_TD_SECONDS(offset2);
3872 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 if (diff == 0)
3874 diff = TIME_GET_MICROSECOND(self) -
3875 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003876 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003878 else if (op == Py_EQ) {
3879 result = Py_False;
3880 Py_INCREF(result);
3881 }
3882 else if (op == Py_NE) {
3883 result = Py_True;
3884 Py_INCREF(result);
3885 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003886 else {
3887 PyErr_SetString(PyExc_TypeError,
3888 "can't compare offset-naive and "
3889 "offset-aware times");
3890 }
3891 done:
3892 Py_DECREF(offset1);
3893 Py_XDECREF(offset2);
3894 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003895}
3896
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003897static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003898time_hash(PyDateTime_Time *self)
3899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003901 PyObject *offset, *self0;
Victor Stinner423c16b2017-01-03 23:47:12 +01003902 if (TIME_GET_FOLD(self)) {
3903 self0 = new_time_ex2(TIME_GET_HOUR(self),
3904 TIME_GET_MINUTE(self),
3905 TIME_GET_SECOND(self),
3906 TIME_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003907 HASTZINFO(self) ? self->tzinfo : Py_None,
3908 0, Py_TYPE(self));
3909 if (self0 == NULL)
3910 return -1;
3911 }
3912 else {
3913 self0 = (PyObject *)self;
3914 Py_INCREF(self0);
3915 }
3916 offset = time_utcoffset(self0, NULL);
3917 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003918
3919 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003923 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 self->hashcode = generic_hash(
3925 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003927 PyObject *temp1, *temp2;
3928 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003930 seconds = TIME_GET_HOUR(self) * 3600 +
3931 TIME_GET_MINUTE(self) * 60 +
3932 TIME_GET_SECOND(self);
3933 microseconds = TIME_GET_MICROSECOND(self);
3934 temp1 = new_delta(0, seconds, microseconds, 1);
3935 if (temp1 == NULL) {
3936 Py_DECREF(offset);
3937 return -1;
3938 }
3939 temp2 = delta_subtract(temp1, offset);
3940 Py_DECREF(temp1);
3941 if (temp2 == NULL) {
3942 Py_DECREF(offset);
3943 return -1;
3944 }
3945 self->hashcode = PyObject_Hash(temp2);
3946 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003948 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 }
3950 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003951}
Tim Peters2a799bf2002-12-16 20:18:38 +00003952
Tim Peters12bf3392002-12-24 05:41:27 +00003953static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003954time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 PyObject *clone;
3957 PyObject *tuple;
3958 int hh = TIME_GET_HOUR(self);
3959 int mm = TIME_GET_MINUTE(self);
3960 int ss = TIME_GET_SECOND(self);
3961 int us = TIME_GET_MICROSECOND(self);
3962 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003963 int fold = TIME_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00003964
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003965 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 time_kws,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003967 &hh, &mm, &ss, &us, &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03003969 if (fold != 0 && fold != 1) {
3970 PyErr_SetString(PyExc_ValueError,
3971 "fold must be either 0 or 1");
3972 return NULL;
3973 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3975 if (tuple == NULL)
3976 return NULL;
3977 clone = time_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003978 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003979 TIME_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003980 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 Py_DECREF(tuple);
3982 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003983}
3984
Tim Peters371935f2003-02-01 01:52:50 +00003985/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003986
Tim Peters33e0f382003-01-10 02:05:14 +00003987/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003988 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3989 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003990 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003991 */
3992static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003993time_getstate(PyDateTime_Time *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00003994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 PyObject *basestate;
3996 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 basestate = PyBytes_FromStringAndSize((char *)self->data,
3999 _PyDateTime_TIME_DATASIZE);
4000 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004001 if (proto > 3 && TIME_GET_FOLD(self))
4002 /* Set the first bit of the first byte */
4003 PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4005 result = PyTuple_Pack(1, basestate);
4006 else
4007 result = PyTuple_Pack(2, basestate, self->tzinfo);
4008 Py_DECREF(basestate);
4009 }
4010 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004011}
4012
4013static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004014time_reduce_ex(PyDateTime_Time *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00004015{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004016 int proto;
4017 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004018 return NULL;
4019
4020 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00004021}
4022
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004023static PyObject *
4024time_reduce(PyDateTime_Time *self, PyObject *arg)
4025{
4026 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, 2));
4027}
4028
Tim Peters37f39822003-01-10 03:49:02 +00004029static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004030
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004031 {"isoformat", (PyCFunction)time_isoformat, METH_VARARGS | METH_KEYWORDS,
4032 PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
4033 "[+HH:MM].\n\n"
4034 "timespec specifies what components of the time to include.\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
4037 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 {"__format__", (PyCFunction)date_format, METH_VARARGS,
4040 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
4043 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004045 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
4046 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 {"dst", (PyCFunction)time_dst, METH_NOARGS,
4049 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
4052 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004053
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004054 {"__reduce_ex__", (PyCFunction)time_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004055 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004056
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004057 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
4058 PyDoc_STR("__reduce__() -> (cls, state)")},
4059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004061};
4062
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004063static const char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004064PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
4065\n\
4066All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03004067a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004068
Neal Norwitz227b5332006-03-22 09:28:35 +00004069static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 PyVarObject_HEAD_INIT(NULL, 0)
4071 "datetime.time", /* tp_name */
4072 sizeof(PyDateTime_Time), /* tp_basicsize */
4073 0, /* tp_itemsize */
4074 (destructor)time_dealloc, /* tp_dealloc */
4075 0, /* tp_print */
4076 0, /* tp_getattr */
4077 0, /* tp_setattr */
4078 0, /* tp_reserved */
4079 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05004080 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 0, /* tp_as_sequence */
4082 0, /* tp_as_mapping */
4083 (hashfunc)time_hash, /* tp_hash */
4084 0, /* tp_call */
4085 (reprfunc)time_str, /* tp_str */
4086 PyObject_GenericGetAttr, /* tp_getattro */
4087 0, /* tp_setattro */
4088 0, /* tp_as_buffer */
4089 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4090 time_doc, /* tp_doc */
4091 0, /* tp_traverse */
4092 0, /* tp_clear */
4093 time_richcompare, /* tp_richcompare */
4094 0, /* tp_weaklistoffset */
4095 0, /* tp_iter */
4096 0, /* tp_iternext */
4097 time_methods, /* tp_methods */
4098 0, /* tp_members */
4099 time_getset, /* tp_getset */
4100 0, /* tp_base */
4101 0, /* tp_dict */
4102 0, /* tp_descr_get */
4103 0, /* tp_descr_set */
4104 0, /* tp_dictoffset */
4105 0, /* tp_init */
4106 time_alloc, /* tp_alloc */
4107 time_new, /* tp_new */
4108 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004109};
4110
4111/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004112 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00004113 */
4114
Tim Petersa9bc1682003-01-11 03:39:11 +00004115/* Accessor properties. Properties for day, month, and year are inherited
4116 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004117 */
4118
4119static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004120datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00004121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004123}
4124
Tim Petersa9bc1682003-01-11 03:39:11 +00004125static PyObject *
4126datetime_minute(PyDateTime_DateTime *self, void *unused)
4127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004129}
4130
4131static PyObject *
4132datetime_second(PyDateTime_DateTime *self, void *unused)
4133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004135}
4136
4137static PyObject *
4138datetime_microsecond(PyDateTime_DateTime *self, void *unused)
4139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004141}
4142
4143static PyObject *
4144datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
4145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4147 Py_INCREF(result);
4148 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004149}
4150
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004151static PyObject *
4152datetime_fold(PyDateTime_DateTime *self, void *unused)
4153{
4154 return PyLong_FromLong(DATE_GET_FOLD(self));
4155}
4156
Tim Petersa9bc1682003-01-11 03:39:11 +00004157static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 {"hour", (getter)datetime_hour},
4159 {"minute", (getter)datetime_minute},
4160 {"second", (getter)datetime_second},
4161 {"microsecond", (getter)datetime_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004162 {"tzinfo", (getter)datetime_tzinfo},
4163 {"fold", (getter)datetime_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004165};
4166
4167/*
4168 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004169 */
4170
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004171static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 "year", "month", "day", "hour", "minute", "second",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004173 "microsecond", "tzinfo", "fold", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004174};
4175
Tim Peters2a799bf2002-12-16 20:18:38 +00004176static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004177datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 PyObject *self = NULL;
4180 PyObject *state;
4181 int year;
4182 int month;
4183 int day;
4184 int hour = 0;
4185 int minute = 0;
4186 int second = 0;
4187 int usecond = 0;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004188 int fold = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 /* Check for invocation from pickle with __getstate__ state */
4192 if (PyTuple_GET_SIZE(args) >= 1 &&
4193 PyTuple_GET_SIZE(args) <= 2 &&
4194 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4195 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004196 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 {
4198 PyDateTime_DateTime *me;
4199 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 if (PyTuple_GET_SIZE(args) == 2) {
4202 tzinfo = PyTuple_GET_ITEM(args, 1);
4203 if (check_tzinfo_subclass(tzinfo) < 0) {
4204 PyErr_SetString(PyExc_TypeError, "bad "
4205 "tzinfo state arg");
4206 return NULL;
4207 }
4208 }
4209 aware = (char)(tzinfo != Py_None);
4210 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4211 if (me != NULL) {
4212 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4215 me->hashcode = -1;
4216 me->hastzinfo = aware;
4217 if (aware) {
4218 Py_INCREF(tzinfo);
4219 me->tzinfo = tzinfo;
4220 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004221 if (pdata[2] & (1 << 7)) {
4222 me->data[2] -= 128;
4223 me->fold = 1;
4224 }
4225 else {
4226 me->fold = 0;
4227 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 }
4229 return (PyObject *)me;
4230 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004231
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004232 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 &year, &month, &day, &hour, &minute,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004234 &second, &usecond, &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004235 self = new_datetime_ex2(year, month, day,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 hour, minute, second, usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004237 tzinfo, fold, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 }
4239 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004240}
4241
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004242/* TM_FUNC is the shared type of _PyTime_localtime() and
4243 * _PyTime_gmtime(). */
4244typedef int (*TM_FUNC)(time_t timer, struct tm*);
Tim Petersa9bc1682003-01-11 03:39:11 +00004245
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004246/* As of version 2015f max fold in IANA database is
4247 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004248static long long max_fold_seconds = 24 * 3600;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004249/* NB: date(1970,1,1).toordinal() == 719163 */
Benjamin Petersonac965ca2016-09-18 18:12:21 -07004250static long long epoch = 719163LL * 24 * 60 * 60;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004251
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004252static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004253utc_to_seconds(int year, int month, int day,
4254 int hour, int minute, int second)
4255{
Victor Stinnerb67f0962017-02-10 10:34:02 +01004256 long long ordinal;
4257
4258 /* ymd_to_ord() doesn't support year <= 0 */
4259 if (year < MINYEAR || year > MAXYEAR) {
4260 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
4261 return -1;
4262 }
4263
4264 ordinal = ymd_to_ord(year, month, day);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004265 return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
4266}
4267
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004268static long long
4269local(long long u)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004270{
4271 struct tm local_time;
Alexander Belopolsky8e1d3a22016-07-25 13:54:51 -04004272 time_t t;
4273 u -= epoch;
4274 t = u;
4275 if (t != u) {
4276 PyErr_SetString(PyExc_OverflowError,
4277 "timestamp out of range for platform time_t");
4278 return -1;
4279 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004280 if (_PyTime_localtime(t, &local_time) != 0)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004281 return -1;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004282 return utc_to_seconds(local_time.tm_year + 1900,
4283 local_time.tm_mon + 1,
4284 local_time.tm_mday,
4285 local_time.tm_hour,
4286 local_time.tm_min,
4287 local_time.tm_sec);
4288}
4289
Tim Petersa9bc1682003-01-11 03:39:11 +00004290/* Internal helper.
4291 * Build datetime from a time_t and a distinct count of microseconds.
4292 * Pass localtime or gmtime for f, to control the interpretation of timet.
4293 */
4294static PyObject *
4295datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004297{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004298 struct tm tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004299 int year, month, day, hour, minute, second, fold = 0;
Tim Petersa9bc1682003-01-11 03:39:11 +00004300
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004301 if (f(timet, &tm) != 0)
4302 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01004303
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004304 year = tm.tm_year + 1900;
4305 month = tm.tm_mon + 1;
4306 day = tm.tm_mday;
4307 hour = tm.tm_hour;
4308 minute = tm.tm_min;
Victor Stinner21f58932012-03-14 00:15:40 +01004309 /* The platform localtime/gmtime may insert leap seconds,
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004310 * indicated by tm.tm_sec > 59. We don't care about them,
Victor Stinner21f58932012-03-14 00:15:40 +01004311 * except to the extent that passing them on to the datetime
4312 * constructor would raise ValueError for a reason that
4313 * made no sense to the user.
4314 */
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004315 second = Py_MIN(59, tm.tm_sec);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004316
Victor Stinnerb67f0962017-02-10 10:34:02 +01004317 /* local timezone requires to compute fold */
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004318 if (tzinfo == Py_None && f == _PyTime_localtime) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004319 long long probe_seconds, result_seconds, transition;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004320
4321 result_seconds = utc_to_seconds(year, month, day,
4322 hour, minute, second);
4323 /* Probe max_fold_seconds to detect a fold. */
4324 probe_seconds = local(epoch + timet - max_fold_seconds);
4325 if (probe_seconds == -1)
4326 return NULL;
4327 transition = result_seconds - probe_seconds - max_fold_seconds;
4328 if (transition < 0) {
4329 probe_seconds = local(epoch + timet + transition);
4330 if (probe_seconds == -1)
4331 return NULL;
4332 if (probe_seconds == result_seconds)
4333 fold = 1;
4334 }
4335 }
4336 return new_datetime_ex2(year, month, day, hour,
4337 minute, second, us, tzinfo, fold,
4338 (PyTypeObject *)cls);
Tim Petersa9bc1682003-01-11 03:39:11 +00004339}
4340
4341/* Internal helper.
4342 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4343 * to control the interpretation of the timestamp. Since a double doesn't
4344 * have enough bits to cover a datetime's full range of precision, it's
4345 * better to call datetime_from_timet_and_us provided you have a way
4346 * to get that much precision (e.g., C time() isn't good enough).
4347 */
4348static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004349datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004353 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004354
Victor Stinnere4a994d2015-03-30 01:10:14 +02004355 if (_PyTime_ObjectToTimeval(timestamp,
Victor Stinner7667f582015-09-09 01:02:23 +02004356 &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004358
Victor Stinner21f58932012-03-14 00:15:40 +01004359 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004360}
4361
4362/* Internal helper.
4363 * Build most accurate possible datetime for current time. Pass localtime or
4364 * gmtime for f as appropriate.
4365 */
4366static PyObject *
4367datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4368{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004369 _PyTime_t ts = _PyTime_GetSystemClock();
Victor Stinner1e2b6882015-09-18 13:23:02 +02004370 time_t secs;
4371 int us;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004372
Victor Stinner1e2b6882015-09-18 13:23:02 +02004373 if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner09e5cf22015-03-30 00:09:18 +02004374 return NULL;
Victor Stinner1e2b6882015-09-18 13:23:02 +02004375 assert(0 <= us && us <= 999999);
Victor Stinner09e5cf22015-03-30 00:09:18 +02004376
Victor Stinner1e2b6882015-09-18 13:23:02 +02004377 return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004378}
4379
Larry Hastings61272b72014-01-07 12:41:53 -08004380/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004381
4382@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004383datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004384
4385 tz: object = None
4386 Timezone object.
4387
4388Returns new datetime object representing current time local to tz.
4389
4390If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004391[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004392
Larry Hastings31826802013-10-19 00:09:25 -07004393static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004394datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03004395/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004398
Larry Hastings31826802013-10-19 00:09:25 -07004399 /* Return best possible local time -- this isn't constrained by the
4400 * precision of a timestamp.
4401 */
4402 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004404
Larry Hastings5c661892014-01-24 06:17:25 -08004405 self = datetime_best_possible((PyObject *)type,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004406 tz == Py_None ? _PyTime_localtime :
4407 _PyTime_gmtime,
Larry Hastings31826802013-10-19 00:09:25 -07004408 tz);
4409 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004411 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 }
4413 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004414}
4415
Tim Petersa9bc1682003-01-11 03:39:11 +00004416/* Return best possible UTC time -- this isn't constrained by the
4417 * precision of a timestamp.
4418 */
4419static PyObject *
4420datetime_utcnow(PyObject *cls, PyObject *dummy)
4421{
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004422 return datetime_best_possible(cls, _PyTime_gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004423}
4424
Tim Peters2a799bf2002-12-16 20:18:38 +00004425/* Return new local datetime from timestamp (Python timestamp -- a double). */
4426static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004427datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004430 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 PyObject *tzinfo = Py_None;
4432 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004433
Victor Stinner5d272cc2012-03-13 13:35:55 +01004434 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 keywords, &timestamp, &tzinfo))
4436 return NULL;
4437 if (check_tzinfo_subclass(tzinfo) < 0)
4438 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 self = datetime_from_timestamp(cls,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004441 tzinfo == Py_None ? _PyTime_localtime :
4442 _PyTime_gmtime,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 timestamp,
4444 tzinfo);
4445 if (self != NULL && tzinfo != Py_None) {
4446 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004447 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 }
4449 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004450}
4451
Tim Petersa9bc1682003-01-11 03:39:11 +00004452/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4453static PyObject *
4454datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4455{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004456 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004458
Victor Stinner5d272cc2012-03-13 13:35:55 +01004459 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004460 result = datetime_from_timestamp(cls, _PyTime_gmtime, timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 Py_None);
4462 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004463}
4464
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004465/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004466static PyObject *
4467datetime_strptime(PyObject *cls, PyObject *args)
4468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004470 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004471 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004472
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004473 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004475
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004476 if (module == NULL) {
4477 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004478 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004479 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 }
Victor Stinner20401de2016-12-09 15:24:31 +01004481 return _PyObject_CallMethodIdObjArgs(module, &PyId__strptime_datetime,
4482 cls, string, format, NULL);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004483}
4484
Tim Petersa9bc1682003-01-11 03:39:11 +00004485/* Return new datetime from date/datetime and time arguments. */
4486static PyObject *
4487datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4488{
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004489 static char *keywords[] = {"date", "time", "tzinfo", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 PyObject *date;
4491 PyObject *time;
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004492 PyObject *tzinfo = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004494
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004495 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 &PyDateTime_DateType, &date,
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004497 &PyDateTime_TimeType, &time, &tzinfo)) {
4498 if (tzinfo == NULL) {
4499 if (HASTZINFO(time))
4500 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4501 else
4502 tzinfo = Py_None;
4503 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 result = PyObject_CallFunction(cls, "iiiiiiiO",
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004505 GET_YEAR(date),
4506 GET_MONTH(date),
4507 GET_DAY(date),
4508 TIME_GET_HOUR(time),
4509 TIME_GET_MINUTE(time),
4510 TIME_GET_SECOND(time),
4511 TIME_GET_MICROSECOND(time),
4512 tzinfo);
4513 if (result)
4514 DATE_SET_FOLD(result, TIME_GET_FOLD(time));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 }
4516 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004517}
Tim Peters2a799bf2002-12-16 20:18:38 +00004518
4519/*
4520 * Destructor.
4521 */
4522
4523static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004524datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 if (HASTZINFO(self)) {
4527 Py_XDECREF(self->tzinfo);
4528 }
4529 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004530}
4531
4532/*
4533 * Indirect access to tzinfo methods.
4534 */
4535
Tim Peters2a799bf2002-12-16 20:18:38 +00004536/* These are all METH_NOARGS, so don't need to check the arglist. */
4537static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004538datetime_utcoffset(PyObject *self, PyObject *unused) {
4539 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004540}
4541
4542static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004543datetime_dst(PyObject *self, PyObject *unused) {
4544 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004545}
4546
4547static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004548datetime_tzname(PyObject *self, PyObject *unused) {
4549 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004550}
4551
4552/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004553 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004554 */
4555
Tim Petersa9bc1682003-01-11 03:39:11 +00004556/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4557 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004558 */
4559static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004560add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 /* Note that the C-level additions can't overflow, because of
4564 * invariant bounds on the member values.
4565 */
4566 int year = GET_YEAR(date);
4567 int month = GET_MONTH(date);
4568 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4569 int hour = DATE_GET_HOUR(date);
4570 int minute = DATE_GET_MINUTE(date);
4571 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4572 int microsecond = DATE_GET_MICROSECOND(date) +
4573 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 assert(factor == 1 || factor == -1);
4576 if (normalize_datetime(&year, &month, &day,
Victor Stinnerb67f0962017-02-10 10:34:02 +01004577 &hour, &minute, &second, &microsecond) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 return NULL;
Victor Stinnerb67f0962017-02-10 10:34:02 +01004579 }
4580
4581 return new_datetime(year, month, day,
4582 hour, minute, second, microsecond,
4583 HASTZINFO(date) ? date->tzinfo : Py_None, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004584}
4585
4586static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004587datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (PyDateTime_Check(left)) {
4590 /* datetime + ??? */
4591 if (PyDelta_Check(right))
4592 /* datetime + delta */
4593 return add_datetime_timedelta(
4594 (PyDateTime_DateTime *)left,
4595 (PyDateTime_Delta *)right,
4596 1);
4597 }
4598 else if (PyDelta_Check(left)) {
4599 /* delta + datetime */
4600 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4601 (PyDateTime_Delta *) left,
4602 1);
4603 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004604 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004605}
4606
4607static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004608datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004610 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 if (PyDateTime_Check(left)) {
4613 /* datetime - ??? */
4614 if (PyDateTime_Check(right)) {
4615 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004616 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004618
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004619 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4620 offset2 = offset1 = Py_None;
4621 Py_INCREF(offset1);
4622 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004624 else {
4625 offset1 = datetime_utcoffset(left, NULL);
4626 if (offset1 == NULL)
4627 return NULL;
4628 offset2 = datetime_utcoffset(right, NULL);
4629 if (offset2 == NULL) {
4630 Py_DECREF(offset1);
4631 return NULL;
4632 }
4633 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4634 PyErr_SetString(PyExc_TypeError,
4635 "can't subtract offset-naive and "
4636 "offset-aware datetimes");
4637 Py_DECREF(offset1);
4638 Py_DECREF(offset2);
4639 return NULL;
4640 }
4641 }
4642 if ((offset1 != offset2) &&
4643 delta_cmp(offset1, offset2) != 0) {
4644 offdiff = delta_subtract(offset1, offset2);
4645 if (offdiff == NULL) {
4646 Py_DECREF(offset1);
4647 Py_DECREF(offset2);
4648 return NULL;
4649 }
4650 }
4651 Py_DECREF(offset1);
4652 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 delta_d = ymd_to_ord(GET_YEAR(left),
4654 GET_MONTH(left),
4655 GET_DAY(left)) -
4656 ymd_to_ord(GET_YEAR(right),
4657 GET_MONTH(right),
4658 GET_DAY(right));
4659 /* These can't overflow, since the values are
4660 * normalized. At most this gives the number of
4661 * seconds in one day.
4662 */
4663 delta_s = (DATE_GET_HOUR(left) -
4664 DATE_GET_HOUR(right)) * 3600 +
4665 (DATE_GET_MINUTE(left) -
4666 DATE_GET_MINUTE(right)) * 60 +
4667 (DATE_GET_SECOND(left) -
4668 DATE_GET_SECOND(right));
4669 delta_us = DATE_GET_MICROSECOND(left) -
4670 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004672 if (result == NULL)
4673 return NULL;
4674
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004675 if (offdiff != NULL) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03004676 Py_SETREF(result, delta_subtract(result, offdiff));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004677 Py_DECREF(offdiff);
4678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 }
4680 else if (PyDelta_Check(right)) {
4681 /* datetime - delta */
4682 result = add_datetime_timedelta(
4683 (PyDateTime_DateTime *)left,
4684 (PyDateTime_Delta *)right,
4685 -1);
4686 }
4687 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 if (result == Py_NotImplemented)
4690 Py_INCREF(result);
4691 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004692}
4693
4694/* Various ways to turn a datetime into a string. */
4695
4696static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004697datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 const char *type_name = Py_TYPE(self)->tp_name;
4700 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 if (DATE_GET_MICROSECOND(self)) {
4703 baserepr = PyUnicode_FromFormat(
4704 "%s(%d, %d, %d, %d, %d, %d, %d)",
4705 type_name,
4706 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4707 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4708 DATE_GET_SECOND(self),
4709 DATE_GET_MICROSECOND(self));
4710 }
4711 else if (DATE_GET_SECOND(self)) {
4712 baserepr = PyUnicode_FromFormat(
4713 "%s(%d, %d, %d, %d, %d, %d)",
4714 type_name,
4715 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4716 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4717 DATE_GET_SECOND(self));
4718 }
4719 else {
4720 baserepr = PyUnicode_FromFormat(
4721 "%s(%d, %d, %d, %d, %d)",
4722 type_name,
4723 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4724 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4725 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004726 if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
4727 baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 if (baserepr == NULL || ! HASTZINFO(self))
4729 return baserepr;
4730 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004731}
4732
Tim Petersa9bc1682003-01-11 03:39:11 +00004733static PyObject *
4734datetime_str(PyDateTime_DateTime *self)
4735{
Victor Stinner4c381542016-12-09 00:33:39 +01004736 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "s", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004737}
Tim Peters2a799bf2002-12-16 20:18:38 +00004738
4739static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004740datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 int sep = 'T';
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004743 char *timespec = NULL;
4744 static char *keywords[] = {"sep", "timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 char buffer[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004746 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 int us = DATE_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004748 static char *specs[][2] = {
4749 {"hours", "%04d-%02d-%02d%c%02d"},
4750 {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
4751 {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
4752 {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
4753 {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
4754 };
4755 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00004756
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004757 if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 return NULL;
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004759
4760 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4761 if (us == 0) {
4762 /* seconds */
4763 given_spec = 2;
4764 }
4765 else {
4766 /* microseconds */
4767 given_spec = 4;
4768 }
4769 }
4770 else {
4771 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4772 if (strcmp(timespec, specs[given_spec][0]) == 0) {
4773 if (given_spec == 3) {
4774 us = us / 1000;
4775 }
4776 break;
4777 }
4778 }
4779 }
4780
4781 if (given_spec == Py_ARRAY_LENGTH(specs)) {
4782 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4783 return NULL;
4784 }
4785 else {
4786 result = PyUnicode_FromFormat(specs[given_spec][1],
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 GET_YEAR(self), GET_MONTH(self),
4788 GET_DAY(self), (int)sep,
4789 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4790 DATE_GET_SECOND(self), us);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004791 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 if (!result || !HASTZINFO(self))
4794 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 /* We need to append the UTC offset. */
4797 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4798 (PyObject *)self) < 0) {
4799 Py_DECREF(result);
4800 return NULL;
4801 }
4802 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4803 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004804}
4805
Tim Petersa9bc1682003-01-11 03:39:11 +00004806static PyObject *
4807datetime_ctime(PyDateTime_DateTime *self)
4808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 return format_ctime((PyDateTime_Date *)self,
4810 DATE_GET_HOUR(self),
4811 DATE_GET_MINUTE(self),
4812 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004813}
4814
Tim Peters2a799bf2002-12-16 20:18:38 +00004815/* Miscellaneous methods. */
4816
Tim Petersa9bc1682003-01-11 03:39:11 +00004817static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004818flip_fold(PyObject *dt)
4819{
4820 return new_datetime_ex2(GET_YEAR(dt),
4821 GET_MONTH(dt),
4822 GET_DAY(dt),
4823 DATE_GET_HOUR(dt),
4824 DATE_GET_MINUTE(dt),
4825 DATE_GET_SECOND(dt),
4826 DATE_GET_MICROSECOND(dt),
4827 HASTZINFO(dt) ?
4828 ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
4829 !DATE_GET_FOLD(dt),
4830 Py_TYPE(dt));
4831}
4832
4833static PyObject *
4834get_flip_fold_offset(PyObject *dt)
4835{
4836 PyObject *result, *flip_dt;
4837
4838 flip_dt = flip_fold(dt);
4839 if (flip_dt == NULL)
4840 return NULL;
4841 result = datetime_utcoffset(flip_dt, NULL);
4842 Py_DECREF(flip_dt);
4843 return result;
4844}
4845
4846/* PEP 495 exception: Whenever one or both of the operands in
4847 * inter-zone comparison is such that its utcoffset() depends
4848 * on the value of its fold fold attribute, the result is False.
4849 *
4850 * Return 1 if exception applies, 0 if not, and -1 on error.
4851 */
4852static int
4853pep495_eq_exception(PyObject *self, PyObject *other,
4854 PyObject *offset_self, PyObject *offset_other)
4855{
4856 int result = 0;
4857 PyObject *flip_offset;
4858
4859 flip_offset = get_flip_fold_offset(self);
4860 if (flip_offset == NULL)
4861 return -1;
4862 if (flip_offset != offset_self &&
4863 delta_cmp(flip_offset, offset_self))
4864 {
4865 result = 1;
4866 goto done;
4867 }
4868 Py_DECREF(flip_offset);
4869
4870 flip_offset = get_flip_fold_offset(other);
4871 if (flip_offset == NULL)
4872 return -1;
4873 if (flip_offset != offset_other &&
4874 delta_cmp(flip_offset, offset_other))
4875 result = 1;
4876 done:
4877 Py_DECREF(flip_offset);
4878 return result;
4879}
4880
4881static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004882datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004883{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004884 PyObject *result = NULL;
4885 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004886 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 if (! PyDateTime_Check(other)) {
4889 if (PyDate_Check(other)) {
4890 /* Prevent invocation of date_richcompare. We want to
4891 return NotImplemented here to give the other object
4892 a chance. But since DateTime is a subclass of
4893 Date, if the other object is a Date, it would
4894 compute an ordering based on the date part alone,
4895 and we don't want that. So force unequal or
4896 uncomparable here in that case. */
4897 if (op == Py_EQ)
4898 Py_RETURN_FALSE;
4899 if (op == Py_NE)
4900 Py_RETURN_TRUE;
4901 return cmperror(self, other);
4902 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004903 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004905
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004906 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004907 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4908 ((PyDateTime_DateTime *)other)->data,
4909 _PyDateTime_DATETIME_DATASIZE);
4910 return diff_to_bool(diff, op);
4911 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004912 offset1 = datetime_utcoffset(self, NULL);
4913 if (offset1 == NULL)
4914 return NULL;
4915 offset2 = datetime_utcoffset(other, NULL);
4916 if (offset2 == NULL)
4917 goto done;
4918 /* If they're both naive, or both aware and have the same offsets,
4919 * we get off cheap. Note that if they're both naive, offset1 ==
4920 * offset2 == Py_None at this point.
4921 */
4922 if ((offset1 == offset2) ||
4923 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4924 delta_cmp(offset1, offset2) == 0)) {
4925 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4926 ((PyDateTime_DateTime *)other)->data,
4927 _PyDateTime_DATETIME_DATASIZE);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004928 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4929 int ex = pep495_eq_exception(self, other, offset1, offset2);
4930 if (ex == -1)
4931 goto done;
4932 if (ex)
4933 diff = 1;
4934 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004935 result = diff_to_bool(diff, op);
4936 }
4937 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004939
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004940 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4942 other);
4943 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004944 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004945 diff = GET_TD_DAYS(delta);
4946 if (diff == 0)
4947 diff = GET_TD_SECONDS(delta) |
4948 GET_TD_MICROSECONDS(delta);
4949 Py_DECREF(delta);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004950 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4951 int ex = pep495_eq_exception(self, other, offset1, offset2);
4952 if (ex == -1)
4953 goto done;
4954 if (ex)
4955 diff = 1;
4956 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004957 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004959 else if (op == Py_EQ) {
4960 result = Py_False;
4961 Py_INCREF(result);
4962 }
4963 else if (op == Py_NE) {
4964 result = Py_True;
4965 Py_INCREF(result);
4966 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004967 else {
4968 PyErr_SetString(PyExc_TypeError,
4969 "can't compare offset-naive and "
4970 "offset-aware datetimes");
4971 }
4972 done:
4973 Py_DECREF(offset1);
4974 Py_XDECREF(offset2);
4975 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004976}
4977
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004978static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004979datetime_hash(PyDateTime_DateTime *self)
4980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004982 PyObject *offset, *self0;
4983 if (DATE_GET_FOLD(self)) {
4984 self0 = new_datetime_ex2(GET_YEAR(self),
4985 GET_MONTH(self),
4986 GET_DAY(self),
4987 DATE_GET_HOUR(self),
4988 DATE_GET_MINUTE(self),
4989 DATE_GET_SECOND(self),
4990 DATE_GET_MICROSECOND(self),
4991 HASTZINFO(self) ? self->tzinfo : Py_None,
4992 0, Py_TYPE(self));
4993 if (self0 == NULL)
4994 return -1;
4995 }
4996 else {
4997 self0 = (PyObject *)self;
4998 Py_INCREF(self0);
4999 }
5000 offset = datetime_utcoffset(self0, NULL);
5001 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005002
5003 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00005005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005006 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005007 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 self->hashcode = generic_hash(
5009 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005011 PyObject *temp1, *temp2;
5012 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00005013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 assert(HASTZINFO(self));
5015 days = ymd_to_ord(GET_YEAR(self),
5016 GET_MONTH(self),
5017 GET_DAY(self));
5018 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005019 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005021 temp1 = new_delta(days, seconds,
5022 DATE_GET_MICROSECOND(self),
5023 1);
5024 if (temp1 == NULL) {
5025 Py_DECREF(offset);
5026 return -1;
5027 }
5028 temp2 = delta_subtract(temp1, offset);
5029 Py_DECREF(temp1);
5030 if (temp2 == NULL) {
5031 Py_DECREF(offset);
5032 return -1;
5033 }
5034 self->hashcode = PyObject_Hash(temp2);
5035 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005037 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 }
5039 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00005040}
Tim Peters2a799bf2002-12-16 20:18:38 +00005041
5042static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005043datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00005044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 PyObject *clone;
5046 PyObject *tuple;
5047 int y = GET_YEAR(self);
5048 int m = GET_MONTH(self);
5049 int d = GET_DAY(self);
5050 int hh = DATE_GET_HOUR(self);
5051 int mm = DATE_GET_MINUTE(self);
5052 int ss = DATE_GET_SECOND(self);
5053 int us = DATE_GET_MICROSECOND(self);
5054 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005055 int fold = DATE_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00005056
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005057 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 datetime_kws,
5059 &y, &m, &d, &hh, &mm, &ss, &us,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005060 &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03005062 if (fold != 0 && fold != 1) {
5063 PyErr_SetString(PyExc_ValueError,
5064 "fold must be either 0 or 1");
5065 return NULL;
5066 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
5068 if (tuple == NULL)
5069 return NULL;
5070 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005071 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005072 DATE_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005073 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 Py_DECREF(tuple);
5075 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00005076}
5077
5078static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005079local_timezone_from_timestamp(time_t timestamp)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005080{
5081 PyObject *result = NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005082 PyObject *delta;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005083 struct tm local_time_tm;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005084 PyObject *nameo = NULL;
5085 const char *zone = NULL;
5086
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005087 if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005088 return NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005089#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005090 zone = local_time_tm.tm_zone;
5091 delta = new_delta(0, local_time_tm.tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005092#else /* HAVE_STRUCT_TM_TM_ZONE */
5093 {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005094 PyObject *local_time, *utc_time;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005095 struct tm utc_time_tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005096 char buf[100];
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005097 strftime(buf, sizeof(buf), "%Z", &local_time_tm);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005098 zone = buf;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005099 local_time = new_datetime(local_time_tm.tm_year + 1900,
5100 local_time_tm.tm_mon + 1,
5101 local_time_tm.tm_mday,
5102 local_time_tm.tm_hour,
5103 local_time_tm.tm_min,
5104 local_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005105 if (local_time == NULL) {
5106 return NULL;
5107 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005108 if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005109 return NULL;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005110 utc_time = new_datetime(utc_time_tm.tm_year + 1900,
5111 utc_time_tm.tm_mon + 1,
5112 utc_time_tm.tm_mday,
5113 utc_time_tm.tm_hour,
5114 utc_time_tm.tm_min,
5115 utc_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005116 if (utc_time == NULL) {
5117 Py_DECREF(local_time);
5118 return NULL;
5119 }
5120 delta = datetime_subtract(local_time, utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005121 Py_DECREF(local_time);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005122 Py_DECREF(utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005123 }
5124#endif /* HAVE_STRUCT_TM_TM_ZONE */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005125 if (delta == NULL) {
5126 return NULL;
5127 }
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005128 if (zone != NULL) {
5129 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
5130 if (nameo == NULL)
5131 goto error;
5132 }
5133 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02005134 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005135 error:
5136 Py_DECREF(delta);
5137 return result;
5138}
5139
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005140static PyObject *
5141local_timezone(PyDateTime_DateTime *utc_time)
5142{
5143 time_t timestamp;
5144 PyObject *delta;
5145 PyObject *one_second;
5146 PyObject *seconds;
5147
5148 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
5149 if (delta == NULL)
5150 return NULL;
5151 one_second = new_delta(0, 1, 0, 0);
5152 if (one_second == NULL) {
5153 Py_DECREF(delta);
5154 return NULL;
5155 }
5156 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
5157 (PyDateTime_Delta *)one_second);
5158 Py_DECREF(one_second);
5159 Py_DECREF(delta);
5160 if (seconds == NULL)
5161 return NULL;
5162 timestamp = _PyLong_AsTime_t(seconds);
5163 Py_DECREF(seconds);
5164 if (timestamp == -1 && PyErr_Occurred())
5165 return NULL;
5166 return local_timezone_from_timestamp(timestamp);
5167}
5168
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005169static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005170local_to_seconds(int year, int month, int day,
5171 int hour, int minute, int second, int fold);
5172
5173static PyObject *
5174local_timezone_from_local(PyDateTime_DateTime *local_dt)
5175{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005176 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005177 time_t timestamp;
5178 seconds = local_to_seconds(GET_YEAR(local_dt),
5179 GET_MONTH(local_dt),
5180 GET_DAY(local_dt),
5181 DATE_GET_HOUR(local_dt),
5182 DATE_GET_MINUTE(local_dt),
5183 DATE_GET_SECOND(local_dt),
5184 DATE_GET_FOLD(local_dt));
5185 if (seconds == -1)
5186 return NULL;
5187 /* XXX: add bounds check */
5188 timestamp = seconds - epoch;
5189 return local_timezone_from_timestamp(timestamp);
5190}
5191
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005192static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00005193datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00005194{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005195 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005196 PyObject *offset;
5197 PyObject *temp;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005198 PyObject *self_tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005199 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00005201
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005202 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07005203 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005204 return NULL;
5205
5206 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00005208
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005209 if (!HASTZINFO(self) || self->tzinfo == Py_None) {
5210 self_tzinfo = local_timezone_from_local(self);
5211 if (self_tzinfo == NULL)
5212 return NULL;
5213 } else {
5214 self_tzinfo = self->tzinfo;
5215 Py_INCREF(self_tzinfo);
5216 }
Tim Peters521fc152002-12-31 17:36:56 +00005217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005218 /* Conversion to self's own time zone is a NOP. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005219 if (self_tzinfo == tzinfo) {
5220 Py_DECREF(self_tzinfo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005221 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005222 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 }
Tim Peters521fc152002-12-31 17:36:56 +00005224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 /* Convert self to UTC. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005226 offset = call_utcoffset(self_tzinfo, (PyObject *)self);
5227 Py_DECREF(self_tzinfo);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005228 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005230 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005231 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5232 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005233 Py_DECREF(offset);
5234 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00005236
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005237 /* Make sure result is aware and UTC. */
5238 if (!HASTZINFO(result)) {
5239 temp = (PyObject *)result;
5240 result = (PyDateTime_DateTime *)
5241 new_datetime_ex2(GET_YEAR(result),
5242 GET_MONTH(result),
5243 GET_DAY(result),
5244 DATE_GET_HOUR(result),
5245 DATE_GET_MINUTE(result),
5246 DATE_GET_SECOND(result),
5247 DATE_GET_MICROSECOND(result),
5248 PyDateTime_TimeZone_UTC,
5249 DATE_GET_FOLD(result),
5250 Py_TYPE(result));
5251 Py_DECREF(temp);
5252 if (result == NULL)
5253 return NULL;
5254 }
5255 else {
5256 /* Result is already aware - just replace tzinfo. */
5257 temp = result->tzinfo;
5258 result->tzinfo = PyDateTime_TimeZone_UTC;
5259 Py_INCREF(result->tzinfo);
5260 Py_DECREF(temp);
5261 }
5262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005264 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005265 if (tzinfo == Py_None) {
5266 tzinfo = local_timezone(result);
5267 if (tzinfo == NULL) {
5268 Py_DECREF(result);
5269 return NULL;
5270 }
5271 }
5272 else
5273 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005274 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005275 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00005276
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005277 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005278 result = (PyDateTime_DateTime *)
Victor Stinner20401de2016-12-09 15:24:31 +01005279 _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_fromutc, temp, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005280 Py_DECREF(temp);
5281
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005282 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00005283}
5284
5285static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005286datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00005289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005291 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00005292
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005293 dst = call_dst(self->tzinfo, (PyObject *)self);
5294 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005296
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005297 if (dst != Py_None)
5298 dstflag = delta_bool((PyDateTime_Delta *)dst);
5299 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005300 }
5301 return build_struct_time(GET_YEAR(self),
5302 GET_MONTH(self),
5303 GET_DAY(self),
5304 DATE_GET_HOUR(self),
5305 DATE_GET_MINUTE(self),
5306 DATE_GET_SECOND(self),
5307 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00005308}
5309
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005310static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005311local_to_seconds(int year, int month, int day,
5312 int hour, int minute, int second, int fold)
5313{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005314 long long t, a, b, u1, u2, t1, t2, lt;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005315 t = utc_to_seconds(year, month, day, hour, minute, second);
5316 /* Our goal is to solve t = local(u) for u. */
5317 lt = local(t);
5318 if (lt == -1)
5319 return -1;
5320 a = lt - t;
5321 u1 = t - a;
5322 t1 = local(u1);
5323 if (t1 == -1)
5324 return -1;
5325 if (t1 == t) {
5326 /* We found one solution, but it may not be the one we need.
5327 * Look for an earlier solution (if `fold` is 0), or a
5328 * later one (if `fold` is 1). */
5329 if (fold)
5330 u2 = u1 + max_fold_seconds;
5331 else
5332 u2 = u1 - max_fold_seconds;
5333 lt = local(u2);
5334 if (lt == -1)
5335 return -1;
5336 b = lt - u2;
5337 if (a == b)
5338 return u1;
5339 }
5340 else {
5341 b = t1 - u1;
5342 assert(a != b);
5343 }
5344 u2 = t - b;
5345 t2 = local(u2);
5346 if (t2 == -1)
5347 return -1;
5348 if (t2 == t)
5349 return u2;
5350 if (t1 == t)
5351 return u1;
5352 /* We have found both offsets a and b, but neither t - a nor t - b is
5353 * a solution. This means t is in the gap. */
5354 return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
5355}
5356
5357/* date(1970,1,1).toordinal() == 719163 */
5358#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
5359
Tim Peters2a799bf2002-12-16 20:18:38 +00005360static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04005361datetime_timestamp(PyDateTime_DateTime *self)
5362{
5363 PyObject *result;
5364
5365 if (HASTZINFO(self) && self->tzinfo != Py_None) {
5366 PyObject *delta;
5367 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
5368 if (delta == NULL)
5369 return NULL;
5370 result = delta_total_seconds(delta);
5371 Py_DECREF(delta);
5372 }
5373 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005374 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005375 seconds = local_to_seconds(GET_YEAR(self),
5376 GET_MONTH(self),
5377 GET_DAY(self),
5378 DATE_GET_HOUR(self),
5379 DATE_GET_MINUTE(self),
5380 DATE_GET_SECOND(self),
5381 DATE_GET_FOLD(self));
5382 if (seconds == -1)
Alexander Belopolskya4415142012-06-08 12:33:09 -04005383 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005384 result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
5385 DATE_GET_MICROSECOND(self) / 1e6);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005386 }
5387 return result;
5388}
5389
5390static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005391datetime_getdate(PyDateTime_DateTime *self)
5392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005393 return new_date(GET_YEAR(self),
5394 GET_MONTH(self),
5395 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005396}
5397
5398static PyObject *
5399datetime_gettime(PyDateTime_DateTime *self)
5400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 return new_time(DATE_GET_HOUR(self),
5402 DATE_GET_MINUTE(self),
5403 DATE_GET_SECOND(self),
5404 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005405 Py_None,
5406 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005407}
5408
5409static PyObject *
5410datetime_gettimetz(PyDateTime_DateTime *self)
5411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 return new_time(DATE_GET_HOUR(self),
5413 DATE_GET_MINUTE(self),
5414 DATE_GET_SECOND(self),
5415 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005416 GET_DT_TZINFO(self),
5417 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005418}
5419
5420static PyObject *
5421datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005422{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005423 int y, m, d, hh, mm, ss;
5424 PyObject *tzinfo;
5425 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00005426
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005427 tzinfo = GET_DT_TZINFO(self);
5428 if (tzinfo == Py_None) {
5429 utcself = self;
5430 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005432 else {
5433 PyObject *offset;
5434 offset = call_utcoffset(tzinfo, (PyObject *)self);
5435 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00005436 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005437 if (offset == Py_None) {
5438 Py_DECREF(offset);
5439 utcself = self;
5440 Py_INCREF(utcself);
5441 }
5442 else {
5443 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5444 (PyDateTime_Delta *)offset, -1);
5445 Py_DECREF(offset);
5446 if (utcself == NULL)
5447 return NULL;
5448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005450 y = GET_YEAR(utcself);
5451 m = GET_MONTH(utcself);
5452 d = GET_DAY(utcself);
5453 hh = DATE_GET_HOUR(utcself);
5454 mm = DATE_GET_MINUTE(utcself);
5455 ss = DATE_GET_SECOND(utcself);
5456
5457 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005459}
5460
Tim Peters371935f2003-02-01 01:52:50 +00005461/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00005462
Tim Petersa9bc1682003-01-11 03:39:11 +00005463/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00005464 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5465 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00005466 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00005467 */
5468static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005469datetime_getstate(PyDateTime_DateTime *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00005470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 PyObject *basestate;
5472 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005474 basestate = PyBytes_FromStringAndSize((char *)self->data,
5475 _PyDateTime_DATETIME_DATASIZE);
5476 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005477 if (proto > 3 && DATE_GET_FOLD(self))
5478 /* Set the first bit of the third byte */
5479 PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5481 result = PyTuple_Pack(1, basestate);
5482 else
5483 result = PyTuple_Pack(2, basestate, self->tzinfo);
5484 Py_DECREF(basestate);
5485 }
5486 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005487}
5488
5489static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005490datetime_reduce_ex(PyDateTime_DateTime *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00005491{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005492 int proto;
5493 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005494 return NULL;
5495
5496 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00005497}
5498
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005499static PyObject *
5500datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
5501{
5502 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, 2));
5503}
5504
Tim Petersa9bc1682003-01-11 03:39:11 +00005505static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005508
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005509 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 {"utcnow", (PyCFunction)datetime_utcnow,
5512 METH_NOARGS | METH_CLASS,
5513 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005515 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5516 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5517 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5520 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05005521 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 {"strptime", (PyCFunction)datetime_strptime,
5524 METH_VARARGS | METH_CLASS,
5525 PyDoc_STR("string, format -> new datetime parsed from a string "
5526 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 {"combine", (PyCFunction)datetime_combine,
5529 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5530 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5535 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5538 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5541 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5544 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5547 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005548
Alexander Belopolskya4415142012-06-08 12:33:09 -04005549 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5550 PyDoc_STR("Return POSIX timestamp as float.")},
5551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5553 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5556 PyDoc_STR("[sep] -> string in ISO 8601 format, "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005557 "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 "sep is used to separate the year from the time, and "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005559 "defaults to 'T'.\n"
5560 "timespec specifies what components of the time to include"
5561 " (allowed values are 'auto', 'hours', 'minutes', 'seconds',"
5562 " 'milliseconds', and 'microseconds').\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5565 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5568 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5571 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005573 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5574 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5577 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005578
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005579 {"__reduce_ex__", (PyCFunction)datetime_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005580 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005581
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005582 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
5583 PyDoc_STR("__reduce__() -> (cls, state)")},
5584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005586};
5587
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02005588static const char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005589PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5590\n\
5591The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005592instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005593
Tim Petersa9bc1682003-01-11 03:39:11 +00005594static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 datetime_add, /* nb_add */
5596 datetime_subtract, /* nb_subtract */
5597 0, /* nb_multiply */
5598 0, /* nb_remainder */
5599 0, /* nb_divmod */
5600 0, /* nb_power */
5601 0, /* nb_negative */
5602 0, /* nb_positive */
5603 0, /* nb_absolute */
5604 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005605};
5606
Neal Norwitz227b5332006-03-22 09:28:35 +00005607static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005608 PyVarObject_HEAD_INIT(NULL, 0)
5609 "datetime.datetime", /* tp_name */
5610 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5611 0, /* tp_itemsize */
5612 (destructor)datetime_dealloc, /* tp_dealloc */
5613 0, /* tp_print */
5614 0, /* tp_getattr */
5615 0, /* tp_setattr */
5616 0, /* tp_reserved */
5617 (reprfunc)datetime_repr, /* tp_repr */
5618 &datetime_as_number, /* tp_as_number */
5619 0, /* tp_as_sequence */
5620 0, /* tp_as_mapping */
5621 (hashfunc)datetime_hash, /* tp_hash */
5622 0, /* tp_call */
5623 (reprfunc)datetime_str, /* tp_str */
5624 PyObject_GenericGetAttr, /* tp_getattro */
5625 0, /* tp_setattro */
5626 0, /* tp_as_buffer */
5627 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5628 datetime_doc, /* tp_doc */
5629 0, /* tp_traverse */
5630 0, /* tp_clear */
5631 datetime_richcompare, /* tp_richcompare */
5632 0, /* tp_weaklistoffset */
5633 0, /* tp_iter */
5634 0, /* tp_iternext */
5635 datetime_methods, /* tp_methods */
5636 0, /* tp_members */
5637 datetime_getset, /* tp_getset */
5638 &PyDateTime_DateType, /* tp_base */
5639 0, /* tp_dict */
5640 0, /* tp_descr_get */
5641 0, /* tp_descr_set */
5642 0, /* tp_dictoffset */
5643 0, /* tp_init */
5644 datetime_alloc, /* tp_alloc */
5645 datetime_new, /* tp_new */
5646 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005647};
5648
5649/* ---------------------------------------------------------------------------
5650 * Module methods and initialization.
5651 */
5652
5653static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005655};
5656
Tim Peters9ddf40b2004-06-20 22:41:32 +00005657/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5658 * datetime.h.
5659 */
5660static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 &PyDateTime_DateType,
5662 &PyDateTime_DateTimeType,
5663 &PyDateTime_TimeType,
5664 &PyDateTime_DeltaType,
5665 &PyDateTime_TZInfoType,
5666 new_date_ex,
5667 new_datetime_ex,
5668 new_time_ex,
5669 new_delta_ex,
5670 datetime_fromtimestamp,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005671 date_fromtimestamp,
5672 new_datetime_ex2,
5673 new_time_ex2
Tim Peters9ddf40b2004-06-20 22:41:32 +00005674};
5675
5676
Martin v. Löwis1a214512008-06-11 05:26:20 +00005677
5678static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005680 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 "Fast implementation of the datetime type.",
5682 -1,
5683 module_methods,
5684 NULL,
5685 NULL,
5686 NULL,
5687 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005688};
5689
Tim Peters2a799bf2002-12-16 20:18:38 +00005690PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005691PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 PyObject *m; /* a module object */
5694 PyObject *d; /* its dict */
5695 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005696 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 m = PyModule_Create(&datetimemodule);
5699 if (m == NULL)
5700 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 if (PyType_Ready(&PyDateTime_DateType) < 0)
5703 return NULL;
5704 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5705 return NULL;
5706 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5707 return NULL;
5708 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5709 return NULL;
5710 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5711 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005712 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5713 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 /* timedelta values */
5716 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 x = new_delta(0, 0, 1, 0);
5719 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5720 return NULL;
5721 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5724 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5725 return NULL;
5726 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005728 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5729 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5730 return NULL;
5731 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005733 /* date values */
5734 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 x = new_date(1, 1, 1);
5737 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5738 return NULL;
5739 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005741 x = new_date(MAXYEAR, 12, 31);
5742 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5743 return NULL;
5744 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 x = new_delta(1, 0, 0, 0);
5747 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5748 return NULL;
5749 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005751 /* time values */
5752 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005753
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005754 x = new_time(0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5756 return NULL;
5757 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005758
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005759 x = new_time(23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005760 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5761 return NULL;
5762 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005764 x = new_delta(0, 0, 1, 0);
5765 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5766 return NULL;
5767 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005769 /* datetime values */
5770 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005771
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005772 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5774 return NULL;
5775 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005776
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005777 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005778 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5779 return NULL;
5780 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005782 x = new_delta(0, 0, 1, 0);
5783 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5784 return NULL;
5785 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005786
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005787 /* timezone values */
5788 d = PyDateTime_TimeZoneType.tp_dict;
5789
5790 delta = new_delta(0, 0, 0, 0);
5791 if (delta == NULL)
5792 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005793 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005794 Py_DECREF(delta);
5795 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5796 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005797 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005798
5799 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5800 if (delta == NULL)
5801 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005802 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005803 Py_DECREF(delta);
5804 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5805 return NULL;
5806 Py_DECREF(x);
5807
5808 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5809 if (delta == NULL)
5810 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005811 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005812 Py_DECREF(delta);
5813 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5814 return NULL;
5815 Py_DECREF(x);
5816
Alexander Belopolskya4415142012-06-08 12:33:09 -04005817 /* Epoch */
5818 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005819 PyDateTime_TimeZone_UTC, 0);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005820 if (PyDateTime_Epoch == NULL)
5821 return NULL;
5822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005824 PyModule_AddIntMacro(m, MINYEAR);
5825 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 Py_INCREF(&PyDateTime_DateType);
5828 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 Py_INCREF(&PyDateTime_DateTimeType);
5831 PyModule_AddObject(m, "datetime",
5832 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 Py_INCREF(&PyDateTime_TimeType);
5835 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 Py_INCREF(&PyDateTime_DeltaType);
5838 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005840 Py_INCREF(&PyDateTime_TZInfoType);
5841 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005842
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005843 Py_INCREF(&PyDateTime_TimeZoneType);
5844 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005846 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5847 if (x == NULL)
5848 return NULL;
5849 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 /* A 4-year cycle has an extra leap day over what we'd get from
5852 * pasting together 4 single years.
5853 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005854 Py_BUILD_ASSERT(DI4Y == 4 * 365 + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005855 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5858 * get from pasting together 4 100-year cycles.
5859 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005860 Py_BUILD_ASSERT(DI400Y == 4 * DI100Y + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005863 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5864 * pasting together 25 4-year cycles.
5865 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005866 Py_BUILD_ASSERT(DI100Y == 25 * DI4Y - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005867 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005869 us_per_ms = PyLong_FromLong(1000);
5870 us_per_second = PyLong_FromLong(1000000);
5871 us_per_minute = PyLong_FromLong(60000000);
5872 seconds_per_day = PyLong_FromLong(24 * 3600);
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005873 if (us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874 us_per_minute == NULL || seconds_per_day == NULL)
5875 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 /* The rest are too big for 32-bit ints, but even
5878 * us_per_week fits in 40 bits, so doubles should be exact.
5879 */
5880 us_per_hour = PyLong_FromDouble(3600000000.0);
5881 us_per_day = PyLong_FromDouble(86400000000.0);
5882 us_per_week = PyLong_FromDouble(604800000000.0);
5883 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5884 return NULL;
5885 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005886}
Tim Petersf3615152003-01-01 21:51:37 +00005887
5888/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005889Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005890 x.n = x stripped of its timezone -- its naive time.
5891 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 return None
Tim Petersf3615152003-01-01 21:51:37 +00005893 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005894 return None
Tim Petersf3615152003-01-01 21:51:37 +00005895 x.s = x's standard offset, x.o - x.d
5896
5897Now some derived rules, where k is a duration (timedelta).
5898
58991. x.o = x.s + x.d
5900 This follows from the definition of x.s.
5901
Tim Petersc5dc4da2003-01-02 17:55:03 +000059022. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005903 This is actually a requirement, an assumption we need to make about
5904 sane tzinfo classes.
5905
59063. The naive UTC time corresponding to x is x.n - x.o.
5907 This is again a requirement for a sane tzinfo class.
5908
59094. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005910 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005911
Tim Petersc5dc4da2003-01-02 17:55:03 +000059125. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005913 Again follows from how arithmetic is defined.
5914
Tim Peters8bb5ad22003-01-24 02:44:45 +00005915Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005916(meaning that the various tzinfo methods exist, and don't blow up or return
5917None when called).
5918
Tim Petersa9bc1682003-01-11 03:39:11 +00005919The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005920x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005921
5922By #3, we want
5923
Tim Peters8bb5ad22003-01-24 02:44:45 +00005924 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005925
5926The algorithm starts by attaching tz to x.n, and calling that y. So
5927x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5928becomes true; in effect, we want to solve [2] for k:
5929
Tim Peters8bb5ad22003-01-24 02:44:45 +00005930 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005931
5932By #1, this is the same as
5933
Tim Peters8bb5ad22003-01-24 02:44:45 +00005934 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005935
5936By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5937Substituting that into [3],
5938
Tim Peters8bb5ad22003-01-24 02:44:45 +00005939 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5940 k - (y+k).s - (y+k).d = 0; rearranging,
5941 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5942 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005943
Tim Peters8bb5ad22003-01-24 02:44:45 +00005944On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5945approximate k by ignoring the (y+k).d term at first. Note that k can't be
5946very large, since all offset-returning methods return a duration of magnitude
5947less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5948be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005949
5950In any case, the new value is
5951
Tim Peters8bb5ad22003-01-24 02:44:45 +00005952 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005953
Tim Peters8bb5ad22003-01-24 02:44:45 +00005954It's helpful to step back at look at [4] from a higher level: it's simply
5955mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005956
5957At this point, if
5958
Tim Peters8bb5ad22003-01-24 02:44:45 +00005959 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005960
5961we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005962at the start of daylight time. Picture US Eastern for concreteness. The wall
5963time 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 +00005964sense then. The docs ask that an Eastern tzinfo class consider such a time to
5965be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5966on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005967the only spelling that makes sense on the local wall clock.
5968
Tim Petersc5dc4da2003-01-02 17:55:03 +00005969In fact, if [5] holds at this point, we do have the standard-time spelling,
5970but that takes a bit of proof. We first prove a stronger result. What's the
5971difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005972
Tim Peters8bb5ad22003-01-24 02:44:45 +00005973 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005974
Tim Petersc5dc4da2003-01-02 17:55:03 +00005975Now
5976 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005977 (y + y.s).n = by #5
5978 y.n + y.s = since y.n = x.n
5979 x.n + y.s = since z and y are have the same tzinfo member,
5980 y.s = z.s by #2
5981 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005982
Tim Petersc5dc4da2003-01-02 17:55:03 +00005983Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005984
Tim Petersc5dc4da2003-01-02 17:55:03 +00005985 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005986 x.n - ((x.n + z.s) - z.o) = expanding
5987 x.n - x.n - z.s + z.o = cancelling
5988 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005989 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005990
Tim Petersc5dc4da2003-01-02 17:55:03 +00005991So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005992
Tim Petersc5dc4da2003-01-02 17:55:03 +00005993If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005994spelling we wanted in the endcase described above. We're done. Contrarily,
5995if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005996
Tim Petersc5dc4da2003-01-02 17:55:03 +00005997If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5998add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005999local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00006000
Tim Petersc5dc4da2003-01-02 17:55:03 +00006001Let
Tim Petersf3615152003-01-01 21:51:37 +00006002
Tim Peters4fede1a2003-01-04 00:26:59 +00006003 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00006004
Tim Peters4fede1a2003-01-04 00:26:59 +00006005and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00006006
Tim Peters8bb5ad22003-01-24 02:44:45 +00006007 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00006008
Tim Peters8bb5ad22003-01-24 02:44:45 +00006009If so, we're done. If not, the tzinfo class is insane, according to the
6010assumptions we've made. This also requires a bit of proof. As before, let's
6011compute the difference between the LHS and RHS of [8] (and skipping some of
6012the justifications for the kinds of substitutions we've done several times
6013already):
Tim Peters4fede1a2003-01-04 00:26:59 +00006014
Tim Peters8bb5ad22003-01-24 02:44:45 +00006015 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006016 x.n - (z.n + diff - z'.o) = replacing diff via [6]
6017 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
6018 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
6019 - z.n + z.n - z.o + z'.o = cancel z.n
6020 - z.o + z'.o = #1 twice
6021 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
6022 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00006023
6024So 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 +00006025we've found the UTC-equivalent so are done. In fact, we stop with [7] and
6026return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00006027
Tim Peters8bb5ad22003-01-24 02:44:45 +00006028How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
6029a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
6030would have to change the result dst() returns: we start in DST, and moving
6031a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00006032
Tim Peters8bb5ad22003-01-24 02:44:45 +00006033There isn't a sane case where this can happen. The closest it gets is at
6034the end of DST, where there's an hour in UTC with no spelling in a hybrid
6035tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
6036that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
6037UTC) because the docs insist on that, but 0:MM is taken as being in daylight
6038time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
6039clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
6040standard time. Since that's what the local clock *does*, we want to map both
6041UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00006042in local time, but so it goes -- it's the way the local clock works.
6043
Tim Peters8bb5ad22003-01-24 02:44:45 +00006044When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
6045so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
6046z' = 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 +00006047(correctly) concludes that z' is not UTC-equivalent to x.
6048
6049Because we know z.d said z was in daylight time (else [5] would have held and
6050we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006051and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00006052return in Eastern, it follows that z'.d must be 0 (which it is in the example,
6053but the reasoning doesn't depend on the example -- it depends on there being
6054two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00006055z' must be in standard time, and is the spelling we want in this case.
6056
6057Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
6058concerned (because it takes z' as being in standard time rather than the
6059daylight time we intend here), but returning it gives the real-life "local
6060clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
6061tz.
6062
6063When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
6064the 1:MM standard time spelling we want.
6065
6066So how can this break? One of the assumptions must be violated. Two
6067possibilities:
6068
60691) [2] effectively says that y.s is invariant across all y belong to a given
6070 time zone. This isn't true if, for political reasons or continental drift,
6071 a region decides to change its base offset from UTC.
6072
60732) There may be versions of "double daylight" time where the tail end of
6074 the analysis gives up a step too early. I haven't thought about that
6075 enough to say.
6076
6077In any case, it's clear that the default fromutc() is strong enough to handle
6078"almost all" time zones: so long as the standard offset is invariant, it
6079doesn't matter if daylight time transition points change from year to year, or
6080if daylight time is skipped in some years; it doesn't matter how large or
6081small dst() may get within its bounds; and it doesn't even matter if some
6082perverse time zone returns a negative dst()). So a breaking case must be
6083pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00006084--------------------------------------------------------------------------- */