blob: 3439040d2d91b971fb9028e3691465f2d22d86e9 [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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (GET_TD_MICROSECONDS(self) != 0)
2288 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2289 Py_TYPE(self)->tp_name,
2290 GET_TD_DAYS(self),
2291 GET_TD_SECONDS(self),
2292 GET_TD_MICROSECONDS(self));
2293 if (GET_TD_SECONDS(self) != 0)
2294 return PyUnicode_FromFormat("%s(%d, %d)",
2295 Py_TYPE(self)->tp_name,
2296 GET_TD_DAYS(self),
2297 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 return PyUnicode_FromFormat("%s(%d)",
2300 Py_TYPE(self)->tp_name,
2301 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002302}
2303
2304static PyObject *
2305delta_str(PyDateTime_Delta *self)
2306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 int us = GET_TD_MICROSECONDS(self);
2308 int seconds = GET_TD_SECONDS(self);
2309 int minutes = divmod(seconds, 60, &seconds);
2310 int hours = divmod(minutes, 60, &minutes);
2311 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 if (days) {
2314 if (us)
2315 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2316 days, (days == 1 || days == -1) ? "" : "s",
2317 hours, minutes, seconds, us);
2318 else
2319 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2320 days, (days == 1 || days == -1) ? "" : "s",
2321 hours, minutes, seconds);
2322 } else {
2323 if (us)
2324 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2325 hours, minutes, seconds, us);
2326 else
2327 return PyUnicode_FromFormat("%d:%02d:%02d",
2328 hours, minutes, seconds);
2329 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002330
Tim Peters2a799bf2002-12-16 20:18:38 +00002331}
2332
Tim Peters371935f2003-02-01 01:52:50 +00002333/* Pickle support, a simple use of __reduce__. */
2334
Tim Petersb57f8f02003-02-01 02:54:15 +00002335/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002336static PyObject *
2337delta_getstate(PyDateTime_Delta *self)
2338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 return Py_BuildValue("iii", GET_TD_DAYS(self),
2340 GET_TD_SECONDS(self),
2341 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002342}
2343
Tim Peters2a799bf2002-12-16 20:18:38 +00002344static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002345delta_total_seconds(PyObject *self)
2346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 PyObject *total_seconds;
2348 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2351 if (total_microseconds == NULL)
2352 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002353
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002354 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002358}
2359
2360static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002361delta_reduce(PyDateTime_Delta* self)
2362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002364}
2365
2366#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2367
2368static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 {"days", T_INT, OFFSET(days), READONLY,
2371 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 {"seconds", T_INT, OFFSET(seconds), READONLY,
2374 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2377 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2378 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002379};
2380
2381static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2383 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2386 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002389};
2390
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002391static const char delta_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00002392PyDoc_STR("Difference between two datetime values.");
2393
2394static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 delta_add, /* nb_add */
2396 delta_subtract, /* nb_subtract */
2397 delta_multiply, /* nb_multiply */
2398 delta_remainder, /* nb_remainder */
2399 delta_divmod, /* nb_divmod */
2400 0, /* nb_power */
2401 (unaryfunc)delta_negative, /* nb_negative */
2402 (unaryfunc)delta_positive, /* nb_positive */
2403 (unaryfunc)delta_abs, /* nb_absolute */
2404 (inquiry)delta_bool, /* nb_bool */
2405 0, /*nb_invert*/
2406 0, /*nb_lshift*/
2407 0, /*nb_rshift*/
2408 0, /*nb_and*/
2409 0, /*nb_xor*/
2410 0, /*nb_or*/
2411 0, /*nb_int*/
2412 0, /*nb_reserved*/
2413 0, /*nb_float*/
2414 0, /*nb_inplace_add*/
2415 0, /*nb_inplace_subtract*/
2416 0, /*nb_inplace_multiply*/
2417 0, /*nb_inplace_remainder*/
2418 0, /*nb_inplace_power*/
2419 0, /*nb_inplace_lshift*/
2420 0, /*nb_inplace_rshift*/
2421 0, /*nb_inplace_and*/
2422 0, /*nb_inplace_xor*/
2423 0, /*nb_inplace_or*/
2424 delta_divide, /* nb_floor_divide */
2425 delta_truedivide, /* nb_true_divide */
2426 0, /* nb_inplace_floor_divide */
2427 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002428};
2429
2430static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 PyVarObject_HEAD_INIT(NULL, 0)
2432 "datetime.timedelta", /* tp_name */
2433 sizeof(PyDateTime_Delta), /* tp_basicsize */
2434 0, /* tp_itemsize */
2435 0, /* tp_dealloc */
2436 0, /* tp_print */
2437 0, /* tp_getattr */
2438 0, /* tp_setattr */
2439 0, /* tp_reserved */
2440 (reprfunc)delta_repr, /* tp_repr */
2441 &delta_as_number, /* tp_as_number */
2442 0, /* tp_as_sequence */
2443 0, /* tp_as_mapping */
2444 (hashfunc)delta_hash, /* tp_hash */
2445 0, /* tp_call */
2446 (reprfunc)delta_str, /* tp_str */
2447 PyObject_GenericGetAttr, /* tp_getattro */
2448 0, /* tp_setattro */
2449 0, /* tp_as_buffer */
2450 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2451 delta_doc, /* tp_doc */
2452 0, /* tp_traverse */
2453 0, /* tp_clear */
2454 delta_richcompare, /* tp_richcompare */
2455 0, /* tp_weaklistoffset */
2456 0, /* tp_iter */
2457 0, /* tp_iternext */
2458 delta_methods, /* tp_methods */
2459 delta_members, /* tp_members */
2460 0, /* tp_getset */
2461 0, /* tp_base */
2462 0, /* tp_dict */
2463 0, /* tp_descr_get */
2464 0, /* tp_descr_set */
2465 0, /* tp_dictoffset */
2466 0, /* tp_init */
2467 0, /* tp_alloc */
2468 delta_new, /* tp_new */
2469 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002470};
2471
2472/*
2473 * PyDateTime_Date implementation.
2474 */
2475
2476/* Accessor properties. */
2477
2478static PyObject *
2479date_year(PyDateTime_Date *self, void *unused)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002482}
2483
2484static PyObject *
2485date_month(PyDateTime_Date *self, void *unused)
2486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002488}
2489
2490static PyObject *
2491date_day(PyDateTime_Date *self, void *unused)
2492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002494}
2495
2496static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 {"year", (getter)date_year},
2498 {"month", (getter)date_month},
2499 {"day", (getter)date_day},
2500 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002501};
2502
2503/* Constructors. */
2504
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002505static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002506
Tim Peters2a799bf2002-12-16 20:18:38 +00002507static PyObject *
2508date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 PyObject *self = NULL;
2511 PyObject *state;
2512 int year;
2513 int month;
2514 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 /* Check for invocation from pickle with __getstate__ state */
2517 if (PyTuple_GET_SIZE(args) == 1 &&
2518 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2519 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2520 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2521 {
2522 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2525 if (me != NULL) {
2526 char *pdata = PyBytes_AS_STRING(state);
2527 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2528 me->hashcode = -1;
2529 }
2530 return (PyObject *)me;
2531 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2534 &year, &month, &day)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 self = new_date_ex(year, month, day, type);
2536 }
2537 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002538}
2539
2540/* Return new date from localtime(t). */
2541static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002542date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002543{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002544 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002546
Victor Stinnere4a994d2015-03-30 01:10:14 +02002547 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002549
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04002550 if (_PyTime_localtime(t, &tm) != 0)
Victor Stinner21f58932012-03-14 00:15:40 +01002551 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01002552
2553 return PyObject_CallFunction(cls, "iii",
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002554 tm.tm_year + 1900,
2555 tm.tm_mon + 1,
2556 tm.tm_mday);
Tim Peters2a799bf2002-12-16 20:18:38 +00002557}
2558
2559/* Return new date from current time.
2560 * We say this is equivalent to fromtimestamp(time.time()), and the
2561 * only way to be sure of that is to *call* time.time(). That's not
2562 * generally the same as calling C's time.
2563 */
2564static PyObject *
2565date_today(PyObject *cls, PyObject *dummy)
2566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 PyObject *time;
2568 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002569 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 time = time_time();
2572 if (time == NULL)
2573 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 /* Note well: today() is a class method, so this may not call
2576 * date.fromtimestamp. For example, it may call
2577 * datetime.fromtimestamp. That's why we need all the accuracy
2578 * time.time() delivers; if someone were gonzo about optimization,
2579 * date.today() could get away with plain C time().
2580 */
Victor Stinner20401de2016-12-09 15:24:31 +01002581 result = _PyObject_CallMethodIdObjArgs(cls, &PyId_fromtimestamp,
2582 time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 Py_DECREF(time);
2584 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002585}
2586
2587/* Return new date from given timestamp (Python timestamp -- a double). */
2588static PyObject *
2589date_fromtimestamp(PyObject *cls, PyObject *args)
2590{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002591 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002593
Victor Stinner5d272cc2012-03-13 13:35:55 +01002594 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2595 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002597}
2598
2599/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2600 * the ordinal is out of range.
2601 */
2602static PyObject *
2603date_fromordinal(PyObject *cls, PyObject *args)
2604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 PyObject *result = NULL;
2606 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2609 int year;
2610 int month;
2611 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 if (ordinal < 1)
2614 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2615 ">= 1");
2616 else {
2617 ord_to_ymd(ordinal, &year, &month, &day);
2618 result = PyObject_CallFunction(cls, "iii",
2619 year, month, day);
2620 }
2621 }
2622 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002623}
2624
2625/*
2626 * Date arithmetic.
2627 */
2628
2629/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2630 * instead.
2631 */
2632static PyObject *
2633add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 PyObject *result = NULL;
2636 int year = GET_YEAR(date);
2637 int month = GET_MONTH(date);
2638 int deltadays = GET_TD_DAYS(delta);
2639 /* C-level overflow is impossible because |deltadays| < 1e9. */
2640 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 if (normalize_date(&year, &month, &day) >= 0)
2643 result = new_date(year, month, day);
2644 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002645}
2646
2647static PyObject *
2648date_add(PyObject *left, PyObject *right)
2649{
Brian Curtindfc80e32011-08-10 20:28:54 -05002650 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2651 Py_RETURN_NOTIMPLEMENTED;
2652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (PyDate_Check(left)) {
2654 /* date + ??? */
2655 if (PyDelta_Check(right))
2656 /* date + delta */
2657 return add_date_timedelta((PyDateTime_Date *) left,
2658 (PyDateTime_Delta *) right,
2659 0);
2660 }
2661 else {
2662 /* ??? + date
2663 * 'right' must be one of us, or we wouldn't have been called
2664 */
2665 if (PyDelta_Check(left))
2666 /* delta + date */
2667 return add_date_timedelta((PyDateTime_Date *) right,
2668 (PyDateTime_Delta *) left,
2669 0);
2670 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002671 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002672}
2673
2674static PyObject *
2675date_subtract(PyObject *left, PyObject *right)
2676{
Brian Curtindfc80e32011-08-10 20:28:54 -05002677 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2678 Py_RETURN_NOTIMPLEMENTED;
2679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 if (PyDate_Check(left)) {
2681 if (PyDate_Check(right)) {
2682 /* date - date */
2683 int left_ord = ymd_to_ord(GET_YEAR(left),
2684 GET_MONTH(left),
2685 GET_DAY(left));
2686 int right_ord = ymd_to_ord(GET_YEAR(right),
2687 GET_MONTH(right),
2688 GET_DAY(right));
2689 return new_delta(left_ord - right_ord, 0, 0, 0);
2690 }
2691 if (PyDelta_Check(right)) {
2692 /* date - delta */
2693 return add_date_timedelta((PyDateTime_Date *) left,
2694 (PyDateTime_Delta *) right,
2695 1);
2696 }
2697 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002698 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002699}
2700
2701
2702/* Various ways to turn a date into a string. */
2703
2704static PyObject *
2705date_repr(PyDateTime_Date *self)
2706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2708 Py_TYPE(self)->tp_name,
2709 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002710}
2711
2712static PyObject *
2713date_isoformat(PyDateTime_Date *self)
2714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 return PyUnicode_FromFormat("%04d-%02d-%02d",
2716 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002717}
2718
Tim Peterse2df5ff2003-05-02 18:39:55 +00002719/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002720static PyObject *
2721date_str(PyDateTime_Date *self)
2722{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002723 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002724}
2725
2726
2727static PyObject *
2728date_ctime(PyDateTime_Date *self)
2729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002731}
2732
2733static PyObject *
2734date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 /* This method can be inherited, and needs to call the
2737 * timetuple() method appropriate to self's class.
2738 */
2739 PyObject *result;
2740 PyObject *tuple;
2741 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002742 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2746 &format))
2747 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002748
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002749 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 if (tuple == NULL)
2751 return NULL;
2752 result = wrap_strftime((PyObject *)self, format, tuple,
2753 (PyObject *)self);
2754 Py_DECREF(tuple);
2755 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002756}
2757
Eric Smith1ba31142007-09-11 18:06:02 +00002758static PyObject *
2759date_format(PyDateTime_Date *self, PyObject *args)
2760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2764 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002767 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002769
Victor Stinner20401de2016-12-09 15:24:31 +01002770 return _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_strftime,
2771 format, NULL);
Eric Smith1ba31142007-09-11 18:06:02 +00002772}
2773
Tim Peters2a799bf2002-12-16 20:18:38 +00002774/* ISO methods. */
2775
2776static PyObject *
2777date_isoweekday(PyDateTime_Date *self)
2778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002782}
2783
2784static PyObject *
2785date_isocalendar(PyDateTime_Date *self)
2786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 int year = GET_YEAR(self);
2788 int week1_monday = iso_week1_monday(year);
2789 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2790 int week;
2791 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 week = divmod(today - week1_monday, 7, &day);
2794 if (week < 0) {
2795 --year;
2796 week1_monday = iso_week1_monday(year);
2797 week = divmod(today - week1_monday, 7, &day);
2798 }
2799 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2800 ++year;
2801 week = 0;
2802 }
2803 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002804}
2805
2806/* Miscellaneous methods. */
2807
Tim Peters2a799bf2002-12-16 20:18:38 +00002808static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002809date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 if (PyDate_Check(other)) {
2812 int diff = memcmp(((PyDateTime_Date *)self)->data,
2813 ((PyDateTime_Date *)other)->data,
2814 _PyDateTime_DATE_DATASIZE);
2815 return diff_to_bool(diff, op);
2816 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002817 else
2818 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002819}
2820
2821static PyObject *
2822date_timetuple(PyDateTime_Date *self)
2823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 return build_struct_time(GET_YEAR(self),
2825 GET_MONTH(self),
2826 GET_DAY(self),
2827 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002828}
2829
Tim Peters12bf3392002-12-24 05:41:27 +00002830static PyObject *
2831date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 PyObject *clone;
2834 PyObject *tuple;
2835 int year = GET_YEAR(self);
2836 int month = GET_MONTH(self);
2837 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2840 &year, &month, &day))
2841 return NULL;
2842 tuple = Py_BuildValue("iii", year, month, day);
2843 if (tuple == NULL)
2844 return NULL;
2845 clone = date_new(Py_TYPE(self), tuple, NULL);
2846 Py_DECREF(tuple);
2847 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002848}
2849
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002850static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002851generic_hash(unsigned char *data, int len)
2852{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002853 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002854}
2855
2856
2857static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002858
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002859static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002860date_hash(PyDateTime_Date *self)
2861{
Benjamin Petersondec2df32016-09-09 17:46:24 -07002862 if (self->hashcode == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 self->hashcode = generic_hash(
2864 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Benjamin Petersondec2df32016-09-09 17:46:24 -07002865 }
Guido van Rossum254348e2007-11-21 19:29:53 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002868}
2869
2870static PyObject *
2871date_toordinal(PyDateTime_Date *self)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2874 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002875}
2876
2877static PyObject *
2878date_weekday(PyDateTime_Date *self)
2879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002883}
2884
Tim Peters371935f2003-02-01 01:52:50 +00002885/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002886
Tim Petersb57f8f02003-02-01 02:54:15 +00002887/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002888static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002889date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 PyObject* field;
2892 field = PyBytes_FromStringAndSize((char*)self->data,
2893 _PyDateTime_DATE_DATASIZE);
2894 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002895}
2896
2897static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002898date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002901}
2902
2903static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2908 METH_CLASS,
2909 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2910 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002912 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2913 METH_CLASS,
2914 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2915 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2918 PyDoc_STR("Current date or datetime: same as "
2919 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2924 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2927 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2930 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2933 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2936 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2937 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2940 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2943 PyDoc_STR("Return the day of the week represented by the date.\n"
2944 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2947 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2948 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2951 PyDoc_STR("Return the day of the week represented by the date.\n"
2952 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2955 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2958 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002961};
2962
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002963static const char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002964PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002965
2966static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 date_add, /* nb_add */
2968 date_subtract, /* nb_subtract */
2969 0, /* nb_multiply */
2970 0, /* nb_remainder */
2971 0, /* nb_divmod */
2972 0, /* nb_power */
2973 0, /* nb_negative */
2974 0, /* nb_positive */
2975 0, /* nb_absolute */
2976 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002977};
2978
2979static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 PyVarObject_HEAD_INIT(NULL, 0)
2981 "datetime.date", /* tp_name */
2982 sizeof(PyDateTime_Date), /* tp_basicsize */
2983 0, /* tp_itemsize */
2984 0, /* tp_dealloc */
2985 0, /* tp_print */
2986 0, /* tp_getattr */
2987 0, /* tp_setattr */
2988 0, /* tp_reserved */
2989 (reprfunc)date_repr, /* tp_repr */
2990 &date_as_number, /* tp_as_number */
2991 0, /* tp_as_sequence */
2992 0, /* tp_as_mapping */
2993 (hashfunc)date_hash, /* tp_hash */
2994 0, /* tp_call */
2995 (reprfunc)date_str, /* tp_str */
2996 PyObject_GenericGetAttr, /* tp_getattro */
2997 0, /* tp_setattro */
2998 0, /* tp_as_buffer */
2999 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3000 date_doc, /* tp_doc */
3001 0, /* tp_traverse */
3002 0, /* tp_clear */
3003 date_richcompare, /* tp_richcompare */
3004 0, /* tp_weaklistoffset */
3005 0, /* tp_iter */
3006 0, /* tp_iternext */
3007 date_methods, /* tp_methods */
3008 0, /* tp_members */
3009 date_getset, /* tp_getset */
3010 0, /* tp_base */
3011 0, /* tp_dict */
3012 0, /* tp_descr_get */
3013 0, /* tp_descr_set */
3014 0, /* tp_dictoffset */
3015 0, /* tp_init */
3016 0, /* tp_alloc */
3017 date_new, /* tp_new */
3018 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003019};
3020
3021/*
Tim Peters2a799bf2002-12-16 20:18:38 +00003022 * PyDateTime_TZInfo implementation.
3023 */
3024
3025/* This is a pure abstract base class, so doesn't do anything beyond
3026 * raising NotImplemented exceptions. Real tzinfo classes need
3027 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00003028 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00003029 * be subclasses of this tzinfo class, which is easy and quick to check).
3030 *
3031 * Note: For reasons having to do with pickling of subclasses, we have
3032 * to allow tzinfo objects to be instantiated. This wasn't an issue
3033 * in the Python implementation (__init__() could raise NotImplementedError
3034 * there without ill effect), but doing so in the C implementation hit a
3035 * brick wall.
3036 */
3037
3038static PyObject *
3039tzinfo_nogo(const char* methodname)
3040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 PyErr_Format(PyExc_NotImplementedError,
3042 "a tzinfo subclass must implement %s()",
3043 methodname);
3044 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003045}
3046
3047/* Methods. A subclass must implement these. */
3048
Tim Peters52dcce22003-01-23 16:36:11 +00003049static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003050tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00003053}
3054
Tim Peters52dcce22003-01-23 16:36:11 +00003055static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003056tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00003059}
3060
Tim Peters52dcce22003-01-23 16:36:11 +00003061static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003062tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003065}
3066
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003067
3068static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
3069 PyDateTime_Delta *delta,
3070 int factor);
3071static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
3072static PyObject *datetime_dst(PyObject *self, PyObject *);
3073
Tim Peters52dcce22003-01-23 16:36:11 +00003074static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003075tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003076{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003077 PyObject *result = NULL;
3078 PyObject *off = NULL, *dst = NULL;
3079 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003080
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003081 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 PyErr_SetString(PyExc_TypeError,
3083 "fromutc: argument must be a datetime");
3084 return NULL;
3085 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003086 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3088 "is not self");
3089 return NULL;
3090 }
Tim Peters52dcce22003-01-23 16:36:11 +00003091
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003092 off = datetime_utcoffset(dt, NULL);
3093 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003095 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3097 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003098 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 }
Tim Peters52dcce22003-01-23 16:36:11 +00003100
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003101 dst = datetime_dst(dt, NULL);
3102 if (dst == NULL)
3103 goto Fail;
3104 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3106 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003107 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 }
Tim Peters52dcce22003-01-23 16:36:11 +00003109
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003110 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3111 if (delta == NULL)
3112 goto Fail;
3113 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003116
3117 Py_DECREF(dst);
3118 dst = call_dst(GET_DT_TZINFO(dt), result);
3119 if (dst == NULL)
3120 goto Fail;
3121 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 goto Inconsistent;
Alexander Belopolskyc79447b2015-09-27 21:41:55 -04003123 if (delta_bool((PyDateTime_Delta *)dst) != 0) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03003124 Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
Serhiy Storchaka576f1322016-01-05 21:27:54 +02003125 (PyDateTime_Delta *)dst, 1));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003126 if (result == NULL)
3127 goto Fail;
3128 }
3129 Py_DECREF(delta);
3130 Py_DECREF(dst);
3131 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003133
3134Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3136 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003139Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003140 Py_XDECREF(off);
3141 Py_XDECREF(dst);
3142 Py_XDECREF(delta);
3143 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003145}
3146
Tim Peters2a799bf2002-12-16 20:18:38 +00003147/*
3148 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003149 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003150 */
3151
Guido van Rossum177e41a2003-01-30 22:06:23 +00003152static PyObject *
3153tzinfo_reduce(PyObject *self)
3154{
Victor Stinnerd1584d32016-08-23 00:11:04 +02003155 PyObject *args, *state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003157 _Py_IDENTIFIER(__getinitargs__);
3158 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003159
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003160 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 if (getinitargs != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003162 args = _PyObject_CallNoArg(getinitargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 Py_DECREF(getinitargs);
3164 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 return NULL;
3166 }
3167 }
3168 else {
3169 PyErr_Clear();
Victor Stinnerd1584d32016-08-23 00:11:04 +02003170
3171 args = PyTuple_New(0);
3172 if (args == NULL) {
3173 return NULL;
3174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003176
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003177 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 if (getstate != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003179 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 Py_DECREF(getstate);
3181 if (state == NULL) {
3182 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 return NULL;
3184 }
3185 }
3186 else {
3187 PyObject **dictptr;
3188 PyErr_Clear();
3189 state = Py_None;
3190 dictptr = _PyObject_GetDictPtr(self);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02003191 if (dictptr && *dictptr && PyDict_GET_SIZE(*dictptr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 state = *dictptr;
Victor Stinnerd1584d32016-08-23 00:11:04 +02003193 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 Py_INCREF(state);
3195 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 if (state == Py_None) {
3198 Py_DECREF(state);
3199 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3200 }
3201 else
3202 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003203}
Tim Peters2a799bf2002-12-16 20:18:38 +00003204
3205static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3208 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003211 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3212 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3215 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003218 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3221 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003224};
3225
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003226static const char tzinfo_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00003227PyDoc_STR("Abstract base class for time zone info objects.");
3228
Neal Norwitz227b5332006-03-22 09:28:35 +00003229static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 PyVarObject_HEAD_INIT(NULL, 0)
3231 "datetime.tzinfo", /* tp_name */
3232 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3233 0, /* tp_itemsize */
3234 0, /* tp_dealloc */
3235 0, /* tp_print */
3236 0, /* tp_getattr */
3237 0, /* tp_setattr */
3238 0, /* tp_reserved */
3239 0, /* tp_repr */
3240 0, /* tp_as_number */
3241 0, /* tp_as_sequence */
3242 0, /* tp_as_mapping */
3243 0, /* tp_hash */
3244 0, /* tp_call */
3245 0, /* tp_str */
3246 PyObject_GenericGetAttr, /* tp_getattro */
3247 0, /* tp_setattro */
3248 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003249 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 tzinfo_doc, /* tp_doc */
3251 0, /* tp_traverse */
3252 0, /* tp_clear */
3253 0, /* tp_richcompare */
3254 0, /* tp_weaklistoffset */
3255 0, /* tp_iter */
3256 0, /* tp_iternext */
3257 tzinfo_methods, /* tp_methods */
3258 0, /* tp_members */
3259 0, /* tp_getset */
3260 0, /* tp_base */
3261 0, /* tp_dict */
3262 0, /* tp_descr_get */
3263 0, /* tp_descr_set */
3264 0, /* tp_dictoffset */
3265 0, /* tp_init */
3266 0, /* tp_alloc */
3267 PyType_GenericNew, /* tp_new */
3268 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003269};
3270
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003271static char *timezone_kws[] = {"offset", "name", NULL};
3272
3273static PyObject *
3274timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3275{
3276 PyObject *offset;
3277 PyObject *name = NULL;
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03003278 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|U:timezone", timezone_kws,
3279 &PyDateTime_DeltaType, &offset, &name))
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003280 return new_timezone(offset, name);
3281
3282 return NULL;
3283}
3284
3285static void
3286timezone_dealloc(PyDateTime_TimeZone *self)
3287{
3288 Py_CLEAR(self->offset);
3289 Py_CLEAR(self->name);
3290 Py_TYPE(self)->tp_free((PyObject *)self);
3291}
3292
3293static PyObject *
3294timezone_richcompare(PyDateTime_TimeZone *self,
3295 PyDateTime_TimeZone *other, int op)
3296{
Brian Curtindfc80e32011-08-10 20:28:54 -05003297 if (op != Py_EQ && op != Py_NE)
3298 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003299 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003300 if (op == Py_EQ)
3301 Py_RETURN_FALSE;
3302 else
3303 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003304 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003305 return delta_richcompare(self->offset, other->offset, op);
3306}
3307
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003308static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003309timezone_hash(PyDateTime_TimeZone *self)
3310{
3311 return delta_hash((PyDateTime_Delta *)self->offset);
3312}
3313
3314/* Check argument type passed to tzname, utcoffset, or dst methods.
3315 Returns 0 for good argument. Returns -1 and sets exception info
3316 otherwise.
3317 */
3318static int
3319_timezone_check_argument(PyObject *dt, const char *meth)
3320{
3321 if (dt == Py_None || PyDateTime_Check(dt))
3322 return 0;
3323 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3324 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3325 return -1;
3326}
3327
3328static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003329timezone_repr(PyDateTime_TimeZone *self)
3330{
3331 /* Note that although timezone is not subclassable, it is convenient
3332 to use Py_TYPE(self)->tp_name here. */
3333 const char *type_name = Py_TYPE(self)->tp_name;
3334
3335 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3336 return PyUnicode_FromFormat("%s.utc", type_name);
3337
3338 if (self->name == NULL)
3339 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3340
3341 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3342 self->name);
3343}
3344
3345
3346static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003347timezone_str(PyDateTime_TimeZone *self)
3348{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003349 int hours, minutes, seconds;
3350 PyObject *offset;
3351 char sign;
3352
3353 if (self->name != NULL) {
3354 Py_INCREF(self->name);
3355 return self->name;
3356 }
Victor Stinner90fd8952015-09-08 00:12:49 +02003357 if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04003358 (GET_TD_DAYS(self->offset) == 0 &&
3359 GET_TD_SECONDS(self->offset) == 0 &&
3360 GET_TD_MICROSECONDS(self->offset) == 0))
3361 return PyUnicode_FromString("UTC");
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003362 /* Offset is normalized, so it is negative if days < 0 */
3363 if (GET_TD_DAYS(self->offset) < 0) {
3364 sign = '-';
3365 offset = delta_negative((PyDateTime_Delta *)self->offset);
3366 if (offset == NULL)
3367 return NULL;
3368 }
3369 else {
3370 sign = '+';
3371 offset = self->offset;
3372 Py_INCREF(offset);
3373 }
3374 /* Offset is not negative here. */
3375 seconds = GET_TD_SECONDS(offset);
3376 Py_DECREF(offset);
3377 minutes = divmod(seconds, 60, &seconds);
3378 hours = divmod(minutes, 60, &minutes);
Martin Pantere26da7c2016-06-02 10:07:09 +00003379 /* XXX ignore sub-minute data, currently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003380 assert(seconds == 0);
3381 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003382}
3383
3384static PyObject *
3385timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3386{
3387 if (_timezone_check_argument(dt, "tzname") == -1)
3388 return NULL;
3389
3390 return timezone_str(self);
3391}
3392
3393static PyObject *
3394timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3395{
3396 if (_timezone_check_argument(dt, "utcoffset") == -1)
3397 return NULL;
3398
3399 Py_INCREF(self->offset);
3400 return self->offset;
3401}
3402
3403static PyObject *
3404timezone_dst(PyObject *self, PyObject *dt)
3405{
3406 if (_timezone_check_argument(dt, "dst") == -1)
3407 return NULL;
3408
3409 Py_RETURN_NONE;
3410}
3411
3412static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003413timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3414{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003415 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003416 PyErr_SetString(PyExc_TypeError,
3417 "fromutc: argument must be a datetime");
3418 return NULL;
3419 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003420 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003421 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3422 "is not self");
3423 return NULL;
3424 }
3425
3426 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3427}
3428
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003429static PyObject *
3430timezone_getinitargs(PyDateTime_TimeZone *self)
3431{
3432 if (self->name == NULL)
3433 return Py_BuildValue("(O)", self->offset);
3434 return Py_BuildValue("(OO)", self->offset, self->name);
3435}
3436
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003437static PyMethodDef timezone_methods[] = {
3438 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3439 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003440 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003441
3442 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003443 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003444
3445 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003446 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003447
3448 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3449 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3450
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003451 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3452 PyDoc_STR("pickle support")},
3453
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003454 {NULL, NULL}
3455};
3456
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003457static const char timezone_doc[] =
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003458PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3459
3460static PyTypeObject PyDateTime_TimeZoneType = {
3461 PyVarObject_HEAD_INIT(NULL, 0)
3462 "datetime.timezone", /* tp_name */
3463 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3464 0, /* tp_itemsize */
3465 (destructor)timezone_dealloc, /* tp_dealloc */
3466 0, /* tp_print */
3467 0, /* tp_getattr */
3468 0, /* tp_setattr */
3469 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003470 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003471 0, /* tp_as_number */
3472 0, /* tp_as_sequence */
3473 0, /* tp_as_mapping */
3474 (hashfunc)timezone_hash, /* tp_hash */
3475 0, /* tp_call */
3476 (reprfunc)timezone_str, /* tp_str */
3477 0, /* tp_getattro */
3478 0, /* tp_setattro */
3479 0, /* tp_as_buffer */
3480 Py_TPFLAGS_DEFAULT, /* tp_flags */
3481 timezone_doc, /* tp_doc */
3482 0, /* tp_traverse */
3483 0, /* tp_clear */
3484 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3485 0, /* tp_weaklistoffset */
3486 0, /* tp_iter */
3487 0, /* tp_iternext */
3488 timezone_methods, /* tp_methods */
3489 0, /* tp_members */
3490 0, /* tp_getset */
3491 &PyDateTime_TZInfoType, /* tp_base */
3492 0, /* tp_dict */
3493 0, /* tp_descr_get */
3494 0, /* tp_descr_set */
3495 0, /* tp_dictoffset */
3496 0, /* tp_init */
3497 0, /* tp_alloc */
3498 timezone_new, /* tp_new */
3499};
3500
Tim Peters2a799bf2002-12-16 20:18:38 +00003501/*
Tim Peters37f39822003-01-10 03:49:02 +00003502 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003503 */
3504
Tim Peters37f39822003-01-10 03:49:02 +00003505/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003506 */
3507
3508static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003509time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003512}
3513
Tim Peters37f39822003-01-10 03:49:02 +00003514static PyObject *
3515time_minute(PyDateTime_Time *self, void *unused)
3516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003518}
3519
3520/* The name time_second conflicted with some platform header file. */
3521static PyObject *
3522py_time_second(PyDateTime_Time *self, void *unused)
3523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003525}
3526
3527static PyObject *
3528time_microsecond(PyDateTime_Time *self, void *unused)
3529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003531}
3532
3533static PyObject *
3534time_tzinfo(PyDateTime_Time *self, void *unused)
3535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3537 Py_INCREF(result);
3538 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003539}
3540
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003541static PyObject *
3542time_fold(PyDateTime_Time *self, void *unused)
3543{
3544 return PyLong_FromLong(TIME_GET_FOLD(self));
3545}
3546
Tim Peters37f39822003-01-10 03:49:02 +00003547static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 {"hour", (getter)time_hour},
3549 {"minute", (getter)time_minute},
3550 {"second", (getter)py_time_second},
3551 {"microsecond", (getter)time_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003552 {"tzinfo", (getter)time_tzinfo},
3553 {"fold", (getter)time_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003555};
3556
3557/*
3558 * Constructors.
3559 */
3560
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003561static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003562 "tzinfo", "fold", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003563
Tim Peters2a799bf2002-12-16 20:18:38 +00003564static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003565time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 PyObject *self = NULL;
3568 PyObject *state;
3569 int hour = 0;
3570 int minute = 0;
3571 int second = 0;
3572 int usecond = 0;
3573 PyObject *tzinfo = Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003574 int fold = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 /* Check for invocation from pickle with __getstate__ state */
3577 if (PyTuple_GET_SIZE(args) >= 1 &&
3578 PyTuple_GET_SIZE(args) <= 2 &&
3579 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3580 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003581 (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 {
3583 PyDateTime_Time *me;
3584 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 if (PyTuple_GET_SIZE(args) == 2) {
3587 tzinfo = PyTuple_GET_ITEM(args, 1);
3588 if (check_tzinfo_subclass(tzinfo) < 0) {
3589 PyErr_SetString(PyExc_TypeError, "bad "
3590 "tzinfo state arg");
3591 return NULL;
3592 }
3593 }
3594 aware = (char)(tzinfo != Py_None);
3595 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3596 if (me != NULL) {
3597 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3600 me->hashcode = -1;
3601 me->hastzinfo = aware;
3602 if (aware) {
3603 Py_INCREF(tzinfo);
3604 me->tzinfo = tzinfo;
3605 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003606 if (pdata[0] & (1 << 7)) {
3607 me->data[0] -= 128;
3608 me->fold = 1;
3609 }
3610 else {
3611 me->fold = 0;
3612 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 }
3614 return (PyObject *)me;
3615 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003616
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003617 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 &hour, &minute, &second, &usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003619 &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003620 self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
3621 type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 }
3623 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003624}
3625
3626/*
3627 * Destructor.
3628 */
3629
3630static void
Tim Peters37f39822003-01-10 03:49:02 +00003631time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 if (HASTZINFO(self)) {
3634 Py_XDECREF(self->tzinfo);
3635 }
3636 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003637}
3638
3639/*
Tim Peters855fe882002-12-22 03:43:39 +00003640 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003641 */
3642
Tim Peters2a799bf2002-12-16 20:18:38 +00003643/* These are all METH_NOARGS, so don't need to check the arglist. */
3644static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003645time_utcoffset(PyObject *self, PyObject *unused) {
3646 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003647}
3648
3649static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003650time_dst(PyObject *self, PyObject *unused) {
3651 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003652}
3653
3654static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003655time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003656 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003657}
3658
3659/*
Tim Peters37f39822003-01-10 03:49:02 +00003660 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003661 */
3662
3663static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003664time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 const char *type_name = Py_TYPE(self)->tp_name;
3667 int h = TIME_GET_HOUR(self);
3668 int m = TIME_GET_MINUTE(self);
3669 int s = TIME_GET_SECOND(self);
3670 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003671 int fold = TIME_GET_FOLD(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 if (us)
3675 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3676 type_name, h, m, s, us);
3677 else if (s)
3678 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3679 type_name, h, m, s);
3680 else
3681 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3682 if (result != NULL && HASTZINFO(self))
3683 result = append_keyword_tzinfo(result, self->tzinfo);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003684 if (result != NULL && fold)
3685 result = append_keyword_fold(result, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003687}
3688
Tim Peters37f39822003-01-10 03:49:02 +00003689static PyObject *
3690time_str(PyDateTime_Time *self)
3691{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003692 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters37f39822003-01-10 03:49:02 +00003693}
Tim Peters2a799bf2002-12-16 20:18:38 +00003694
3695static PyObject *
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003696time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 char buf[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003699 char *timespec = NULL;
3700 static char *keywords[] = {"timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02003702 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003703 static char *specs[][2] = {
3704 {"hours", "%02d"},
3705 {"minutes", "%02d:%02d"},
3706 {"seconds", "%02d:%02d:%02d"},
3707 {"milliseconds", "%02d:%02d:%02d.%03d"},
3708 {"microseconds", "%02d:%02d:%02d.%06d"},
3709 };
3710 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00003711
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003712 if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
3713 return NULL;
3714
3715 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
3716 if (us == 0) {
3717 /* seconds */
3718 given_spec = 2;
3719 }
3720 else {
3721 /* microseconds */
3722 given_spec = 4;
3723 }
3724 }
3725 else {
3726 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
3727 if (strcmp(timespec, specs[given_spec][0]) == 0) {
3728 if (given_spec == 3) {
3729 /* milliseconds */
3730 us = us / 1000;
3731 }
3732 break;
3733 }
3734 }
3735 }
3736
3737 if (given_spec == Py_ARRAY_LENGTH(specs)) {
3738 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
3739 return NULL;
3740 }
3741 else {
3742 result = PyUnicode_FromFormat(specs[given_spec][1],
3743 TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
3744 TIME_GET_SECOND(self), us);
3745 }
Tim Peters37f39822003-01-10 03:49:02 +00003746
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003747 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 /* We need to append the UTC offset. */
3751 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3752 Py_None) < 0) {
3753 Py_DECREF(result);
3754 return NULL;
3755 }
3756 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3757 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003758}
3759
Tim Peters37f39822003-01-10 03:49:02 +00003760static PyObject *
3761time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 PyObject *result;
3764 PyObject *tuple;
3765 PyObject *format;
3766 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3769 &format))
3770 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 /* Python's strftime does insane things with the year part of the
3773 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003774 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 */
3776 tuple = Py_BuildValue("iiiiiiiii",
3777 1900, 1, 1, /* year, month, day */
3778 TIME_GET_HOUR(self),
3779 TIME_GET_MINUTE(self),
3780 TIME_GET_SECOND(self),
3781 0, 1, -1); /* weekday, daynum, dst */
3782 if (tuple == NULL)
3783 return NULL;
3784 assert(PyTuple_Size(tuple) == 9);
3785 result = wrap_strftime((PyObject *)self, format, tuple,
3786 Py_None);
3787 Py_DECREF(tuple);
3788 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003789}
Tim Peters2a799bf2002-12-16 20:18:38 +00003790
3791/*
3792 * Miscellaneous methods.
3793 */
3794
Tim Peters37f39822003-01-10 03:49:02 +00003795static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003796time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003797{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003798 PyObject *result = NULL;
3799 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003801
Brian Curtindfc80e32011-08-10 20:28:54 -05003802 if (! PyTime_Check(other))
3803 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003804
3805 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 diff = memcmp(((PyDateTime_Time *)self)->data,
3807 ((PyDateTime_Time *)other)->data,
3808 _PyDateTime_TIME_DATASIZE);
3809 return diff_to_bool(diff, op);
3810 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003811 offset1 = time_utcoffset(self, NULL);
3812 if (offset1 == NULL)
3813 return NULL;
3814 offset2 = time_utcoffset(other, NULL);
3815 if (offset2 == NULL)
3816 goto done;
3817 /* If they're both naive, or both aware and have the same offsets,
3818 * we get off cheap. Note that if they're both naive, offset1 ==
3819 * offset2 == Py_None at this point.
3820 */
3821 if ((offset1 == offset2) ||
3822 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3823 delta_cmp(offset1, offset2) == 0)) {
3824 diff = memcmp(((PyDateTime_Time *)self)->data,
3825 ((PyDateTime_Time *)other)->data,
3826 _PyDateTime_TIME_DATASIZE);
3827 result = diff_to_bool(diff, op);
3828 }
3829 /* The hard case: both aware with different UTC offsets */
3830 else if (offset1 != Py_None && offset2 != Py_None) {
3831 int offsecs1, offsecs2;
3832 assert(offset1 != offset2); /* else last "if" handled it */
3833 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3834 TIME_GET_MINUTE(self) * 60 +
3835 TIME_GET_SECOND(self) -
3836 GET_TD_DAYS(offset1) * 86400 -
3837 GET_TD_SECONDS(offset1);
3838 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3839 TIME_GET_MINUTE(other) * 60 +
3840 TIME_GET_SECOND(other) -
3841 GET_TD_DAYS(offset2) * 86400 -
3842 GET_TD_SECONDS(offset2);
3843 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 if (diff == 0)
3845 diff = TIME_GET_MICROSECOND(self) -
3846 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003847 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003849 else if (op == Py_EQ) {
3850 result = Py_False;
3851 Py_INCREF(result);
3852 }
3853 else if (op == Py_NE) {
3854 result = Py_True;
3855 Py_INCREF(result);
3856 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003857 else {
3858 PyErr_SetString(PyExc_TypeError,
3859 "can't compare offset-naive and "
3860 "offset-aware times");
3861 }
3862 done:
3863 Py_DECREF(offset1);
3864 Py_XDECREF(offset2);
3865 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003866}
3867
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003868static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003869time_hash(PyDateTime_Time *self)
3870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003872 PyObject *offset, *self0;
Victor Stinner423c16b2017-01-03 23:47:12 +01003873 if (TIME_GET_FOLD(self)) {
3874 self0 = new_time_ex2(TIME_GET_HOUR(self),
3875 TIME_GET_MINUTE(self),
3876 TIME_GET_SECOND(self),
3877 TIME_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003878 HASTZINFO(self) ? self->tzinfo : Py_None,
3879 0, Py_TYPE(self));
3880 if (self0 == NULL)
3881 return -1;
3882 }
3883 else {
3884 self0 = (PyObject *)self;
3885 Py_INCREF(self0);
3886 }
3887 offset = time_utcoffset(self0, NULL);
3888 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003889
3890 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003894 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 self->hashcode = generic_hash(
3896 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003898 PyObject *temp1, *temp2;
3899 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003901 seconds = TIME_GET_HOUR(self) * 3600 +
3902 TIME_GET_MINUTE(self) * 60 +
3903 TIME_GET_SECOND(self);
3904 microseconds = TIME_GET_MICROSECOND(self);
3905 temp1 = new_delta(0, seconds, microseconds, 1);
3906 if (temp1 == NULL) {
3907 Py_DECREF(offset);
3908 return -1;
3909 }
3910 temp2 = delta_subtract(temp1, offset);
3911 Py_DECREF(temp1);
3912 if (temp2 == NULL) {
3913 Py_DECREF(offset);
3914 return -1;
3915 }
3916 self->hashcode = PyObject_Hash(temp2);
3917 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003919 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 }
3921 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003922}
Tim Peters2a799bf2002-12-16 20:18:38 +00003923
Tim Peters12bf3392002-12-24 05:41:27 +00003924static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003925time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 PyObject *clone;
3928 PyObject *tuple;
3929 int hh = TIME_GET_HOUR(self);
3930 int mm = TIME_GET_MINUTE(self);
3931 int ss = TIME_GET_SECOND(self);
3932 int us = TIME_GET_MICROSECOND(self);
3933 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003934 int fold = TIME_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00003935
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003936 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 time_kws,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003938 &hh, &mm, &ss, &us, &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03003940 if (fold != 0 && fold != 1) {
3941 PyErr_SetString(PyExc_ValueError,
3942 "fold must be either 0 or 1");
3943 return NULL;
3944 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003945 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3946 if (tuple == NULL)
3947 return NULL;
3948 clone = time_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003949 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003950 TIME_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003951 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 Py_DECREF(tuple);
3953 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003954}
3955
Tim Peters371935f2003-02-01 01:52:50 +00003956/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003957
Tim Peters33e0f382003-01-10 02:05:14 +00003958/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003959 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3960 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003961 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003962 */
3963static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003964time_getstate(PyDateTime_Time *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00003965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 PyObject *basestate;
3967 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 basestate = PyBytes_FromStringAndSize((char *)self->data,
3970 _PyDateTime_TIME_DATASIZE);
3971 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003972 if (proto > 3 && TIME_GET_FOLD(self))
3973 /* Set the first bit of the first byte */
3974 PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3976 result = PyTuple_Pack(1, basestate);
3977 else
3978 result = PyTuple_Pack(2, basestate, self->tzinfo);
3979 Py_DECREF(basestate);
3980 }
3981 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003982}
3983
3984static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02003985time_reduce_ex(PyDateTime_Time *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00003986{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02003987 int proto;
3988 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003989 return NULL;
3990
3991 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00003992}
3993
Serhiy Storchaka546ce652016-11-22 00:29:42 +02003994static PyObject *
3995time_reduce(PyDateTime_Time *self, PyObject *arg)
3996{
3997 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, 2));
3998}
3999
Tim Peters37f39822003-01-10 03:49:02 +00004000static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004001
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004002 {"isoformat", (PyCFunction)time_isoformat, METH_VARARGS | METH_KEYWORDS,
4003 PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
4004 "[+HH:MM].\n\n"
4005 "timespec specifies what components of the time to include.\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004007 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
4008 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00004009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004010 {"__format__", (PyCFunction)date_format, METH_VARARGS,
4011 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00004012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
4014 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
4017 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 {"dst", (PyCFunction)time_dst, METH_NOARGS,
4020 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
4023 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004024
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004025 {"__reduce_ex__", (PyCFunction)time_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004026 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004027
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004028 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
4029 PyDoc_STR("__reduce__() -> (cls, state)")},
4030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004032};
4033
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004034static const char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004035PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
4036\n\
4037All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03004038a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004039
Neal Norwitz227b5332006-03-22 09:28:35 +00004040static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 PyVarObject_HEAD_INIT(NULL, 0)
4042 "datetime.time", /* tp_name */
4043 sizeof(PyDateTime_Time), /* tp_basicsize */
4044 0, /* tp_itemsize */
4045 (destructor)time_dealloc, /* tp_dealloc */
4046 0, /* tp_print */
4047 0, /* tp_getattr */
4048 0, /* tp_setattr */
4049 0, /* tp_reserved */
4050 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05004051 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 0, /* tp_as_sequence */
4053 0, /* tp_as_mapping */
4054 (hashfunc)time_hash, /* tp_hash */
4055 0, /* tp_call */
4056 (reprfunc)time_str, /* tp_str */
4057 PyObject_GenericGetAttr, /* tp_getattro */
4058 0, /* tp_setattro */
4059 0, /* tp_as_buffer */
4060 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4061 time_doc, /* tp_doc */
4062 0, /* tp_traverse */
4063 0, /* tp_clear */
4064 time_richcompare, /* tp_richcompare */
4065 0, /* tp_weaklistoffset */
4066 0, /* tp_iter */
4067 0, /* tp_iternext */
4068 time_methods, /* tp_methods */
4069 0, /* tp_members */
4070 time_getset, /* tp_getset */
4071 0, /* tp_base */
4072 0, /* tp_dict */
4073 0, /* tp_descr_get */
4074 0, /* tp_descr_set */
4075 0, /* tp_dictoffset */
4076 0, /* tp_init */
4077 time_alloc, /* tp_alloc */
4078 time_new, /* tp_new */
4079 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004080};
4081
4082/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004083 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00004084 */
4085
Tim Petersa9bc1682003-01-11 03:39:11 +00004086/* Accessor properties. Properties for day, month, and year are inherited
4087 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004088 */
4089
4090static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004091datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00004092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004094}
4095
Tim Petersa9bc1682003-01-11 03:39:11 +00004096static PyObject *
4097datetime_minute(PyDateTime_DateTime *self, void *unused)
4098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004100}
4101
4102static PyObject *
4103datetime_second(PyDateTime_DateTime *self, void *unused)
4104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004106}
4107
4108static PyObject *
4109datetime_microsecond(PyDateTime_DateTime *self, void *unused)
4110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004112}
4113
4114static PyObject *
4115datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
4116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4118 Py_INCREF(result);
4119 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004120}
4121
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004122static PyObject *
4123datetime_fold(PyDateTime_DateTime *self, void *unused)
4124{
4125 return PyLong_FromLong(DATE_GET_FOLD(self));
4126}
4127
Tim Petersa9bc1682003-01-11 03:39:11 +00004128static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 {"hour", (getter)datetime_hour},
4130 {"minute", (getter)datetime_minute},
4131 {"second", (getter)datetime_second},
4132 {"microsecond", (getter)datetime_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004133 {"tzinfo", (getter)datetime_tzinfo},
4134 {"fold", (getter)datetime_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004136};
4137
4138/*
4139 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004140 */
4141
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004142static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 "year", "month", "day", "hour", "minute", "second",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004144 "microsecond", "tzinfo", "fold", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004145};
4146
Tim Peters2a799bf2002-12-16 20:18:38 +00004147static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004148datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 PyObject *self = NULL;
4151 PyObject *state;
4152 int year;
4153 int month;
4154 int day;
4155 int hour = 0;
4156 int minute = 0;
4157 int second = 0;
4158 int usecond = 0;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004159 int fold = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 /* Check for invocation from pickle with __getstate__ state */
4163 if (PyTuple_GET_SIZE(args) >= 1 &&
4164 PyTuple_GET_SIZE(args) <= 2 &&
4165 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4166 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004167 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 {
4169 PyDateTime_DateTime *me;
4170 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 if (PyTuple_GET_SIZE(args) == 2) {
4173 tzinfo = PyTuple_GET_ITEM(args, 1);
4174 if (check_tzinfo_subclass(tzinfo) < 0) {
4175 PyErr_SetString(PyExc_TypeError, "bad "
4176 "tzinfo state arg");
4177 return NULL;
4178 }
4179 }
4180 aware = (char)(tzinfo != Py_None);
4181 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4182 if (me != NULL) {
4183 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4186 me->hashcode = -1;
4187 me->hastzinfo = aware;
4188 if (aware) {
4189 Py_INCREF(tzinfo);
4190 me->tzinfo = tzinfo;
4191 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004192 if (pdata[2] & (1 << 7)) {
4193 me->data[2] -= 128;
4194 me->fold = 1;
4195 }
4196 else {
4197 me->fold = 0;
4198 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 }
4200 return (PyObject *)me;
4201 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004202
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004203 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 &year, &month, &day, &hour, &minute,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004205 &second, &usecond, &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004206 self = new_datetime_ex2(year, month, day,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 hour, minute, second, usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004208 tzinfo, fold, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 }
4210 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004211}
4212
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004213/* TM_FUNC is the shared type of _PyTime_localtime() and
4214 * _PyTime_gmtime(). */
4215typedef int (*TM_FUNC)(time_t timer, struct tm*);
Tim Petersa9bc1682003-01-11 03:39:11 +00004216
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004217/* As of version 2015f max fold in IANA database is
4218 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004219static long long max_fold_seconds = 24 * 3600;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004220/* NB: date(1970,1,1).toordinal() == 719163 */
Benjamin Petersonac965ca2016-09-18 18:12:21 -07004221static long long epoch = 719163LL * 24 * 60 * 60;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004222
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004223static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004224utc_to_seconds(int year, int month, int day,
4225 int hour, int minute, int second)
4226{
Victor Stinnerb67f0962017-02-10 10:34:02 +01004227 long long ordinal;
4228
4229 /* ymd_to_ord() doesn't support year <= 0 */
4230 if (year < MINYEAR || year > MAXYEAR) {
4231 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
4232 return -1;
4233 }
4234
4235 ordinal = ymd_to_ord(year, month, day);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004236 return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
4237}
4238
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004239static long long
4240local(long long u)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004241{
4242 struct tm local_time;
Alexander Belopolsky8e1d3a22016-07-25 13:54:51 -04004243 time_t t;
4244 u -= epoch;
4245 t = u;
4246 if (t != u) {
4247 PyErr_SetString(PyExc_OverflowError,
4248 "timestamp out of range for platform time_t");
4249 return -1;
4250 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004251 if (_PyTime_localtime(t, &local_time) != 0)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004252 return -1;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004253 return utc_to_seconds(local_time.tm_year + 1900,
4254 local_time.tm_mon + 1,
4255 local_time.tm_mday,
4256 local_time.tm_hour,
4257 local_time.tm_min,
4258 local_time.tm_sec);
4259}
4260
Tim Petersa9bc1682003-01-11 03:39:11 +00004261/* Internal helper.
4262 * Build datetime from a time_t and a distinct count of microseconds.
4263 * Pass localtime or gmtime for f, to control the interpretation of timet.
4264 */
4265static PyObject *
4266datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004268{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004269 struct tm tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004270 int year, month, day, hour, minute, second, fold = 0;
Tim Petersa9bc1682003-01-11 03:39:11 +00004271
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004272 if (f(timet, &tm) != 0)
4273 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01004274
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004275 year = tm.tm_year + 1900;
4276 month = tm.tm_mon + 1;
4277 day = tm.tm_mday;
4278 hour = tm.tm_hour;
4279 minute = tm.tm_min;
Victor Stinner21f58932012-03-14 00:15:40 +01004280 /* The platform localtime/gmtime may insert leap seconds,
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004281 * indicated by tm.tm_sec > 59. We don't care about them,
Victor Stinner21f58932012-03-14 00:15:40 +01004282 * except to the extent that passing them on to the datetime
4283 * constructor would raise ValueError for a reason that
4284 * made no sense to the user.
4285 */
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004286 second = Py_MIN(59, tm.tm_sec);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004287
Victor Stinnerb67f0962017-02-10 10:34:02 +01004288 /* local timezone requires to compute fold */
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004289 if (tzinfo == Py_None && f == _PyTime_localtime) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004290 long long probe_seconds, result_seconds, transition;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004291
4292 result_seconds = utc_to_seconds(year, month, day,
4293 hour, minute, second);
4294 /* Probe max_fold_seconds to detect a fold. */
4295 probe_seconds = local(epoch + timet - max_fold_seconds);
4296 if (probe_seconds == -1)
4297 return NULL;
4298 transition = result_seconds - probe_seconds - max_fold_seconds;
4299 if (transition < 0) {
4300 probe_seconds = local(epoch + timet + transition);
4301 if (probe_seconds == -1)
4302 return NULL;
4303 if (probe_seconds == result_seconds)
4304 fold = 1;
4305 }
4306 }
4307 return new_datetime_ex2(year, month, day, hour,
4308 minute, second, us, tzinfo, fold,
4309 (PyTypeObject *)cls);
Tim Petersa9bc1682003-01-11 03:39:11 +00004310}
4311
4312/* Internal helper.
4313 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4314 * to control the interpretation of the timestamp. Since a double doesn't
4315 * have enough bits to cover a datetime's full range of precision, it's
4316 * better to call datetime_from_timet_and_us provided you have a way
4317 * to get that much precision (e.g., C time() isn't good enough).
4318 */
4319static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004320datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004324 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004325
Victor Stinnere4a994d2015-03-30 01:10:14 +02004326 if (_PyTime_ObjectToTimeval(timestamp,
Victor Stinner7667f582015-09-09 01:02:23 +02004327 &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004329
Victor Stinner21f58932012-03-14 00:15:40 +01004330 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004331}
4332
4333/* Internal helper.
4334 * Build most accurate possible datetime for current time. Pass localtime or
4335 * gmtime for f as appropriate.
4336 */
4337static PyObject *
4338datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4339{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004340 _PyTime_t ts = _PyTime_GetSystemClock();
Victor Stinner1e2b6882015-09-18 13:23:02 +02004341 time_t secs;
4342 int us;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004343
Victor Stinner1e2b6882015-09-18 13:23:02 +02004344 if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner09e5cf22015-03-30 00:09:18 +02004345 return NULL;
Victor Stinner1e2b6882015-09-18 13:23:02 +02004346 assert(0 <= us && us <= 999999);
Victor Stinner09e5cf22015-03-30 00:09:18 +02004347
Victor Stinner1e2b6882015-09-18 13:23:02 +02004348 return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004349}
4350
Larry Hastings61272b72014-01-07 12:41:53 -08004351/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004352
4353@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004354datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004355
4356 tz: object = None
4357 Timezone object.
4358
4359Returns new datetime object representing current time local to tz.
4360
4361If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004362[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004363
Larry Hastings31826802013-10-19 00:09:25 -07004364static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004365datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03004366/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004369
Larry Hastings31826802013-10-19 00:09:25 -07004370 /* Return best possible local time -- this isn't constrained by the
4371 * precision of a timestamp.
4372 */
4373 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004375
Larry Hastings5c661892014-01-24 06:17:25 -08004376 self = datetime_best_possible((PyObject *)type,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004377 tz == Py_None ? _PyTime_localtime :
4378 _PyTime_gmtime,
Larry Hastings31826802013-10-19 00:09:25 -07004379 tz);
4380 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004382 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 }
4384 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004385}
4386
Tim Petersa9bc1682003-01-11 03:39:11 +00004387/* Return best possible UTC time -- this isn't constrained by the
4388 * precision of a timestamp.
4389 */
4390static PyObject *
4391datetime_utcnow(PyObject *cls, PyObject *dummy)
4392{
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004393 return datetime_best_possible(cls, _PyTime_gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004394}
4395
Tim Peters2a799bf2002-12-16 20:18:38 +00004396/* Return new local datetime from timestamp (Python timestamp -- a double). */
4397static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004398datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004401 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 PyObject *tzinfo = Py_None;
4403 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004404
Victor Stinner5d272cc2012-03-13 13:35:55 +01004405 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 keywords, &timestamp, &tzinfo))
4407 return NULL;
4408 if (check_tzinfo_subclass(tzinfo) < 0)
4409 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 self = datetime_from_timestamp(cls,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004412 tzinfo == Py_None ? _PyTime_localtime :
4413 _PyTime_gmtime,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 timestamp,
4415 tzinfo);
4416 if (self != NULL && tzinfo != Py_None) {
4417 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004418 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 }
4420 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004421}
4422
Tim Petersa9bc1682003-01-11 03:39:11 +00004423/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4424static PyObject *
4425datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4426{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004427 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004429
Victor Stinner5d272cc2012-03-13 13:35:55 +01004430 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004431 result = datetime_from_timestamp(cls, _PyTime_gmtime, timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 Py_None);
4433 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004434}
4435
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004436/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004437static PyObject *
4438datetime_strptime(PyObject *cls, PyObject *args)
4439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004441 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004442 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004444 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004446
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004447 if (module == NULL) {
4448 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004449 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004450 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 }
Victor Stinner20401de2016-12-09 15:24:31 +01004452 return _PyObject_CallMethodIdObjArgs(module, &PyId__strptime_datetime,
4453 cls, string, format, NULL);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004454}
4455
Tim Petersa9bc1682003-01-11 03:39:11 +00004456/* Return new datetime from date/datetime and time arguments. */
4457static PyObject *
4458datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4459{
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004460 static char *keywords[] = {"date", "time", "tzinfo", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 PyObject *date;
4462 PyObject *time;
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004463 PyObject *tzinfo = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004465
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004466 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 &PyDateTime_DateType, &date,
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004468 &PyDateTime_TimeType, &time, &tzinfo)) {
4469 if (tzinfo == NULL) {
4470 if (HASTZINFO(time))
4471 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4472 else
4473 tzinfo = Py_None;
4474 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 result = PyObject_CallFunction(cls, "iiiiiiiO",
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004476 GET_YEAR(date),
4477 GET_MONTH(date),
4478 GET_DAY(date),
4479 TIME_GET_HOUR(time),
4480 TIME_GET_MINUTE(time),
4481 TIME_GET_SECOND(time),
4482 TIME_GET_MICROSECOND(time),
4483 tzinfo);
4484 if (result)
4485 DATE_SET_FOLD(result, TIME_GET_FOLD(time));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 }
4487 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004488}
Tim Peters2a799bf2002-12-16 20:18:38 +00004489
4490/*
4491 * Destructor.
4492 */
4493
4494static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004495datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 if (HASTZINFO(self)) {
4498 Py_XDECREF(self->tzinfo);
4499 }
4500 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004501}
4502
4503/*
4504 * Indirect access to tzinfo methods.
4505 */
4506
Tim Peters2a799bf2002-12-16 20:18:38 +00004507/* These are all METH_NOARGS, so don't need to check the arglist. */
4508static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004509datetime_utcoffset(PyObject *self, PyObject *unused) {
4510 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004511}
4512
4513static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004514datetime_dst(PyObject *self, PyObject *unused) {
4515 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004516}
4517
4518static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004519datetime_tzname(PyObject *self, PyObject *unused) {
4520 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004521}
4522
4523/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004524 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004525 */
4526
Tim Petersa9bc1682003-01-11 03:39:11 +00004527/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4528 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004529 */
4530static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004531add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 /* Note that the C-level additions can't overflow, because of
4535 * invariant bounds on the member values.
4536 */
4537 int year = GET_YEAR(date);
4538 int month = GET_MONTH(date);
4539 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4540 int hour = DATE_GET_HOUR(date);
4541 int minute = DATE_GET_MINUTE(date);
4542 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4543 int microsecond = DATE_GET_MICROSECOND(date) +
4544 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 assert(factor == 1 || factor == -1);
4547 if (normalize_datetime(&year, &month, &day,
Victor Stinnerb67f0962017-02-10 10:34:02 +01004548 &hour, &minute, &second, &microsecond) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 return NULL;
Victor Stinnerb67f0962017-02-10 10:34:02 +01004550 }
4551
4552 return new_datetime(year, month, day,
4553 hour, minute, second, microsecond,
4554 HASTZINFO(date) ? date->tzinfo : Py_None, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004555}
4556
4557static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004558datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 if (PyDateTime_Check(left)) {
4561 /* datetime + ??? */
4562 if (PyDelta_Check(right))
4563 /* datetime + delta */
4564 return add_datetime_timedelta(
4565 (PyDateTime_DateTime *)left,
4566 (PyDateTime_Delta *)right,
4567 1);
4568 }
4569 else if (PyDelta_Check(left)) {
4570 /* delta + datetime */
4571 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4572 (PyDateTime_Delta *) left,
4573 1);
4574 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004575 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004576}
4577
4578static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004579datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (PyDateTime_Check(left)) {
4584 /* datetime - ??? */
4585 if (PyDateTime_Check(right)) {
4586 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004587 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004589
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004590 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4591 offset2 = offset1 = Py_None;
4592 Py_INCREF(offset1);
4593 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004595 else {
4596 offset1 = datetime_utcoffset(left, NULL);
4597 if (offset1 == NULL)
4598 return NULL;
4599 offset2 = datetime_utcoffset(right, NULL);
4600 if (offset2 == NULL) {
4601 Py_DECREF(offset1);
4602 return NULL;
4603 }
4604 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4605 PyErr_SetString(PyExc_TypeError,
4606 "can't subtract offset-naive and "
4607 "offset-aware datetimes");
4608 Py_DECREF(offset1);
4609 Py_DECREF(offset2);
4610 return NULL;
4611 }
4612 }
4613 if ((offset1 != offset2) &&
4614 delta_cmp(offset1, offset2) != 0) {
4615 offdiff = delta_subtract(offset1, offset2);
4616 if (offdiff == NULL) {
4617 Py_DECREF(offset1);
4618 Py_DECREF(offset2);
4619 return NULL;
4620 }
4621 }
4622 Py_DECREF(offset1);
4623 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 delta_d = ymd_to_ord(GET_YEAR(left),
4625 GET_MONTH(left),
4626 GET_DAY(left)) -
4627 ymd_to_ord(GET_YEAR(right),
4628 GET_MONTH(right),
4629 GET_DAY(right));
4630 /* These can't overflow, since the values are
4631 * normalized. At most this gives the number of
4632 * seconds in one day.
4633 */
4634 delta_s = (DATE_GET_HOUR(left) -
4635 DATE_GET_HOUR(right)) * 3600 +
4636 (DATE_GET_MINUTE(left) -
4637 DATE_GET_MINUTE(right)) * 60 +
4638 (DATE_GET_SECOND(left) -
4639 DATE_GET_SECOND(right));
4640 delta_us = DATE_GET_MICROSECOND(left) -
4641 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004643 if (result == NULL)
4644 return NULL;
4645
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004646 if (offdiff != NULL) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03004647 Py_SETREF(result, delta_subtract(result, offdiff));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004648 Py_DECREF(offdiff);
4649 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 }
4651 else if (PyDelta_Check(right)) {
4652 /* datetime - delta */
4653 result = add_datetime_timedelta(
4654 (PyDateTime_DateTime *)left,
4655 (PyDateTime_Delta *)right,
4656 -1);
4657 }
4658 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 if (result == Py_NotImplemented)
4661 Py_INCREF(result);
4662 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004663}
4664
4665/* Various ways to turn a datetime into a string. */
4666
4667static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004668datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 const char *type_name = Py_TYPE(self)->tp_name;
4671 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 if (DATE_GET_MICROSECOND(self)) {
4674 baserepr = PyUnicode_FromFormat(
4675 "%s(%d, %d, %d, %d, %d, %d, %d)",
4676 type_name,
4677 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4678 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4679 DATE_GET_SECOND(self),
4680 DATE_GET_MICROSECOND(self));
4681 }
4682 else if (DATE_GET_SECOND(self)) {
4683 baserepr = PyUnicode_FromFormat(
4684 "%s(%d, %d, %d, %d, %d, %d)",
4685 type_name,
4686 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4687 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4688 DATE_GET_SECOND(self));
4689 }
4690 else {
4691 baserepr = PyUnicode_FromFormat(
4692 "%s(%d, %d, %d, %d, %d)",
4693 type_name,
4694 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4695 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4696 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004697 if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
4698 baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (baserepr == NULL || ! HASTZINFO(self))
4700 return baserepr;
4701 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004702}
4703
Tim Petersa9bc1682003-01-11 03:39:11 +00004704static PyObject *
4705datetime_str(PyDateTime_DateTime *self)
4706{
Victor Stinner4c381542016-12-09 00:33:39 +01004707 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "s", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004708}
Tim Peters2a799bf2002-12-16 20:18:38 +00004709
4710static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004711datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 int sep = 'T';
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004714 char *timespec = NULL;
4715 static char *keywords[] = {"sep", "timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 char buffer[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004717 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 int us = DATE_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004719 static char *specs[][2] = {
4720 {"hours", "%04d-%02d-%02d%c%02d"},
4721 {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
4722 {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
4723 {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
4724 {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
4725 };
4726 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00004727
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004728 if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004729 return NULL;
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004730
4731 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4732 if (us == 0) {
4733 /* seconds */
4734 given_spec = 2;
4735 }
4736 else {
4737 /* microseconds */
4738 given_spec = 4;
4739 }
4740 }
4741 else {
4742 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4743 if (strcmp(timespec, specs[given_spec][0]) == 0) {
4744 if (given_spec == 3) {
4745 us = us / 1000;
4746 }
4747 break;
4748 }
4749 }
4750 }
4751
4752 if (given_spec == Py_ARRAY_LENGTH(specs)) {
4753 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4754 return NULL;
4755 }
4756 else {
4757 result = PyUnicode_FromFormat(specs[given_spec][1],
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 GET_YEAR(self), GET_MONTH(self),
4759 GET_DAY(self), (int)sep,
4760 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4761 DATE_GET_SECOND(self), us);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004762 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 if (!result || !HASTZINFO(self))
4765 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 /* We need to append the UTC offset. */
4768 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4769 (PyObject *)self) < 0) {
4770 Py_DECREF(result);
4771 return NULL;
4772 }
4773 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4774 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004775}
4776
Tim Petersa9bc1682003-01-11 03:39:11 +00004777static PyObject *
4778datetime_ctime(PyDateTime_DateTime *self)
4779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 return format_ctime((PyDateTime_Date *)self,
4781 DATE_GET_HOUR(self),
4782 DATE_GET_MINUTE(self),
4783 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004784}
4785
Tim Peters2a799bf2002-12-16 20:18:38 +00004786/* Miscellaneous methods. */
4787
Tim Petersa9bc1682003-01-11 03:39:11 +00004788static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004789flip_fold(PyObject *dt)
4790{
4791 return new_datetime_ex2(GET_YEAR(dt),
4792 GET_MONTH(dt),
4793 GET_DAY(dt),
4794 DATE_GET_HOUR(dt),
4795 DATE_GET_MINUTE(dt),
4796 DATE_GET_SECOND(dt),
4797 DATE_GET_MICROSECOND(dt),
4798 HASTZINFO(dt) ?
4799 ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
4800 !DATE_GET_FOLD(dt),
4801 Py_TYPE(dt));
4802}
4803
4804static PyObject *
4805get_flip_fold_offset(PyObject *dt)
4806{
4807 PyObject *result, *flip_dt;
4808
4809 flip_dt = flip_fold(dt);
4810 if (flip_dt == NULL)
4811 return NULL;
4812 result = datetime_utcoffset(flip_dt, NULL);
4813 Py_DECREF(flip_dt);
4814 return result;
4815}
4816
4817/* PEP 495 exception: Whenever one or both of the operands in
4818 * inter-zone comparison is such that its utcoffset() depends
4819 * on the value of its fold fold attribute, the result is False.
4820 *
4821 * Return 1 if exception applies, 0 if not, and -1 on error.
4822 */
4823static int
4824pep495_eq_exception(PyObject *self, PyObject *other,
4825 PyObject *offset_self, PyObject *offset_other)
4826{
4827 int result = 0;
4828 PyObject *flip_offset;
4829
4830 flip_offset = get_flip_fold_offset(self);
4831 if (flip_offset == NULL)
4832 return -1;
4833 if (flip_offset != offset_self &&
4834 delta_cmp(flip_offset, offset_self))
4835 {
4836 result = 1;
4837 goto done;
4838 }
4839 Py_DECREF(flip_offset);
4840
4841 flip_offset = get_flip_fold_offset(other);
4842 if (flip_offset == NULL)
4843 return -1;
4844 if (flip_offset != offset_other &&
4845 delta_cmp(flip_offset, offset_other))
4846 result = 1;
4847 done:
4848 Py_DECREF(flip_offset);
4849 return result;
4850}
4851
4852static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004853datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004854{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004855 PyObject *result = NULL;
4856 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 if (! PyDateTime_Check(other)) {
4860 if (PyDate_Check(other)) {
4861 /* Prevent invocation of date_richcompare. We want to
4862 return NotImplemented here to give the other object
4863 a chance. But since DateTime is a subclass of
4864 Date, if the other object is a Date, it would
4865 compute an ordering based on the date part alone,
4866 and we don't want that. So force unequal or
4867 uncomparable here in that case. */
4868 if (op == Py_EQ)
4869 Py_RETURN_FALSE;
4870 if (op == Py_NE)
4871 Py_RETURN_TRUE;
4872 return cmperror(self, other);
4873 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004874 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004876
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004877 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4879 ((PyDateTime_DateTime *)other)->data,
4880 _PyDateTime_DATETIME_DATASIZE);
4881 return diff_to_bool(diff, op);
4882 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004883 offset1 = datetime_utcoffset(self, NULL);
4884 if (offset1 == NULL)
4885 return NULL;
4886 offset2 = datetime_utcoffset(other, NULL);
4887 if (offset2 == NULL)
4888 goto done;
4889 /* If they're both naive, or both aware and have the same offsets,
4890 * we get off cheap. Note that if they're both naive, offset1 ==
4891 * offset2 == Py_None at this point.
4892 */
4893 if ((offset1 == offset2) ||
4894 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4895 delta_cmp(offset1, offset2) == 0)) {
4896 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4897 ((PyDateTime_DateTime *)other)->data,
4898 _PyDateTime_DATETIME_DATASIZE);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004899 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4900 int ex = pep495_eq_exception(self, other, offset1, offset2);
4901 if (ex == -1)
4902 goto done;
4903 if (ex)
4904 diff = 1;
4905 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004906 result = diff_to_bool(diff, op);
4907 }
4908 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004910
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004911 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4913 other);
4914 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004915 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004916 diff = GET_TD_DAYS(delta);
4917 if (diff == 0)
4918 diff = GET_TD_SECONDS(delta) |
4919 GET_TD_MICROSECONDS(delta);
4920 Py_DECREF(delta);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004921 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4922 int ex = pep495_eq_exception(self, other, offset1, offset2);
4923 if (ex == -1)
4924 goto done;
4925 if (ex)
4926 diff = 1;
4927 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004928 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004929 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004930 else if (op == Py_EQ) {
4931 result = Py_False;
4932 Py_INCREF(result);
4933 }
4934 else if (op == Py_NE) {
4935 result = Py_True;
4936 Py_INCREF(result);
4937 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004938 else {
4939 PyErr_SetString(PyExc_TypeError,
4940 "can't compare offset-naive and "
4941 "offset-aware datetimes");
4942 }
4943 done:
4944 Py_DECREF(offset1);
4945 Py_XDECREF(offset2);
4946 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004947}
4948
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004949static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004950datetime_hash(PyDateTime_DateTime *self)
4951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004953 PyObject *offset, *self0;
4954 if (DATE_GET_FOLD(self)) {
4955 self0 = new_datetime_ex2(GET_YEAR(self),
4956 GET_MONTH(self),
4957 GET_DAY(self),
4958 DATE_GET_HOUR(self),
4959 DATE_GET_MINUTE(self),
4960 DATE_GET_SECOND(self),
4961 DATE_GET_MICROSECOND(self),
4962 HASTZINFO(self) ? self->tzinfo : Py_None,
4963 0, Py_TYPE(self));
4964 if (self0 == NULL)
4965 return -1;
4966 }
4967 else {
4968 self0 = (PyObject *)self;
4969 Py_INCREF(self0);
4970 }
4971 offset = datetime_utcoffset(self0, NULL);
4972 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004973
4974 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004978 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 self->hashcode = generic_hash(
4980 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004982 PyObject *temp1, *temp2;
4983 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 assert(HASTZINFO(self));
4986 days = ymd_to_ord(GET_YEAR(self),
4987 GET_MONTH(self),
4988 GET_DAY(self));
4989 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004990 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004992 temp1 = new_delta(days, seconds,
4993 DATE_GET_MICROSECOND(self),
4994 1);
4995 if (temp1 == NULL) {
4996 Py_DECREF(offset);
4997 return -1;
4998 }
4999 temp2 = delta_subtract(temp1, offset);
5000 Py_DECREF(temp1);
5001 if (temp2 == NULL) {
5002 Py_DECREF(offset);
5003 return -1;
5004 }
5005 self->hashcode = PyObject_Hash(temp2);
5006 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005008 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 }
5010 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00005011}
Tim Peters2a799bf2002-12-16 20:18:38 +00005012
5013static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005014datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00005015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 PyObject *clone;
5017 PyObject *tuple;
5018 int y = GET_YEAR(self);
5019 int m = GET_MONTH(self);
5020 int d = GET_DAY(self);
5021 int hh = DATE_GET_HOUR(self);
5022 int mm = DATE_GET_MINUTE(self);
5023 int ss = DATE_GET_SECOND(self);
5024 int us = DATE_GET_MICROSECOND(self);
5025 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005026 int fold = DATE_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00005027
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005028 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 datetime_kws,
5030 &y, &m, &d, &hh, &mm, &ss, &us,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005031 &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 return NULL;
Serhiy Storchaka314d6fc2017-03-31 22:48:16 +03005033 if (fold != 0 && fold != 1) {
5034 PyErr_SetString(PyExc_ValueError,
5035 "fold must be either 0 or 1");
5036 return NULL;
5037 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
5039 if (tuple == NULL)
5040 return NULL;
5041 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005042 if (clone != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005043 DATE_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005044 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 Py_DECREF(tuple);
5046 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00005047}
5048
5049static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005050local_timezone_from_timestamp(time_t timestamp)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005051{
5052 PyObject *result = NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005053 PyObject *delta;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005054 struct tm local_time_tm;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005055 PyObject *nameo = NULL;
5056 const char *zone = NULL;
5057
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005058 if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005059 return NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005060#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005061 zone = local_time_tm.tm_zone;
5062 delta = new_delta(0, local_time_tm.tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005063#else /* HAVE_STRUCT_TM_TM_ZONE */
5064 {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005065 PyObject *local_time, *utc_time;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005066 struct tm utc_time_tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005067 char buf[100];
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005068 strftime(buf, sizeof(buf), "%Z", &local_time_tm);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005069 zone = buf;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005070 local_time = new_datetime(local_time_tm.tm_year + 1900,
5071 local_time_tm.tm_mon + 1,
5072 local_time_tm.tm_mday,
5073 local_time_tm.tm_hour,
5074 local_time_tm.tm_min,
5075 local_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005076 if (local_time == NULL) {
5077 return NULL;
5078 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005079 if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005080 return NULL;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005081 utc_time = new_datetime(utc_time_tm.tm_year + 1900,
5082 utc_time_tm.tm_mon + 1,
5083 utc_time_tm.tm_mday,
5084 utc_time_tm.tm_hour,
5085 utc_time_tm.tm_min,
5086 utc_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005087 if (utc_time == NULL) {
5088 Py_DECREF(local_time);
5089 return NULL;
5090 }
5091 delta = datetime_subtract(local_time, utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005092 Py_DECREF(local_time);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005093 Py_DECREF(utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005094 }
5095#endif /* HAVE_STRUCT_TM_TM_ZONE */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005096 if (delta == NULL) {
5097 return NULL;
5098 }
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005099 if (zone != NULL) {
5100 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
5101 if (nameo == NULL)
5102 goto error;
5103 }
5104 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02005105 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005106 error:
5107 Py_DECREF(delta);
5108 return result;
5109}
5110
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005111static PyObject *
5112local_timezone(PyDateTime_DateTime *utc_time)
5113{
5114 time_t timestamp;
5115 PyObject *delta;
5116 PyObject *one_second;
5117 PyObject *seconds;
5118
5119 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
5120 if (delta == NULL)
5121 return NULL;
5122 one_second = new_delta(0, 1, 0, 0);
5123 if (one_second == NULL) {
5124 Py_DECREF(delta);
5125 return NULL;
5126 }
5127 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
5128 (PyDateTime_Delta *)one_second);
5129 Py_DECREF(one_second);
5130 Py_DECREF(delta);
5131 if (seconds == NULL)
5132 return NULL;
5133 timestamp = _PyLong_AsTime_t(seconds);
5134 Py_DECREF(seconds);
5135 if (timestamp == -1 && PyErr_Occurred())
5136 return NULL;
5137 return local_timezone_from_timestamp(timestamp);
5138}
5139
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005140static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005141local_to_seconds(int year, int month, int day,
5142 int hour, int minute, int second, int fold);
5143
5144static PyObject *
5145local_timezone_from_local(PyDateTime_DateTime *local_dt)
5146{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005147 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005148 time_t timestamp;
5149 seconds = local_to_seconds(GET_YEAR(local_dt),
5150 GET_MONTH(local_dt),
5151 GET_DAY(local_dt),
5152 DATE_GET_HOUR(local_dt),
5153 DATE_GET_MINUTE(local_dt),
5154 DATE_GET_SECOND(local_dt),
5155 DATE_GET_FOLD(local_dt));
5156 if (seconds == -1)
5157 return NULL;
5158 /* XXX: add bounds check */
5159 timestamp = seconds - epoch;
5160 return local_timezone_from_timestamp(timestamp);
5161}
5162
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005163static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00005164datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00005165{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005166 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005167 PyObject *offset;
5168 PyObject *temp;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005169 PyObject *self_tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005170 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00005172
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005173 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07005174 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005175 return NULL;
5176
5177 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00005179
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005180 if (!HASTZINFO(self) || self->tzinfo == Py_None) {
5181 self_tzinfo = local_timezone_from_local(self);
5182 if (self_tzinfo == NULL)
5183 return NULL;
5184 } else {
5185 self_tzinfo = self->tzinfo;
5186 Py_INCREF(self_tzinfo);
5187 }
Tim Peters521fc152002-12-31 17:36:56 +00005188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005189 /* Conversion to self's own time zone is a NOP. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005190 if (self_tzinfo == tzinfo) {
5191 Py_DECREF(self_tzinfo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005192 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005193 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 }
Tim Peters521fc152002-12-31 17:36:56 +00005195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 /* Convert self to UTC. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005197 offset = call_utcoffset(self_tzinfo, (PyObject *)self);
5198 Py_DECREF(self_tzinfo);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005199 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005201 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005202 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5203 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005204 Py_DECREF(offset);
5205 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00005207
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005208 /* Make sure result is aware and UTC. */
5209 if (!HASTZINFO(result)) {
5210 temp = (PyObject *)result;
5211 result = (PyDateTime_DateTime *)
5212 new_datetime_ex2(GET_YEAR(result),
5213 GET_MONTH(result),
5214 GET_DAY(result),
5215 DATE_GET_HOUR(result),
5216 DATE_GET_MINUTE(result),
5217 DATE_GET_SECOND(result),
5218 DATE_GET_MICROSECOND(result),
5219 PyDateTime_TimeZone_UTC,
5220 DATE_GET_FOLD(result),
5221 Py_TYPE(result));
5222 Py_DECREF(temp);
5223 if (result == NULL)
5224 return NULL;
5225 }
5226 else {
5227 /* Result is already aware - just replace tzinfo. */
5228 temp = result->tzinfo;
5229 result->tzinfo = PyDateTime_TimeZone_UTC;
5230 Py_INCREF(result->tzinfo);
5231 Py_DECREF(temp);
5232 }
5233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005234 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005235 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005236 if (tzinfo == Py_None) {
5237 tzinfo = local_timezone(result);
5238 if (tzinfo == NULL) {
5239 Py_DECREF(result);
5240 return NULL;
5241 }
5242 }
5243 else
5244 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005245 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005246 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00005247
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005248 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005249 result = (PyDateTime_DateTime *)
Victor Stinner20401de2016-12-09 15:24:31 +01005250 _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_fromutc, temp, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005251 Py_DECREF(temp);
5252
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005253 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00005254}
5255
5256static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005257datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00005260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005262 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00005263
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005264 dst = call_dst(self->tzinfo, (PyObject *)self);
5265 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005267
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005268 if (dst != Py_None)
5269 dstflag = delta_bool((PyDateTime_Delta *)dst);
5270 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005271 }
5272 return build_struct_time(GET_YEAR(self),
5273 GET_MONTH(self),
5274 GET_DAY(self),
5275 DATE_GET_HOUR(self),
5276 DATE_GET_MINUTE(self),
5277 DATE_GET_SECOND(self),
5278 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00005279}
5280
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005281static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005282local_to_seconds(int year, int month, int day,
5283 int hour, int minute, int second, int fold)
5284{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005285 long long t, a, b, u1, u2, t1, t2, lt;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005286 t = utc_to_seconds(year, month, day, hour, minute, second);
5287 /* Our goal is to solve t = local(u) for u. */
5288 lt = local(t);
5289 if (lt == -1)
5290 return -1;
5291 a = lt - t;
5292 u1 = t - a;
5293 t1 = local(u1);
5294 if (t1 == -1)
5295 return -1;
5296 if (t1 == t) {
5297 /* We found one solution, but it may not be the one we need.
5298 * Look for an earlier solution (if `fold` is 0), or a
5299 * later one (if `fold` is 1). */
5300 if (fold)
5301 u2 = u1 + max_fold_seconds;
5302 else
5303 u2 = u1 - max_fold_seconds;
5304 lt = local(u2);
5305 if (lt == -1)
5306 return -1;
5307 b = lt - u2;
5308 if (a == b)
5309 return u1;
5310 }
5311 else {
5312 b = t1 - u1;
5313 assert(a != b);
5314 }
5315 u2 = t - b;
5316 t2 = local(u2);
5317 if (t2 == -1)
5318 return -1;
5319 if (t2 == t)
5320 return u2;
5321 if (t1 == t)
5322 return u1;
5323 /* We have found both offsets a and b, but neither t - a nor t - b is
5324 * a solution. This means t is in the gap. */
5325 return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
5326}
5327
5328/* date(1970,1,1).toordinal() == 719163 */
5329#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
5330
Tim Peters2a799bf2002-12-16 20:18:38 +00005331static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04005332datetime_timestamp(PyDateTime_DateTime *self)
5333{
5334 PyObject *result;
5335
5336 if (HASTZINFO(self) && self->tzinfo != Py_None) {
5337 PyObject *delta;
5338 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
5339 if (delta == NULL)
5340 return NULL;
5341 result = delta_total_seconds(delta);
5342 Py_DECREF(delta);
5343 }
5344 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005345 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005346 seconds = local_to_seconds(GET_YEAR(self),
5347 GET_MONTH(self),
5348 GET_DAY(self),
5349 DATE_GET_HOUR(self),
5350 DATE_GET_MINUTE(self),
5351 DATE_GET_SECOND(self),
5352 DATE_GET_FOLD(self));
5353 if (seconds == -1)
Alexander Belopolskya4415142012-06-08 12:33:09 -04005354 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005355 result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
5356 DATE_GET_MICROSECOND(self) / 1e6);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005357 }
5358 return result;
5359}
5360
5361static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005362datetime_getdate(PyDateTime_DateTime *self)
5363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 return new_date(GET_YEAR(self),
5365 GET_MONTH(self),
5366 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005367}
5368
5369static PyObject *
5370datetime_gettime(PyDateTime_DateTime *self)
5371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 return new_time(DATE_GET_HOUR(self),
5373 DATE_GET_MINUTE(self),
5374 DATE_GET_SECOND(self),
5375 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005376 Py_None,
5377 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005378}
5379
5380static PyObject *
5381datetime_gettimetz(PyDateTime_DateTime *self)
5382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 return new_time(DATE_GET_HOUR(self),
5384 DATE_GET_MINUTE(self),
5385 DATE_GET_SECOND(self),
5386 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005387 GET_DT_TZINFO(self),
5388 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005389}
5390
5391static PyObject *
5392datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005393{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005394 int y, m, d, hh, mm, ss;
5395 PyObject *tzinfo;
5396 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00005397
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005398 tzinfo = GET_DT_TZINFO(self);
5399 if (tzinfo == Py_None) {
5400 utcself = self;
5401 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005403 else {
5404 PyObject *offset;
5405 offset = call_utcoffset(tzinfo, (PyObject *)self);
5406 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00005407 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005408 if (offset == Py_None) {
5409 Py_DECREF(offset);
5410 utcself = self;
5411 Py_INCREF(utcself);
5412 }
5413 else {
5414 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5415 (PyDateTime_Delta *)offset, -1);
5416 Py_DECREF(offset);
5417 if (utcself == NULL)
5418 return NULL;
5419 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005421 y = GET_YEAR(utcself);
5422 m = GET_MONTH(utcself);
5423 d = GET_DAY(utcself);
5424 hh = DATE_GET_HOUR(utcself);
5425 mm = DATE_GET_MINUTE(utcself);
5426 ss = DATE_GET_SECOND(utcself);
5427
5428 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005430}
5431
Tim Peters371935f2003-02-01 01:52:50 +00005432/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00005433
Tim Petersa9bc1682003-01-11 03:39:11 +00005434/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00005435 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5436 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00005437 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00005438 */
5439static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005440datetime_getstate(PyDateTime_DateTime *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00005441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 PyObject *basestate;
5443 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 basestate = PyBytes_FromStringAndSize((char *)self->data,
5446 _PyDateTime_DATETIME_DATASIZE);
5447 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005448 if (proto > 3 && DATE_GET_FOLD(self))
5449 /* Set the first bit of the third byte */
5450 PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5452 result = PyTuple_Pack(1, basestate);
5453 else
5454 result = PyTuple_Pack(2, basestate, self->tzinfo);
5455 Py_DECREF(basestate);
5456 }
5457 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005458}
5459
5460static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005461datetime_reduce_ex(PyDateTime_DateTime *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00005462{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005463 int proto;
5464 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005465 return NULL;
5466
5467 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00005468}
5469
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005470static PyObject *
5471datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
5472{
5473 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, 2));
5474}
5475
Tim Petersa9bc1682003-01-11 03:39:11 +00005476static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005478 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005479
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005480 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005482 {"utcnow", (PyCFunction)datetime_utcnow,
5483 METH_NOARGS | METH_CLASS,
5484 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005486 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5487 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5488 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005490 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5491 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05005492 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 {"strptime", (PyCFunction)datetime_strptime,
5495 METH_VARARGS | METH_CLASS,
5496 PyDoc_STR("string, format -> new datetime parsed from a string "
5497 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 {"combine", (PyCFunction)datetime_combine,
5500 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5501 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5506 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005508 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5509 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5512 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5515 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5518 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005519
Alexander Belopolskya4415142012-06-08 12:33:09 -04005520 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5521 PyDoc_STR("Return POSIX timestamp as float.")},
5522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5524 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005526 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5527 PyDoc_STR("[sep] -> string in ISO 8601 format, "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005528 "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 "sep is used to separate the year from the time, and "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005530 "defaults to 'T'.\n"
5531 "timespec specifies what components of the time to include"
5532 " (allowed values are 'auto', 'hours', 'minutes', 'seconds',"
5533 " 'milliseconds', and 'microseconds').\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5536 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5539 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5542 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5545 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5548 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005549
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005550 {"__reduce_ex__", (PyCFunction)datetime_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005551 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005552
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005553 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
5554 PyDoc_STR("__reduce__() -> (cls, state)")},
5555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005557};
5558
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02005559static const char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005560PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5561\n\
5562The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005563instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005564
Tim Petersa9bc1682003-01-11 03:39:11 +00005565static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 datetime_add, /* nb_add */
5567 datetime_subtract, /* nb_subtract */
5568 0, /* nb_multiply */
5569 0, /* nb_remainder */
5570 0, /* nb_divmod */
5571 0, /* nb_power */
5572 0, /* nb_negative */
5573 0, /* nb_positive */
5574 0, /* nb_absolute */
5575 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005576};
5577
Neal Norwitz227b5332006-03-22 09:28:35 +00005578static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005579 PyVarObject_HEAD_INIT(NULL, 0)
5580 "datetime.datetime", /* tp_name */
5581 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5582 0, /* tp_itemsize */
5583 (destructor)datetime_dealloc, /* tp_dealloc */
5584 0, /* tp_print */
5585 0, /* tp_getattr */
5586 0, /* tp_setattr */
5587 0, /* tp_reserved */
5588 (reprfunc)datetime_repr, /* tp_repr */
5589 &datetime_as_number, /* tp_as_number */
5590 0, /* tp_as_sequence */
5591 0, /* tp_as_mapping */
5592 (hashfunc)datetime_hash, /* tp_hash */
5593 0, /* tp_call */
5594 (reprfunc)datetime_str, /* tp_str */
5595 PyObject_GenericGetAttr, /* tp_getattro */
5596 0, /* tp_setattro */
5597 0, /* tp_as_buffer */
5598 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5599 datetime_doc, /* tp_doc */
5600 0, /* tp_traverse */
5601 0, /* tp_clear */
5602 datetime_richcompare, /* tp_richcompare */
5603 0, /* tp_weaklistoffset */
5604 0, /* tp_iter */
5605 0, /* tp_iternext */
5606 datetime_methods, /* tp_methods */
5607 0, /* tp_members */
5608 datetime_getset, /* tp_getset */
5609 &PyDateTime_DateType, /* tp_base */
5610 0, /* tp_dict */
5611 0, /* tp_descr_get */
5612 0, /* tp_descr_set */
5613 0, /* tp_dictoffset */
5614 0, /* tp_init */
5615 datetime_alloc, /* tp_alloc */
5616 datetime_new, /* tp_new */
5617 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005618};
5619
5620/* ---------------------------------------------------------------------------
5621 * Module methods and initialization.
5622 */
5623
5624static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005626};
5627
Tim Peters9ddf40b2004-06-20 22:41:32 +00005628/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5629 * datetime.h.
5630 */
5631static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005632 &PyDateTime_DateType,
5633 &PyDateTime_DateTimeType,
5634 &PyDateTime_TimeType,
5635 &PyDateTime_DeltaType,
5636 &PyDateTime_TZInfoType,
5637 new_date_ex,
5638 new_datetime_ex,
5639 new_time_ex,
5640 new_delta_ex,
5641 datetime_fromtimestamp,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005642 date_fromtimestamp,
5643 new_datetime_ex2,
5644 new_time_ex2
Tim Peters9ddf40b2004-06-20 22:41:32 +00005645};
5646
5647
Martin v. Löwis1a214512008-06-11 05:26:20 +00005648
5649static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005651 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 "Fast implementation of the datetime type.",
5653 -1,
5654 module_methods,
5655 NULL,
5656 NULL,
5657 NULL,
5658 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005659};
5660
Tim Peters2a799bf2002-12-16 20:18:38 +00005661PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005662PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 PyObject *m; /* a module object */
5665 PyObject *d; /* its dict */
5666 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005667 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005669 m = PyModule_Create(&datetimemodule);
5670 if (m == NULL)
5671 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 if (PyType_Ready(&PyDateTime_DateType) < 0)
5674 return NULL;
5675 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5676 return NULL;
5677 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5678 return NULL;
5679 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5680 return NULL;
5681 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5682 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005683 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5684 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 /* timedelta values */
5687 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 x = new_delta(0, 0, 1, 0);
5690 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5691 return NULL;
5692 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5695 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5696 return NULL;
5697 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5700 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5701 return NULL;
5702 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 /* date values */
5705 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 x = new_date(1, 1, 1);
5708 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5709 return NULL;
5710 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 x = new_date(MAXYEAR, 12, 31);
5713 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5714 return NULL;
5715 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 x = new_delta(1, 0, 0, 0);
5718 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5719 return NULL;
5720 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 /* time values */
5723 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005724
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005725 x = new_time(0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5727 return NULL;
5728 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005729
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005730 x = new_time(23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005731 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5732 return NULL;
5733 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 x = new_delta(0, 0, 1, 0);
5736 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5737 return NULL;
5738 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005740 /* datetime values */
5741 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005742
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005743 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005744 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5745 return NULL;
5746 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005747
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005748 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005749 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5750 return NULL;
5751 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 x = new_delta(0, 0, 1, 0);
5754 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5755 return NULL;
5756 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005757
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005758 /* timezone values */
5759 d = PyDateTime_TimeZoneType.tp_dict;
5760
5761 delta = new_delta(0, 0, 0, 0);
5762 if (delta == NULL)
5763 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005764 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005765 Py_DECREF(delta);
5766 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5767 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005768 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005769
5770 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5771 if (delta == NULL)
5772 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005773 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005774 Py_DECREF(delta);
5775 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5776 return NULL;
5777 Py_DECREF(x);
5778
5779 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5780 if (delta == NULL)
5781 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005782 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005783 Py_DECREF(delta);
5784 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5785 return NULL;
5786 Py_DECREF(x);
5787
Alexander Belopolskya4415142012-06-08 12:33:09 -04005788 /* Epoch */
5789 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005790 PyDateTime_TimeZone_UTC, 0);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005791 if (PyDateTime_Epoch == NULL)
5792 return NULL;
5793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005795 PyModule_AddIntMacro(m, MINYEAR);
5796 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005798 Py_INCREF(&PyDateTime_DateType);
5799 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 Py_INCREF(&PyDateTime_DateTimeType);
5802 PyModule_AddObject(m, "datetime",
5803 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805 Py_INCREF(&PyDateTime_TimeType);
5806 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 Py_INCREF(&PyDateTime_DeltaType);
5809 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 Py_INCREF(&PyDateTime_TZInfoType);
5812 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005813
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005814 Py_INCREF(&PyDateTime_TimeZoneType);
5815 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5818 if (x == NULL)
5819 return NULL;
5820 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 /* A 4-year cycle has an extra leap day over what we'd get from
5823 * pasting together 4 single years.
5824 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005825 Py_BUILD_ASSERT(DI4Y == 4 * 365 + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5829 * get from pasting together 4 100-year cycles.
5830 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005831 Py_BUILD_ASSERT(DI400Y == 4 * DI100Y + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5835 * pasting together 25 4-year cycles.
5836 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005837 Py_BUILD_ASSERT(DI100Y == 25 * DI4Y - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005840 us_per_ms = PyLong_FromLong(1000);
5841 us_per_second = PyLong_FromLong(1000000);
5842 us_per_minute = PyLong_FromLong(60000000);
5843 seconds_per_day = PyLong_FromLong(24 * 3600);
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005844 if (us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 us_per_minute == NULL || seconds_per_day == NULL)
5846 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005848 /* The rest are too big for 32-bit ints, but even
5849 * us_per_week fits in 40 bits, so doubles should be exact.
5850 */
5851 us_per_hour = PyLong_FromDouble(3600000000.0);
5852 us_per_day = PyLong_FromDouble(86400000000.0);
5853 us_per_week = PyLong_FromDouble(604800000000.0);
5854 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5855 return NULL;
5856 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005857}
Tim Petersf3615152003-01-01 21:51:37 +00005858
5859/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005860Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005861 x.n = x stripped of its timezone -- its naive time.
5862 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005863 return None
Tim Petersf3615152003-01-01 21:51:37 +00005864 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 return None
Tim Petersf3615152003-01-01 21:51:37 +00005866 x.s = x's standard offset, x.o - x.d
5867
5868Now some derived rules, where k is a duration (timedelta).
5869
58701. x.o = x.s + x.d
5871 This follows from the definition of x.s.
5872
Tim Petersc5dc4da2003-01-02 17:55:03 +000058732. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005874 This is actually a requirement, an assumption we need to make about
5875 sane tzinfo classes.
5876
58773. The naive UTC time corresponding to x is x.n - x.o.
5878 This is again a requirement for a sane tzinfo class.
5879
58804. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005881 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005882
Tim Petersc5dc4da2003-01-02 17:55:03 +000058835. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005884 Again follows from how arithmetic is defined.
5885
Tim Peters8bb5ad22003-01-24 02:44:45 +00005886Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005887(meaning that the various tzinfo methods exist, and don't blow up or return
5888None when called).
5889
Tim Petersa9bc1682003-01-11 03:39:11 +00005890The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005891x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005892
5893By #3, we want
5894
Tim Peters8bb5ad22003-01-24 02:44:45 +00005895 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005896
5897The algorithm starts by attaching tz to x.n, and calling that y. So
5898x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5899becomes true; in effect, we want to solve [2] for k:
5900
Tim Peters8bb5ad22003-01-24 02:44:45 +00005901 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005902
5903By #1, this is the same as
5904
Tim Peters8bb5ad22003-01-24 02:44:45 +00005905 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005906
5907By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5908Substituting that into [3],
5909
Tim Peters8bb5ad22003-01-24 02:44:45 +00005910 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5911 k - (y+k).s - (y+k).d = 0; rearranging,
5912 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5913 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005914
Tim Peters8bb5ad22003-01-24 02:44:45 +00005915On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5916approximate k by ignoring the (y+k).d term at first. Note that k can't be
5917very large, since all offset-returning methods return a duration of magnitude
5918less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5919be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005920
5921In any case, the new value is
5922
Tim Peters8bb5ad22003-01-24 02:44:45 +00005923 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005924
Tim Peters8bb5ad22003-01-24 02:44:45 +00005925It's helpful to step back at look at [4] from a higher level: it's simply
5926mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005927
5928At this point, if
5929
Tim Peters8bb5ad22003-01-24 02:44:45 +00005930 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005931
5932we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005933at the start of daylight time. Picture US Eastern for concreteness. The wall
5934time 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 +00005935sense then. The docs ask that an Eastern tzinfo class consider such a time to
5936be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5937on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005938the only spelling that makes sense on the local wall clock.
5939
Tim Petersc5dc4da2003-01-02 17:55:03 +00005940In fact, if [5] holds at this point, we do have the standard-time spelling,
5941but that takes a bit of proof. We first prove a stronger result. What's the
5942difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005943
Tim Peters8bb5ad22003-01-24 02:44:45 +00005944 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005945
Tim Petersc5dc4da2003-01-02 17:55:03 +00005946Now
5947 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005948 (y + y.s).n = by #5
5949 y.n + y.s = since y.n = x.n
5950 x.n + y.s = since z and y are have the same tzinfo member,
5951 y.s = z.s by #2
5952 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005953
Tim Petersc5dc4da2003-01-02 17:55:03 +00005954Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005955
Tim Petersc5dc4da2003-01-02 17:55:03 +00005956 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005957 x.n - ((x.n + z.s) - z.o) = expanding
5958 x.n - x.n - z.s + z.o = cancelling
5959 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005960 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005961
Tim Petersc5dc4da2003-01-02 17:55:03 +00005962So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005963
Tim Petersc5dc4da2003-01-02 17:55:03 +00005964If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005965spelling we wanted in the endcase described above. We're done. Contrarily,
5966if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005967
Tim Petersc5dc4da2003-01-02 17:55:03 +00005968If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5969add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005970local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005971
Tim Petersc5dc4da2003-01-02 17:55:03 +00005972Let
Tim Petersf3615152003-01-01 21:51:37 +00005973
Tim Peters4fede1a2003-01-04 00:26:59 +00005974 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005975
Tim Peters4fede1a2003-01-04 00:26:59 +00005976and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005977
Tim Peters8bb5ad22003-01-24 02:44:45 +00005978 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005979
Tim Peters8bb5ad22003-01-24 02:44:45 +00005980If so, we're done. If not, the tzinfo class is insane, according to the
5981assumptions we've made. This also requires a bit of proof. As before, let's
5982compute the difference between the LHS and RHS of [8] (and skipping some of
5983the justifications for the kinds of substitutions we've done several times
5984already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005985
Tim Peters8bb5ad22003-01-24 02:44:45 +00005986 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005987 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5988 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5989 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5990 - z.n + z.n - z.o + z'.o = cancel z.n
5991 - z.o + z'.o = #1 twice
5992 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5993 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005994
5995So 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 +00005996we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5997return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005998
Tim Peters8bb5ad22003-01-24 02:44:45 +00005999How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
6000a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
6001would have to change the result dst() returns: we start in DST, and moving
6002a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00006003
Tim Peters8bb5ad22003-01-24 02:44:45 +00006004There isn't a sane case where this can happen. The closest it gets is at
6005the end of DST, where there's an hour in UTC with no spelling in a hybrid
6006tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
6007that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
6008UTC) because the docs insist on that, but 0:MM is taken as being in daylight
6009time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
6010clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
6011standard time. Since that's what the local clock *does*, we want to map both
6012UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00006013in local time, but so it goes -- it's the way the local clock works.
6014
Tim Peters8bb5ad22003-01-24 02:44:45 +00006015When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
6016so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
6017z' = 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 +00006018(correctly) concludes that z' is not UTC-equivalent to x.
6019
6020Because we know z.d said z was in daylight time (else [5] would have held and
6021we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006022and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00006023return in Eastern, it follows that z'.d must be 0 (which it is in the example,
6024but the reasoning doesn't depend on the example -- it depends on there being
6025two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00006026z' must be in standard time, and is the spelling we want in this case.
6027
6028Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
6029concerned (because it takes z' as being in standard time rather than the
6030daylight time we intend here), but returning it gives the real-life "local
6031clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
6032tz.
6033
6034When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
6035the 1:MM standard time spelling we want.
6036
6037So how can this break? One of the assumptions must be violated. Two
6038possibilities:
6039
60401) [2] effectively says that y.s is invariant across all y belong to a given
6041 time zone. This isn't true if, for political reasons or continental drift,
6042 a region decides to change its base offset from UTC.
6043
60442) There may be versions of "double daylight" time where the tail end of
6045 the analysis gives up a step too early. I haven't thought about that
6046 enough to say.
6047
6048In any case, it's clear that the default fromutc() is strong enough to handle
6049"almost all" time zones: so long as the standard offset is invariant, it
6050doesn't matter if daylight time transition points change from year to year, or
6051if daylight time is skipped in some years; it doesn't matter how large or
6052small dst() may get within its bounds; and it doesn't even matter if some
6053perverse time zone returns a negative dst()). So a breaking case must be
6054pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00006055--------------------------------------------------------------------------- */