blob: a62f5929578d7ea4853545e4d5643b0a8d175875 [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 */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040012static struct tm *localtime_r(const time_t *timep, struct tm *result)
13{
14 if (localtime_s(result, timep) == 0)
15 return result;
16 return NULL;
17}
Victor Stinner09e5cf22015-03-30 00:09:18 +020018#endif
19
Tim Peters9ddf40b2004-06-20 22:41:32 +000020/* Differentiate between building the core module and building extension
21 * modules.
22 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000023#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000024#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000025#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000026#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000027#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000028
Larry Hastings61272b72014-01-07 12:41:53 -080029/*[clinic input]
Larry Hastings44e2eaa2013-11-23 15:37:55 -080030module datetime
Larry Hastingsc2047262014-01-25 20:43:29 -080031class datetime.datetime "PyDateTime_DateTime *" "&PyDateTime_DateTimeType"
Larry Hastings61272b72014-01-07 12:41:53 -080032[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080033/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78142cb64b9e98bc]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080034
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030035#include "clinic/_datetimemodule.c.h"
36
Tim Peters2a799bf2002-12-16 20:18:38 +000037/* We require that C int be at least 32 bits, and use int virtually
38 * everywhere. In just a few cases we use a temp long, where a Python
39 * API returns a C long. In such cases, we have to ensure that the
40 * final result fits in a C int (this can be an issue on 64-bit boxes).
41 */
42#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000043# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000044#endif
45
46#define MINYEAR 1
47#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000048#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000049
50/* Nine decimal digits is easy to communicate, and leaves enough room
51 * so that two delta days can be added w/o fear of overflowing a signed
52 * 32-bit int, and with plenty of room left over to absorb any possible
53 * carries from adding seconds.
54 */
55#define MAX_DELTA_DAYS 999999999
56
57/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058#define GET_YEAR PyDateTime_GET_YEAR
59#define GET_MONTH PyDateTime_GET_MONTH
60#define GET_DAY PyDateTime_GET_DAY
61#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
62#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
63#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
64#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040065#define DATE_GET_FOLD PyDateTime_DATE_GET_FOLD
Tim Peters2a799bf2002-12-16 20:18:38 +000066
67/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
69 ((o)->data[1] = ((v) & 0x00ff)))
70#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
71#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000072
73/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
75#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
76#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
77#define DATE_SET_MICROSECOND(o, v) \
78 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
79 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
80 ((o)->data[9] = ((v) & 0x0000ff)))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040081#define DATE_SET_FOLD(o, v) (PyDateTime_DATE_GET_FOLD(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000082
83/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
85#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
86#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
87#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040088#define TIME_GET_FOLD PyDateTime_TIME_GET_FOLD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
90#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
91#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
92#define TIME_SET_MICROSECOND(o, v) \
93 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
94 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
95 ((o)->data[5] = ((v) & 0x0000ff)))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040096#define TIME_SET_FOLD(o, v) (PyDateTime_TIME_GET_FOLD(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000097
98/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
100#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
101#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +0000102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103#define SET_TD_DAYS(o, v) ((o)->days = (v))
104#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +0000105#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
106
Tim Petersa032d2e2003-01-11 00:15:54 +0000107/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
108 * p->hastzinfo.
109 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000110#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
111#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
112 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
113#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
114 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +0000115/* M is a char or int claiming to be a valid month. The macro is equivalent
116 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +0000118 */
119#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
120
Tim Peters2a799bf2002-12-16 20:18:38 +0000121/* Forward declarations. */
122static PyTypeObject PyDateTime_DateType;
123static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000124static PyTypeObject PyDateTime_DeltaType;
125static PyTypeObject PyDateTime_TimeType;
126static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000127static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000128
Martin v. Löwise75fc142013-11-07 18:46:53 +0100129_Py_IDENTIFIER(as_integer_ratio);
130_Py_IDENTIFIER(fromutc);
131_Py_IDENTIFIER(isoformat);
132_Py_IDENTIFIER(strftime);
133
Tim Peters2a799bf2002-12-16 20:18:38 +0000134/* ---------------------------------------------------------------------------
135 * Math utilities.
136 */
137
138/* k = i+j overflows iff k differs in sign from both inputs,
139 * iff k^i has sign bit set and k^j has sign bit set,
140 * iff (k^i)&(k^j) has sign bit set.
141 */
142#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000144
145/* Compute Python divmod(x, y), returning the quotient and storing the
146 * remainder into *r. The quotient is the floor of x/y, and that's
147 * the real point of this. C will probably truncate instead (C99
148 * requires truncation; C89 left it implementation-defined).
149 * Simplification: we *require* that y > 0 here. That's appropriate
150 * for all the uses made of it. This simplifies the code and makes
151 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
152 * overflow case).
153 */
154static int
155divmod(int x, int y, int *r)
156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 assert(y > 0);
160 quo = x / y;
161 *r = x - quo * y;
162 if (*r < 0) {
163 --quo;
164 *r += y;
165 }
166 assert(0 <= *r && *r < y);
167 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000168}
169
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000170/* Nearest integer to m / n for integers m and n. Half-integer results
171 * are rounded to even.
172 */
173static PyObject *
174divide_nearest(PyObject *m, PyObject *n)
175{
176 PyObject *result;
177 PyObject *temp;
178
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000179 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000180 if (temp == NULL)
181 return NULL;
182 result = PyTuple_GET_ITEM(temp, 0);
183 Py_INCREF(result);
184 Py_DECREF(temp);
185
186 return result;
187}
188
Tim Peters2a799bf2002-12-16 20:18:38 +0000189/* ---------------------------------------------------------------------------
190 * General calendrical helper functions
191 */
192
193/* For each month ordinal in 1..12, the number of days in that month,
194 * and the number of days before that month in the same year. These
195 * are correct for non-leap years only.
196 */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200197static const int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 0, /* unused; this vector uses 1-based indexing */
199 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000200};
201
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200202static const int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 0, /* unused; this vector uses 1-based indexing */
204 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000205};
206
207/* year -> 1 if leap year, else 0. */
208static int
209is_leap(int year)
210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 /* Cast year to unsigned. The result is the same either way, but
212 * C can generate faster code for unsigned mod than for signed
213 * mod (especially for % 4 -- a good compiler should just grab
214 * the last 2 bits when the LHS is unsigned).
215 */
216 const unsigned int ayear = (unsigned int)year;
217 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000218}
219
220/* year, month -> number of days in that month in that year */
221static int
222days_in_month(int year, int month)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 assert(month >= 1);
225 assert(month <= 12);
226 if (month == 2 && is_leap(year))
227 return 29;
228 else
229 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000230}
231
Martin Panter46f50722016-05-26 05:35:26 +0000232/* year, month -> number of days in year preceding first day of month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000233static int
234days_before_month(int year, int month)
235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 assert(month >= 1);
239 assert(month <= 12);
240 days = _days_before_month[month];
241 if (month > 2 && is_leap(year))
242 ++days;
243 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000244}
245
246/* year -> number of days before January 1st of year. Remember that we
247 * start with year 1, so days_before_year(1) == 0.
248 */
249static int
250days_before_year(int year)
251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 int y = year - 1;
253 /* This is incorrect if year <= 0; we really want the floor
254 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000255 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000257 assert (year >= 1);
258 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000259}
260
261/* Number of days in 4, 100, and 400 year cycles. That these have
262 * the correct values is asserted in the module init function.
263 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264#define DI4Y 1461 /* days_before_year(5); days in 4 years */
265#define DI100Y 36524 /* days_before_year(101); days in 100 years */
266#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000267
268/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
269static void
270ord_to_ymd(int ordinal, int *year, int *month, int *day)
271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
275 * leap years repeats exactly every 400 years. The basic strategy is
276 * to find the closest 400-year boundary at or before ordinal, then
277 * work with the offset from that boundary to ordinal. Life is much
278 * clearer if we subtract 1 from ordinal first -- then the values
279 * of ordinal at 400-year boundaries are exactly those divisible
280 * by DI400Y:
281 *
282 * D M Y n n-1
283 * -- --- ---- ---------- ----------------
284 * 31 Dec -400 -DI400Y -DI400Y -1
285 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
286 * ...
287 * 30 Dec 000 -1 -2
288 * 31 Dec 000 0 -1
289 * 1 Jan 001 1 0 400-year boundary
290 * 2 Jan 001 2 1
291 * 3 Jan 001 3 2
292 * ...
293 * 31 Dec 400 DI400Y DI400Y -1
294 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
295 */
296 assert(ordinal >= 1);
297 --ordinal;
298 n400 = ordinal / DI400Y;
299 n = ordinal % DI400Y;
300 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 /* Now n is the (non-negative) offset, in days, from January 1 of
303 * year, to the desired date. Now compute how many 100-year cycles
304 * precede n.
305 * Note that it's possible for n100 to equal 4! In that case 4 full
306 * 100-year cycles precede the desired day, which implies the
307 * desired day is December 31 at the end of a 400-year cycle.
308 */
309 n100 = n / DI100Y;
310 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 /* Now compute how many 4-year cycles precede it. */
313 n4 = n / DI4Y;
314 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 /* And now how many single years. Again n1 can be 4, and again
317 * meaning that the desired day is December 31 at the end of the
318 * 4-year cycle.
319 */
320 n1 = n / 365;
321 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 *year += n100 * 100 + n4 * 4 + n1;
324 if (n1 == 4 || n100 == 4) {
325 assert(n == 0);
326 *year -= 1;
327 *month = 12;
328 *day = 31;
329 return;
330 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* Now the year is correct, and n is the offset from January 1. We
333 * find the month via an estimate that's either exact or one too
334 * large.
335 */
336 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
337 assert(leapyear == is_leap(*year));
338 *month = (n + 50) >> 5;
339 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
340 if (preceding > n) {
341 /* estimate is too large */
342 *month -= 1;
343 preceding -= days_in_month(*year, *month);
344 }
345 n -= preceding;
346 assert(0 <= n);
347 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000350}
351
352/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
353static int
354ymd_to_ord(int year, int month, int day)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000357}
358
359/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
360static int
361weekday(int year, int month, int day)
362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000364}
365
366/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
367 * first calendar week containing a Thursday.
368 */
369static int
370iso_week1_monday(int year)
371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
373 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
374 int first_weekday = (first_day + 6) % 7;
375 /* ordinal of closest Monday at or before 1/1 */
376 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
379 week1_monday += 7;
380 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000381}
382
383/* ---------------------------------------------------------------------------
384 * Range checkers.
385 */
386
387/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
388 * If not, raise OverflowError and return -1.
389 */
390static int
391check_delta_day_range(int days)
392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
394 return 0;
395 PyErr_Format(PyExc_OverflowError,
396 "days=%d; must have magnitude <= %d",
397 days, MAX_DELTA_DAYS);
398 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000399}
400
401/* Check that date arguments are in range. Return 0 if they are. If they
402 * aren't, raise ValueError and return -1.
403 */
404static int
405check_date_args(int year, int month, int day)
406{
407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (year < MINYEAR || year > MAXYEAR) {
409 PyErr_SetString(PyExc_ValueError,
410 "year is out of range");
411 return -1;
412 }
413 if (month < 1 || month > 12) {
414 PyErr_SetString(PyExc_ValueError,
415 "month must be in 1..12");
416 return -1;
417 }
418 if (day < 1 || day > days_in_month(year, month)) {
419 PyErr_SetString(PyExc_ValueError,
420 "day is out of range for month");
421 return -1;
422 }
423 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000424}
425
426/* Check that time arguments are in range. Return 0 if they are. If they
427 * aren't, raise ValueError and return -1.
428 */
429static int
Alexander Belopolsky47649ab2016-08-08 17:05:40 -0400430check_time_args(int h, int m, int s, int us, int fold)
Tim Peters2a799bf2002-12-16 20:18:38 +0000431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 if (h < 0 || h > 23) {
433 PyErr_SetString(PyExc_ValueError,
434 "hour must be in 0..23");
435 return -1;
436 }
437 if (m < 0 || m > 59) {
438 PyErr_SetString(PyExc_ValueError,
439 "minute must be in 0..59");
440 return -1;
441 }
442 if (s < 0 || s > 59) {
443 PyErr_SetString(PyExc_ValueError,
444 "second must be in 0..59");
445 return -1;
446 }
447 if (us < 0 || us > 999999) {
448 PyErr_SetString(PyExc_ValueError,
449 "microsecond must be in 0..999999");
450 return -1;
451 }
Alexander Belopolsky47649ab2016-08-08 17:05:40 -0400452 if (fold != 0 && fold != 1) {
453 PyErr_SetString(PyExc_ValueError,
454 "fold must be either 0 or 1");
455 return -1;
456 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000458}
459
460/* ---------------------------------------------------------------------------
461 * Normalization utilities.
462 */
463
464/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
465 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
466 * at least factor, enough of *lo is converted into "hi" units so that
467 * 0 <= *lo < factor. The input values must be such that int overflow
468 * is impossible.
469 */
470static void
471normalize_pair(int *hi, int *lo, int factor)
472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 assert(factor > 0);
474 assert(lo != hi);
475 if (*lo < 0 || *lo >= factor) {
476 const int num_hi = divmod(*lo, factor, lo);
477 const int new_hi = *hi + num_hi;
478 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
479 *hi = new_hi;
480 }
481 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000482}
483
484/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 * 0 <= *s < 24*3600
486 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000487 * The input values must be such that the internals don't overflow.
488 * The way this routine is used, we don't get close.
489 */
490static void
491normalize_d_s_us(int *d, int *s, int *us)
492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (*us < 0 || *us >= 1000000) {
494 normalize_pair(s, us, 1000000);
495 /* |s| can't be bigger than about
496 * |original s| + |original us|/1000000 now.
497 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 }
500 if (*s < 0 || *s >= 24*3600) {
501 normalize_pair(d, s, 24*3600);
502 /* |d| can't be bigger than about
503 * |original d| +
504 * (|original s| + |original us|/1000000) / (24*3600) now.
505 */
506 }
507 assert(0 <= *s && *s < 24*3600);
508 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000509}
510
511/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 * 1 <= *m <= 12
513 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000514 * The input values must be such that the internals don't overflow.
515 * The way this routine is used, we don't get close.
516 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000517static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000518normalize_y_m_d(int *y, int *m, int *d)
519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000521
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000522 /* In actual use, m is always the month component extracted from a
523 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* Now only day can be out of bounds (year may also be out of bounds
529 * for a datetime object, but we don't care about that here).
530 * If day is out of bounds, what to do is arguable, but at least the
531 * method here is principled and explainable.
532 */
533 dim = days_in_month(*y, *m);
534 if (*d < 1 || *d > dim) {
535 /* Move day-1 days from the first of the month. First try to
536 * get off cheap if we're only one day out of range
537 * (adjustments for timezone alone can't be worse than that).
538 */
539 if (*d == 0) {
540 --*m;
541 if (*m > 0)
542 *d = days_in_month(*y, *m);
543 else {
544 --*y;
545 *m = 12;
546 *d = 31;
547 }
548 }
549 else if (*d == dim + 1) {
550 /* move forward a day */
551 ++*m;
552 *d = 1;
553 if (*m > 12) {
554 *m = 1;
555 ++*y;
556 }
557 }
558 else {
559 int ordinal = ymd_to_ord(*y, *m, 1) +
560 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000561 if (ordinal < 1 || ordinal > MAXORDINAL) {
562 goto error;
563 } else {
564 ord_to_ymd(ordinal, y, m, d);
565 return 0;
566 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
568 }
569 assert(*m > 0);
570 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000571 if (MINYEAR <= *y && *y <= MAXYEAR)
572 return 0;
573 error:
574 PyErr_SetString(PyExc_OverflowError,
575 "date value out of range");
576 return -1;
577
Tim Peters2a799bf2002-12-16 20:18:38 +0000578}
579
580/* Fiddle out-of-bounds months and days so that the result makes some kind
581 * of sense. The parameters are both inputs and outputs. Returns < 0 on
582 * failure, where failure means the adjusted year is out of bounds.
583 */
584static int
585normalize_date(int *year, int *month, int *day)
586{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000587 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000588}
589
590/* Force all the datetime fields into range. The parameters are both
591 * inputs and outputs. Returns < 0 on error.
592 */
593static int
594normalize_datetime(int *year, int *month, int *day,
595 int *hour, int *minute, int *second,
596 int *microsecond)
597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 normalize_pair(second, microsecond, 1000000);
599 normalize_pair(minute, second, 60);
600 normalize_pair(hour, minute, 60);
601 normalize_pair(day, hour, 24);
602 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000603}
604
605/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000606 * Basic object allocation: tp_alloc implementations. These allocate
607 * Python objects of the right size and type, and do the Python object-
608 * initialization bit. If there's not enough memory, they return NULL after
609 * setting MemoryError. All data members remain uninitialized trash.
610 *
611 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000612 * member is needed. This is ugly, imprecise, and possibly insecure.
613 * tp_basicsize for the time and datetime types is set to the size of the
614 * struct that has room for the tzinfo member, so subclasses in Python will
615 * allocate enough space for a tzinfo member whether or not one is actually
616 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
617 * part is that PyType_GenericAlloc() (which subclasses in Python end up
618 * using) just happens today to effectively ignore the nitems argument
619 * when tp_itemsize is 0, which it is for these type objects. If that
620 * changes, perhaps the callers of tp_alloc slots in this file should
621 * be changed to force a 0 nitems argument unless the type being allocated
622 * is a base type implemented in this file (so that tp_alloc is time_alloc
623 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000624 */
625
626static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000627time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 self = (PyObject *)
632 PyObject_MALLOC(aware ?
633 sizeof(PyDateTime_Time) :
634 sizeof(_PyDateTime_BaseTime));
635 if (self == NULL)
636 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100637 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000639}
640
641static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000642datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 self = (PyObject *)
647 PyObject_MALLOC(aware ?
648 sizeof(PyDateTime_DateTime) :
649 sizeof(_PyDateTime_BaseDateTime));
650 if (self == NULL)
651 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100652 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000654}
655
656/* ---------------------------------------------------------------------------
657 * Helpers for setting object fields. These work on pointers to the
658 * appropriate base class.
659 */
660
661/* For date and datetime. */
662static void
663set_date_fields(PyDateTime_Date *self, int y, int m, int d)
664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 self->hashcode = -1;
666 SET_YEAR(self, y);
667 SET_MONTH(self, m);
668 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000669}
670
671/* ---------------------------------------------------------------------------
672 * Create various objects, mostly without range checking.
673 */
674
675/* Create a date instance with no range checking. */
676static PyObject *
677new_date_ex(int year, int month, int day, PyTypeObject *type)
678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
682 if (self != NULL)
683 set_date_fields(self, year, month, day);
684 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000685}
686
687#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000689
690/* Create a datetime instance with no range checking. */
691static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400692new_datetime_ex2(int year, int month, int day, int hour, int minute,
693 int second, int usecond, PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 PyDateTime_DateTime *self;
696 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
699 if (self != NULL) {
700 self->hastzinfo = aware;
701 set_date_fields((PyDateTime_Date *)self, year, month, day);
702 DATE_SET_HOUR(self, hour);
703 DATE_SET_MINUTE(self, minute);
704 DATE_SET_SECOND(self, second);
705 DATE_SET_MICROSECOND(self, usecond);
706 if (aware) {
707 Py_INCREF(tzinfo);
708 self->tzinfo = tzinfo;
709 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400710 DATE_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 }
712 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000713}
714
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400715static PyObject *
716new_datetime_ex(int year, int month, int day, int hour, int minute,
717 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
718{
719 return new_datetime_ex2(year, month, day, hour, minute, second, usecond,
720 tzinfo, 0, type);
721}
722
723#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo, fold) \
724 new_datetime_ex2(y, m, d, hh, mm, ss, us, tzinfo, fold, \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000726
727/* Create a time instance with no range checking. */
728static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400729new_time_ex2(int hour, int minute, int second, int usecond,
730 PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyDateTime_Time *self;
733 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
736 if (self != NULL) {
737 self->hastzinfo = aware;
738 self->hashcode = -1;
739 TIME_SET_HOUR(self, hour);
740 TIME_SET_MINUTE(self, minute);
741 TIME_SET_SECOND(self, second);
742 TIME_SET_MICROSECOND(self, usecond);
743 if (aware) {
744 Py_INCREF(tzinfo);
745 self->tzinfo = tzinfo;
746 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400747 TIME_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 }
749 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000750}
751
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400752static PyObject *
753new_time_ex(int hour, int minute, int second, int usecond,
754 PyObject *tzinfo, PyTypeObject *type)
755{
756 return new_time_ex2(hour, minute, second, usecond, tzinfo, 0, type);
757}
758
759#define new_time(hh, mm, ss, us, tzinfo, fold) \
760 new_time_ex2(hh, mm, ss, us, tzinfo, fold, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000761
762/* Create a timedelta instance. Normalize the members iff normalize is
763 * true. Passing false is a speed optimization, if you know for sure
764 * that seconds and microseconds are already in their proper ranges. In any
765 * case, raises OverflowError and returns NULL if the normalized days is out
766 * of range).
767 */
768static PyObject *
769new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 if (normalize)
775 normalize_d_s_us(&days, &seconds, &microseconds);
776 assert(0 <= seconds && seconds < 24*3600);
777 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (check_delta_day_range(days) < 0)
780 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
783 if (self != NULL) {
784 self->hashcode = -1;
785 SET_TD_DAYS(self, days);
786 SET_TD_SECONDS(self, seconds);
787 SET_TD_MICROSECONDS(self, microseconds);
788 }
789 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000790}
791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792#define new_delta(d, s, us, normalize) \
793 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000794
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000795
796typedef struct
797{
798 PyObject_HEAD
799 PyObject *offset;
800 PyObject *name;
801} PyDateTime_TimeZone;
802
Victor Stinner6ced7c42011-03-21 18:15:42 +0100803/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000804static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya4415142012-06-08 12:33:09 -0400805/* The interned Epoch datetime instance */
806static PyObject *PyDateTime_Epoch;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +0000807
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000808/* Create new timezone instance checking offset range. This
809 function does not check the name argument. Caller must assure
810 that offset is a timedelta instance and name is either NULL
811 or a unicode object. */
812static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000813create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000814{
815 PyDateTime_TimeZone *self;
816 PyTypeObject *type = &PyDateTime_TimeZoneType;
817
818 assert(offset != NULL);
819 assert(PyDelta_Check(offset));
820 assert(name == NULL || PyUnicode_Check(name));
821
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000822 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
823 if (self == NULL) {
824 return NULL;
825 }
826 Py_INCREF(offset);
827 self->offset = offset;
828 Py_XINCREF(name);
829 self->name = name;
830 return (PyObject *)self;
831}
832
833static int delta_bool(PyDateTime_Delta *self);
834
835static PyObject *
836new_timezone(PyObject *offset, PyObject *name)
837{
838 assert(offset != NULL);
839 assert(PyDelta_Check(offset));
840 assert(name == NULL || PyUnicode_Check(name));
841
842 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
843 Py_INCREF(PyDateTime_TimeZone_UTC);
844 return PyDateTime_TimeZone_UTC;
845 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000846 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
847 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400848 " representing a whole number of minutes,"
849 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000850 return NULL;
851 }
852 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
853 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
854 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
855 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400856 " timedelta(hours=24),"
857 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000858 return NULL;
859 }
860
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000861 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000862}
863
Tim Petersb0c854d2003-05-17 15:57:00 +0000864/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000865 * tzinfo helpers.
866 */
867
Tim Peters855fe882002-12-22 03:43:39 +0000868/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
869 * raise TypeError and return -1.
870 */
871static int
872check_tzinfo_subclass(PyObject *p)
873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (p == Py_None || PyTZInfo_Check(p))
875 return 0;
876 PyErr_Format(PyExc_TypeError,
877 "tzinfo argument must be None or of a tzinfo subclass, "
878 "not type '%s'",
879 Py_TYPE(p)->tp_name);
880 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000881}
882
Tim Peters2a799bf2002-12-16 20:18:38 +0000883/* If self has a tzinfo member, return a BORROWED reference to it. Else
884 * return NULL, which is NOT AN ERROR. There are no error returns here,
885 * and the caller must not decref the result.
886 */
887static PyObject *
888get_tzinfo_member(PyObject *self)
889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (PyDateTime_Check(self) && HASTZINFO(self))
893 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
894 else if (PyTime_Check(self) && HASTZINFO(self))
895 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000898}
899
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000900/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
901 * be an instance of the tzinfo class. If the method returns None, this
902 * returns None. If the method doesn't return None or timedelta, TypeError is
903 * raised and this returns NULL. If it returns a timedelta and the value is
904 * out of range or isn't a whole number of minutes, ValueError is raised and
905 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000906 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000907static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200908call_tzinfo_method(PyObject *tzinfo, const char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000909{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000910 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000913 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000915
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000916 if (tzinfo == Py_None)
917 Py_RETURN_NONE;
918 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
919 if (offset == Py_None || offset == NULL)
920 return offset;
921 if (PyDelta_Check(offset)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400922 if (GET_TD_MICROSECONDS(offset) != 0) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000923 Py_DECREF(offset);
924 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400925 " representing a whole number of seconds");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000926 return NULL;
927 }
928 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
929 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
930 Py_DECREF(offset);
931 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
932 " strictly between -timedelta(hours=24) and"
933 " timedelta(hours=24).");
934 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 }
936 }
937 else {
938 PyErr_Format(PyExc_TypeError,
939 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000940 "timedelta, not '%.200s'",
941 name, Py_TYPE(offset)->tp_name);
Raymond Hettinger5a2146a2014-07-25 14:59:48 -0700942 Py_DECREF(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000943 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000945
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000946 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000947}
948
949/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
950 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
951 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000952 * doesn't return None or timedelta, TypeError is raised and this returns -1.
953 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
954 * # of minutes), ValueError is raised and this returns -1. Else *none is
955 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000956 */
Tim Peters855fe882002-12-22 03:43:39 +0000957static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000958call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
959{
960 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000961}
962
Tim Peters2a799bf2002-12-16 20:18:38 +0000963/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
964 * result. tzinfo must be an instance of the tzinfo class. If dst()
965 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000966 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000967 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000968 * ValueError is raised and this returns -1. Else *none is set to 0 and
969 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000970 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000971static PyObject *
972call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000973{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000974 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000975}
976
Tim Petersbad8ff02002-12-30 20:52:32 +0000977/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000978 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000979 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000980 * returns NULL. If the result is a string, we ensure it is a Unicode
981 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000982 */
983static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000984call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200987 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 assert(tzinfo != NULL);
990 assert(check_tzinfo_subclass(tzinfo) >= 0);
991 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000994 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +0000995
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200996 result = _PyObject_CallMethodId(tzinfo, &PyId_tzname, "O", tzinfoarg);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000997
998 if (result == NULL || result == Py_None)
999 return result;
1000
1001 if (!PyUnicode_Check(result)) {
1002 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
1003 "return None or a string, not '%s'",
1004 Py_TYPE(result)->tp_name);
1005 Py_DECREF(result);
1006 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001008
1009 return result;
Tim Peters00237032002-12-27 02:21:51 +00001010}
1011
Tim Peters2a799bf2002-12-16 20:18:38 +00001012/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1013 * stuff
1014 * ", tzinfo=" + repr(tzinfo)
1015 * before the closing ")".
1016 */
1017static PyObject *
1018append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 assert(PyUnicode_Check(repr));
1023 assert(tzinfo);
1024 if (tzinfo == Py_None)
1025 return repr;
1026 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001027 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1028 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 Py_DECREF(repr);
1030 if (temp == NULL)
1031 return NULL;
1032 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1033 Py_DECREF(temp);
1034 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001035}
1036
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001037/* repr is like "someclass(arg1, arg2)". If fold isn't 0,
1038 * stuff
1039 * ", fold=" + repr(tzinfo)
1040 * before the closing ")".
1041 */
1042static PyObject *
1043append_keyword_fold(PyObject *repr, int fold)
1044{
1045 PyObject *temp;
1046
1047 assert(PyUnicode_Check(repr));
1048 if (fold == 0)
1049 return repr;
1050 /* Get rid of the trailing ')'. */
1051 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1052 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
1053 Py_DECREF(repr);
1054 if (temp == NULL)
1055 return NULL;
1056 repr = PyUnicode_FromFormat("%U, fold=%d)", temp, fold);
1057 Py_DECREF(temp);
1058 return repr;
1059}
1060
Tim Peters2a799bf2002-12-16 20:18:38 +00001061/* ---------------------------------------------------------------------------
1062 * String format helpers.
1063 */
1064
1065static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001066format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001067{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001068 static const char * const DayNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1070 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001071 static const char * const MonthNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1073 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1074 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1079 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1080 GET_DAY(date), hours, minutes, seconds,
1081 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001082}
1083
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001084static PyObject *delta_negative(PyDateTime_Delta *self);
1085
Tim Peters2a799bf2002-12-16 20:18:38 +00001086/* Add an hours & minutes UTC offset string to buf. buf has no more than
1087 * buflen bytes remaining. The UTC offset is gotten by calling
1088 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1089 * *buf, and that's all. Else the returned value is checked for sanity (an
1090 * integer in range), and if that's OK it's converted to an hours & minutes
1091 * string of the form
1092 * sign HH sep MM
1093 * Returns 0 if everything is OK. If the return value from utcoffset() is
1094 * bogus, an appropriate exception is set and -1 is returned.
1095 */
1096static int
Tim Peters328fff72002-12-20 01:31:27 +00001097format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001099{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001100 PyObject *offset;
1101 int hours, minutes, seconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001105
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001106 offset = call_utcoffset(tzinfo, tzinfoarg);
1107 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001109 if (offset == Py_None) {
1110 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 *buf = '\0';
1112 return 0;
1113 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001114 /* Offset is normalized, so it is negative if days < 0 */
1115 if (GET_TD_DAYS(offset) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 sign = '-';
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03001117 Py_SETREF(offset, delta_negative((PyDateTime_Delta *)offset));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001118 if (offset == NULL)
1119 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001121 else {
1122 sign = '+';
1123 }
1124 /* Offset is not negative here. */
1125 seconds = GET_TD_SECONDS(offset);
1126 Py_DECREF(offset);
1127 minutes = divmod(seconds, 60, &seconds);
1128 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001129 if (seconds == 0)
1130 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1131 else
1132 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d", sign, hours,
1133 sep, minutes, sep, seconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001135}
1136
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001137static PyObject *
1138make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyObject *temp;
1141 PyObject *tzinfo = get_tzinfo_member(object);
1142 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001143 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (Zreplacement == NULL)
1146 return NULL;
1147 if (tzinfo == Py_None || tzinfo == NULL)
1148 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 assert(tzinfoarg != NULL);
1151 temp = call_tzname(tzinfo, tzinfoarg);
1152 if (temp == NULL)
1153 goto Error;
1154 if (temp == Py_None) {
1155 Py_DECREF(temp);
1156 return Zreplacement;
1157 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 assert(PyUnicode_Check(temp));
1160 /* Since the tzname is getting stuffed into the
1161 * format, we have to double any % signs so that
1162 * strftime doesn't treat them as format codes.
1163 */
1164 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001165 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 Py_DECREF(temp);
1167 if (Zreplacement == NULL)
1168 return NULL;
1169 if (!PyUnicode_Check(Zreplacement)) {
1170 PyErr_SetString(PyExc_TypeError,
1171 "tzname.replace() did not return a string");
1172 goto Error;
1173 }
1174 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001175
1176 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 Py_DECREF(Zreplacement);
1178 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001179}
1180
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001181static PyObject *
1182make_freplacement(PyObject *object)
1183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 char freplacement[64];
1185 if (PyTime_Check(object))
1186 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1187 else if (PyDateTime_Check(object))
1188 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1189 else
1190 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001193}
1194
Tim Peters2a799bf2002-12-16 20:18:38 +00001195/* I sure don't want to reproduce the strftime code from the time module,
1196 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001197 * giving special meanings to the %z, %Z and %f format codes via a
1198 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001199 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1200 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001201 */
1202static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001203wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1209 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1210 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 const char *pin; /* pointer to next char in input format */
1213 Py_ssize_t flen; /* length of input format */
1214 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyObject *newfmt = NULL; /* py string, the output format */
1217 char *pnew; /* pointer to available byte in output format */
1218 size_t totalnew; /* number bytes total in output format buffer,
1219 exclusive of trailing \0 */
1220 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 const char *ptoappend; /* ptr to string to append to output buffer */
1223 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 assert(object && format && timetuple);
1226 assert(PyUnicode_Check(format));
1227 /* Convert the input format to a C string and size */
1228 pin = _PyUnicode_AsStringAndSize(format, &flen);
1229 if (!pin)
1230 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 /* Scan the input format, looking for %z/%Z/%f escapes, building
1233 * a new format. Since computing the replacements for those codes
1234 * is expensive, don't unless they're actually used.
1235 */
1236 if (flen > INT_MAX - 1) {
1237 PyErr_NoMemory();
1238 goto Done;
1239 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 totalnew = flen + 1; /* realistic if no %z/%Z */
1242 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1243 if (newfmt == NULL) goto Done;
1244 pnew = PyBytes_AsString(newfmt);
1245 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 while ((ch = *pin++) != '\0') {
1248 if (ch != '%') {
1249 ptoappend = pin - 1;
1250 ntoappend = 1;
1251 }
1252 else if ((ch = *pin++) == '\0') {
1253 /* There's a lone trailing %; doesn't make sense. */
1254 PyErr_SetString(PyExc_ValueError, "strftime format "
1255 "ends with raw %");
1256 goto Done;
1257 }
1258 /* A % has been seen and ch is the character after it. */
1259 else if (ch == 'z') {
1260 if (zreplacement == NULL) {
1261 /* format utcoffset */
1262 char buf[100];
1263 PyObject *tzinfo = get_tzinfo_member(object);
1264 zreplacement = PyBytes_FromStringAndSize("", 0);
1265 if (zreplacement == NULL) goto Done;
1266 if (tzinfo != Py_None && tzinfo != NULL) {
1267 assert(tzinfoarg != NULL);
1268 if (format_utcoffset(buf,
1269 sizeof(buf),
1270 "",
1271 tzinfo,
1272 tzinfoarg) < 0)
1273 goto Done;
1274 Py_DECREF(zreplacement);
1275 zreplacement =
1276 PyBytes_FromStringAndSize(buf,
1277 strlen(buf));
1278 if (zreplacement == NULL)
1279 goto Done;
1280 }
1281 }
1282 assert(zreplacement != NULL);
1283 ptoappend = PyBytes_AS_STRING(zreplacement);
1284 ntoappend = PyBytes_GET_SIZE(zreplacement);
1285 }
1286 else if (ch == 'Z') {
1287 /* format tzname */
1288 if (Zreplacement == NULL) {
1289 Zreplacement = make_Zreplacement(object,
1290 tzinfoarg);
1291 if (Zreplacement == NULL)
1292 goto Done;
1293 }
1294 assert(Zreplacement != NULL);
1295 assert(PyUnicode_Check(Zreplacement));
1296 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1297 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001298 if (ptoappend == NULL)
1299 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 }
1301 else if (ch == 'f') {
1302 /* format microseconds */
1303 if (freplacement == NULL) {
1304 freplacement = make_freplacement(object);
1305 if (freplacement == NULL)
1306 goto Done;
1307 }
1308 assert(freplacement != NULL);
1309 assert(PyBytes_Check(freplacement));
1310 ptoappend = PyBytes_AS_STRING(freplacement);
1311 ntoappend = PyBytes_GET_SIZE(freplacement);
1312 }
1313 else {
1314 /* percent followed by neither z nor Z */
1315 ptoappend = pin - 2;
1316 ntoappend = 2;
1317 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 /* Append the ntoappend chars starting at ptoappend to
1320 * the new format.
1321 */
1322 if (ntoappend == 0)
1323 continue;
1324 assert(ptoappend != NULL);
1325 assert(ntoappend > 0);
1326 while (usednew + ntoappend > totalnew) {
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001327 if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyErr_NoMemory();
1329 goto Done;
1330 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001331 totalnew <<= 1;
1332 if (_PyBytes_Resize(&newfmt, totalnew) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 pnew = PyBytes_AsString(newfmt) + usednew;
1335 }
1336 memcpy(pnew, ptoappend, ntoappend);
1337 pnew += ntoappend;
1338 usednew += ntoappend;
1339 assert(usednew <= totalnew);
1340 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1343 goto Done;
1344 {
1345 PyObject *format;
1346 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (time == NULL)
1349 goto Done;
1350 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1351 if (format != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001352 result = _PyObject_CallMethodId(time, &PyId_strftime, "OO",
1353 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 Py_DECREF(format);
1355 }
1356 Py_DECREF(time);
1357 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001358 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 Py_XDECREF(freplacement);
1360 Py_XDECREF(zreplacement);
1361 Py_XDECREF(Zreplacement);
1362 Py_XDECREF(newfmt);
1363 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001364}
1365
Tim Peters2a799bf2002-12-16 20:18:38 +00001366/* ---------------------------------------------------------------------------
1367 * Wrap functions from the time module. These aren't directly available
1368 * from C. Perhaps they should be.
1369 */
1370
1371/* Call time.time() and return its result (a Python float). */
1372static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001373time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 PyObject *result = NULL;
1376 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001379 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001380
1381 result = _PyObject_CallMethodId(time, &PyId_time, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 Py_DECREF(time);
1383 }
1384 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001385}
1386
1387/* Build a time.struct_time. The weekday and day number are automatically
1388 * computed from the y,m,d args.
1389 */
1390static PyObject *
1391build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 PyObject *time;
1394 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 time = PyImport_ImportModuleNoBlock("time");
1397 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001398 _Py_IDENTIFIER(struct_time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001399
1400 result = _PyObject_CallMethodId(time, &PyId_struct_time,
1401 "((iiiiiiiii))",
1402 y, m, d,
1403 hh, mm, ss,
1404 weekday(y, m, d),
1405 days_before_month(y, m) + d,
1406 dstflag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 Py_DECREF(time);
1408 }
1409 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001410}
1411
1412/* ---------------------------------------------------------------------------
1413 * Miscellaneous helpers.
1414 */
1415
Mark Dickinsone94c6792009-02-02 20:36:42 +00001416/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001417 * The comparisons here all most naturally compute a cmp()-like result.
1418 * This little helper turns that into a bool result for rich comparisons.
1419 */
1420static PyObject *
1421diff_to_bool(int diff, int op)
1422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 PyObject *result;
1424 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 switch (op) {
1427 case Py_EQ: istrue = diff == 0; break;
1428 case Py_NE: istrue = diff != 0; break;
1429 case Py_LE: istrue = diff <= 0; break;
1430 case Py_GE: istrue = diff >= 0; break;
1431 case Py_LT: istrue = diff < 0; break;
1432 case Py_GT: istrue = diff > 0; break;
1433 default:
1434 assert(! "op unknown");
1435 istrue = 0; /* To shut up compiler */
1436 }
1437 result = istrue ? Py_True : Py_False;
1438 Py_INCREF(result);
1439 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001440}
1441
Tim Peters07534a62003-02-07 22:50:28 +00001442/* Raises a "can't compare" TypeError and returns NULL. */
1443static PyObject *
1444cmperror(PyObject *a, PyObject *b)
1445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyErr_Format(PyExc_TypeError,
1447 "can't compare %s to %s",
1448 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1449 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001450}
1451
Tim Peters2a799bf2002-12-16 20:18:38 +00001452/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001453 * Cached Python objects; these are set by the module init function.
1454 */
1455
1456/* Conversion factors. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04001457static PyObject *one = NULL; /* 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458static PyObject *us_per_ms = NULL; /* 1000 */
1459static PyObject *us_per_second = NULL; /* 1000000 */
1460static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001461static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
1462static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
1463static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
Tim Peters2a799bf2002-12-16 20:18:38 +00001464static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1465
Tim Peters2a799bf2002-12-16 20:18:38 +00001466/* ---------------------------------------------------------------------------
1467 * Class implementations.
1468 */
1469
1470/*
1471 * PyDateTime_Delta implementation.
1472 */
1473
1474/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Serhiy Storchaka95949422013-08-27 19:40:23 +03001476 * as a Python int.
Tim Peters2a799bf2002-12-16 20:18:38 +00001477 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1478 * due to ubiquitous overflow possibilities.
1479 */
1480static PyObject *
1481delta_to_microseconds(PyDateTime_Delta *self)
1482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyObject *x1 = NULL;
1484 PyObject *x2 = NULL;
1485 PyObject *x3 = NULL;
1486 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1489 if (x1 == NULL)
1490 goto Done;
1491 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1492 if (x2 == NULL)
1493 goto Done;
1494 Py_DECREF(x1);
1495 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 /* x2 has days in seconds */
1498 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1499 if (x1 == NULL)
1500 goto Done;
1501 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1502 if (x3 == NULL)
1503 goto Done;
1504 Py_DECREF(x1);
1505 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001506 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 /* x3 has days+seconds in seconds */
1509 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1510 if (x1 == NULL)
1511 goto Done;
1512 Py_DECREF(x3);
1513 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 /* x1 has days+seconds in us */
1516 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1517 if (x2 == NULL)
1518 goto Done;
1519 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001520
1521Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_XDECREF(x1);
1523 Py_XDECREF(x2);
1524 Py_XDECREF(x3);
1525 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001526}
1527
Serhiy Storchaka95949422013-08-27 19:40:23 +03001528/* Convert a number of us (as a Python int) to a timedelta.
Tim Peters2a799bf2002-12-16 20:18:38 +00001529 */
1530static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001531microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 int us;
1534 int s;
1535 int d;
1536 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 PyObject *tuple = NULL;
1539 PyObject *num = NULL;
1540 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 tuple = PyNumber_Divmod(pyus, us_per_second);
1543 if (tuple == NULL)
1544 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 num = PyTuple_GetItem(tuple, 1); /* us */
1547 if (num == NULL)
1548 goto Done;
1549 temp = PyLong_AsLong(num);
1550 num = NULL;
1551 if (temp == -1 && PyErr_Occurred())
1552 goto Done;
1553 assert(0 <= temp && temp < 1000000);
1554 us = (int)temp;
1555 if (us < 0) {
1556 /* The divisor was positive, so this must be an error. */
1557 assert(PyErr_Occurred());
1558 goto Done;
1559 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1562 if (num == NULL)
1563 goto Done;
1564 Py_INCREF(num);
1565 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 tuple = PyNumber_Divmod(num, seconds_per_day);
1568 if (tuple == NULL)
1569 goto Done;
1570 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 num = PyTuple_GetItem(tuple, 1); /* seconds */
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 < 24*3600);
1580 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (s < 0) {
1583 /* The divisor was positive, so this must be an error. */
1584 assert(PyErr_Occurred());
1585 goto Done;
1586 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1589 if (num == NULL)
1590 goto Done;
1591 Py_INCREF(num);
1592 temp = PyLong_AsLong(num);
1593 if (temp == -1 && PyErr_Occurred())
1594 goto Done;
1595 d = (int)temp;
1596 if ((long)d != temp) {
1597 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1598 "large to fit in a C int");
1599 goto Done;
1600 }
1601 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001602
1603Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 Py_XDECREF(tuple);
1605 Py_XDECREF(num);
1606 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001607}
1608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609#define microseconds_to_delta(pymicros) \
1610 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001611
Tim Peters2a799bf2002-12-16 20:18:38 +00001612static PyObject *
1613multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 PyObject *pyus_in;
1616 PyObject *pyus_out;
1617 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 pyus_in = delta_to_microseconds(delta);
1620 if (pyus_in == NULL)
1621 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1624 Py_DECREF(pyus_in);
1625 if (pyus_out == NULL)
1626 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 result = microseconds_to_delta(pyus_out);
1629 Py_DECREF(pyus_out);
1630 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001631}
1632
1633static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001634multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1635{
1636 PyObject *result = NULL;
1637 PyObject *pyus_in = NULL, *temp, *pyus_out;
1638 PyObject *ratio = NULL;
1639
1640 pyus_in = delta_to_microseconds(delta);
1641 if (pyus_in == NULL)
1642 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001643 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001644 if (ratio == NULL)
1645 goto error;
1646 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1647 Py_DECREF(pyus_in);
1648 pyus_in = NULL;
1649 if (temp == NULL)
1650 goto error;
1651 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1652 Py_DECREF(temp);
1653 if (pyus_out == NULL)
1654 goto error;
1655 result = microseconds_to_delta(pyus_out);
1656 Py_DECREF(pyus_out);
1657 error:
1658 Py_XDECREF(pyus_in);
1659 Py_XDECREF(ratio);
1660
1661 return result;
1662}
1663
1664static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001665divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 PyObject *pyus_in;
1668 PyObject *pyus_out;
1669 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 pyus_in = delta_to_microseconds(delta);
1672 if (pyus_in == NULL)
1673 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1676 Py_DECREF(pyus_in);
1677 if (pyus_out == NULL)
1678 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 result = microseconds_to_delta(pyus_out);
1681 Py_DECREF(pyus_out);
1682 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001683}
1684
1685static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001686divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyObject *pyus_left;
1689 PyObject *pyus_right;
1690 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 pyus_left = delta_to_microseconds(left);
1693 if (pyus_left == NULL)
1694 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 pyus_right = delta_to_microseconds(right);
1697 if (pyus_right == NULL) {
1698 Py_DECREF(pyus_left);
1699 return NULL;
1700 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1703 Py_DECREF(pyus_left);
1704 Py_DECREF(pyus_right);
1705 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001706}
1707
1708static PyObject *
1709truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 PyObject *pyus_left;
1712 PyObject *pyus_right;
1713 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 pyus_left = delta_to_microseconds(left);
1716 if (pyus_left == NULL)
1717 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 pyus_right = delta_to_microseconds(right);
1720 if (pyus_right == NULL) {
1721 Py_DECREF(pyus_left);
1722 return NULL;
1723 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1726 Py_DECREF(pyus_left);
1727 Py_DECREF(pyus_right);
1728 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001729}
1730
1731static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001732truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1733{
1734 PyObject *result = NULL;
1735 PyObject *pyus_in = NULL, *temp, *pyus_out;
1736 PyObject *ratio = NULL;
1737
1738 pyus_in = delta_to_microseconds(delta);
1739 if (pyus_in == NULL)
1740 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001741 ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001742 if (ratio == NULL)
1743 goto error;
1744 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1745 Py_DECREF(pyus_in);
1746 pyus_in = NULL;
1747 if (temp == NULL)
1748 goto error;
1749 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1750 Py_DECREF(temp);
1751 if (pyus_out == NULL)
1752 goto error;
1753 result = microseconds_to_delta(pyus_out);
1754 Py_DECREF(pyus_out);
1755 error:
1756 Py_XDECREF(pyus_in);
1757 Py_XDECREF(ratio);
1758
1759 return result;
1760}
1761
1762static PyObject *
1763truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1764{
1765 PyObject *result;
1766 PyObject *pyus_in, *pyus_out;
1767 pyus_in = delta_to_microseconds(delta);
1768 if (pyus_in == NULL)
1769 return NULL;
1770 pyus_out = divide_nearest(pyus_in, i);
1771 Py_DECREF(pyus_in);
1772 if (pyus_out == NULL)
1773 return NULL;
1774 result = microseconds_to_delta(pyus_out);
1775 Py_DECREF(pyus_out);
1776
1777 return result;
1778}
1779
1780static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001781delta_add(PyObject *left, PyObject *right)
1782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1786 /* delta + delta */
1787 /* The C-level additions can't overflow because of the
1788 * invariant bounds.
1789 */
1790 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1791 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1792 int microseconds = GET_TD_MICROSECONDS(left) +
1793 GET_TD_MICROSECONDS(right);
1794 result = new_delta(days, seconds, microseconds, 1);
1795 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 if (result == Py_NotImplemented)
1798 Py_INCREF(result);
1799 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001800}
1801
1802static PyObject *
1803delta_negative(PyDateTime_Delta *self)
1804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 return new_delta(-GET_TD_DAYS(self),
1806 -GET_TD_SECONDS(self),
1807 -GET_TD_MICROSECONDS(self),
1808 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001809}
1810
1811static PyObject *
1812delta_positive(PyDateTime_Delta *self)
1813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 /* Could optimize this (by returning self) if this isn't a
1815 * subclass -- but who uses unary + ? Approximately nobody.
1816 */
1817 return new_delta(GET_TD_DAYS(self),
1818 GET_TD_SECONDS(self),
1819 GET_TD_MICROSECONDS(self),
1820 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001821}
1822
1823static PyObject *
1824delta_abs(PyDateTime_Delta *self)
1825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 assert(GET_TD_MICROSECONDS(self) >= 0);
1829 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (GET_TD_DAYS(self) < 0)
1832 result = delta_negative(self);
1833 else
1834 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001837}
1838
1839static PyObject *
1840delta_subtract(PyObject *left, PyObject *right)
1841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1845 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04001846 /* The C-level additions can't overflow because of the
1847 * invariant bounds.
1848 */
1849 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1850 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1851 int microseconds = GET_TD_MICROSECONDS(left) -
1852 GET_TD_MICROSECONDS(right);
1853 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 if (result == Py_NotImplemented)
1857 Py_INCREF(result);
1858 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001859}
1860
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001861static int
1862delta_cmp(PyObject *self, PyObject *other)
1863{
1864 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1865 if (diff == 0) {
1866 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1867 if (diff == 0)
1868 diff = GET_TD_MICROSECONDS(self) -
1869 GET_TD_MICROSECONDS(other);
1870 }
1871 return diff;
1872}
1873
Tim Peters2a799bf2002-12-16 20:18:38 +00001874static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001875delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001878 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 return diff_to_bool(diff, op);
1880 }
1881 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05001882 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001884}
1885
1886static PyObject *delta_getstate(PyDateTime_Delta *self);
1887
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001888static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001889delta_hash(PyDateTime_Delta *self)
1890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 if (self->hashcode == -1) {
1892 PyObject *temp = delta_getstate(self);
1893 if (temp != NULL) {
1894 self->hashcode = PyObject_Hash(temp);
1895 Py_DECREF(temp);
1896 }
1897 }
1898 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001899}
1900
1901static PyObject *
1902delta_multiply(PyObject *left, PyObject *right)
1903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 if (PyDelta_Check(left)) {
1907 /* delta * ??? */
1908 if (PyLong_Check(right))
1909 result = multiply_int_timedelta(right,
1910 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001911 else if (PyFloat_Check(right))
1912 result = multiply_float_timedelta(right,
1913 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 }
1915 else if (PyLong_Check(left))
1916 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001917 (PyDateTime_Delta *) right);
1918 else if (PyFloat_Check(left))
1919 result = multiply_float_timedelta(left,
1920 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 if (result == Py_NotImplemented)
1923 Py_INCREF(result);
1924 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001925}
1926
1927static PyObject *
1928delta_divide(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 = divide_timedelta_int(
1936 (PyDateTime_Delta *)left,
1937 right);
1938 else if (PyDelta_Check(right))
1939 result = divide_timedelta_timedelta(
1940 (PyDateTime_Delta *)left,
1941 (PyDateTime_Delta *)right);
1942 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 if (result == Py_NotImplemented)
1945 Py_INCREF(result);
1946 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001947}
1948
Mark Dickinson7c186e22010-04-20 22:32:49 +00001949static PyObject *
1950delta_truedivide(PyObject *left, PyObject *right)
1951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 if (PyDelta_Check(left)) {
1955 if (PyDelta_Check(right))
1956 result = truedivide_timedelta_timedelta(
1957 (PyDateTime_Delta *)left,
1958 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001959 else if (PyFloat_Check(right))
1960 result = truedivide_timedelta_float(
1961 (PyDateTime_Delta *)left, right);
1962 else if (PyLong_Check(right))
1963 result = truedivide_timedelta_int(
1964 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 if (result == Py_NotImplemented)
1968 Py_INCREF(result);
1969 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001970}
1971
1972static PyObject *
1973delta_remainder(PyObject *left, PyObject *right)
1974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 PyObject *pyus_left;
1976 PyObject *pyus_right;
1977 PyObject *pyus_remainder;
1978 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001979
Brian Curtindfc80e32011-08-10 20:28:54 -05001980 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1981 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1984 if (pyus_left == NULL)
1985 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1988 if (pyus_right == NULL) {
1989 Py_DECREF(pyus_left);
1990 return NULL;
1991 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
1994 Py_DECREF(pyus_left);
1995 Py_DECREF(pyus_right);
1996 if (pyus_remainder == NULL)
1997 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 remainder = microseconds_to_delta(pyus_remainder);
2000 Py_DECREF(pyus_remainder);
2001 if (remainder == NULL)
2002 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002005}
2006
2007static PyObject *
2008delta_divmod(PyObject *left, PyObject *right)
2009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 PyObject *pyus_left;
2011 PyObject *pyus_right;
2012 PyObject *divmod;
2013 PyObject *delta;
2014 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002015
Brian Curtindfc80e32011-08-10 20:28:54 -05002016 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2017 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2020 if (pyus_left == NULL)
2021 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2024 if (pyus_right == NULL) {
2025 Py_DECREF(pyus_left);
2026 return NULL;
2027 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 divmod = PyNumber_Divmod(pyus_left, pyus_right);
2030 Py_DECREF(pyus_left);
2031 Py_DECREF(pyus_right);
2032 if (divmod == NULL)
2033 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 assert(PyTuple_Size(divmod) == 2);
2036 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
2037 if (delta == NULL) {
2038 Py_DECREF(divmod);
2039 return NULL;
2040 }
2041 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
2042 Py_DECREF(delta);
2043 Py_DECREF(divmod);
2044 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002045}
2046
Tim Peters2a799bf2002-12-16 20:18:38 +00002047/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2048 * timedelta constructor. sofar is the # of microseconds accounted for
2049 * so far, and there are factor microseconds per current unit, the number
2050 * of which is given by num. num * factor is added to sofar in a
2051 * numerically careful way, and that's the result. Any fractional
2052 * microseconds left over (this can happen if num is a float type) are
2053 * added into *leftover.
2054 * Note that there are many ways this can give an error (NULL) return.
2055 */
2056static PyObject *
2057accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2058 double *leftover)
2059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyObject *prod;
2061 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (PyLong_Check(num)) {
2066 prod = PyNumber_Multiply(num, factor);
2067 if (prod == NULL)
2068 return NULL;
2069 sum = PyNumber_Add(sofar, prod);
2070 Py_DECREF(prod);
2071 return sum;
2072 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 if (PyFloat_Check(num)) {
2075 double dnum;
2076 double fracpart;
2077 double intpart;
2078 PyObject *x;
2079 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 /* The Plan: decompose num into an integer part and a
2082 * fractional part, num = intpart + fracpart.
2083 * Then num * factor ==
2084 * intpart * factor + fracpart * factor
2085 * and the LHS can be computed exactly in long arithmetic.
2086 * The RHS is again broken into an int part and frac part.
2087 * and the frac part is added into *leftover.
2088 */
2089 dnum = PyFloat_AsDouble(num);
2090 if (dnum == -1.0 && PyErr_Occurred())
2091 return NULL;
2092 fracpart = modf(dnum, &intpart);
2093 x = PyLong_FromDouble(intpart);
2094 if (x == NULL)
2095 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 prod = PyNumber_Multiply(x, factor);
2098 Py_DECREF(x);
2099 if (prod == NULL)
2100 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 sum = PyNumber_Add(sofar, prod);
2103 Py_DECREF(prod);
2104 if (sum == NULL)
2105 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (fracpart == 0.0)
2108 return sum;
2109 /* So far we've lost no information. Dealing with the
2110 * fractional part requires float arithmetic, and may
2111 * lose a little info.
2112 */
2113 assert(PyLong_Check(factor));
2114 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 dnum *= fracpart;
2117 fracpart = modf(dnum, &intpart);
2118 x = PyLong_FromDouble(intpart);
2119 if (x == NULL) {
2120 Py_DECREF(sum);
2121 return NULL;
2122 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 y = PyNumber_Add(sum, x);
2125 Py_DECREF(sum);
2126 Py_DECREF(x);
2127 *leftover += fracpart;
2128 return y;
2129 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 PyErr_Format(PyExc_TypeError,
2132 "unsupported type for timedelta %s component: %s",
2133 tag, Py_TYPE(num)->tp_name);
2134 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002135}
2136
2137static PyObject *
2138delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 /* Argument objects. */
2143 PyObject *day = NULL;
2144 PyObject *second = NULL;
2145 PyObject *us = NULL;
2146 PyObject *ms = NULL;
2147 PyObject *minute = NULL;
2148 PyObject *hour = NULL;
2149 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 PyObject *x = NULL; /* running sum of microseconds */
2152 PyObject *y = NULL; /* temp sum of microseconds */
2153 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 static char *keywords[] = {
2156 "days", "seconds", "microseconds", "milliseconds",
2157 "minutes", "hours", "weeks", NULL
2158 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2161 keywords,
2162 &day, &second, &us,
2163 &ms, &minute, &hour, &week) == 0)
2164 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 x = PyLong_FromLong(0);
2167 if (x == NULL)
2168 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170#define CLEANUP \
2171 Py_DECREF(x); \
2172 x = y; \
2173 if (x == NULL) \
2174 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (us) {
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002177 y = accum("microseconds", x, us, one, &leftover_us);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 CLEANUP;
2179 }
2180 if (ms) {
2181 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2182 CLEANUP;
2183 }
2184 if (second) {
2185 y = accum("seconds", x, second, us_per_second, &leftover_us);
2186 CLEANUP;
2187 }
2188 if (minute) {
2189 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2190 CLEANUP;
2191 }
2192 if (hour) {
2193 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2194 CLEANUP;
2195 }
2196 if (day) {
2197 y = accum("days", x, day, us_per_day, &leftover_us);
2198 CLEANUP;
2199 }
2200 if (week) {
2201 y = accum("weeks", x, week, us_per_week, &leftover_us);
2202 CLEANUP;
2203 }
2204 if (leftover_us) {
2205 /* Round to nearest whole # of us, and add into x. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002206 double whole_us = round(leftover_us);
Victor Stinner69cc4872015-09-08 23:58:54 +02002207 int x_is_odd;
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002208 PyObject *temp;
2209
Victor Stinner69cc4872015-09-08 23:58:54 +02002210 whole_us = round(leftover_us);
2211 if (fabs(whole_us - leftover_us) == 0.5) {
2212 /* We're exactly halfway between two integers. In order
2213 * to do round-half-to-even, we must determine whether x
2214 * is odd. Note that x is odd when it's last bit is 1. The
2215 * code below uses bitwise and operation to check the last
2216 * bit. */
2217 temp = PyNumber_And(x, one); /* temp <- x & 1 */
2218 if (temp == NULL) {
2219 Py_DECREF(x);
2220 goto Done;
2221 }
2222 x_is_odd = PyObject_IsTrue(temp);
2223 Py_DECREF(temp);
2224 if (x_is_odd == -1) {
2225 Py_DECREF(x);
2226 goto Done;
2227 }
2228 whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2229 }
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002230
Victor Stinner36a5a062013-08-28 01:53:39 +02002231 temp = PyLong_FromLong((long)whole_us);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 if (temp == NULL) {
2234 Py_DECREF(x);
2235 goto Done;
2236 }
2237 y = PyNumber_Add(x, temp);
2238 Py_DECREF(temp);
2239 CLEANUP;
2240 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 self = microseconds_to_delta_ex(x, type);
2243 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002244Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002246
2247#undef CLEANUP
2248}
2249
2250static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002251delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 return (GET_TD_DAYS(self) != 0
2254 || GET_TD_SECONDS(self) != 0
2255 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002256}
2257
2258static PyObject *
2259delta_repr(PyDateTime_Delta *self)
2260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 if (GET_TD_MICROSECONDS(self) != 0)
2262 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2263 Py_TYPE(self)->tp_name,
2264 GET_TD_DAYS(self),
2265 GET_TD_SECONDS(self),
2266 GET_TD_MICROSECONDS(self));
2267 if (GET_TD_SECONDS(self) != 0)
2268 return PyUnicode_FromFormat("%s(%d, %d)",
2269 Py_TYPE(self)->tp_name,
2270 GET_TD_DAYS(self),
2271 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 return PyUnicode_FromFormat("%s(%d)",
2274 Py_TYPE(self)->tp_name,
2275 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002276}
2277
2278static PyObject *
2279delta_str(PyDateTime_Delta *self)
2280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 int us = GET_TD_MICROSECONDS(self);
2282 int seconds = GET_TD_SECONDS(self);
2283 int minutes = divmod(seconds, 60, &seconds);
2284 int hours = divmod(minutes, 60, &minutes);
2285 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (days) {
2288 if (us)
2289 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2290 days, (days == 1 || days == -1) ? "" : "s",
2291 hours, minutes, seconds, us);
2292 else
2293 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2294 days, (days == 1 || days == -1) ? "" : "s",
2295 hours, minutes, seconds);
2296 } else {
2297 if (us)
2298 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2299 hours, minutes, seconds, us);
2300 else
2301 return PyUnicode_FromFormat("%d:%02d:%02d",
2302 hours, minutes, seconds);
2303 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002304
Tim Peters2a799bf2002-12-16 20:18:38 +00002305}
2306
Tim Peters371935f2003-02-01 01:52:50 +00002307/* Pickle support, a simple use of __reduce__. */
2308
Tim Petersb57f8f02003-02-01 02:54:15 +00002309/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002310static PyObject *
2311delta_getstate(PyDateTime_Delta *self)
2312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 return Py_BuildValue("iii", GET_TD_DAYS(self),
2314 GET_TD_SECONDS(self),
2315 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002316}
2317
Tim Peters2a799bf2002-12-16 20:18:38 +00002318static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002319delta_total_seconds(PyObject *self)
2320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 PyObject *total_seconds;
2322 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2325 if (total_microseconds == NULL)
2326 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002327
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002328 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002332}
2333
2334static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002335delta_reduce(PyDateTime_Delta* self)
2336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002338}
2339
2340#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2341
2342static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 {"days", T_INT, OFFSET(days), READONLY,
2345 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 {"seconds", T_INT, OFFSET(seconds), READONLY,
2348 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2351 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2352 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002353};
2354
2355static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2357 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2360 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002363};
2364
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002365static const char delta_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00002366PyDoc_STR("Difference between two datetime values.");
2367
2368static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 delta_add, /* nb_add */
2370 delta_subtract, /* nb_subtract */
2371 delta_multiply, /* nb_multiply */
2372 delta_remainder, /* nb_remainder */
2373 delta_divmod, /* nb_divmod */
2374 0, /* nb_power */
2375 (unaryfunc)delta_negative, /* nb_negative */
2376 (unaryfunc)delta_positive, /* nb_positive */
2377 (unaryfunc)delta_abs, /* nb_absolute */
2378 (inquiry)delta_bool, /* nb_bool */
2379 0, /*nb_invert*/
2380 0, /*nb_lshift*/
2381 0, /*nb_rshift*/
2382 0, /*nb_and*/
2383 0, /*nb_xor*/
2384 0, /*nb_or*/
2385 0, /*nb_int*/
2386 0, /*nb_reserved*/
2387 0, /*nb_float*/
2388 0, /*nb_inplace_add*/
2389 0, /*nb_inplace_subtract*/
2390 0, /*nb_inplace_multiply*/
2391 0, /*nb_inplace_remainder*/
2392 0, /*nb_inplace_power*/
2393 0, /*nb_inplace_lshift*/
2394 0, /*nb_inplace_rshift*/
2395 0, /*nb_inplace_and*/
2396 0, /*nb_inplace_xor*/
2397 0, /*nb_inplace_or*/
2398 delta_divide, /* nb_floor_divide */
2399 delta_truedivide, /* nb_true_divide */
2400 0, /* nb_inplace_floor_divide */
2401 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002402};
2403
2404static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 PyVarObject_HEAD_INIT(NULL, 0)
2406 "datetime.timedelta", /* tp_name */
2407 sizeof(PyDateTime_Delta), /* tp_basicsize */
2408 0, /* tp_itemsize */
2409 0, /* tp_dealloc */
2410 0, /* tp_print */
2411 0, /* tp_getattr */
2412 0, /* tp_setattr */
2413 0, /* tp_reserved */
2414 (reprfunc)delta_repr, /* tp_repr */
2415 &delta_as_number, /* tp_as_number */
2416 0, /* tp_as_sequence */
2417 0, /* tp_as_mapping */
2418 (hashfunc)delta_hash, /* tp_hash */
2419 0, /* tp_call */
2420 (reprfunc)delta_str, /* tp_str */
2421 PyObject_GenericGetAttr, /* tp_getattro */
2422 0, /* tp_setattro */
2423 0, /* tp_as_buffer */
2424 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2425 delta_doc, /* tp_doc */
2426 0, /* tp_traverse */
2427 0, /* tp_clear */
2428 delta_richcompare, /* tp_richcompare */
2429 0, /* tp_weaklistoffset */
2430 0, /* tp_iter */
2431 0, /* tp_iternext */
2432 delta_methods, /* tp_methods */
2433 delta_members, /* tp_members */
2434 0, /* tp_getset */
2435 0, /* tp_base */
2436 0, /* tp_dict */
2437 0, /* tp_descr_get */
2438 0, /* tp_descr_set */
2439 0, /* tp_dictoffset */
2440 0, /* tp_init */
2441 0, /* tp_alloc */
2442 delta_new, /* tp_new */
2443 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002444};
2445
2446/*
2447 * PyDateTime_Date implementation.
2448 */
2449
2450/* Accessor properties. */
2451
2452static PyObject *
2453date_year(PyDateTime_Date *self, void *unused)
2454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002456}
2457
2458static PyObject *
2459date_month(PyDateTime_Date *self, void *unused)
2460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002462}
2463
2464static PyObject *
2465date_day(PyDateTime_Date *self, void *unused)
2466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002468}
2469
2470static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 {"year", (getter)date_year},
2472 {"month", (getter)date_month},
2473 {"day", (getter)date_day},
2474 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002475};
2476
2477/* Constructors. */
2478
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002479static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002480
Tim Peters2a799bf2002-12-16 20:18:38 +00002481static PyObject *
2482date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 PyObject *self = NULL;
2485 PyObject *state;
2486 int year;
2487 int month;
2488 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* Check for invocation from pickle with __getstate__ state */
2491 if (PyTuple_GET_SIZE(args) == 1 &&
2492 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2493 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2494 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2495 {
2496 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2499 if (me != NULL) {
2500 char *pdata = PyBytes_AS_STRING(state);
2501 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2502 me->hashcode = -1;
2503 }
2504 return (PyObject *)me;
2505 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2508 &year, &month, &day)) {
2509 if (check_date_args(year, month, day) < 0)
2510 return NULL;
2511 self = new_date_ex(year, month, day, type);
2512 }
2513 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002514}
2515
2516/* Return new date from localtime(t). */
2517static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002518date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 struct tm *tm;
2521 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002522
Victor Stinnere4a994d2015-03-30 01:10:14 +02002523 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 tm = localtime(&t);
Victor Stinner21f58932012-03-14 00:15:40 +01002527 if (tm == NULL) {
2528 /* unconvertible time */
2529#ifdef EINVAL
2530 if (errno == 0)
2531 errno = EINVAL;
2532#endif
2533 PyErr_SetFromErrno(PyExc_OSError);
2534 return NULL;
2535 }
2536
2537 return PyObject_CallFunction(cls, "iii",
2538 tm->tm_year + 1900,
2539 tm->tm_mon + 1,
2540 tm->tm_mday);
Tim Peters2a799bf2002-12-16 20:18:38 +00002541}
2542
2543/* Return new date from current time.
2544 * We say this is equivalent to fromtimestamp(time.time()), and the
2545 * only way to be sure of that is to *call* time.time(). That's not
2546 * generally the same as calling C's time.
2547 */
2548static PyObject *
2549date_today(PyObject *cls, PyObject *dummy)
2550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 PyObject *time;
2552 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002553 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 time = time_time();
2556 if (time == NULL)
2557 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 /* Note well: today() is a class method, so this may not call
2560 * date.fromtimestamp. For example, it may call
2561 * datetime.fromtimestamp. That's why we need all the accuracy
2562 * time.time() delivers; if someone were gonzo about optimization,
2563 * date.today() could get away with plain C time().
2564 */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002565 result = _PyObject_CallMethodId(cls, &PyId_fromtimestamp, "O", time);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 Py_DECREF(time);
2567 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002568}
2569
2570/* Return new date from given timestamp (Python timestamp -- a double). */
2571static PyObject *
2572date_fromtimestamp(PyObject *cls, PyObject *args)
2573{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002574 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002576
Victor Stinner5d272cc2012-03-13 13:35:55 +01002577 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2578 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002580}
2581
2582/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2583 * the ordinal is out of range.
2584 */
2585static PyObject *
2586date_fromordinal(PyObject *cls, PyObject *args)
2587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 PyObject *result = NULL;
2589 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2592 int year;
2593 int month;
2594 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 if (ordinal < 1)
2597 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2598 ">= 1");
2599 else {
2600 ord_to_ymd(ordinal, &year, &month, &day);
2601 result = PyObject_CallFunction(cls, "iii",
2602 year, month, day);
2603 }
2604 }
2605 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002606}
2607
2608/*
2609 * Date arithmetic.
2610 */
2611
2612/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2613 * instead.
2614 */
2615static PyObject *
2616add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 PyObject *result = NULL;
2619 int year = GET_YEAR(date);
2620 int month = GET_MONTH(date);
2621 int deltadays = GET_TD_DAYS(delta);
2622 /* C-level overflow is impossible because |deltadays| < 1e9. */
2623 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 if (normalize_date(&year, &month, &day) >= 0)
2626 result = new_date(year, month, day);
2627 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002628}
2629
2630static PyObject *
2631date_add(PyObject *left, PyObject *right)
2632{
Brian Curtindfc80e32011-08-10 20:28:54 -05002633 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2634 Py_RETURN_NOTIMPLEMENTED;
2635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 if (PyDate_Check(left)) {
2637 /* date + ??? */
2638 if (PyDelta_Check(right))
2639 /* date + delta */
2640 return add_date_timedelta((PyDateTime_Date *) left,
2641 (PyDateTime_Delta *) right,
2642 0);
2643 }
2644 else {
2645 /* ??? + date
2646 * 'right' must be one of us, or we wouldn't have been called
2647 */
2648 if (PyDelta_Check(left))
2649 /* delta + date */
2650 return add_date_timedelta((PyDateTime_Date *) right,
2651 (PyDateTime_Delta *) left,
2652 0);
2653 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002654 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002655}
2656
2657static PyObject *
2658date_subtract(PyObject *left, PyObject *right)
2659{
Brian Curtindfc80e32011-08-10 20:28:54 -05002660 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2661 Py_RETURN_NOTIMPLEMENTED;
2662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 if (PyDate_Check(left)) {
2664 if (PyDate_Check(right)) {
2665 /* date - date */
2666 int left_ord = ymd_to_ord(GET_YEAR(left),
2667 GET_MONTH(left),
2668 GET_DAY(left));
2669 int right_ord = ymd_to_ord(GET_YEAR(right),
2670 GET_MONTH(right),
2671 GET_DAY(right));
2672 return new_delta(left_ord - right_ord, 0, 0, 0);
2673 }
2674 if (PyDelta_Check(right)) {
2675 /* date - delta */
2676 return add_date_timedelta((PyDateTime_Date *) left,
2677 (PyDateTime_Delta *) right,
2678 1);
2679 }
2680 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002681 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002682}
2683
2684
2685/* Various ways to turn a date into a string. */
2686
2687static PyObject *
2688date_repr(PyDateTime_Date *self)
2689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2691 Py_TYPE(self)->tp_name,
2692 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002693}
2694
2695static PyObject *
2696date_isoformat(PyDateTime_Date *self)
2697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 return PyUnicode_FromFormat("%04d-%02d-%02d",
2699 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002700}
2701
Tim Peterse2df5ff2003-05-02 18:39:55 +00002702/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002703static PyObject *
2704date_str(PyDateTime_Date *self)
2705{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002706 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002707}
2708
2709
2710static PyObject *
2711date_ctime(PyDateTime_Date *self)
2712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002714}
2715
2716static PyObject *
2717date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 /* This method can be inherited, and needs to call the
2720 * timetuple() method appropriate to self's class.
2721 */
2722 PyObject *result;
2723 PyObject *tuple;
2724 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002725 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2729 &format))
2730 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002731
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002732 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 if (tuple == NULL)
2734 return NULL;
2735 result = wrap_strftime((PyObject *)self, format, tuple,
2736 (PyObject *)self);
2737 Py_DECREF(tuple);
2738 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002739}
2740
Eric Smith1ba31142007-09-11 18:06:02 +00002741static PyObject *
2742date_format(PyDateTime_Date *self, PyObject *args)
2743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2747 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002750 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002752
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002753 return _PyObject_CallMethodId((PyObject *)self, &PyId_strftime, "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002754}
2755
Tim Peters2a799bf2002-12-16 20:18:38 +00002756/* ISO methods. */
2757
2758static PyObject *
2759date_isoweekday(PyDateTime_Date *self)
2760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002764}
2765
2766static PyObject *
2767date_isocalendar(PyDateTime_Date *self)
2768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 int year = GET_YEAR(self);
2770 int week1_monday = iso_week1_monday(year);
2771 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2772 int week;
2773 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 week = divmod(today - week1_monday, 7, &day);
2776 if (week < 0) {
2777 --year;
2778 week1_monday = iso_week1_monday(year);
2779 week = divmod(today - week1_monday, 7, &day);
2780 }
2781 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2782 ++year;
2783 week = 0;
2784 }
2785 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002786}
2787
2788/* Miscellaneous methods. */
2789
Tim Peters2a799bf2002-12-16 20:18:38 +00002790static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002791date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 if (PyDate_Check(other)) {
2794 int diff = memcmp(((PyDateTime_Date *)self)->data,
2795 ((PyDateTime_Date *)other)->data,
2796 _PyDateTime_DATE_DATASIZE);
2797 return diff_to_bool(diff, op);
2798 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002799 else
2800 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002801}
2802
2803static PyObject *
2804date_timetuple(PyDateTime_Date *self)
2805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 return build_struct_time(GET_YEAR(self),
2807 GET_MONTH(self),
2808 GET_DAY(self),
2809 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002810}
2811
Tim Peters12bf3392002-12-24 05:41:27 +00002812static PyObject *
2813date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 PyObject *clone;
2816 PyObject *tuple;
2817 int year = GET_YEAR(self);
2818 int month = GET_MONTH(self);
2819 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2822 &year, &month, &day))
2823 return NULL;
2824 tuple = Py_BuildValue("iii", year, month, day);
2825 if (tuple == NULL)
2826 return NULL;
2827 clone = date_new(Py_TYPE(self), tuple, NULL);
2828 Py_DECREF(tuple);
2829 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002830}
2831
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002832static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002833generic_hash(unsigned char *data, int len)
2834{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002835 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002836}
2837
2838
2839static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002840
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002841static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002842date_hash(PyDateTime_Date *self)
2843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 if (self->hashcode == -1)
2845 self->hashcode = generic_hash(
2846 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002849}
2850
2851static PyObject *
2852date_toordinal(PyDateTime_Date *self)
2853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2855 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002856}
2857
2858static PyObject *
2859date_weekday(PyDateTime_Date *self)
2860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002864}
2865
Tim Peters371935f2003-02-01 01:52:50 +00002866/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002867
Tim Petersb57f8f02003-02-01 02:54:15 +00002868/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002869static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002870date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 PyObject* field;
2873 field = PyBytes_FromStringAndSize((char*)self->data,
2874 _PyDateTime_DATE_DATASIZE);
2875 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002876}
2877
2878static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002879date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002882}
2883
2884static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2889 METH_CLASS,
2890 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2891 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2894 METH_CLASS,
2895 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2896 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2899 PyDoc_STR("Current date or datetime: same as "
2900 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2905 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2908 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2911 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2914 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2917 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2918 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2921 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2924 PyDoc_STR("Return the day of the week represented by the date.\n"
2925 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2928 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2929 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2932 PyDoc_STR("Return the day of the week represented by the date.\n"
2933 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2936 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2939 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002942};
2943
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002944static const char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002945PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002946
2947static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 date_add, /* nb_add */
2949 date_subtract, /* nb_subtract */
2950 0, /* nb_multiply */
2951 0, /* nb_remainder */
2952 0, /* nb_divmod */
2953 0, /* nb_power */
2954 0, /* nb_negative */
2955 0, /* nb_positive */
2956 0, /* nb_absolute */
2957 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002958};
2959
2960static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 PyVarObject_HEAD_INIT(NULL, 0)
2962 "datetime.date", /* tp_name */
2963 sizeof(PyDateTime_Date), /* tp_basicsize */
2964 0, /* tp_itemsize */
2965 0, /* tp_dealloc */
2966 0, /* tp_print */
2967 0, /* tp_getattr */
2968 0, /* tp_setattr */
2969 0, /* tp_reserved */
2970 (reprfunc)date_repr, /* tp_repr */
2971 &date_as_number, /* tp_as_number */
2972 0, /* tp_as_sequence */
2973 0, /* tp_as_mapping */
2974 (hashfunc)date_hash, /* tp_hash */
2975 0, /* tp_call */
2976 (reprfunc)date_str, /* tp_str */
2977 PyObject_GenericGetAttr, /* tp_getattro */
2978 0, /* tp_setattro */
2979 0, /* tp_as_buffer */
2980 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2981 date_doc, /* tp_doc */
2982 0, /* tp_traverse */
2983 0, /* tp_clear */
2984 date_richcompare, /* tp_richcompare */
2985 0, /* tp_weaklistoffset */
2986 0, /* tp_iter */
2987 0, /* tp_iternext */
2988 date_methods, /* tp_methods */
2989 0, /* tp_members */
2990 date_getset, /* tp_getset */
2991 0, /* tp_base */
2992 0, /* tp_dict */
2993 0, /* tp_descr_get */
2994 0, /* tp_descr_set */
2995 0, /* tp_dictoffset */
2996 0, /* tp_init */
2997 0, /* tp_alloc */
2998 date_new, /* tp_new */
2999 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003000};
3001
3002/*
Tim Peters2a799bf2002-12-16 20:18:38 +00003003 * PyDateTime_TZInfo implementation.
3004 */
3005
3006/* This is a pure abstract base class, so doesn't do anything beyond
3007 * raising NotImplemented exceptions. Real tzinfo classes need
3008 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00003009 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00003010 * be subclasses of this tzinfo class, which is easy and quick to check).
3011 *
3012 * Note: For reasons having to do with pickling of subclasses, we have
3013 * to allow tzinfo objects to be instantiated. This wasn't an issue
3014 * in the Python implementation (__init__() could raise NotImplementedError
3015 * there without ill effect), but doing so in the C implementation hit a
3016 * brick wall.
3017 */
3018
3019static PyObject *
3020tzinfo_nogo(const char* methodname)
3021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 PyErr_Format(PyExc_NotImplementedError,
3023 "a tzinfo subclass must implement %s()",
3024 methodname);
3025 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003026}
3027
3028/* Methods. A subclass must implement these. */
3029
Tim Peters52dcce22003-01-23 16:36:11 +00003030static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003031tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00003034}
3035
Tim Peters52dcce22003-01-23 16:36:11 +00003036static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003037tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00003040}
3041
Tim Peters52dcce22003-01-23 16:36:11 +00003042static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003043tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003046}
3047
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003048
3049static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
3050 PyDateTime_Delta *delta,
3051 int factor);
3052static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
3053static PyObject *datetime_dst(PyObject *self, PyObject *);
3054
Tim Peters52dcce22003-01-23 16:36:11 +00003055static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003056tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003057{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003058 PyObject *result = NULL;
3059 PyObject *off = NULL, *dst = NULL;
3060 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003061
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003062 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 PyErr_SetString(PyExc_TypeError,
3064 "fromutc: argument must be a datetime");
3065 return NULL;
3066 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003067 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3069 "is not self");
3070 return NULL;
3071 }
Tim Peters52dcce22003-01-23 16:36:11 +00003072
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003073 off = datetime_utcoffset(dt, NULL);
3074 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003076 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3078 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003079 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 }
Tim Peters52dcce22003-01-23 16:36:11 +00003081
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003082 dst = datetime_dst(dt, NULL);
3083 if (dst == NULL)
3084 goto Fail;
3085 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3087 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003088 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 }
Tim Peters52dcce22003-01-23 16:36:11 +00003090
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003091 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3092 if (delta == NULL)
3093 goto Fail;
3094 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003097
3098 Py_DECREF(dst);
3099 dst = call_dst(GET_DT_TZINFO(dt), result);
3100 if (dst == NULL)
3101 goto Fail;
3102 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 goto Inconsistent;
Alexander Belopolskyc79447b2015-09-27 21:41:55 -04003104 if (delta_bool((PyDateTime_Delta *)dst) != 0) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03003105 Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
Serhiy Storchaka576f1322016-01-05 21:27:54 +02003106 (PyDateTime_Delta *)dst, 1));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003107 if (result == NULL)
3108 goto Fail;
3109 }
3110 Py_DECREF(delta);
3111 Py_DECREF(dst);
3112 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003114
3115Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3117 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003120Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003121 Py_XDECREF(off);
3122 Py_XDECREF(dst);
3123 Py_XDECREF(delta);
3124 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003126}
3127
Tim Peters2a799bf2002-12-16 20:18:38 +00003128/*
3129 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003130 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003131 */
3132
Guido van Rossum177e41a2003-01-30 22:06:23 +00003133static PyObject *
3134tzinfo_reduce(PyObject *self)
3135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 PyObject *args, *state, *tmp;
3137 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003138 _Py_IDENTIFIER(__getinitargs__);
3139 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 tmp = PyTuple_New(0);
3142 if (tmp == NULL)
3143 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003144
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003145 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 if (getinitargs != NULL) {
3147 args = PyObject_CallObject(getinitargs, tmp);
3148 Py_DECREF(getinitargs);
3149 if (args == NULL) {
3150 Py_DECREF(tmp);
3151 return NULL;
3152 }
3153 }
3154 else {
3155 PyErr_Clear();
3156 args = tmp;
3157 Py_INCREF(args);
3158 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003159
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003160 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 if (getstate != NULL) {
3162 state = PyObject_CallObject(getstate, tmp);
3163 Py_DECREF(getstate);
3164 if (state == NULL) {
3165 Py_DECREF(args);
3166 Py_DECREF(tmp);
3167 return NULL;
3168 }
3169 }
3170 else {
3171 PyObject **dictptr;
3172 PyErr_Clear();
3173 state = Py_None;
3174 dictptr = _PyObject_GetDictPtr(self);
3175 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3176 state = *dictptr;
3177 Py_INCREF(state);
3178 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 if (state == Py_None) {
3183 Py_DECREF(state);
3184 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3185 }
3186 else
3187 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003188}
Tim Peters2a799bf2002-12-16 20:18:38 +00003189
3190static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3193 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003196 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3197 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3200 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003203 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3206 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003209};
3210
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003211static const char tzinfo_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00003212PyDoc_STR("Abstract base class for time zone info objects.");
3213
Neal Norwitz227b5332006-03-22 09:28:35 +00003214static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 PyVarObject_HEAD_INIT(NULL, 0)
3216 "datetime.tzinfo", /* tp_name */
3217 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3218 0, /* tp_itemsize */
3219 0, /* tp_dealloc */
3220 0, /* tp_print */
3221 0, /* tp_getattr */
3222 0, /* tp_setattr */
3223 0, /* tp_reserved */
3224 0, /* tp_repr */
3225 0, /* tp_as_number */
3226 0, /* tp_as_sequence */
3227 0, /* tp_as_mapping */
3228 0, /* tp_hash */
3229 0, /* tp_call */
3230 0, /* tp_str */
3231 PyObject_GenericGetAttr, /* tp_getattro */
3232 0, /* tp_setattro */
3233 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003234 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 tzinfo_doc, /* tp_doc */
3236 0, /* tp_traverse */
3237 0, /* tp_clear */
3238 0, /* tp_richcompare */
3239 0, /* tp_weaklistoffset */
3240 0, /* tp_iter */
3241 0, /* tp_iternext */
3242 tzinfo_methods, /* tp_methods */
3243 0, /* tp_members */
3244 0, /* tp_getset */
3245 0, /* tp_base */
3246 0, /* tp_dict */
3247 0, /* tp_descr_get */
3248 0, /* tp_descr_set */
3249 0, /* tp_dictoffset */
3250 0, /* tp_init */
3251 0, /* tp_alloc */
3252 PyType_GenericNew, /* tp_new */
3253 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003254};
3255
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003256static char *timezone_kws[] = {"offset", "name", NULL};
3257
3258static PyObject *
3259timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3260{
3261 PyObject *offset;
3262 PyObject *name = NULL;
3263 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
3264 &PyDateTime_DeltaType, &offset,
3265 &PyUnicode_Type, &name))
3266 return new_timezone(offset, name);
3267
3268 return NULL;
3269}
3270
3271static void
3272timezone_dealloc(PyDateTime_TimeZone *self)
3273{
3274 Py_CLEAR(self->offset);
3275 Py_CLEAR(self->name);
3276 Py_TYPE(self)->tp_free((PyObject *)self);
3277}
3278
3279static PyObject *
3280timezone_richcompare(PyDateTime_TimeZone *self,
3281 PyDateTime_TimeZone *other, int op)
3282{
Brian Curtindfc80e32011-08-10 20:28:54 -05003283 if (op != Py_EQ && op != Py_NE)
3284 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003285 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003286 if (op == Py_EQ)
3287 Py_RETURN_FALSE;
3288 else
3289 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003290 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003291 return delta_richcompare(self->offset, other->offset, op);
3292}
3293
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003294static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003295timezone_hash(PyDateTime_TimeZone *self)
3296{
3297 return delta_hash((PyDateTime_Delta *)self->offset);
3298}
3299
3300/* Check argument type passed to tzname, utcoffset, or dst methods.
3301 Returns 0 for good argument. Returns -1 and sets exception info
3302 otherwise.
3303 */
3304static int
3305_timezone_check_argument(PyObject *dt, const char *meth)
3306{
3307 if (dt == Py_None || PyDateTime_Check(dt))
3308 return 0;
3309 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3310 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3311 return -1;
3312}
3313
3314static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003315timezone_repr(PyDateTime_TimeZone *self)
3316{
3317 /* Note that although timezone is not subclassable, it is convenient
3318 to use Py_TYPE(self)->tp_name here. */
3319 const char *type_name = Py_TYPE(self)->tp_name;
3320
3321 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3322 return PyUnicode_FromFormat("%s.utc", type_name);
3323
3324 if (self->name == NULL)
3325 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3326
3327 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3328 self->name);
3329}
3330
3331
3332static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003333timezone_str(PyDateTime_TimeZone *self)
3334{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003335 int hours, minutes, seconds;
3336 PyObject *offset;
3337 char sign;
3338
3339 if (self->name != NULL) {
3340 Py_INCREF(self->name);
3341 return self->name;
3342 }
Victor Stinner90fd8952015-09-08 00:12:49 +02003343 if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04003344 (GET_TD_DAYS(self->offset) == 0 &&
3345 GET_TD_SECONDS(self->offset) == 0 &&
3346 GET_TD_MICROSECONDS(self->offset) == 0))
3347 return PyUnicode_FromString("UTC");
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003348 /* Offset is normalized, so it is negative if days < 0 */
3349 if (GET_TD_DAYS(self->offset) < 0) {
3350 sign = '-';
3351 offset = delta_negative((PyDateTime_Delta *)self->offset);
3352 if (offset == NULL)
3353 return NULL;
3354 }
3355 else {
3356 sign = '+';
3357 offset = self->offset;
3358 Py_INCREF(offset);
3359 }
3360 /* Offset is not negative here. */
3361 seconds = GET_TD_SECONDS(offset);
3362 Py_DECREF(offset);
3363 minutes = divmod(seconds, 60, &seconds);
3364 hours = divmod(minutes, 60, &minutes);
Martin Pantere26da7c2016-06-02 10:07:09 +00003365 /* XXX ignore sub-minute data, currently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003366 assert(seconds == 0);
3367 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003368}
3369
3370static PyObject *
3371timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3372{
3373 if (_timezone_check_argument(dt, "tzname") == -1)
3374 return NULL;
3375
3376 return timezone_str(self);
3377}
3378
3379static PyObject *
3380timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3381{
3382 if (_timezone_check_argument(dt, "utcoffset") == -1)
3383 return NULL;
3384
3385 Py_INCREF(self->offset);
3386 return self->offset;
3387}
3388
3389static PyObject *
3390timezone_dst(PyObject *self, PyObject *dt)
3391{
3392 if (_timezone_check_argument(dt, "dst") == -1)
3393 return NULL;
3394
3395 Py_RETURN_NONE;
3396}
3397
3398static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003399timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3400{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003401 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003402 PyErr_SetString(PyExc_TypeError,
3403 "fromutc: argument must be a datetime");
3404 return NULL;
3405 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003406 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003407 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3408 "is not self");
3409 return NULL;
3410 }
3411
3412 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3413}
3414
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003415static PyObject *
3416timezone_getinitargs(PyDateTime_TimeZone *self)
3417{
3418 if (self->name == NULL)
3419 return Py_BuildValue("(O)", self->offset);
3420 return Py_BuildValue("(OO)", self->offset, self->name);
3421}
3422
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003423static PyMethodDef timezone_methods[] = {
3424 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3425 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003426 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003427
3428 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003429 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003430
3431 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003432 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003433
3434 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3435 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3436
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003437 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3438 PyDoc_STR("pickle support")},
3439
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003440 {NULL, NULL}
3441};
3442
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003443static const char timezone_doc[] =
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003444PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3445
3446static PyTypeObject PyDateTime_TimeZoneType = {
3447 PyVarObject_HEAD_INIT(NULL, 0)
3448 "datetime.timezone", /* tp_name */
3449 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3450 0, /* tp_itemsize */
3451 (destructor)timezone_dealloc, /* tp_dealloc */
3452 0, /* tp_print */
3453 0, /* tp_getattr */
3454 0, /* tp_setattr */
3455 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003456 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003457 0, /* tp_as_number */
3458 0, /* tp_as_sequence */
3459 0, /* tp_as_mapping */
3460 (hashfunc)timezone_hash, /* tp_hash */
3461 0, /* tp_call */
3462 (reprfunc)timezone_str, /* tp_str */
3463 0, /* tp_getattro */
3464 0, /* tp_setattro */
3465 0, /* tp_as_buffer */
3466 Py_TPFLAGS_DEFAULT, /* tp_flags */
3467 timezone_doc, /* tp_doc */
3468 0, /* tp_traverse */
3469 0, /* tp_clear */
3470 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3471 0, /* tp_weaklistoffset */
3472 0, /* tp_iter */
3473 0, /* tp_iternext */
3474 timezone_methods, /* tp_methods */
3475 0, /* tp_members */
3476 0, /* tp_getset */
3477 &PyDateTime_TZInfoType, /* tp_base */
3478 0, /* tp_dict */
3479 0, /* tp_descr_get */
3480 0, /* tp_descr_set */
3481 0, /* tp_dictoffset */
3482 0, /* tp_init */
3483 0, /* tp_alloc */
3484 timezone_new, /* tp_new */
3485};
3486
Tim Peters2a799bf2002-12-16 20:18:38 +00003487/*
Tim Peters37f39822003-01-10 03:49:02 +00003488 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003489 */
3490
Tim Peters37f39822003-01-10 03:49:02 +00003491/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003492 */
3493
3494static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003495time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003498}
3499
Tim Peters37f39822003-01-10 03:49:02 +00003500static PyObject *
3501time_minute(PyDateTime_Time *self, void *unused)
3502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003504}
3505
3506/* The name time_second conflicted with some platform header file. */
3507static PyObject *
3508py_time_second(PyDateTime_Time *self, void *unused)
3509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003511}
3512
3513static PyObject *
3514time_microsecond(PyDateTime_Time *self, void *unused)
3515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003517}
3518
3519static PyObject *
3520time_tzinfo(PyDateTime_Time *self, void *unused)
3521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3523 Py_INCREF(result);
3524 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003525}
3526
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003527static PyObject *
3528time_fold(PyDateTime_Time *self, void *unused)
3529{
3530 return PyLong_FromLong(TIME_GET_FOLD(self));
3531}
3532
Tim Peters37f39822003-01-10 03:49:02 +00003533static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 {"hour", (getter)time_hour},
3535 {"minute", (getter)time_minute},
3536 {"second", (getter)py_time_second},
3537 {"microsecond", (getter)time_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003538 {"tzinfo", (getter)time_tzinfo},
3539 {"fold", (getter)time_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003541};
3542
3543/*
3544 * Constructors.
3545 */
3546
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003547static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003548 "tzinfo", "fold", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003549
Tim Peters2a799bf2002-12-16 20:18:38 +00003550static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003551time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 PyObject *self = NULL;
3554 PyObject *state;
3555 int hour = 0;
3556 int minute = 0;
3557 int second = 0;
3558 int usecond = 0;
3559 PyObject *tzinfo = Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003560 int fold = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 /* Check for invocation from pickle with __getstate__ state */
3563 if (PyTuple_GET_SIZE(args) >= 1 &&
3564 PyTuple_GET_SIZE(args) <= 2 &&
3565 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3566 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003567 (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 {
3569 PyDateTime_Time *me;
3570 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 if (PyTuple_GET_SIZE(args) == 2) {
3573 tzinfo = PyTuple_GET_ITEM(args, 1);
3574 if (check_tzinfo_subclass(tzinfo) < 0) {
3575 PyErr_SetString(PyExc_TypeError, "bad "
3576 "tzinfo state arg");
3577 return NULL;
3578 }
3579 }
3580 aware = (char)(tzinfo != Py_None);
3581 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3582 if (me != NULL) {
3583 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3586 me->hashcode = -1;
3587 me->hastzinfo = aware;
3588 if (aware) {
3589 Py_INCREF(tzinfo);
3590 me->tzinfo = tzinfo;
3591 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003592 if (pdata[0] & (1 << 7)) {
3593 me->data[0] -= 128;
3594 me->fold = 1;
3595 }
3596 else {
3597 me->fold = 0;
3598 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 }
3600 return (PyObject *)me;
3601 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003602
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003603 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 &hour, &minute, &second, &usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003605 &tzinfo, &fold)) {
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003606 if (check_time_args(hour, minute, second, usecond, fold) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 return NULL;
3608 if (check_tzinfo_subclass(tzinfo) < 0)
3609 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003610 self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
3611 type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 }
3613 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003614}
3615
3616/*
3617 * Destructor.
3618 */
3619
3620static void
Tim Peters37f39822003-01-10 03:49:02 +00003621time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 if (HASTZINFO(self)) {
3624 Py_XDECREF(self->tzinfo);
3625 }
3626 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003627}
3628
3629/*
Tim Peters855fe882002-12-22 03:43:39 +00003630 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003631 */
3632
Tim Peters2a799bf2002-12-16 20:18:38 +00003633/* These are all METH_NOARGS, so don't need to check the arglist. */
3634static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003635time_utcoffset(PyObject *self, PyObject *unused) {
3636 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003637}
3638
3639static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003640time_dst(PyObject *self, PyObject *unused) {
3641 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003642}
3643
3644static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003645time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003646 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003647}
3648
3649/*
Tim Peters37f39822003-01-10 03:49:02 +00003650 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003651 */
3652
3653static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003654time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 const char *type_name = Py_TYPE(self)->tp_name;
3657 int h = TIME_GET_HOUR(self);
3658 int m = TIME_GET_MINUTE(self);
3659 int s = TIME_GET_SECOND(self);
3660 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003661 int fold = TIME_GET_FOLD(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 if (us)
3665 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3666 type_name, h, m, s, us);
3667 else if (s)
3668 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3669 type_name, h, m, s);
3670 else
3671 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3672 if (result != NULL && HASTZINFO(self))
3673 result = append_keyword_tzinfo(result, self->tzinfo);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003674 if (result != NULL && fold)
3675 result = append_keyword_fold(result, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003677}
3678
Tim Peters37f39822003-01-10 03:49:02 +00003679static PyObject *
3680time_str(PyDateTime_Time *self)
3681{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003682 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters37f39822003-01-10 03:49:02 +00003683}
Tim Peters2a799bf2002-12-16 20:18:38 +00003684
3685static PyObject *
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003686time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 char buf[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003689 char *timespec = NULL;
3690 static char *keywords[] = {"timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02003692 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003693 static char *specs[][2] = {
3694 {"hours", "%02d"},
3695 {"minutes", "%02d:%02d"},
3696 {"seconds", "%02d:%02d:%02d"},
3697 {"milliseconds", "%02d:%02d:%02d.%03d"},
3698 {"microseconds", "%02d:%02d:%02d.%06d"},
3699 };
3700 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00003701
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003702 if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
3703 return NULL;
3704
3705 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
3706 if (us == 0) {
3707 /* seconds */
3708 given_spec = 2;
3709 }
3710 else {
3711 /* microseconds */
3712 given_spec = 4;
3713 }
3714 }
3715 else {
3716 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
3717 if (strcmp(timespec, specs[given_spec][0]) == 0) {
3718 if (given_spec == 3) {
3719 /* milliseconds */
3720 us = us / 1000;
3721 }
3722 break;
3723 }
3724 }
3725 }
3726
3727 if (given_spec == Py_ARRAY_LENGTH(specs)) {
3728 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
3729 return NULL;
3730 }
3731 else {
3732 result = PyUnicode_FromFormat(specs[given_spec][1],
3733 TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
3734 TIME_GET_SECOND(self), us);
3735 }
Tim Peters37f39822003-01-10 03:49:02 +00003736
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003737 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 /* We need to append the UTC offset. */
3741 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3742 Py_None) < 0) {
3743 Py_DECREF(result);
3744 return NULL;
3745 }
3746 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3747 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003748}
3749
Tim Peters37f39822003-01-10 03:49:02 +00003750static PyObject *
3751time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 PyObject *result;
3754 PyObject *tuple;
3755 PyObject *format;
3756 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3759 &format))
3760 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 /* Python's strftime does insane things with the year part of the
3763 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003764 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 */
3766 tuple = Py_BuildValue("iiiiiiiii",
3767 1900, 1, 1, /* year, month, day */
3768 TIME_GET_HOUR(self),
3769 TIME_GET_MINUTE(self),
3770 TIME_GET_SECOND(self),
3771 0, 1, -1); /* weekday, daynum, dst */
3772 if (tuple == NULL)
3773 return NULL;
3774 assert(PyTuple_Size(tuple) == 9);
3775 result = wrap_strftime((PyObject *)self, format, tuple,
3776 Py_None);
3777 Py_DECREF(tuple);
3778 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003779}
Tim Peters2a799bf2002-12-16 20:18:38 +00003780
3781/*
3782 * Miscellaneous methods.
3783 */
3784
Tim Peters37f39822003-01-10 03:49:02 +00003785static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003786time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003787{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003788 PyObject *result = NULL;
3789 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003791
Brian Curtindfc80e32011-08-10 20:28:54 -05003792 if (! PyTime_Check(other))
3793 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003794
3795 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 diff = memcmp(((PyDateTime_Time *)self)->data,
3797 ((PyDateTime_Time *)other)->data,
3798 _PyDateTime_TIME_DATASIZE);
3799 return diff_to_bool(diff, op);
3800 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003801 offset1 = time_utcoffset(self, NULL);
3802 if (offset1 == NULL)
3803 return NULL;
3804 offset2 = time_utcoffset(other, NULL);
3805 if (offset2 == NULL)
3806 goto done;
3807 /* If they're both naive, or both aware and have the same offsets,
3808 * we get off cheap. Note that if they're both naive, offset1 ==
3809 * offset2 == Py_None at this point.
3810 */
3811 if ((offset1 == offset2) ||
3812 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3813 delta_cmp(offset1, offset2) == 0)) {
3814 diff = memcmp(((PyDateTime_Time *)self)->data,
3815 ((PyDateTime_Time *)other)->data,
3816 _PyDateTime_TIME_DATASIZE);
3817 result = diff_to_bool(diff, op);
3818 }
3819 /* The hard case: both aware with different UTC offsets */
3820 else if (offset1 != Py_None && offset2 != Py_None) {
3821 int offsecs1, offsecs2;
3822 assert(offset1 != offset2); /* else last "if" handled it */
3823 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3824 TIME_GET_MINUTE(self) * 60 +
3825 TIME_GET_SECOND(self) -
3826 GET_TD_DAYS(offset1) * 86400 -
3827 GET_TD_SECONDS(offset1);
3828 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3829 TIME_GET_MINUTE(other) * 60 +
3830 TIME_GET_SECOND(other) -
3831 GET_TD_DAYS(offset2) * 86400 -
3832 GET_TD_SECONDS(offset2);
3833 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 if (diff == 0)
3835 diff = TIME_GET_MICROSECOND(self) -
3836 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003837 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003839 else if (op == Py_EQ) {
3840 result = Py_False;
3841 Py_INCREF(result);
3842 }
3843 else if (op == Py_NE) {
3844 result = Py_True;
3845 Py_INCREF(result);
3846 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003847 else {
3848 PyErr_SetString(PyExc_TypeError,
3849 "can't compare offset-naive and "
3850 "offset-aware times");
3851 }
3852 done:
3853 Py_DECREF(offset1);
3854 Py_XDECREF(offset2);
3855 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003856}
3857
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003858static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003859time_hash(PyDateTime_Time *self)
3860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003862 PyObject *offset, *self0;
3863 if (DATE_GET_FOLD(self)) {
3864 self0 = new_time_ex2(DATE_GET_HOUR(self),
3865 DATE_GET_MINUTE(self),
3866 DATE_GET_SECOND(self),
3867 DATE_GET_MICROSECOND(self),
3868 HASTZINFO(self) ? self->tzinfo : Py_None,
3869 0, Py_TYPE(self));
3870 if (self0 == NULL)
3871 return -1;
3872 }
3873 else {
3874 self0 = (PyObject *)self;
3875 Py_INCREF(self0);
3876 }
3877 offset = time_utcoffset(self0, NULL);
3878 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003879
3880 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003884 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 self->hashcode = generic_hash(
3886 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003888 PyObject *temp1, *temp2;
3889 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003891 seconds = TIME_GET_HOUR(self) * 3600 +
3892 TIME_GET_MINUTE(self) * 60 +
3893 TIME_GET_SECOND(self);
3894 microseconds = TIME_GET_MICROSECOND(self);
3895 temp1 = new_delta(0, seconds, microseconds, 1);
3896 if (temp1 == NULL) {
3897 Py_DECREF(offset);
3898 return -1;
3899 }
3900 temp2 = delta_subtract(temp1, offset);
3901 Py_DECREF(temp1);
3902 if (temp2 == NULL) {
3903 Py_DECREF(offset);
3904 return -1;
3905 }
3906 self->hashcode = PyObject_Hash(temp2);
3907 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003909 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 }
3911 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003912}
Tim Peters2a799bf2002-12-16 20:18:38 +00003913
Tim Peters12bf3392002-12-24 05:41:27 +00003914static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003915time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 PyObject *clone;
3918 PyObject *tuple;
3919 int hh = TIME_GET_HOUR(self);
3920 int mm = TIME_GET_MINUTE(self);
3921 int ss = TIME_GET_SECOND(self);
3922 int us = TIME_GET_MICROSECOND(self);
3923 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003924 int fold = TIME_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00003925
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003926 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 time_kws,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003928 &hh, &mm, &ss, &us, &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 return NULL;
3930 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3931 if (tuple == NULL)
3932 return NULL;
3933 clone = time_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003934 if (clone != NULL) {
3935 if (fold != 0 && fold != 1) {
3936 PyErr_SetString(PyExc_ValueError,
3937 "fold must be either 0 or 1");
3938 return NULL;
3939 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003940 TIME_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003941 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 Py_DECREF(tuple);
3943 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003944}
3945
Tim Peters371935f2003-02-01 01:52:50 +00003946/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003947
Tim Peters33e0f382003-01-10 02:05:14 +00003948/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003949 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3950 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003951 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003952 */
3953static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003954time_getstate(PyDateTime_Time *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00003955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 PyObject *basestate;
3957 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 basestate = PyBytes_FromStringAndSize((char *)self->data,
3960 _PyDateTime_TIME_DATASIZE);
3961 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003962 if (proto > 3 && TIME_GET_FOLD(self))
3963 /* Set the first bit of the first byte */
3964 PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3966 result = PyTuple_Pack(1, basestate);
3967 else
3968 result = PyTuple_Pack(2, basestate, self->tzinfo);
3969 Py_DECREF(basestate);
3970 }
3971 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003972}
3973
3974static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003975time_reduce(PyDateTime_Time *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00003976{
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003977 int proto = 0;
3978 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3979 return NULL;
3980
3981 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00003982}
3983
Tim Peters37f39822003-01-10 03:49:02 +00003984static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003985
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003986 {"isoformat", (PyCFunction)time_isoformat, METH_VARARGS | METH_KEYWORDS,
3987 PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
3988 "[+HH:MM].\n\n"
3989 "timespec specifies what components of the time to include.\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3992 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3995 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3998 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
4001 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 {"dst", (PyCFunction)time_dst, METH_NOARGS,
4004 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
4007 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004008
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004009 {"__reduce_ex__", (PyCFunction)time_reduce, METH_VARARGS,
4010 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004013};
4014
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004015static const char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004016PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
4017\n\
4018All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03004019a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004020
Neal Norwitz227b5332006-03-22 09:28:35 +00004021static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 PyVarObject_HEAD_INIT(NULL, 0)
4023 "datetime.time", /* tp_name */
4024 sizeof(PyDateTime_Time), /* tp_basicsize */
4025 0, /* tp_itemsize */
4026 (destructor)time_dealloc, /* tp_dealloc */
4027 0, /* tp_print */
4028 0, /* tp_getattr */
4029 0, /* tp_setattr */
4030 0, /* tp_reserved */
4031 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05004032 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 0, /* tp_as_sequence */
4034 0, /* tp_as_mapping */
4035 (hashfunc)time_hash, /* tp_hash */
4036 0, /* tp_call */
4037 (reprfunc)time_str, /* tp_str */
4038 PyObject_GenericGetAttr, /* tp_getattro */
4039 0, /* tp_setattro */
4040 0, /* tp_as_buffer */
4041 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4042 time_doc, /* tp_doc */
4043 0, /* tp_traverse */
4044 0, /* tp_clear */
4045 time_richcompare, /* tp_richcompare */
4046 0, /* tp_weaklistoffset */
4047 0, /* tp_iter */
4048 0, /* tp_iternext */
4049 time_methods, /* tp_methods */
4050 0, /* tp_members */
4051 time_getset, /* tp_getset */
4052 0, /* tp_base */
4053 0, /* tp_dict */
4054 0, /* tp_descr_get */
4055 0, /* tp_descr_set */
4056 0, /* tp_dictoffset */
4057 0, /* tp_init */
4058 time_alloc, /* tp_alloc */
4059 time_new, /* tp_new */
4060 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004061};
4062
4063/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004064 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00004065 */
4066
Tim Petersa9bc1682003-01-11 03:39:11 +00004067/* Accessor properties. Properties for day, month, and year are inherited
4068 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004069 */
4070
4071static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004072datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00004073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004075}
4076
Tim Petersa9bc1682003-01-11 03:39:11 +00004077static PyObject *
4078datetime_minute(PyDateTime_DateTime *self, void *unused)
4079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004081}
4082
4083static PyObject *
4084datetime_second(PyDateTime_DateTime *self, void *unused)
4085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004087}
4088
4089static PyObject *
4090datetime_microsecond(PyDateTime_DateTime *self, void *unused)
4091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004093}
4094
4095static PyObject *
4096datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
4097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4099 Py_INCREF(result);
4100 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004101}
4102
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004103static PyObject *
4104datetime_fold(PyDateTime_DateTime *self, void *unused)
4105{
4106 return PyLong_FromLong(DATE_GET_FOLD(self));
4107}
4108
Tim Petersa9bc1682003-01-11 03:39:11 +00004109static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 {"hour", (getter)datetime_hour},
4111 {"minute", (getter)datetime_minute},
4112 {"second", (getter)datetime_second},
4113 {"microsecond", (getter)datetime_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004114 {"tzinfo", (getter)datetime_tzinfo},
4115 {"fold", (getter)datetime_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004117};
4118
4119/*
4120 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004121 */
4122
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004123static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 "year", "month", "day", "hour", "minute", "second",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004125 "microsecond", "tzinfo", "fold", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004126};
4127
Tim Peters2a799bf2002-12-16 20:18:38 +00004128static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004129datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 PyObject *self = NULL;
4132 PyObject *state;
4133 int year;
4134 int month;
4135 int day;
4136 int hour = 0;
4137 int minute = 0;
4138 int second = 0;
4139 int usecond = 0;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004140 int fold = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 /* Check for invocation from pickle with __getstate__ state */
4144 if (PyTuple_GET_SIZE(args) >= 1 &&
4145 PyTuple_GET_SIZE(args) <= 2 &&
4146 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4147 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004148 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 {
4150 PyDateTime_DateTime *me;
4151 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004153 if (PyTuple_GET_SIZE(args) == 2) {
4154 tzinfo = PyTuple_GET_ITEM(args, 1);
4155 if (check_tzinfo_subclass(tzinfo) < 0) {
4156 PyErr_SetString(PyExc_TypeError, "bad "
4157 "tzinfo state arg");
4158 return NULL;
4159 }
4160 }
4161 aware = (char)(tzinfo != Py_None);
4162 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4163 if (me != NULL) {
4164 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4167 me->hashcode = -1;
4168 me->hastzinfo = aware;
4169 if (aware) {
4170 Py_INCREF(tzinfo);
4171 me->tzinfo = tzinfo;
4172 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004173 if (pdata[2] & (1 << 7)) {
4174 me->data[2] -= 128;
4175 me->fold = 1;
4176 }
4177 else {
4178 me->fold = 0;
4179 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 }
4181 return (PyObject *)me;
4182 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004183
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004184 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 &year, &month, &day, &hour, &minute,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004186 &second, &usecond, &tzinfo, &fold)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 if (check_date_args(year, month, day) < 0)
4188 return NULL;
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04004189 if (check_time_args(hour, minute, second, usecond, fold) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 return NULL;
4191 if (check_tzinfo_subclass(tzinfo) < 0)
4192 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004193 self = new_datetime_ex2(year, month, day,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 hour, minute, second, usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004195 tzinfo, fold, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 }
4197 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004198}
4199
Tim Petersa9bc1682003-01-11 03:39:11 +00004200/* TM_FUNC is the shared type of localtime() and gmtime(). */
4201typedef struct tm *(*TM_FUNC)(const time_t *timer);
4202
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004203/* As of version 2015f max fold in IANA database is
4204 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
4205static PY_LONG_LONG max_fold_seconds = 24 * 3600;
4206/* NB: date(1970,1,1).toordinal() == 719163 */
4207static PY_LONG_LONG epoch = Py_LL(719163) * 24 * 60 * 60;
4208
4209static PY_LONG_LONG
4210utc_to_seconds(int year, int month, int day,
4211 int hour, int minute, int second)
4212{
4213 PY_LONG_LONG ordinal = ymd_to_ord(year, month, day);
4214 return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
4215}
4216
4217static PY_LONG_LONG
4218local(PY_LONG_LONG u)
4219{
4220 struct tm local_time;
Alexander Belopolsky8e1d3a22016-07-25 13:54:51 -04004221 time_t t;
4222 u -= epoch;
4223 t = u;
4224 if (t != u) {
4225 PyErr_SetString(PyExc_OverflowError,
4226 "timestamp out of range for platform time_t");
4227 return -1;
4228 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004229 /* XXX: add bounds checking */
4230 if (localtime_r(&t, &local_time) == NULL) {
4231 PyErr_SetFromErrno(PyExc_OSError);
4232 return -1;
4233 }
4234 return utc_to_seconds(local_time.tm_year + 1900,
4235 local_time.tm_mon + 1,
4236 local_time.tm_mday,
4237 local_time.tm_hour,
4238 local_time.tm_min,
4239 local_time.tm_sec);
4240}
4241
Tim Petersa9bc1682003-01-11 03:39:11 +00004242/* Internal helper.
4243 * Build datetime from a time_t and a distinct count of microseconds.
4244 * Pass localtime or gmtime for f, to control the interpretation of timet.
4245 */
4246static PyObject *
4247datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 struct tm *tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004251 int year, month, day, hour, minute, second, fold = 0;
Tim Petersa9bc1682003-01-11 03:39:11 +00004252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 tm = f(&timet);
Victor Stinner21f58932012-03-14 00:15:40 +01004254 if (tm == NULL) {
4255#ifdef EINVAL
4256 if (errno == 0)
4257 errno = EINVAL;
4258#endif
4259 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 }
Victor Stinner21f58932012-03-14 00:15:40 +01004261
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004262 year = tm->tm_year + 1900;
4263 month = tm->tm_mon + 1;
4264 day = tm->tm_mday;
4265 hour = tm->tm_hour;
4266 minute = tm->tm_min;
Victor Stinner21f58932012-03-14 00:15:40 +01004267 /* The platform localtime/gmtime may insert leap seconds,
4268 * indicated by tm->tm_sec > 59. We don't care about them,
4269 * except to the extent that passing them on to the datetime
4270 * constructor would raise ValueError for a reason that
4271 * made no sense to the user.
4272 */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004273 second = Py_MIN(59, tm->tm_sec);
4274
4275 if (tzinfo == Py_None && f == localtime) {
4276 PY_LONG_LONG probe_seconds, result_seconds, transition;
4277
4278 result_seconds = utc_to_seconds(year, month, day,
4279 hour, minute, second);
4280 /* Probe max_fold_seconds to detect a fold. */
4281 probe_seconds = local(epoch + timet - max_fold_seconds);
4282 if (probe_seconds == -1)
4283 return NULL;
4284 transition = result_seconds - probe_seconds - max_fold_seconds;
4285 if (transition < 0) {
4286 probe_seconds = local(epoch + timet + transition);
4287 if (probe_seconds == -1)
4288 return NULL;
4289 if (probe_seconds == result_seconds)
4290 fold = 1;
4291 }
4292 }
4293 return new_datetime_ex2(year, month, day, hour,
4294 minute, second, us, tzinfo, fold,
4295 (PyTypeObject *)cls);
Tim Petersa9bc1682003-01-11 03:39:11 +00004296}
4297
4298/* Internal helper.
4299 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4300 * to control the interpretation of the timestamp. Since a double doesn't
4301 * have enough bits to cover a datetime's full range of precision, it's
4302 * better to call datetime_from_timet_and_us provided you have a way
4303 * to get that much precision (e.g., C time() isn't good enough).
4304 */
4305static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004306datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004310 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004311
Victor Stinnere4a994d2015-03-30 01:10:14 +02004312 if (_PyTime_ObjectToTimeval(timestamp,
Victor Stinner7667f582015-09-09 01:02:23 +02004313 &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004315
Victor Stinner21f58932012-03-14 00:15:40 +01004316 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004317}
4318
4319/* Internal helper.
4320 * Build most accurate possible datetime for current time. Pass localtime or
4321 * gmtime for f as appropriate.
4322 */
4323static PyObject *
4324datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4325{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004326 _PyTime_t ts = _PyTime_GetSystemClock();
Victor Stinner1e2b6882015-09-18 13:23:02 +02004327 time_t secs;
4328 int us;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004329
Victor Stinner1e2b6882015-09-18 13:23:02 +02004330 if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner09e5cf22015-03-30 00:09:18 +02004331 return NULL;
Victor Stinner1e2b6882015-09-18 13:23:02 +02004332 assert(0 <= us && us <= 999999);
Victor Stinner09e5cf22015-03-30 00:09:18 +02004333
Victor Stinner1e2b6882015-09-18 13:23:02 +02004334 return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004335}
4336
Larry Hastings61272b72014-01-07 12:41:53 -08004337/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004338
4339@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004340datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004341
4342 tz: object = None
4343 Timezone object.
4344
4345Returns new datetime object representing current time local to tz.
4346
4347If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004348[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004349
Larry Hastings31826802013-10-19 00:09:25 -07004350static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004351datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03004352/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004355
Larry Hastings31826802013-10-19 00:09:25 -07004356 /* Return best possible local time -- this isn't constrained by the
4357 * precision of a timestamp.
4358 */
4359 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004361
Larry Hastings5c661892014-01-24 06:17:25 -08004362 self = datetime_best_possible((PyObject *)type,
Larry Hastings31826802013-10-19 00:09:25 -07004363 tz == Py_None ? localtime : gmtime,
4364 tz);
4365 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004367 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 }
4369 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004370}
4371
Tim Petersa9bc1682003-01-11 03:39:11 +00004372/* Return best possible UTC time -- this isn't constrained by the
4373 * precision of a timestamp.
4374 */
4375static PyObject *
4376datetime_utcnow(PyObject *cls, PyObject *dummy)
4377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004379}
4380
Tim Peters2a799bf2002-12-16 20:18:38 +00004381/* Return new local datetime from timestamp (Python timestamp -- a double). */
4382static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004383datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004386 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 PyObject *tzinfo = Py_None;
4388 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004389
Victor Stinner5d272cc2012-03-13 13:35:55 +01004390 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 keywords, &timestamp, &tzinfo))
4392 return NULL;
4393 if (check_tzinfo_subclass(tzinfo) < 0)
4394 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 self = datetime_from_timestamp(cls,
4397 tzinfo == Py_None ? localtime : gmtime,
4398 timestamp,
4399 tzinfo);
4400 if (self != NULL && tzinfo != Py_None) {
4401 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004402 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 }
4404 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004405}
4406
Tim Petersa9bc1682003-01-11 03:39:11 +00004407/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4408static PyObject *
4409datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4410{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004411 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004413
Victor Stinner5d272cc2012-03-13 13:35:55 +01004414 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 result = datetime_from_timestamp(cls, gmtime, timestamp,
4416 Py_None);
4417 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004418}
4419
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004420/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004421static PyObject *
4422datetime_strptime(PyObject *cls, PyObject *args)
4423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004425 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004426 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004428 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004430
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004431 if (module == NULL) {
4432 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004433 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004434 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004436 return _PyObject_CallMethodId(module, &PyId__strptime_datetime, "OOO",
4437 cls, string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004438}
4439
Tim Petersa9bc1682003-01-11 03:39:11 +00004440/* Return new datetime from date/datetime and time arguments. */
4441static PyObject *
4442datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4443{
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004444 static char *keywords[] = {"date", "time", "tzinfo", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 PyObject *date;
4446 PyObject *time;
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004447 PyObject *tzinfo = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004449
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004450 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 &PyDateTime_DateType, &date,
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004452 &PyDateTime_TimeType, &time, &tzinfo)) {
4453 if (tzinfo == NULL) {
4454 if (HASTZINFO(time))
4455 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4456 else
4457 tzinfo = Py_None;
4458 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 result = PyObject_CallFunction(cls, "iiiiiiiO",
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004460 GET_YEAR(date),
4461 GET_MONTH(date),
4462 GET_DAY(date),
4463 TIME_GET_HOUR(time),
4464 TIME_GET_MINUTE(time),
4465 TIME_GET_SECOND(time),
4466 TIME_GET_MICROSECOND(time),
4467 tzinfo);
4468 if (result)
4469 DATE_SET_FOLD(result, TIME_GET_FOLD(time));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 }
4471 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004472}
Tim Peters2a799bf2002-12-16 20:18:38 +00004473
4474/*
4475 * Destructor.
4476 */
4477
4478static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004479datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 if (HASTZINFO(self)) {
4482 Py_XDECREF(self->tzinfo);
4483 }
4484 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004485}
4486
4487/*
4488 * Indirect access to tzinfo methods.
4489 */
4490
Tim Peters2a799bf2002-12-16 20:18:38 +00004491/* These are all METH_NOARGS, so don't need to check the arglist. */
4492static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004493datetime_utcoffset(PyObject *self, PyObject *unused) {
4494 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004495}
4496
4497static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004498datetime_dst(PyObject *self, PyObject *unused) {
4499 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004500}
4501
4502static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004503datetime_tzname(PyObject *self, PyObject *unused) {
4504 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004505}
4506
4507/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004508 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004509 */
4510
Tim Petersa9bc1682003-01-11 03:39:11 +00004511/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4512 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004513 */
4514static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004515add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 /* Note that the C-level additions can't overflow, because of
4519 * invariant bounds on the member values.
4520 */
4521 int year = GET_YEAR(date);
4522 int month = GET_MONTH(date);
4523 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4524 int hour = DATE_GET_HOUR(date);
4525 int minute = DATE_GET_MINUTE(date);
4526 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4527 int microsecond = DATE_GET_MICROSECOND(date) +
4528 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 assert(factor == 1 || factor == -1);
4531 if (normalize_datetime(&year, &month, &day,
4532 &hour, &minute, &second, &microsecond) < 0)
4533 return NULL;
4534 else
4535 return new_datetime(year, month, day,
4536 hour, minute, second, microsecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004537 HASTZINFO(date) ? date->tzinfo : Py_None, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004538}
4539
4540static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004541datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 if (PyDateTime_Check(left)) {
4544 /* datetime + ??? */
4545 if (PyDelta_Check(right))
4546 /* datetime + delta */
4547 return add_datetime_timedelta(
4548 (PyDateTime_DateTime *)left,
4549 (PyDateTime_Delta *)right,
4550 1);
4551 }
4552 else if (PyDelta_Check(left)) {
4553 /* delta + datetime */
4554 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4555 (PyDateTime_Delta *) left,
4556 1);
4557 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004558 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004559}
4560
4561static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004562datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 if (PyDateTime_Check(left)) {
4567 /* datetime - ??? */
4568 if (PyDateTime_Check(right)) {
4569 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004570 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004572
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004573 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4574 offset2 = offset1 = Py_None;
4575 Py_INCREF(offset1);
4576 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004578 else {
4579 offset1 = datetime_utcoffset(left, NULL);
4580 if (offset1 == NULL)
4581 return NULL;
4582 offset2 = datetime_utcoffset(right, NULL);
4583 if (offset2 == NULL) {
4584 Py_DECREF(offset1);
4585 return NULL;
4586 }
4587 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4588 PyErr_SetString(PyExc_TypeError,
4589 "can't subtract offset-naive and "
4590 "offset-aware datetimes");
4591 Py_DECREF(offset1);
4592 Py_DECREF(offset2);
4593 return NULL;
4594 }
4595 }
4596 if ((offset1 != offset2) &&
4597 delta_cmp(offset1, offset2) != 0) {
4598 offdiff = delta_subtract(offset1, offset2);
4599 if (offdiff == NULL) {
4600 Py_DECREF(offset1);
4601 Py_DECREF(offset2);
4602 return NULL;
4603 }
4604 }
4605 Py_DECREF(offset1);
4606 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 delta_d = ymd_to_ord(GET_YEAR(left),
4608 GET_MONTH(left),
4609 GET_DAY(left)) -
4610 ymd_to_ord(GET_YEAR(right),
4611 GET_MONTH(right),
4612 GET_DAY(right));
4613 /* These can't overflow, since the values are
4614 * normalized. At most this gives the number of
4615 * seconds in one day.
4616 */
4617 delta_s = (DATE_GET_HOUR(left) -
4618 DATE_GET_HOUR(right)) * 3600 +
4619 (DATE_GET_MINUTE(left) -
4620 DATE_GET_MINUTE(right)) * 60 +
4621 (DATE_GET_SECOND(left) -
4622 DATE_GET_SECOND(right));
4623 delta_us = DATE_GET_MICROSECOND(left) -
4624 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004626 if (result == NULL)
4627 return NULL;
4628
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004629 if (offdiff != NULL) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03004630 Py_SETREF(result, delta_subtract(result, offdiff));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004631 Py_DECREF(offdiff);
4632 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 }
4634 else if (PyDelta_Check(right)) {
4635 /* datetime - delta */
4636 result = add_datetime_timedelta(
4637 (PyDateTime_DateTime *)left,
4638 (PyDateTime_Delta *)right,
4639 -1);
4640 }
4641 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 if (result == Py_NotImplemented)
4644 Py_INCREF(result);
4645 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004646}
4647
4648/* Various ways to turn a datetime into a string. */
4649
4650static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004651datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 const char *type_name = Py_TYPE(self)->tp_name;
4654 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 if (DATE_GET_MICROSECOND(self)) {
4657 baserepr = PyUnicode_FromFormat(
4658 "%s(%d, %d, %d, %d, %d, %d, %d)",
4659 type_name,
4660 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4661 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4662 DATE_GET_SECOND(self),
4663 DATE_GET_MICROSECOND(self));
4664 }
4665 else if (DATE_GET_SECOND(self)) {
4666 baserepr = PyUnicode_FromFormat(
4667 "%s(%d, %d, %d, %d, %d, %d)",
4668 type_name,
4669 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4670 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4671 DATE_GET_SECOND(self));
4672 }
4673 else {
4674 baserepr = PyUnicode_FromFormat(
4675 "%s(%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 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004680 if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
4681 baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 if (baserepr == NULL || ! HASTZINFO(self))
4683 return baserepr;
4684 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004685}
4686
Tim Petersa9bc1682003-01-11 03:39:11 +00004687static PyObject *
4688datetime_str(PyDateTime_DateTime *self)
4689{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004690 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004691}
Tim Peters2a799bf2002-12-16 20:18:38 +00004692
4693static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004694datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 int sep = 'T';
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004697 char *timespec = NULL;
4698 static char *keywords[] = {"sep", "timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 char buffer[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004700 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 int us = DATE_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004702 static char *specs[][2] = {
4703 {"hours", "%04d-%02d-%02d%c%02d"},
4704 {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
4705 {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
4706 {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
4707 {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
4708 };
4709 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00004710
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004711 if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 return NULL;
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004713
4714 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4715 if (us == 0) {
4716 /* seconds */
4717 given_spec = 2;
4718 }
4719 else {
4720 /* microseconds */
4721 given_spec = 4;
4722 }
4723 }
4724 else {
4725 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4726 if (strcmp(timespec, specs[given_spec][0]) == 0) {
4727 if (given_spec == 3) {
4728 us = us / 1000;
4729 }
4730 break;
4731 }
4732 }
4733 }
4734
4735 if (given_spec == Py_ARRAY_LENGTH(specs)) {
4736 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4737 return NULL;
4738 }
4739 else {
4740 result = PyUnicode_FromFormat(specs[given_spec][1],
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 GET_YEAR(self), GET_MONTH(self),
4742 GET_DAY(self), (int)sep,
4743 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4744 DATE_GET_SECOND(self), us);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004745 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 if (!result || !HASTZINFO(self))
4748 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 /* We need to append the UTC offset. */
4751 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4752 (PyObject *)self) < 0) {
4753 Py_DECREF(result);
4754 return NULL;
4755 }
4756 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4757 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004758}
4759
Tim Petersa9bc1682003-01-11 03:39:11 +00004760static PyObject *
4761datetime_ctime(PyDateTime_DateTime *self)
4762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 return format_ctime((PyDateTime_Date *)self,
4764 DATE_GET_HOUR(self),
4765 DATE_GET_MINUTE(self),
4766 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004767}
4768
Tim Peters2a799bf2002-12-16 20:18:38 +00004769/* Miscellaneous methods. */
4770
Tim Petersa9bc1682003-01-11 03:39:11 +00004771static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004772flip_fold(PyObject *dt)
4773{
4774 return new_datetime_ex2(GET_YEAR(dt),
4775 GET_MONTH(dt),
4776 GET_DAY(dt),
4777 DATE_GET_HOUR(dt),
4778 DATE_GET_MINUTE(dt),
4779 DATE_GET_SECOND(dt),
4780 DATE_GET_MICROSECOND(dt),
4781 HASTZINFO(dt) ?
4782 ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
4783 !DATE_GET_FOLD(dt),
4784 Py_TYPE(dt));
4785}
4786
4787static PyObject *
4788get_flip_fold_offset(PyObject *dt)
4789{
4790 PyObject *result, *flip_dt;
4791
4792 flip_dt = flip_fold(dt);
4793 if (flip_dt == NULL)
4794 return NULL;
4795 result = datetime_utcoffset(flip_dt, NULL);
4796 Py_DECREF(flip_dt);
4797 return result;
4798}
4799
4800/* PEP 495 exception: Whenever one or both of the operands in
4801 * inter-zone comparison is such that its utcoffset() depends
4802 * on the value of its fold fold attribute, the result is False.
4803 *
4804 * Return 1 if exception applies, 0 if not, and -1 on error.
4805 */
4806static int
4807pep495_eq_exception(PyObject *self, PyObject *other,
4808 PyObject *offset_self, PyObject *offset_other)
4809{
4810 int result = 0;
4811 PyObject *flip_offset;
4812
4813 flip_offset = get_flip_fold_offset(self);
4814 if (flip_offset == NULL)
4815 return -1;
4816 if (flip_offset != offset_self &&
4817 delta_cmp(flip_offset, offset_self))
4818 {
4819 result = 1;
4820 goto done;
4821 }
4822 Py_DECREF(flip_offset);
4823
4824 flip_offset = get_flip_fold_offset(other);
4825 if (flip_offset == NULL)
4826 return -1;
4827 if (flip_offset != offset_other &&
4828 delta_cmp(flip_offset, offset_other))
4829 result = 1;
4830 done:
4831 Py_DECREF(flip_offset);
4832 return result;
4833}
4834
4835static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004836datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004837{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004838 PyObject *result = NULL;
4839 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 if (! PyDateTime_Check(other)) {
4843 if (PyDate_Check(other)) {
4844 /* Prevent invocation of date_richcompare. We want to
4845 return NotImplemented here to give the other object
4846 a chance. But since DateTime is a subclass of
4847 Date, if the other object is a Date, it would
4848 compute an ordering based on the date part alone,
4849 and we don't want that. So force unequal or
4850 uncomparable here in that case. */
4851 if (op == Py_EQ)
4852 Py_RETURN_FALSE;
4853 if (op == Py_NE)
4854 Py_RETURN_TRUE;
4855 return cmperror(self, other);
4856 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004857 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004859
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004860 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4862 ((PyDateTime_DateTime *)other)->data,
4863 _PyDateTime_DATETIME_DATASIZE);
4864 return diff_to_bool(diff, op);
4865 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004866 offset1 = datetime_utcoffset(self, NULL);
4867 if (offset1 == NULL)
4868 return NULL;
4869 offset2 = datetime_utcoffset(other, NULL);
4870 if (offset2 == NULL)
4871 goto done;
4872 /* If they're both naive, or both aware and have the same offsets,
4873 * we get off cheap. Note that if they're both naive, offset1 ==
4874 * offset2 == Py_None at this point.
4875 */
4876 if ((offset1 == offset2) ||
4877 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4878 delta_cmp(offset1, offset2) == 0)) {
4879 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4880 ((PyDateTime_DateTime *)other)->data,
4881 _PyDateTime_DATETIME_DATASIZE);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004882 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4883 int ex = pep495_eq_exception(self, other, offset1, offset2);
4884 if (ex == -1)
4885 goto done;
4886 if (ex)
4887 diff = 1;
4888 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004889 result = diff_to_bool(diff, op);
4890 }
4891 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004893
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004894 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4896 other);
4897 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004898 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 diff = GET_TD_DAYS(delta);
4900 if (diff == 0)
4901 diff = GET_TD_SECONDS(delta) |
4902 GET_TD_MICROSECONDS(delta);
4903 Py_DECREF(delta);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004904 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4905 int ex = pep495_eq_exception(self, other, offset1, offset2);
4906 if (ex == -1)
4907 goto done;
4908 if (ex)
4909 diff = 1;
4910 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004911 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004913 else if (op == Py_EQ) {
4914 result = Py_False;
4915 Py_INCREF(result);
4916 }
4917 else if (op == Py_NE) {
4918 result = Py_True;
4919 Py_INCREF(result);
4920 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004921 else {
4922 PyErr_SetString(PyExc_TypeError,
4923 "can't compare offset-naive and "
4924 "offset-aware datetimes");
4925 }
4926 done:
4927 Py_DECREF(offset1);
4928 Py_XDECREF(offset2);
4929 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004930}
4931
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004932static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004933datetime_hash(PyDateTime_DateTime *self)
4934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004935 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004936 PyObject *offset, *self0;
4937 if (DATE_GET_FOLD(self)) {
4938 self0 = new_datetime_ex2(GET_YEAR(self),
4939 GET_MONTH(self),
4940 GET_DAY(self),
4941 DATE_GET_HOUR(self),
4942 DATE_GET_MINUTE(self),
4943 DATE_GET_SECOND(self),
4944 DATE_GET_MICROSECOND(self),
4945 HASTZINFO(self) ? self->tzinfo : Py_None,
4946 0, Py_TYPE(self));
4947 if (self0 == NULL)
4948 return -1;
4949 }
4950 else {
4951 self0 = (PyObject *)self;
4952 Py_INCREF(self0);
4953 }
4954 offset = datetime_utcoffset(self0, NULL);
4955 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004956
4957 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004961 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004962 self->hashcode = generic_hash(
4963 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004965 PyObject *temp1, *temp2;
4966 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 assert(HASTZINFO(self));
4969 days = ymd_to_ord(GET_YEAR(self),
4970 GET_MONTH(self),
4971 GET_DAY(self));
4972 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004973 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004974 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004975 temp1 = new_delta(days, seconds,
4976 DATE_GET_MICROSECOND(self),
4977 1);
4978 if (temp1 == NULL) {
4979 Py_DECREF(offset);
4980 return -1;
4981 }
4982 temp2 = delta_subtract(temp1, offset);
4983 Py_DECREF(temp1);
4984 if (temp2 == NULL) {
4985 Py_DECREF(offset);
4986 return -1;
4987 }
4988 self->hashcode = PyObject_Hash(temp2);
4989 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004991 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 }
4993 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004994}
Tim Peters2a799bf2002-12-16 20:18:38 +00004995
4996static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004997datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 PyObject *clone;
5000 PyObject *tuple;
5001 int y = GET_YEAR(self);
5002 int m = GET_MONTH(self);
5003 int d = GET_DAY(self);
5004 int hh = DATE_GET_HOUR(self);
5005 int mm = DATE_GET_MINUTE(self);
5006 int ss = DATE_GET_SECOND(self);
5007 int us = DATE_GET_MICROSECOND(self);
5008 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005009 int fold = DATE_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00005010
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005011 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 datetime_kws,
5013 &y, &m, &d, &hh, &mm, &ss, &us,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005014 &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 return NULL;
5016 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
5017 if (tuple == NULL)
5018 return NULL;
5019 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005020
5021 if (clone != NULL) {
5022 if (fold != 0 && fold != 1) {
5023 PyErr_SetString(PyExc_ValueError,
5024 "fold must be either 0 or 1");
5025 return NULL;
5026 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005027 DATE_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005028 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 Py_DECREF(tuple);
5030 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00005031}
5032
5033static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005034local_timezone_from_timestamp(time_t timestamp)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005035{
5036 PyObject *result = NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005037 PyObject *delta;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005038 struct tm *local_time_tm;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005039 PyObject *nameo = NULL;
5040 const char *zone = NULL;
5041
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005042 local_time_tm = localtime(&timestamp);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005043#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005044 zone = local_time_tm->tm_zone;
5045 delta = new_delta(0, local_time_tm->tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005046#else /* HAVE_STRUCT_TM_TM_ZONE */
5047 {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005048 PyObject *local_time, *utc_time;
5049 struct tm *utc_time_tm;
5050 char buf[100];
5051 strftime(buf, sizeof(buf), "%Z", local_time_tm);
5052 zone = buf;
5053 local_time = new_datetime(local_time_tm->tm_year + 1900,
5054 local_time_tm->tm_mon + 1,
5055 local_time_tm->tm_mday,
5056 local_time_tm->tm_hour,
5057 local_time_tm->tm_min,
5058 local_time_tm->tm_sec, 0, Py_None, 0);
5059 if (local_time == NULL) {
5060 return NULL;
5061 }
5062 utc_time_tm = gmtime(&timestamp);
5063 utc_time = new_datetime(utc_time_tm->tm_year + 1900,
5064 utc_time_tm->tm_mon + 1,
5065 utc_time_tm->tm_mday,
5066 utc_time_tm->tm_hour,
5067 utc_time_tm->tm_min,
5068 utc_time_tm->tm_sec, 0, Py_None, 0);
5069 if (utc_time == NULL) {
5070 Py_DECREF(local_time);
5071 return NULL;
5072 }
5073 delta = datetime_subtract(local_time, utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005074 Py_DECREF(local_time);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005075 Py_DECREF(utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005076 }
5077#endif /* HAVE_STRUCT_TM_TM_ZONE */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005078 if (delta == NULL) {
5079 return NULL;
5080 }
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005081 if (zone != NULL) {
5082 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
5083 if (nameo == NULL)
5084 goto error;
5085 }
5086 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02005087 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005088 error:
5089 Py_DECREF(delta);
5090 return result;
5091}
5092
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005093static PyObject *
5094local_timezone(PyDateTime_DateTime *utc_time)
5095{
5096 time_t timestamp;
5097 PyObject *delta;
5098 PyObject *one_second;
5099 PyObject *seconds;
5100
5101 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
5102 if (delta == NULL)
5103 return NULL;
5104 one_second = new_delta(0, 1, 0, 0);
5105 if (one_second == NULL) {
5106 Py_DECREF(delta);
5107 return NULL;
5108 }
5109 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
5110 (PyDateTime_Delta *)one_second);
5111 Py_DECREF(one_second);
5112 Py_DECREF(delta);
5113 if (seconds == NULL)
5114 return NULL;
5115 timestamp = _PyLong_AsTime_t(seconds);
5116 Py_DECREF(seconds);
5117 if (timestamp == -1 && PyErr_Occurred())
5118 return NULL;
5119 return local_timezone_from_timestamp(timestamp);
5120}
5121
5122static PY_LONG_LONG
5123local_to_seconds(int year, int month, int day,
5124 int hour, int minute, int second, int fold);
5125
5126static PyObject *
5127local_timezone_from_local(PyDateTime_DateTime *local_dt)
5128{
5129 PY_LONG_LONG seconds;
5130 time_t timestamp;
5131 seconds = local_to_seconds(GET_YEAR(local_dt),
5132 GET_MONTH(local_dt),
5133 GET_DAY(local_dt),
5134 DATE_GET_HOUR(local_dt),
5135 DATE_GET_MINUTE(local_dt),
5136 DATE_GET_SECOND(local_dt),
5137 DATE_GET_FOLD(local_dt));
5138 if (seconds == -1)
5139 return NULL;
5140 /* XXX: add bounds check */
5141 timestamp = seconds - epoch;
5142 return local_timezone_from_timestamp(timestamp);
5143}
5144
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005145static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00005146datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00005147{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005148 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005149 PyObject *offset;
5150 PyObject *temp;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005151 PyObject *self_tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005152 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00005154
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005155 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07005156 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005157 return NULL;
5158
5159 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00005161
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005162 if (!HASTZINFO(self) || self->tzinfo == Py_None) {
5163 self_tzinfo = local_timezone_from_local(self);
5164 if (self_tzinfo == NULL)
5165 return NULL;
5166 } else {
5167 self_tzinfo = self->tzinfo;
5168 Py_INCREF(self_tzinfo);
5169 }
Tim Peters521fc152002-12-31 17:36:56 +00005170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005171 /* Conversion to self's own time zone is a NOP. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005172 if (self_tzinfo == tzinfo) {
5173 Py_DECREF(self_tzinfo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005175 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 }
Tim Peters521fc152002-12-31 17:36:56 +00005177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 /* Convert self to UTC. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005179 offset = call_utcoffset(self_tzinfo, (PyObject *)self);
5180 Py_DECREF(self_tzinfo);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005181 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005183 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005184 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5185 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005186 Py_DECREF(offset);
5187 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00005189
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005190 /* Make sure result is aware and UTC. */
5191 if (!HASTZINFO(result)) {
5192 temp = (PyObject *)result;
5193 result = (PyDateTime_DateTime *)
5194 new_datetime_ex2(GET_YEAR(result),
5195 GET_MONTH(result),
5196 GET_DAY(result),
5197 DATE_GET_HOUR(result),
5198 DATE_GET_MINUTE(result),
5199 DATE_GET_SECOND(result),
5200 DATE_GET_MICROSECOND(result),
5201 PyDateTime_TimeZone_UTC,
5202 DATE_GET_FOLD(result),
5203 Py_TYPE(result));
5204 Py_DECREF(temp);
5205 if (result == NULL)
5206 return NULL;
5207 }
5208 else {
5209 /* Result is already aware - just replace tzinfo. */
5210 temp = result->tzinfo;
5211 result->tzinfo = PyDateTime_TimeZone_UTC;
5212 Py_INCREF(result->tzinfo);
5213 Py_DECREF(temp);
5214 }
5215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005217 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005218 if (tzinfo == Py_None) {
5219 tzinfo = local_timezone(result);
5220 if (tzinfo == NULL) {
5221 Py_DECREF(result);
5222 return NULL;
5223 }
5224 }
5225 else
5226 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005227 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005228 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00005229
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005230 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005231 result = (PyDateTime_DateTime *)
5232 _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", temp);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005233 Py_DECREF(temp);
5234
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005235 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00005236}
5237
5238static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005239datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00005242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005244 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00005245
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005246 dst = call_dst(self->tzinfo, (PyObject *)self);
5247 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005249
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005250 if (dst != Py_None)
5251 dstflag = delta_bool((PyDateTime_Delta *)dst);
5252 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005253 }
5254 return build_struct_time(GET_YEAR(self),
5255 GET_MONTH(self),
5256 GET_DAY(self),
5257 DATE_GET_HOUR(self),
5258 DATE_GET_MINUTE(self),
5259 DATE_GET_SECOND(self),
5260 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00005261}
5262
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005263static PY_LONG_LONG
5264local_to_seconds(int year, int month, int day,
5265 int hour, int minute, int second, int fold)
5266{
5267 PY_LONG_LONG t, a, b, u1, u2, t1, t2, lt;
5268 t = utc_to_seconds(year, month, day, hour, minute, second);
5269 /* Our goal is to solve t = local(u) for u. */
5270 lt = local(t);
5271 if (lt == -1)
5272 return -1;
5273 a = lt - t;
5274 u1 = t - a;
5275 t1 = local(u1);
5276 if (t1 == -1)
5277 return -1;
5278 if (t1 == t) {
5279 /* We found one solution, but it may not be the one we need.
5280 * Look for an earlier solution (if `fold` is 0), or a
5281 * later one (if `fold` is 1). */
5282 if (fold)
5283 u2 = u1 + max_fold_seconds;
5284 else
5285 u2 = u1 - max_fold_seconds;
5286 lt = local(u2);
5287 if (lt == -1)
5288 return -1;
5289 b = lt - u2;
5290 if (a == b)
5291 return u1;
5292 }
5293 else {
5294 b = t1 - u1;
5295 assert(a != b);
5296 }
5297 u2 = t - b;
5298 t2 = local(u2);
5299 if (t2 == -1)
5300 return -1;
5301 if (t2 == t)
5302 return u2;
5303 if (t1 == t)
5304 return u1;
5305 /* We have found both offsets a and b, but neither t - a nor t - b is
5306 * a solution. This means t is in the gap. */
5307 return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
5308}
5309
5310/* date(1970,1,1).toordinal() == 719163 */
5311#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
5312
Tim Peters2a799bf2002-12-16 20:18:38 +00005313static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04005314datetime_timestamp(PyDateTime_DateTime *self)
5315{
5316 PyObject *result;
5317
5318 if (HASTZINFO(self) && self->tzinfo != Py_None) {
5319 PyObject *delta;
5320 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
5321 if (delta == NULL)
5322 return NULL;
5323 result = delta_total_seconds(delta);
5324 Py_DECREF(delta);
5325 }
5326 else {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005327 PY_LONG_LONG seconds;
5328 seconds = local_to_seconds(GET_YEAR(self),
5329 GET_MONTH(self),
5330 GET_DAY(self),
5331 DATE_GET_HOUR(self),
5332 DATE_GET_MINUTE(self),
5333 DATE_GET_SECOND(self),
5334 DATE_GET_FOLD(self));
5335 if (seconds == -1)
Alexander Belopolskya4415142012-06-08 12:33:09 -04005336 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005337 result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
5338 DATE_GET_MICROSECOND(self) / 1e6);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005339 }
5340 return result;
5341}
5342
5343static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005344datetime_getdate(PyDateTime_DateTime *self)
5345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005346 return new_date(GET_YEAR(self),
5347 GET_MONTH(self),
5348 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005349}
5350
5351static PyObject *
5352datetime_gettime(PyDateTime_DateTime *self)
5353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 return new_time(DATE_GET_HOUR(self),
5355 DATE_GET_MINUTE(self),
5356 DATE_GET_SECOND(self),
5357 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005358 Py_None,
5359 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005360}
5361
5362static PyObject *
5363datetime_gettimetz(PyDateTime_DateTime *self)
5364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 return new_time(DATE_GET_HOUR(self),
5366 DATE_GET_MINUTE(self),
5367 DATE_GET_SECOND(self),
5368 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005369 GET_DT_TZINFO(self),
5370 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005371}
5372
5373static PyObject *
5374datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005375{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005376 int y, m, d, hh, mm, ss;
5377 PyObject *tzinfo;
5378 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00005379
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005380 tzinfo = GET_DT_TZINFO(self);
5381 if (tzinfo == Py_None) {
5382 utcself = self;
5383 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005385 else {
5386 PyObject *offset;
5387 offset = call_utcoffset(tzinfo, (PyObject *)self);
5388 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00005389 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005390 if (offset == Py_None) {
5391 Py_DECREF(offset);
5392 utcself = self;
5393 Py_INCREF(utcself);
5394 }
5395 else {
5396 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5397 (PyDateTime_Delta *)offset, -1);
5398 Py_DECREF(offset);
5399 if (utcself == NULL)
5400 return NULL;
5401 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005403 y = GET_YEAR(utcself);
5404 m = GET_MONTH(utcself);
5405 d = GET_DAY(utcself);
5406 hh = DATE_GET_HOUR(utcself);
5407 mm = DATE_GET_MINUTE(utcself);
5408 ss = DATE_GET_SECOND(utcself);
5409
5410 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005411 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005412}
5413
Tim Peters371935f2003-02-01 01:52:50 +00005414/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00005415
Tim Petersa9bc1682003-01-11 03:39:11 +00005416/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00005417 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5418 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00005419 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00005420 */
5421static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005422datetime_getstate(PyDateTime_DateTime *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00005423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 PyObject *basestate;
5425 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005427 basestate = PyBytes_FromStringAndSize((char *)self->data,
5428 _PyDateTime_DATETIME_DATASIZE);
5429 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005430 if (proto > 3 && DATE_GET_FOLD(self))
5431 /* Set the first bit of the third byte */
5432 PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5434 result = PyTuple_Pack(1, basestate);
5435 else
5436 result = PyTuple_Pack(2, basestate, self->tzinfo);
5437 Py_DECREF(basestate);
5438 }
5439 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005440}
5441
5442static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005443datetime_reduce(PyDateTime_DateTime *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00005444{
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005445 int proto = 0;
5446 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
5447 return NULL;
5448
5449 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00005450}
5451
Tim Petersa9bc1682003-01-11 03:39:11 +00005452static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005455
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005456 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 {"utcnow", (PyCFunction)datetime_utcnow,
5459 METH_NOARGS | METH_CLASS,
5460 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5463 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5464 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5467 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05005468 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 {"strptime", (PyCFunction)datetime_strptime,
5471 METH_VARARGS | METH_CLASS,
5472 PyDoc_STR("string, format -> new datetime parsed from a string "
5473 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 {"combine", (PyCFunction)datetime_combine,
5476 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5477 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005481 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5482 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5485 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005487 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5488 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005490 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5491 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5494 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005495
Alexander Belopolskya4415142012-06-08 12:33:09 -04005496 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5497 PyDoc_STR("Return POSIX timestamp as float.")},
5498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005499 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5500 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005502 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5503 PyDoc_STR("[sep] -> string in ISO 8601 format, "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005504 "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 "sep is used to separate the year from the time, and "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005506 "defaults to 'T'.\n"
5507 "timespec specifies what components of the time to include"
5508 " (allowed values are 'auto', 'hours', 'minutes', 'seconds',"
5509 " 'milliseconds', and 'microseconds').\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5512 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5515 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5518 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5521 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5524 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005525
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005526 {"__reduce_ex__", (PyCFunction)datetime_reduce, METH_VARARGS,
5527 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005530};
5531
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02005532static const char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005533PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5534\n\
5535The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005536instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005537
Tim Petersa9bc1682003-01-11 03:39:11 +00005538static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 datetime_add, /* nb_add */
5540 datetime_subtract, /* nb_subtract */
5541 0, /* nb_multiply */
5542 0, /* nb_remainder */
5543 0, /* nb_divmod */
5544 0, /* nb_power */
5545 0, /* nb_negative */
5546 0, /* nb_positive */
5547 0, /* nb_absolute */
5548 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005549};
5550
Neal Norwitz227b5332006-03-22 09:28:35 +00005551static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 PyVarObject_HEAD_INIT(NULL, 0)
5553 "datetime.datetime", /* tp_name */
5554 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5555 0, /* tp_itemsize */
5556 (destructor)datetime_dealloc, /* tp_dealloc */
5557 0, /* tp_print */
5558 0, /* tp_getattr */
5559 0, /* tp_setattr */
5560 0, /* tp_reserved */
5561 (reprfunc)datetime_repr, /* tp_repr */
5562 &datetime_as_number, /* tp_as_number */
5563 0, /* tp_as_sequence */
5564 0, /* tp_as_mapping */
5565 (hashfunc)datetime_hash, /* tp_hash */
5566 0, /* tp_call */
5567 (reprfunc)datetime_str, /* tp_str */
5568 PyObject_GenericGetAttr, /* tp_getattro */
5569 0, /* tp_setattro */
5570 0, /* tp_as_buffer */
5571 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5572 datetime_doc, /* tp_doc */
5573 0, /* tp_traverse */
5574 0, /* tp_clear */
5575 datetime_richcompare, /* tp_richcompare */
5576 0, /* tp_weaklistoffset */
5577 0, /* tp_iter */
5578 0, /* tp_iternext */
5579 datetime_methods, /* tp_methods */
5580 0, /* tp_members */
5581 datetime_getset, /* tp_getset */
5582 &PyDateTime_DateType, /* tp_base */
5583 0, /* tp_dict */
5584 0, /* tp_descr_get */
5585 0, /* tp_descr_set */
5586 0, /* tp_dictoffset */
5587 0, /* tp_init */
5588 datetime_alloc, /* tp_alloc */
5589 datetime_new, /* tp_new */
5590 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005591};
5592
5593/* ---------------------------------------------------------------------------
5594 * Module methods and initialization.
5595 */
5596
5597static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005599};
5600
Tim Peters9ddf40b2004-06-20 22:41:32 +00005601/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5602 * datetime.h.
5603 */
5604static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005605 &PyDateTime_DateType,
5606 &PyDateTime_DateTimeType,
5607 &PyDateTime_TimeType,
5608 &PyDateTime_DeltaType,
5609 &PyDateTime_TZInfoType,
5610 new_date_ex,
5611 new_datetime_ex,
5612 new_time_ex,
5613 new_delta_ex,
5614 datetime_fromtimestamp,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005615 date_fromtimestamp,
5616 new_datetime_ex2,
5617 new_time_ex2
Tim Peters9ddf40b2004-06-20 22:41:32 +00005618};
5619
5620
Martin v. Löwis1a214512008-06-11 05:26:20 +00005621
5622static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005623 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005624 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 "Fast implementation of the datetime type.",
5626 -1,
5627 module_methods,
5628 NULL,
5629 NULL,
5630 NULL,
5631 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005632};
5633
Tim Peters2a799bf2002-12-16 20:18:38 +00005634PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005635PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 PyObject *m; /* a module object */
5638 PyObject *d; /* its dict */
5639 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005640 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 m = PyModule_Create(&datetimemodule);
5643 if (m == NULL)
5644 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 if (PyType_Ready(&PyDateTime_DateType) < 0)
5647 return NULL;
5648 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5649 return NULL;
5650 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5651 return NULL;
5652 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5653 return NULL;
5654 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5655 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005656 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5657 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 /* timedelta values */
5660 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005662 x = new_delta(0, 0, 1, 0);
5663 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5664 return NULL;
5665 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5668 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5669 return NULL;
5670 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5673 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5674 return NULL;
5675 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 /* date values */
5678 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 x = new_date(1, 1, 1);
5681 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5682 return NULL;
5683 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 x = new_date(MAXYEAR, 12, 31);
5686 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5687 return NULL;
5688 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 x = new_delta(1, 0, 0, 0);
5691 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5692 return NULL;
5693 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 /* time values */
5696 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005697
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005698 x = new_time(0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5700 return NULL;
5701 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005702
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005703 x = new_time(23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5705 return NULL;
5706 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 x = new_delta(0, 0, 1, 0);
5709 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5710 return NULL;
5711 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 /* datetime values */
5714 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005715
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005716 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5718 return NULL;
5719 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005720
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005721 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5723 return NULL;
5724 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 x = new_delta(0, 0, 1, 0);
5727 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5728 return NULL;
5729 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005730
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005731 /* timezone values */
5732 d = PyDateTime_TimeZoneType.tp_dict;
5733
5734 delta = new_delta(0, 0, 0, 0);
5735 if (delta == NULL)
5736 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005737 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005738 Py_DECREF(delta);
5739 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5740 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005741 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005742
5743 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5744 if (delta == NULL)
5745 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005746 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005747 Py_DECREF(delta);
5748 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5749 return NULL;
5750 Py_DECREF(x);
5751
5752 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5753 if (delta == NULL)
5754 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005755 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005756 Py_DECREF(delta);
5757 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5758 return NULL;
5759 Py_DECREF(x);
5760
Alexander Belopolskya4415142012-06-08 12:33:09 -04005761 /* Epoch */
5762 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005763 PyDateTime_TimeZone_UTC, 0);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005764 if (PyDateTime_Epoch == NULL)
5765 return NULL;
5766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005767 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005768 PyModule_AddIntMacro(m, MINYEAR);
5769 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005771 Py_INCREF(&PyDateTime_DateType);
5772 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 Py_INCREF(&PyDateTime_DateTimeType);
5775 PyModule_AddObject(m, "datetime",
5776 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005778 Py_INCREF(&PyDateTime_TimeType);
5779 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 Py_INCREF(&PyDateTime_DeltaType);
5782 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005784 Py_INCREF(&PyDateTime_TZInfoType);
5785 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005786
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005787 Py_INCREF(&PyDateTime_TimeZoneType);
5788 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005790 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5791 if (x == NULL)
5792 return NULL;
5793 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005795 /* A 4-year cycle has an extra leap day over what we'd get from
5796 * pasting together 4 single years.
5797 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005798 Py_BUILD_ASSERT(DI4Y == 4 * 365 + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5802 * get from pasting together 4 100-year cycles.
5803 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005804 Py_BUILD_ASSERT(DI400Y == 4 * DI100Y + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005805 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5808 * pasting together 25 4-year cycles.
5809 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005810 Py_BUILD_ASSERT(DI100Y == 25 * DI4Y - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005812
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005813 one = PyLong_FromLong(1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005814 us_per_ms = PyLong_FromLong(1000);
5815 us_per_second = PyLong_FromLong(1000000);
5816 us_per_minute = PyLong_FromLong(60000000);
5817 seconds_per_day = PyLong_FromLong(24 * 3600);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005818 if (one == NULL || us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 us_per_minute == NULL || seconds_per_day == NULL)
5820 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 /* The rest are too big for 32-bit ints, but even
5823 * us_per_week fits in 40 bits, so doubles should be exact.
5824 */
5825 us_per_hour = PyLong_FromDouble(3600000000.0);
5826 us_per_day = PyLong_FromDouble(86400000000.0);
5827 us_per_week = PyLong_FromDouble(604800000000.0);
5828 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5829 return NULL;
5830 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005831}
Tim Petersf3615152003-01-01 21:51:37 +00005832
5833/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005834Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005835 x.n = x stripped of its timezone -- its naive time.
5836 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 return None
Tim Petersf3615152003-01-01 21:51:37 +00005838 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005839 return None
Tim Petersf3615152003-01-01 21:51:37 +00005840 x.s = x's standard offset, x.o - x.d
5841
5842Now some derived rules, where k is a duration (timedelta).
5843
58441. x.o = x.s + x.d
5845 This follows from the definition of x.s.
5846
Tim Petersc5dc4da2003-01-02 17:55:03 +000058472. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005848 This is actually a requirement, an assumption we need to make about
5849 sane tzinfo classes.
5850
58513. The naive UTC time corresponding to x is x.n - x.o.
5852 This is again a requirement for a sane tzinfo class.
5853
58544. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005855 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005856
Tim Petersc5dc4da2003-01-02 17:55:03 +000058575. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005858 Again follows from how arithmetic is defined.
5859
Tim Peters8bb5ad22003-01-24 02:44:45 +00005860Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005861(meaning that the various tzinfo methods exist, and don't blow up or return
5862None when called).
5863
Tim Petersa9bc1682003-01-11 03:39:11 +00005864The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005865x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005866
5867By #3, we want
5868
Tim Peters8bb5ad22003-01-24 02:44:45 +00005869 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005870
5871The algorithm starts by attaching tz to x.n, and calling that y. So
5872x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5873becomes true; in effect, we want to solve [2] for k:
5874
Tim Peters8bb5ad22003-01-24 02:44:45 +00005875 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005876
5877By #1, this is the same as
5878
Tim Peters8bb5ad22003-01-24 02:44:45 +00005879 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005880
5881By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5882Substituting that into [3],
5883
Tim Peters8bb5ad22003-01-24 02:44:45 +00005884 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5885 k - (y+k).s - (y+k).d = 0; rearranging,
5886 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5887 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005888
Tim Peters8bb5ad22003-01-24 02:44:45 +00005889On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5890approximate k by ignoring the (y+k).d term at first. Note that k can't be
5891very large, since all offset-returning methods return a duration of magnitude
5892less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5893be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005894
5895In any case, the new value is
5896
Tim Peters8bb5ad22003-01-24 02:44:45 +00005897 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005898
Tim Peters8bb5ad22003-01-24 02:44:45 +00005899It's helpful to step back at look at [4] from a higher level: it's simply
5900mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005901
5902At this point, if
5903
Tim Peters8bb5ad22003-01-24 02:44:45 +00005904 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005905
5906we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005907at the start of daylight time. Picture US Eastern for concreteness. The wall
5908time 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 +00005909sense then. The docs ask that an Eastern tzinfo class consider such a time to
5910be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5911on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005912the only spelling that makes sense on the local wall clock.
5913
Tim Petersc5dc4da2003-01-02 17:55:03 +00005914In fact, if [5] holds at this point, we do have the standard-time spelling,
5915but that takes a bit of proof. We first prove a stronger result. What's the
5916difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005917
Tim Peters8bb5ad22003-01-24 02:44:45 +00005918 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005919
Tim Petersc5dc4da2003-01-02 17:55:03 +00005920Now
5921 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005922 (y + y.s).n = by #5
5923 y.n + y.s = since y.n = x.n
5924 x.n + y.s = since z and y are have the same tzinfo member,
5925 y.s = z.s by #2
5926 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005927
Tim Petersc5dc4da2003-01-02 17:55:03 +00005928Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005929
Tim Petersc5dc4da2003-01-02 17:55:03 +00005930 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005931 x.n - ((x.n + z.s) - z.o) = expanding
5932 x.n - x.n - z.s + z.o = cancelling
5933 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005934 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005935
Tim Petersc5dc4da2003-01-02 17:55:03 +00005936So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005937
Tim Petersc5dc4da2003-01-02 17:55:03 +00005938If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005939spelling we wanted in the endcase described above. We're done. Contrarily,
5940if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005941
Tim Petersc5dc4da2003-01-02 17:55:03 +00005942If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5943add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005944local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005945
Tim Petersc5dc4da2003-01-02 17:55:03 +00005946Let
Tim Petersf3615152003-01-01 21:51:37 +00005947
Tim Peters4fede1a2003-01-04 00:26:59 +00005948 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005949
Tim Peters4fede1a2003-01-04 00:26:59 +00005950and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005951
Tim Peters8bb5ad22003-01-24 02:44:45 +00005952 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005953
Tim Peters8bb5ad22003-01-24 02:44:45 +00005954If so, we're done. If not, the tzinfo class is insane, according to the
5955assumptions we've made. This also requires a bit of proof. As before, let's
5956compute the difference between the LHS and RHS of [8] (and skipping some of
5957the justifications for the kinds of substitutions we've done several times
5958already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005959
Tim Peters8bb5ad22003-01-24 02:44:45 +00005960 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005961 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5962 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5963 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5964 - z.n + z.n - z.o + z'.o = cancel z.n
5965 - z.o + z'.o = #1 twice
5966 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5967 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005968
5969So 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 +00005970we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5971return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005972
Tim Peters8bb5ad22003-01-24 02:44:45 +00005973How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5974a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5975would have to change the result dst() returns: we start in DST, and moving
5976a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005977
Tim Peters8bb5ad22003-01-24 02:44:45 +00005978There isn't a sane case where this can happen. The closest it gets is at
5979the end of DST, where there's an hour in UTC with no spelling in a hybrid
5980tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5981that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5982UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5983time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5984clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5985standard time. Since that's what the local clock *does*, we want to map both
5986UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005987in local time, but so it goes -- it's the way the local clock works.
5988
Tim Peters8bb5ad22003-01-24 02:44:45 +00005989When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5990so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5991z' = 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 +00005992(correctly) concludes that z' is not UTC-equivalent to x.
5993
5994Because we know z.d said z was in daylight time (else [5] would have held and
5995we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005996and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005997return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5998but the reasoning doesn't depend on the example -- it depends on there being
5999two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00006000z' must be in standard time, and is the spelling we want in this case.
6001
6002Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
6003concerned (because it takes z' as being in standard time rather than the
6004daylight time we intend here), but returning it gives the real-life "local
6005clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
6006tz.
6007
6008When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
6009the 1:MM standard time spelling we want.
6010
6011So how can this break? One of the assumptions must be violated. Two
6012possibilities:
6013
60141) [2] effectively says that y.s is invariant across all y belong to a given
6015 time zone. This isn't true if, for political reasons or continental drift,
6016 a region decides to change its base offset from UTC.
6017
60182) There may be versions of "double daylight" time where the tail end of
6019 the analysis gives up a step too early. I haven't thought about that
6020 enough to say.
6021
6022In any case, it's clear that the default fromutc() is strong enough to handle
6023"almost all" time zones: so long as the standard offset is invariant, it
6024doesn't matter if daylight time transition points change from year to year, or
6025if daylight time is skipped in some years; it doesn't matter how large or
6026small dst() may get within its bounds; and it doesn't even matter if some
6027perverse time zone returns a negative dst()). So a breaking case must be
6028pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00006029--------------------------------------------------------------------------- */