blob: b48dc2dff322a43edebd80b478f1b28bf579cc4c [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
Victor Stinnerad8c83a2016-09-05 17:53:15 -07001381 result = _PyObject_CallMethodId(time, &PyId_time, NULL);
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{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002706 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
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
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002732 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, NULL);
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{
Victor Stinnerd1584d32016-08-23 00:11:04 +02003136 PyObject *args, *state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 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
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003141 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 if (getinitargs != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003143 args = _PyObject_CallNoArg(getinitargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 Py_DECREF(getinitargs);
3145 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 return NULL;
3147 }
3148 }
3149 else {
3150 PyErr_Clear();
Victor Stinnerd1584d32016-08-23 00:11:04 +02003151
3152 args = PyTuple_New(0);
3153 if (args == NULL) {
3154 return NULL;
3155 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003157
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003158 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 if (getstate != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003160 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 Py_DECREF(getstate);
3162 if (state == NULL) {
3163 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 return NULL;
3165 }
3166 }
3167 else {
3168 PyObject **dictptr;
3169 PyErr_Clear();
3170 state = Py_None;
3171 dictptr = _PyObject_GetDictPtr(self);
Victor Stinnerd1584d32016-08-23 00:11:04 +02003172 if (dictptr && *dictptr && PyDict_Size(*dictptr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 state = *dictptr;
Victor Stinnerd1584d32016-08-23 00:11:04 +02003174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 Py_INCREF(state);
3176 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 if (state == Py_None) {
3179 Py_DECREF(state);
3180 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3181 }
3182 else
3183 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003184}
Tim Peters2a799bf2002-12-16 20:18:38 +00003185
3186static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3189 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003192 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3193 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3196 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003199 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3202 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003205};
3206
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003207static const char tzinfo_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00003208PyDoc_STR("Abstract base class for time zone info objects.");
3209
Neal Norwitz227b5332006-03-22 09:28:35 +00003210static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 PyVarObject_HEAD_INIT(NULL, 0)
3212 "datetime.tzinfo", /* tp_name */
3213 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3214 0, /* tp_itemsize */
3215 0, /* tp_dealloc */
3216 0, /* tp_print */
3217 0, /* tp_getattr */
3218 0, /* tp_setattr */
3219 0, /* tp_reserved */
3220 0, /* tp_repr */
3221 0, /* tp_as_number */
3222 0, /* tp_as_sequence */
3223 0, /* tp_as_mapping */
3224 0, /* tp_hash */
3225 0, /* tp_call */
3226 0, /* tp_str */
3227 PyObject_GenericGetAttr, /* tp_getattro */
3228 0, /* tp_setattro */
3229 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003230 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 tzinfo_doc, /* tp_doc */
3232 0, /* tp_traverse */
3233 0, /* tp_clear */
3234 0, /* tp_richcompare */
3235 0, /* tp_weaklistoffset */
3236 0, /* tp_iter */
3237 0, /* tp_iternext */
3238 tzinfo_methods, /* tp_methods */
3239 0, /* tp_members */
3240 0, /* tp_getset */
3241 0, /* tp_base */
3242 0, /* tp_dict */
3243 0, /* tp_descr_get */
3244 0, /* tp_descr_set */
3245 0, /* tp_dictoffset */
3246 0, /* tp_init */
3247 0, /* tp_alloc */
3248 PyType_GenericNew, /* tp_new */
3249 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003250};
3251
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003252static char *timezone_kws[] = {"offset", "name", NULL};
3253
3254static PyObject *
3255timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3256{
3257 PyObject *offset;
3258 PyObject *name = NULL;
3259 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
3260 &PyDateTime_DeltaType, &offset,
3261 &PyUnicode_Type, &name))
3262 return new_timezone(offset, name);
3263
3264 return NULL;
3265}
3266
3267static void
3268timezone_dealloc(PyDateTime_TimeZone *self)
3269{
3270 Py_CLEAR(self->offset);
3271 Py_CLEAR(self->name);
3272 Py_TYPE(self)->tp_free((PyObject *)self);
3273}
3274
3275static PyObject *
3276timezone_richcompare(PyDateTime_TimeZone *self,
3277 PyDateTime_TimeZone *other, int op)
3278{
Brian Curtindfc80e32011-08-10 20:28:54 -05003279 if (op != Py_EQ && op != Py_NE)
3280 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003281 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003282 if (op == Py_EQ)
3283 Py_RETURN_FALSE;
3284 else
3285 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003286 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003287 return delta_richcompare(self->offset, other->offset, op);
3288}
3289
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003290static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003291timezone_hash(PyDateTime_TimeZone *self)
3292{
3293 return delta_hash((PyDateTime_Delta *)self->offset);
3294}
3295
3296/* Check argument type passed to tzname, utcoffset, or dst methods.
3297 Returns 0 for good argument. Returns -1 and sets exception info
3298 otherwise.
3299 */
3300static int
3301_timezone_check_argument(PyObject *dt, const char *meth)
3302{
3303 if (dt == Py_None || PyDateTime_Check(dt))
3304 return 0;
3305 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3306 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3307 return -1;
3308}
3309
3310static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003311timezone_repr(PyDateTime_TimeZone *self)
3312{
3313 /* Note that although timezone is not subclassable, it is convenient
3314 to use Py_TYPE(self)->tp_name here. */
3315 const char *type_name = Py_TYPE(self)->tp_name;
3316
3317 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3318 return PyUnicode_FromFormat("%s.utc", type_name);
3319
3320 if (self->name == NULL)
3321 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3322
3323 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3324 self->name);
3325}
3326
3327
3328static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003329timezone_str(PyDateTime_TimeZone *self)
3330{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003331 int hours, minutes, seconds;
3332 PyObject *offset;
3333 char sign;
3334
3335 if (self->name != NULL) {
3336 Py_INCREF(self->name);
3337 return self->name;
3338 }
Victor Stinner90fd8952015-09-08 00:12:49 +02003339 if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04003340 (GET_TD_DAYS(self->offset) == 0 &&
3341 GET_TD_SECONDS(self->offset) == 0 &&
3342 GET_TD_MICROSECONDS(self->offset) == 0))
3343 return PyUnicode_FromString("UTC");
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003344 /* Offset is normalized, so it is negative if days < 0 */
3345 if (GET_TD_DAYS(self->offset) < 0) {
3346 sign = '-';
3347 offset = delta_negative((PyDateTime_Delta *)self->offset);
3348 if (offset == NULL)
3349 return NULL;
3350 }
3351 else {
3352 sign = '+';
3353 offset = self->offset;
3354 Py_INCREF(offset);
3355 }
3356 /* Offset is not negative here. */
3357 seconds = GET_TD_SECONDS(offset);
3358 Py_DECREF(offset);
3359 minutes = divmod(seconds, 60, &seconds);
3360 hours = divmod(minutes, 60, &minutes);
Martin Pantere26da7c2016-06-02 10:07:09 +00003361 /* XXX ignore sub-minute data, currently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003362 assert(seconds == 0);
3363 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003364}
3365
3366static PyObject *
3367timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3368{
3369 if (_timezone_check_argument(dt, "tzname") == -1)
3370 return NULL;
3371
3372 return timezone_str(self);
3373}
3374
3375static PyObject *
3376timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3377{
3378 if (_timezone_check_argument(dt, "utcoffset") == -1)
3379 return NULL;
3380
3381 Py_INCREF(self->offset);
3382 return self->offset;
3383}
3384
3385static PyObject *
3386timezone_dst(PyObject *self, PyObject *dt)
3387{
3388 if (_timezone_check_argument(dt, "dst") == -1)
3389 return NULL;
3390
3391 Py_RETURN_NONE;
3392}
3393
3394static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003395timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3396{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003397 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003398 PyErr_SetString(PyExc_TypeError,
3399 "fromutc: argument must be a datetime");
3400 return NULL;
3401 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003402 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003403 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3404 "is not self");
3405 return NULL;
3406 }
3407
3408 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3409}
3410
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003411static PyObject *
3412timezone_getinitargs(PyDateTime_TimeZone *self)
3413{
3414 if (self->name == NULL)
3415 return Py_BuildValue("(O)", self->offset);
3416 return Py_BuildValue("(OO)", self->offset, self->name);
3417}
3418
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003419static PyMethodDef timezone_methods[] = {
3420 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3421 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003422 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003423
3424 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003425 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003426
3427 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003428 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003429
3430 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3431 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3432
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003433 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3434 PyDoc_STR("pickle support")},
3435
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003436 {NULL, NULL}
3437};
3438
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003439static const char timezone_doc[] =
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003440PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3441
3442static PyTypeObject PyDateTime_TimeZoneType = {
3443 PyVarObject_HEAD_INIT(NULL, 0)
3444 "datetime.timezone", /* tp_name */
3445 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3446 0, /* tp_itemsize */
3447 (destructor)timezone_dealloc, /* tp_dealloc */
3448 0, /* tp_print */
3449 0, /* tp_getattr */
3450 0, /* tp_setattr */
3451 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003452 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003453 0, /* tp_as_number */
3454 0, /* tp_as_sequence */
3455 0, /* tp_as_mapping */
3456 (hashfunc)timezone_hash, /* tp_hash */
3457 0, /* tp_call */
3458 (reprfunc)timezone_str, /* tp_str */
3459 0, /* tp_getattro */
3460 0, /* tp_setattro */
3461 0, /* tp_as_buffer */
3462 Py_TPFLAGS_DEFAULT, /* tp_flags */
3463 timezone_doc, /* tp_doc */
3464 0, /* tp_traverse */
3465 0, /* tp_clear */
3466 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3467 0, /* tp_weaklistoffset */
3468 0, /* tp_iter */
3469 0, /* tp_iternext */
3470 timezone_methods, /* tp_methods */
3471 0, /* tp_members */
3472 0, /* tp_getset */
3473 &PyDateTime_TZInfoType, /* tp_base */
3474 0, /* tp_dict */
3475 0, /* tp_descr_get */
3476 0, /* tp_descr_set */
3477 0, /* tp_dictoffset */
3478 0, /* tp_init */
3479 0, /* tp_alloc */
3480 timezone_new, /* tp_new */
3481};
3482
Tim Peters2a799bf2002-12-16 20:18:38 +00003483/*
Tim Peters37f39822003-01-10 03:49:02 +00003484 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003485 */
3486
Tim Peters37f39822003-01-10 03:49:02 +00003487/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003488 */
3489
3490static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003491time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003494}
3495
Tim Peters37f39822003-01-10 03:49:02 +00003496static PyObject *
3497time_minute(PyDateTime_Time *self, void *unused)
3498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003500}
3501
3502/* The name time_second conflicted with some platform header file. */
3503static PyObject *
3504py_time_second(PyDateTime_Time *self, void *unused)
3505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003507}
3508
3509static PyObject *
3510time_microsecond(PyDateTime_Time *self, void *unused)
3511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003513}
3514
3515static PyObject *
3516time_tzinfo(PyDateTime_Time *self, void *unused)
3517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3519 Py_INCREF(result);
3520 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003521}
3522
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003523static PyObject *
3524time_fold(PyDateTime_Time *self, void *unused)
3525{
3526 return PyLong_FromLong(TIME_GET_FOLD(self));
3527}
3528
Tim Peters37f39822003-01-10 03:49:02 +00003529static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 {"hour", (getter)time_hour},
3531 {"minute", (getter)time_minute},
3532 {"second", (getter)py_time_second},
3533 {"microsecond", (getter)time_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003534 {"tzinfo", (getter)time_tzinfo},
3535 {"fold", (getter)time_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003537};
3538
3539/*
3540 * Constructors.
3541 */
3542
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003543static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003544 "tzinfo", "fold", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003545
Tim Peters2a799bf2002-12-16 20:18:38 +00003546static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003547time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 PyObject *self = NULL;
3550 PyObject *state;
3551 int hour = 0;
3552 int minute = 0;
3553 int second = 0;
3554 int usecond = 0;
3555 PyObject *tzinfo = Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003556 int fold = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 /* Check for invocation from pickle with __getstate__ state */
3559 if (PyTuple_GET_SIZE(args) >= 1 &&
3560 PyTuple_GET_SIZE(args) <= 2 &&
3561 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3562 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003563 (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 {
3565 PyDateTime_Time *me;
3566 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 if (PyTuple_GET_SIZE(args) == 2) {
3569 tzinfo = PyTuple_GET_ITEM(args, 1);
3570 if (check_tzinfo_subclass(tzinfo) < 0) {
3571 PyErr_SetString(PyExc_TypeError, "bad "
3572 "tzinfo state arg");
3573 return NULL;
3574 }
3575 }
3576 aware = (char)(tzinfo != Py_None);
3577 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3578 if (me != NULL) {
3579 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3582 me->hashcode = -1;
3583 me->hastzinfo = aware;
3584 if (aware) {
3585 Py_INCREF(tzinfo);
3586 me->tzinfo = tzinfo;
3587 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003588 if (pdata[0] & (1 << 7)) {
3589 me->data[0] -= 128;
3590 me->fold = 1;
3591 }
3592 else {
3593 me->fold = 0;
3594 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 }
3596 return (PyObject *)me;
3597 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003598
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003599 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 &hour, &minute, &second, &usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003601 &tzinfo, &fold)) {
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003602 if (check_time_args(hour, minute, second, usecond, fold) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 return NULL;
3604 if (check_tzinfo_subclass(tzinfo) < 0)
3605 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003606 self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
3607 type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 }
3609 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003610}
3611
3612/*
3613 * Destructor.
3614 */
3615
3616static void
Tim Peters37f39822003-01-10 03:49:02 +00003617time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 if (HASTZINFO(self)) {
3620 Py_XDECREF(self->tzinfo);
3621 }
3622 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003623}
3624
3625/*
Tim Peters855fe882002-12-22 03:43:39 +00003626 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003627 */
3628
Tim Peters2a799bf2002-12-16 20:18:38 +00003629/* These are all METH_NOARGS, so don't need to check the arglist. */
3630static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003631time_utcoffset(PyObject *self, PyObject *unused) {
3632 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003633}
3634
3635static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003636time_dst(PyObject *self, PyObject *unused) {
3637 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003638}
3639
3640static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003641time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003642 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003643}
3644
3645/*
Tim Peters37f39822003-01-10 03:49:02 +00003646 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003647 */
3648
3649static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003650time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 const char *type_name = Py_TYPE(self)->tp_name;
3653 int h = TIME_GET_HOUR(self);
3654 int m = TIME_GET_MINUTE(self);
3655 int s = TIME_GET_SECOND(self);
3656 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003657 int fold = TIME_GET_FOLD(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 if (us)
3661 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3662 type_name, h, m, s, us);
3663 else if (s)
3664 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3665 type_name, h, m, s);
3666 else
3667 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3668 if (result != NULL && HASTZINFO(self))
3669 result = append_keyword_tzinfo(result, self->tzinfo);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003670 if (result != NULL && fold)
3671 result = append_keyword_fold(result, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003673}
3674
Tim Peters37f39822003-01-10 03:49:02 +00003675static PyObject *
3676time_str(PyDateTime_Time *self)
3677{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003678 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters37f39822003-01-10 03:49:02 +00003679}
Tim Peters2a799bf2002-12-16 20:18:38 +00003680
3681static PyObject *
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003682time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003684 char buf[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003685 char *timespec = NULL;
3686 static char *keywords[] = {"timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02003688 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003689 static char *specs[][2] = {
3690 {"hours", "%02d"},
3691 {"minutes", "%02d:%02d"},
3692 {"seconds", "%02d:%02d:%02d"},
3693 {"milliseconds", "%02d:%02d:%02d.%03d"},
3694 {"microseconds", "%02d:%02d:%02d.%06d"},
3695 };
3696 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00003697
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003698 if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
3699 return NULL;
3700
3701 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
3702 if (us == 0) {
3703 /* seconds */
3704 given_spec = 2;
3705 }
3706 else {
3707 /* microseconds */
3708 given_spec = 4;
3709 }
3710 }
3711 else {
3712 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
3713 if (strcmp(timespec, specs[given_spec][0]) == 0) {
3714 if (given_spec == 3) {
3715 /* milliseconds */
3716 us = us / 1000;
3717 }
3718 break;
3719 }
3720 }
3721 }
3722
3723 if (given_spec == Py_ARRAY_LENGTH(specs)) {
3724 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
3725 return NULL;
3726 }
3727 else {
3728 result = PyUnicode_FromFormat(specs[given_spec][1],
3729 TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
3730 TIME_GET_SECOND(self), us);
3731 }
Tim Peters37f39822003-01-10 03:49:02 +00003732
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003733 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 /* We need to append the UTC offset. */
3737 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3738 Py_None) < 0) {
3739 Py_DECREF(result);
3740 return NULL;
3741 }
3742 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3743 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003744}
3745
Tim Peters37f39822003-01-10 03:49:02 +00003746static PyObject *
3747time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 PyObject *result;
3750 PyObject *tuple;
3751 PyObject *format;
3752 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3755 &format))
3756 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 /* Python's strftime does insane things with the year part of the
3759 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003760 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 */
3762 tuple = Py_BuildValue("iiiiiiiii",
3763 1900, 1, 1, /* year, month, day */
3764 TIME_GET_HOUR(self),
3765 TIME_GET_MINUTE(self),
3766 TIME_GET_SECOND(self),
3767 0, 1, -1); /* weekday, daynum, dst */
3768 if (tuple == NULL)
3769 return NULL;
3770 assert(PyTuple_Size(tuple) == 9);
3771 result = wrap_strftime((PyObject *)self, format, tuple,
3772 Py_None);
3773 Py_DECREF(tuple);
3774 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003775}
Tim Peters2a799bf2002-12-16 20:18:38 +00003776
3777/*
3778 * Miscellaneous methods.
3779 */
3780
Tim Peters37f39822003-01-10 03:49:02 +00003781static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003782time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003783{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003784 PyObject *result = NULL;
3785 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003787
Brian Curtindfc80e32011-08-10 20:28:54 -05003788 if (! PyTime_Check(other))
3789 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003790
3791 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 diff = memcmp(((PyDateTime_Time *)self)->data,
3793 ((PyDateTime_Time *)other)->data,
3794 _PyDateTime_TIME_DATASIZE);
3795 return diff_to_bool(diff, op);
3796 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003797 offset1 = time_utcoffset(self, NULL);
3798 if (offset1 == NULL)
3799 return NULL;
3800 offset2 = time_utcoffset(other, NULL);
3801 if (offset2 == NULL)
3802 goto done;
3803 /* If they're both naive, or both aware and have the same offsets,
3804 * we get off cheap. Note that if they're both naive, offset1 ==
3805 * offset2 == Py_None at this point.
3806 */
3807 if ((offset1 == offset2) ||
3808 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3809 delta_cmp(offset1, offset2) == 0)) {
3810 diff = memcmp(((PyDateTime_Time *)self)->data,
3811 ((PyDateTime_Time *)other)->data,
3812 _PyDateTime_TIME_DATASIZE);
3813 result = diff_to_bool(diff, op);
3814 }
3815 /* The hard case: both aware with different UTC offsets */
3816 else if (offset1 != Py_None && offset2 != Py_None) {
3817 int offsecs1, offsecs2;
3818 assert(offset1 != offset2); /* else last "if" handled it */
3819 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3820 TIME_GET_MINUTE(self) * 60 +
3821 TIME_GET_SECOND(self) -
3822 GET_TD_DAYS(offset1) * 86400 -
3823 GET_TD_SECONDS(offset1);
3824 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3825 TIME_GET_MINUTE(other) * 60 +
3826 TIME_GET_SECOND(other) -
3827 GET_TD_DAYS(offset2) * 86400 -
3828 GET_TD_SECONDS(offset2);
3829 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 if (diff == 0)
3831 diff = TIME_GET_MICROSECOND(self) -
3832 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003833 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003835 else if (op == Py_EQ) {
3836 result = Py_False;
3837 Py_INCREF(result);
3838 }
3839 else if (op == Py_NE) {
3840 result = Py_True;
3841 Py_INCREF(result);
3842 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003843 else {
3844 PyErr_SetString(PyExc_TypeError,
3845 "can't compare offset-naive and "
3846 "offset-aware times");
3847 }
3848 done:
3849 Py_DECREF(offset1);
3850 Py_XDECREF(offset2);
3851 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003852}
3853
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003854static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003855time_hash(PyDateTime_Time *self)
3856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003858 PyObject *offset, *self0;
3859 if (DATE_GET_FOLD(self)) {
3860 self0 = new_time_ex2(DATE_GET_HOUR(self),
3861 DATE_GET_MINUTE(self),
3862 DATE_GET_SECOND(self),
3863 DATE_GET_MICROSECOND(self),
3864 HASTZINFO(self) ? self->tzinfo : Py_None,
3865 0, Py_TYPE(self));
3866 if (self0 == NULL)
3867 return -1;
3868 }
3869 else {
3870 self0 = (PyObject *)self;
3871 Py_INCREF(self0);
3872 }
3873 offset = time_utcoffset(self0, NULL);
3874 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003875
3876 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003880 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 self->hashcode = generic_hash(
3882 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003884 PyObject *temp1, *temp2;
3885 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003886 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003887 seconds = TIME_GET_HOUR(self) * 3600 +
3888 TIME_GET_MINUTE(self) * 60 +
3889 TIME_GET_SECOND(self);
3890 microseconds = TIME_GET_MICROSECOND(self);
3891 temp1 = new_delta(0, seconds, microseconds, 1);
3892 if (temp1 == NULL) {
3893 Py_DECREF(offset);
3894 return -1;
3895 }
3896 temp2 = delta_subtract(temp1, offset);
3897 Py_DECREF(temp1);
3898 if (temp2 == NULL) {
3899 Py_DECREF(offset);
3900 return -1;
3901 }
3902 self->hashcode = PyObject_Hash(temp2);
3903 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003905 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 }
3907 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003908}
Tim Peters2a799bf2002-12-16 20:18:38 +00003909
Tim Peters12bf3392002-12-24 05:41:27 +00003910static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003911time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 PyObject *clone;
3914 PyObject *tuple;
3915 int hh = TIME_GET_HOUR(self);
3916 int mm = TIME_GET_MINUTE(self);
3917 int ss = TIME_GET_SECOND(self);
3918 int us = TIME_GET_MICROSECOND(self);
3919 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003920 int fold = TIME_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00003921
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003922 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 time_kws,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003924 &hh, &mm, &ss, &us, &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 return NULL;
3926 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3927 if (tuple == NULL)
3928 return NULL;
3929 clone = time_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003930 if (clone != NULL) {
3931 if (fold != 0 && fold != 1) {
3932 PyErr_SetString(PyExc_ValueError,
3933 "fold must be either 0 or 1");
3934 return NULL;
3935 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003936 TIME_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003937 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 Py_DECREF(tuple);
3939 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003940}
3941
Tim Peters371935f2003-02-01 01:52:50 +00003942/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003943
Tim Peters33e0f382003-01-10 02:05:14 +00003944/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003945 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3946 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003947 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003948 */
3949static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003950time_getstate(PyDateTime_Time *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00003951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 PyObject *basestate;
3953 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 basestate = PyBytes_FromStringAndSize((char *)self->data,
3956 _PyDateTime_TIME_DATASIZE);
3957 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003958 if (proto > 3 && TIME_GET_FOLD(self))
3959 /* Set the first bit of the first byte */
3960 PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3962 result = PyTuple_Pack(1, basestate);
3963 else
3964 result = PyTuple_Pack(2, basestate, self->tzinfo);
3965 Py_DECREF(basestate);
3966 }
3967 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003968}
3969
3970static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003971time_reduce(PyDateTime_Time *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00003972{
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003973 int proto = 0;
3974 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
3975 return NULL;
3976
3977 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00003978}
3979
Tim Peters37f39822003-01-10 03:49:02 +00003980static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003981
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003982 {"isoformat", (PyCFunction)time_isoformat, METH_VARARGS | METH_KEYWORDS,
3983 PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
3984 "[+HH:MM].\n\n"
3985 "timespec specifies what components of the time to include.\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3988 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3991 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3994 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3997 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 {"dst", (PyCFunction)time_dst, METH_NOARGS,
4000 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
4003 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004004
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004005 {"__reduce_ex__", (PyCFunction)time_reduce, METH_VARARGS,
4006 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004009};
4010
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004011static const char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004012PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
4013\n\
4014All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03004015a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004016
Neal Norwitz227b5332006-03-22 09:28:35 +00004017static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 PyVarObject_HEAD_INIT(NULL, 0)
4019 "datetime.time", /* tp_name */
4020 sizeof(PyDateTime_Time), /* tp_basicsize */
4021 0, /* tp_itemsize */
4022 (destructor)time_dealloc, /* tp_dealloc */
4023 0, /* tp_print */
4024 0, /* tp_getattr */
4025 0, /* tp_setattr */
4026 0, /* tp_reserved */
4027 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05004028 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 0, /* tp_as_sequence */
4030 0, /* tp_as_mapping */
4031 (hashfunc)time_hash, /* tp_hash */
4032 0, /* tp_call */
4033 (reprfunc)time_str, /* tp_str */
4034 PyObject_GenericGetAttr, /* tp_getattro */
4035 0, /* tp_setattro */
4036 0, /* tp_as_buffer */
4037 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4038 time_doc, /* tp_doc */
4039 0, /* tp_traverse */
4040 0, /* tp_clear */
4041 time_richcompare, /* tp_richcompare */
4042 0, /* tp_weaklistoffset */
4043 0, /* tp_iter */
4044 0, /* tp_iternext */
4045 time_methods, /* tp_methods */
4046 0, /* tp_members */
4047 time_getset, /* tp_getset */
4048 0, /* tp_base */
4049 0, /* tp_dict */
4050 0, /* tp_descr_get */
4051 0, /* tp_descr_set */
4052 0, /* tp_dictoffset */
4053 0, /* tp_init */
4054 time_alloc, /* tp_alloc */
4055 time_new, /* tp_new */
4056 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004057};
4058
4059/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004060 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00004061 */
4062
Tim Petersa9bc1682003-01-11 03:39:11 +00004063/* Accessor properties. Properties for day, month, and year are inherited
4064 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004065 */
4066
4067static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004068datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00004069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004071}
4072
Tim Petersa9bc1682003-01-11 03:39:11 +00004073static PyObject *
4074datetime_minute(PyDateTime_DateTime *self, void *unused)
4075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004077}
4078
4079static PyObject *
4080datetime_second(PyDateTime_DateTime *self, void *unused)
4081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004083}
4084
4085static PyObject *
4086datetime_microsecond(PyDateTime_DateTime *self, void *unused)
4087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004089}
4090
4091static PyObject *
4092datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
4093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4095 Py_INCREF(result);
4096 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004097}
4098
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004099static PyObject *
4100datetime_fold(PyDateTime_DateTime *self, void *unused)
4101{
4102 return PyLong_FromLong(DATE_GET_FOLD(self));
4103}
4104
Tim Petersa9bc1682003-01-11 03:39:11 +00004105static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 {"hour", (getter)datetime_hour},
4107 {"minute", (getter)datetime_minute},
4108 {"second", (getter)datetime_second},
4109 {"microsecond", (getter)datetime_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004110 {"tzinfo", (getter)datetime_tzinfo},
4111 {"fold", (getter)datetime_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004113};
4114
4115/*
4116 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004117 */
4118
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004119static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 "year", "month", "day", "hour", "minute", "second",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004121 "microsecond", "tzinfo", "fold", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004122};
4123
Tim Peters2a799bf2002-12-16 20:18:38 +00004124static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004125datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 PyObject *self = NULL;
4128 PyObject *state;
4129 int year;
4130 int month;
4131 int day;
4132 int hour = 0;
4133 int minute = 0;
4134 int second = 0;
4135 int usecond = 0;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004136 int fold = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 /* Check for invocation from pickle with __getstate__ state */
4140 if (PyTuple_GET_SIZE(args) >= 1 &&
4141 PyTuple_GET_SIZE(args) <= 2 &&
4142 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4143 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004144 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 {
4146 PyDateTime_DateTime *me;
4147 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 if (PyTuple_GET_SIZE(args) == 2) {
4150 tzinfo = PyTuple_GET_ITEM(args, 1);
4151 if (check_tzinfo_subclass(tzinfo) < 0) {
4152 PyErr_SetString(PyExc_TypeError, "bad "
4153 "tzinfo state arg");
4154 return NULL;
4155 }
4156 }
4157 aware = (char)(tzinfo != Py_None);
4158 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4159 if (me != NULL) {
4160 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4163 me->hashcode = -1;
4164 me->hastzinfo = aware;
4165 if (aware) {
4166 Py_INCREF(tzinfo);
4167 me->tzinfo = tzinfo;
4168 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004169 if (pdata[2] & (1 << 7)) {
4170 me->data[2] -= 128;
4171 me->fold = 1;
4172 }
4173 else {
4174 me->fold = 0;
4175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 }
4177 return (PyObject *)me;
4178 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004179
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004180 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004181 &year, &month, &day, &hour, &minute,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004182 &second, &usecond, &tzinfo, &fold)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 if (check_date_args(year, month, day) < 0)
4184 return NULL;
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04004185 if (check_time_args(hour, minute, second, usecond, fold) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 return NULL;
4187 if (check_tzinfo_subclass(tzinfo) < 0)
4188 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004189 self = new_datetime_ex2(year, month, day,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 hour, minute, second, usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004191 tzinfo, fold, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 }
4193 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004194}
4195
Tim Petersa9bc1682003-01-11 03:39:11 +00004196/* TM_FUNC is the shared type of localtime() and gmtime(). */
4197typedef struct tm *(*TM_FUNC)(const time_t *timer);
4198
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004199/* As of version 2015f max fold in IANA database is
4200 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
4201static PY_LONG_LONG max_fold_seconds = 24 * 3600;
4202/* NB: date(1970,1,1).toordinal() == 719163 */
4203static PY_LONG_LONG epoch = Py_LL(719163) * 24 * 60 * 60;
4204
4205static PY_LONG_LONG
4206utc_to_seconds(int year, int month, int day,
4207 int hour, int minute, int second)
4208{
4209 PY_LONG_LONG ordinal = ymd_to_ord(year, month, day);
4210 return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
4211}
4212
4213static PY_LONG_LONG
4214local(PY_LONG_LONG u)
4215{
4216 struct tm local_time;
Alexander Belopolsky8e1d3a22016-07-25 13:54:51 -04004217 time_t t;
4218 u -= epoch;
4219 t = u;
4220 if (t != u) {
4221 PyErr_SetString(PyExc_OverflowError,
4222 "timestamp out of range for platform time_t");
4223 return -1;
4224 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004225 /* XXX: add bounds checking */
4226 if (localtime_r(&t, &local_time) == NULL) {
4227 PyErr_SetFromErrno(PyExc_OSError);
4228 return -1;
4229 }
4230 return utc_to_seconds(local_time.tm_year + 1900,
4231 local_time.tm_mon + 1,
4232 local_time.tm_mday,
4233 local_time.tm_hour,
4234 local_time.tm_min,
4235 local_time.tm_sec);
4236}
4237
Tim Petersa9bc1682003-01-11 03:39:11 +00004238/* Internal helper.
4239 * Build datetime from a time_t and a distinct count of microseconds.
4240 * Pass localtime or gmtime for f, to control the interpretation of timet.
4241 */
4242static PyObject *
4243datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 struct tm *tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004247 int year, month, day, hour, minute, second, fold = 0;
Tim Petersa9bc1682003-01-11 03:39:11 +00004248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 tm = f(&timet);
Victor Stinner21f58932012-03-14 00:15:40 +01004250 if (tm == NULL) {
4251#ifdef EINVAL
4252 if (errno == 0)
4253 errno = EINVAL;
4254#endif
4255 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 }
Victor Stinner21f58932012-03-14 00:15:40 +01004257
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004258 year = tm->tm_year + 1900;
4259 month = tm->tm_mon + 1;
4260 day = tm->tm_mday;
4261 hour = tm->tm_hour;
4262 minute = tm->tm_min;
Victor Stinner21f58932012-03-14 00:15:40 +01004263 /* The platform localtime/gmtime may insert leap seconds,
4264 * indicated by tm->tm_sec > 59. We don't care about them,
4265 * except to the extent that passing them on to the datetime
4266 * constructor would raise ValueError for a reason that
4267 * made no sense to the user.
4268 */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004269 second = Py_MIN(59, tm->tm_sec);
4270
4271 if (tzinfo == Py_None && f == localtime) {
4272 PY_LONG_LONG probe_seconds, result_seconds, transition;
4273
4274 result_seconds = utc_to_seconds(year, month, day,
4275 hour, minute, second);
4276 /* Probe max_fold_seconds to detect a fold. */
4277 probe_seconds = local(epoch + timet - max_fold_seconds);
4278 if (probe_seconds == -1)
4279 return NULL;
4280 transition = result_seconds - probe_seconds - max_fold_seconds;
4281 if (transition < 0) {
4282 probe_seconds = local(epoch + timet + transition);
4283 if (probe_seconds == -1)
4284 return NULL;
4285 if (probe_seconds == result_seconds)
4286 fold = 1;
4287 }
4288 }
4289 return new_datetime_ex2(year, month, day, hour,
4290 minute, second, us, tzinfo, fold,
4291 (PyTypeObject *)cls);
Tim Petersa9bc1682003-01-11 03:39:11 +00004292}
4293
4294/* Internal helper.
4295 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4296 * to control the interpretation of the timestamp. Since a double doesn't
4297 * have enough bits to cover a datetime's full range of precision, it's
4298 * better to call datetime_from_timet_and_us provided you have a way
4299 * to get that much precision (e.g., C time() isn't good enough).
4300 */
4301static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004302datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004303 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004306 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004307
Victor Stinnere4a994d2015-03-30 01:10:14 +02004308 if (_PyTime_ObjectToTimeval(timestamp,
Victor Stinner7667f582015-09-09 01:02:23 +02004309 &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004311
Victor Stinner21f58932012-03-14 00:15:40 +01004312 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004313}
4314
4315/* Internal helper.
4316 * Build most accurate possible datetime for current time. Pass localtime or
4317 * gmtime for f as appropriate.
4318 */
4319static PyObject *
4320datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4321{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004322 _PyTime_t ts = _PyTime_GetSystemClock();
Victor Stinner1e2b6882015-09-18 13:23:02 +02004323 time_t secs;
4324 int us;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004325
Victor Stinner1e2b6882015-09-18 13:23:02 +02004326 if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner09e5cf22015-03-30 00:09:18 +02004327 return NULL;
Victor Stinner1e2b6882015-09-18 13:23:02 +02004328 assert(0 <= us && us <= 999999);
Victor Stinner09e5cf22015-03-30 00:09:18 +02004329
Victor Stinner1e2b6882015-09-18 13:23:02 +02004330 return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004331}
4332
Larry Hastings61272b72014-01-07 12:41:53 -08004333/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004334
4335@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004336datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004337
4338 tz: object = None
4339 Timezone object.
4340
4341Returns new datetime object representing current time local to tz.
4342
4343If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004344[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004345
Larry Hastings31826802013-10-19 00:09:25 -07004346static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004347datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03004348/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004351
Larry Hastings31826802013-10-19 00:09:25 -07004352 /* Return best possible local time -- this isn't constrained by the
4353 * precision of a timestamp.
4354 */
4355 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004357
Larry Hastings5c661892014-01-24 06:17:25 -08004358 self = datetime_best_possible((PyObject *)type,
Larry Hastings31826802013-10-19 00:09:25 -07004359 tz == Py_None ? localtime : gmtime,
4360 tz);
4361 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004363 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 }
4365 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004366}
4367
Tim Petersa9bc1682003-01-11 03:39:11 +00004368/* Return best possible UTC time -- this isn't constrained by the
4369 * precision of a timestamp.
4370 */
4371static PyObject *
4372datetime_utcnow(PyObject *cls, PyObject *dummy)
4373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004375}
4376
Tim Peters2a799bf2002-12-16 20:18:38 +00004377/* Return new local datetime from timestamp (Python timestamp -- a double). */
4378static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004379datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004382 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 PyObject *tzinfo = Py_None;
4384 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004385
Victor Stinner5d272cc2012-03-13 13:35:55 +01004386 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 keywords, &timestamp, &tzinfo))
4388 return NULL;
4389 if (check_tzinfo_subclass(tzinfo) < 0)
4390 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 self = datetime_from_timestamp(cls,
4393 tzinfo == Py_None ? localtime : gmtime,
4394 timestamp,
4395 tzinfo);
4396 if (self != NULL && tzinfo != Py_None) {
4397 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004398 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 }
4400 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004401}
4402
Tim Petersa9bc1682003-01-11 03:39:11 +00004403/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4404static PyObject *
4405datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4406{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004407 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004409
Victor Stinner5d272cc2012-03-13 13:35:55 +01004410 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 result = datetime_from_timestamp(cls, gmtime, timestamp,
4412 Py_None);
4413 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004414}
4415
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004416/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004417static PyObject *
4418datetime_strptime(PyObject *cls, PyObject *args)
4419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004421 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004422 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004423
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004424 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004426
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004427 if (module == NULL) {
4428 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004429 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004430 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004432 return _PyObject_CallMethodId(module, &PyId__strptime_datetime, "OOO",
4433 cls, string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004434}
4435
Tim Petersa9bc1682003-01-11 03:39:11 +00004436/* Return new datetime from date/datetime and time arguments. */
4437static PyObject *
4438datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4439{
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004440 static char *keywords[] = {"date", "time", "tzinfo", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 PyObject *date;
4442 PyObject *time;
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004443 PyObject *tzinfo = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004445
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004446 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 &PyDateTime_DateType, &date,
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004448 &PyDateTime_TimeType, &time, &tzinfo)) {
4449 if (tzinfo == NULL) {
4450 if (HASTZINFO(time))
4451 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4452 else
4453 tzinfo = Py_None;
4454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 result = PyObject_CallFunction(cls, "iiiiiiiO",
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004456 GET_YEAR(date),
4457 GET_MONTH(date),
4458 GET_DAY(date),
4459 TIME_GET_HOUR(time),
4460 TIME_GET_MINUTE(time),
4461 TIME_GET_SECOND(time),
4462 TIME_GET_MICROSECOND(time),
4463 tzinfo);
4464 if (result)
4465 DATE_SET_FOLD(result, TIME_GET_FOLD(time));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 }
4467 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004468}
Tim Peters2a799bf2002-12-16 20:18:38 +00004469
4470/*
4471 * Destructor.
4472 */
4473
4474static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004475datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 if (HASTZINFO(self)) {
4478 Py_XDECREF(self->tzinfo);
4479 }
4480 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004481}
4482
4483/*
4484 * Indirect access to tzinfo methods.
4485 */
4486
Tim Peters2a799bf2002-12-16 20:18:38 +00004487/* These are all METH_NOARGS, so don't need to check the arglist. */
4488static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004489datetime_utcoffset(PyObject *self, PyObject *unused) {
4490 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004491}
4492
4493static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004494datetime_dst(PyObject *self, PyObject *unused) {
4495 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004496}
4497
4498static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004499datetime_tzname(PyObject *self, PyObject *unused) {
4500 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004501}
4502
4503/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004504 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004505 */
4506
Tim Petersa9bc1682003-01-11 03:39:11 +00004507/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4508 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004509 */
4510static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004511add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514 /* Note that the C-level additions can't overflow, because of
4515 * invariant bounds on the member values.
4516 */
4517 int year = GET_YEAR(date);
4518 int month = GET_MONTH(date);
4519 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4520 int hour = DATE_GET_HOUR(date);
4521 int minute = DATE_GET_MINUTE(date);
4522 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4523 int microsecond = DATE_GET_MICROSECOND(date) +
4524 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 assert(factor == 1 || factor == -1);
4527 if (normalize_datetime(&year, &month, &day,
4528 &hour, &minute, &second, &microsecond) < 0)
4529 return NULL;
4530 else
4531 return new_datetime(year, month, day,
4532 hour, minute, second, microsecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004533 HASTZINFO(date) ? date->tzinfo : Py_None, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004534}
4535
4536static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004537datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 if (PyDateTime_Check(left)) {
4540 /* datetime + ??? */
4541 if (PyDelta_Check(right))
4542 /* datetime + delta */
4543 return add_datetime_timedelta(
4544 (PyDateTime_DateTime *)left,
4545 (PyDateTime_Delta *)right,
4546 1);
4547 }
4548 else if (PyDelta_Check(left)) {
4549 /* delta + datetime */
4550 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4551 (PyDateTime_Delta *) left,
4552 1);
4553 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004554 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004555}
4556
4557static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004558datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 if (PyDateTime_Check(left)) {
4563 /* datetime - ??? */
4564 if (PyDateTime_Check(right)) {
4565 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004566 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004568
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004569 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4570 offset2 = offset1 = Py_None;
4571 Py_INCREF(offset1);
4572 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004574 else {
4575 offset1 = datetime_utcoffset(left, NULL);
4576 if (offset1 == NULL)
4577 return NULL;
4578 offset2 = datetime_utcoffset(right, NULL);
4579 if (offset2 == NULL) {
4580 Py_DECREF(offset1);
4581 return NULL;
4582 }
4583 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4584 PyErr_SetString(PyExc_TypeError,
4585 "can't subtract offset-naive and "
4586 "offset-aware datetimes");
4587 Py_DECREF(offset1);
4588 Py_DECREF(offset2);
4589 return NULL;
4590 }
4591 }
4592 if ((offset1 != offset2) &&
4593 delta_cmp(offset1, offset2) != 0) {
4594 offdiff = delta_subtract(offset1, offset2);
4595 if (offdiff == NULL) {
4596 Py_DECREF(offset1);
4597 Py_DECREF(offset2);
4598 return NULL;
4599 }
4600 }
4601 Py_DECREF(offset1);
4602 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 delta_d = ymd_to_ord(GET_YEAR(left),
4604 GET_MONTH(left),
4605 GET_DAY(left)) -
4606 ymd_to_ord(GET_YEAR(right),
4607 GET_MONTH(right),
4608 GET_DAY(right));
4609 /* These can't overflow, since the values are
4610 * normalized. At most this gives the number of
4611 * seconds in one day.
4612 */
4613 delta_s = (DATE_GET_HOUR(left) -
4614 DATE_GET_HOUR(right)) * 3600 +
4615 (DATE_GET_MINUTE(left) -
4616 DATE_GET_MINUTE(right)) * 60 +
4617 (DATE_GET_SECOND(left) -
4618 DATE_GET_SECOND(right));
4619 delta_us = DATE_GET_MICROSECOND(left) -
4620 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004622 if (result == NULL)
4623 return NULL;
4624
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004625 if (offdiff != NULL) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03004626 Py_SETREF(result, delta_subtract(result, offdiff));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004627 Py_DECREF(offdiff);
4628 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 }
4630 else if (PyDelta_Check(right)) {
4631 /* datetime - delta */
4632 result = add_datetime_timedelta(
4633 (PyDateTime_DateTime *)left,
4634 (PyDateTime_Delta *)right,
4635 -1);
4636 }
4637 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 if (result == Py_NotImplemented)
4640 Py_INCREF(result);
4641 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004642}
4643
4644/* Various ways to turn a datetime into a string. */
4645
4646static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004647datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 const char *type_name = Py_TYPE(self)->tp_name;
4650 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 if (DATE_GET_MICROSECOND(self)) {
4653 baserepr = PyUnicode_FromFormat(
4654 "%s(%d, %d, %d, %d, %d, %d, %d)",
4655 type_name,
4656 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4657 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4658 DATE_GET_SECOND(self),
4659 DATE_GET_MICROSECOND(self));
4660 }
4661 else if (DATE_GET_SECOND(self)) {
4662 baserepr = PyUnicode_FromFormat(
4663 "%s(%d, %d, %d, %d, %d, %d)",
4664 type_name,
4665 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4666 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4667 DATE_GET_SECOND(self));
4668 }
4669 else {
4670 baserepr = PyUnicode_FromFormat(
4671 "%s(%d, %d, %d, %d, %d)",
4672 type_name,
4673 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4674 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4675 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004676 if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
4677 baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 if (baserepr == NULL || ! HASTZINFO(self))
4679 return baserepr;
4680 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004681}
4682
Tim Petersa9bc1682003-01-11 03:39:11 +00004683static PyObject *
4684datetime_str(PyDateTime_DateTime *self)
4685{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004686 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004687}
Tim Peters2a799bf2002-12-16 20:18:38 +00004688
4689static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004690datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 int sep = 'T';
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004693 char *timespec = NULL;
4694 static char *keywords[] = {"sep", "timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 char buffer[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004696 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 int us = DATE_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004698 static char *specs[][2] = {
4699 {"hours", "%04d-%02d-%02d%c%02d"},
4700 {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
4701 {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
4702 {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
4703 {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
4704 };
4705 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00004706
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004707 if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 return NULL;
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004709
4710 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4711 if (us == 0) {
4712 /* seconds */
4713 given_spec = 2;
4714 }
4715 else {
4716 /* microseconds */
4717 given_spec = 4;
4718 }
4719 }
4720 else {
4721 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4722 if (strcmp(timespec, specs[given_spec][0]) == 0) {
4723 if (given_spec == 3) {
4724 us = us / 1000;
4725 }
4726 break;
4727 }
4728 }
4729 }
4730
4731 if (given_spec == Py_ARRAY_LENGTH(specs)) {
4732 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4733 return NULL;
4734 }
4735 else {
4736 result = PyUnicode_FromFormat(specs[given_spec][1],
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 GET_YEAR(self), GET_MONTH(self),
4738 GET_DAY(self), (int)sep,
4739 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4740 DATE_GET_SECOND(self), us);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004741 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 if (!result || !HASTZINFO(self))
4744 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 /* We need to append the UTC offset. */
4747 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4748 (PyObject *)self) < 0) {
4749 Py_DECREF(result);
4750 return NULL;
4751 }
4752 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4753 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004754}
4755
Tim Petersa9bc1682003-01-11 03:39:11 +00004756static PyObject *
4757datetime_ctime(PyDateTime_DateTime *self)
4758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 return format_ctime((PyDateTime_Date *)self,
4760 DATE_GET_HOUR(self),
4761 DATE_GET_MINUTE(self),
4762 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004763}
4764
Tim Peters2a799bf2002-12-16 20:18:38 +00004765/* Miscellaneous methods. */
4766
Tim Petersa9bc1682003-01-11 03:39:11 +00004767static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004768flip_fold(PyObject *dt)
4769{
4770 return new_datetime_ex2(GET_YEAR(dt),
4771 GET_MONTH(dt),
4772 GET_DAY(dt),
4773 DATE_GET_HOUR(dt),
4774 DATE_GET_MINUTE(dt),
4775 DATE_GET_SECOND(dt),
4776 DATE_GET_MICROSECOND(dt),
4777 HASTZINFO(dt) ?
4778 ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
4779 !DATE_GET_FOLD(dt),
4780 Py_TYPE(dt));
4781}
4782
4783static PyObject *
4784get_flip_fold_offset(PyObject *dt)
4785{
4786 PyObject *result, *flip_dt;
4787
4788 flip_dt = flip_fold(dt);
4789 if (flip_dt == NULL)
4790 return NULL;
4791 result = datetime_utcoffset(flip_dt, NULL);
4792 Py_DECREF(flip_dt);
4793 return result;
4794}
4795
4796/* PEP 495 exception: Whenever one or both of the operands in
4797 * inter-zone comparison is such that its utcoffset() depends
4798 * on the value of its fold fold attribute, the result is False.
4799 *
4800 * Return 1 if exception applies, 0 if not, and -1 on error.
4801 */
4802static int
4803pep495_eq_exception(PyObject *self, PyObject *other,
4804 PyObject *offset_self, PyObject *offset_other)
4805{
4806 int result = 0;
4807 PyObject *flip_offset;
4808
4809 flip_offset = get_flip_fold_offset(self);
4810 if (flip_offset == NULL)
4811 return -1;
4812 if (flip_offset != offset_self &&
4813 delta_cmp(flip_offset, offset_self))
4814 {
4815 result = 1;
4816 goto done;
4817 }
4818 Py_DECREF(flip_offset);
4819
4820 flip_offset = get_flip_fold_offset(other);
4821 if (flip_offset == NULL)
4822 return -1;
4823 if (flip_offset != offset_other &&
4824 delta_cmp(flip_offset, offset_other))
4825 result = 1;
4826 done:
4827 Py_DECREF(flip_offset);
4828 return result;
4829}
4830
4831static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004832datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004833{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004834 PyObject *result = NULL;
4835 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 if (! PyDateTime_Check(other)) {
4839 if (PyDate_Check(other)) {
4840 /* Prevent invocation of date_richcompare. We want to
4841 return NotImplemented here to give the other object
4842 a chance. But since DateTime is a subclass of
4843 Date, if the other object is a Date, it would
4844 compute an ordering based on the date part alone,
4845 and we don't want that. So force unequal or
4846 uncomparable here in that case. */
4847 if (op == Py_EQ)
4848 Py_RETURN_FALSE;
4849 if (op == Py_NE)
4850 Py_RETURN_TRUE;
4851 return cmperror(self, other);
4852 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004853 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004855
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004856 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4858 ((PyDateTime_DateTime *)other)->data,
4859 _PyDateTime_DATETIME_DATASIZE);
4860 return diff_to_bool(diff, op);
4861 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004862 offset1 = datetime_utcoffset(self, NULL);
4863 if (offset1 == NULL)
4864 return NULL;
4865 offset2 = datetime_utcoffset(other, NULL);
4866 if (offset2 == NULL)
4867 goto done;
4868 /* If they're both naive, or both aware and have the same offsets,
4869 * we get off cheap. Note that if they're both naive, offset1 ==
4870 * offset2 == Py_None at this point.
4871 */
4872 if ((offset1 == offset2) ||
4873 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4874 delta_cmp(offset1, offset2) == 0)) {
4875 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4876 ((PyDateTime_DateTime *)other)->data,
4877 _PyDateTime_DATETIME_DATASIZE);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004878 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4879 int ex = pep495_eq_exception(self, other, offset1, offset2);
4880 if (ex == -1)
4881 goto done;
4882 if (ex)
4883 diff = 1;
4884 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004885 result = diff_to_bool(diff, op);
4886 }
4887 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004889
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004890 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4892 other);
4893 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004894 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004895 diff = GET_TD_DAYS(delta);
4896 if (diff == 0)
4897 diff = GET_TD_SECONDS(delta) |
4898 GET_TD_MICROSECONDS(delta);
4899 Py_DECREF(delta);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004900 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4901 int ex = pep495_eq_exception(self, other, offset1, offset2);
4902 if (ex == -1)
4903 goto done;
4904 if (ex)
4905 diff = 1;
4906 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004907 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004909 else if (op == Py_EQ) {
4910 result = Py_False;
4911 Py_INCREF(result);
4912 }
4913 else if (op == Py_NE) {
4914 result = Py_True;
4915 Py_INCREF(result);
4916 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004917 else {
4918 PyErr_SetString(PyExc_TypeError,
4919 "can't compare offset-naive and "
4920 "offset-aware datetimes");
4921 }
4922 done:
4923 Py_DECREF(offset1);
4924 Py_XDECREF(offset2);
4925 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004926}
4927
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004928static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004929datetime_hash(PyDateTime_DateTime *self)
4930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004932 PyObject *offset, *self0;
4933 if (DATE_GET_FOLD(self)) {
4934 self0 = new_datetime_ex2(GET_YEAR(self),
4935 GET_MONTH(self),
4936 GET_DAY(self),
4937 DATE_GET_HOUR(self),
4938 DATE_GET_MINUTE(self),
4939 DATE_GET_SECOND(self),
4940 DATE_GET_MICROSECOND(self),
4941 HASTZINFO(self) ? self->tzinfo : Py_None,
4942 0, Py_TYPE(self));
4943 if (self0 == NULL)
4944 return -1;
4945 }
4946 else {
4947 self0 = (PyObject *)self;
4948 Py_INCREF(self0);
4949 }
4950 offset = datetime_utcoffset(self0, NULL);
4951 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004952
4953 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004957 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 self->hashcode = generic_hash(
4959 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004961 PyObject *temp1, *temp2;
4962 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 assert(HASTZINFO(self));
4965 days = ymd_to_ord(GET_YEAR(self),
4966 GET_MONTH(self),
4967 GET_DAY(self));
4968 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004969 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004971 temp1 = new_delta(days, seconds,
4972 DATE_GET_MICROSECOND(self),
4973 1);
4974 if (temp1 == NULL) {
4975 Py_DECREF(offset);
4976 return -1;
4977 }
4978 temp2 = delta_subtract(temp1, offset);
4979 Py_DECREF(temp1);
4980 if (temp2 == NULL) {
4981 Py_DECREF(offset);
4982 return -1;
4983 }
4984 self->hashcode = PyObject_Hash(temp2);
4985 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004987 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004988 }
4989 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004990}
Tim Peters2a799bf2002-12-16 20:18:38 +00004991
4992static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004993datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 PyObject *clone;
4996 PyObject *tuple;
4997 int y = GET_YEAR(self);
4998 int m = GET_MONTH(self);
4999 int d = GET_DAY(self);
5000 int hh = DATE_GET_HOUR(self);
5001 int mm = DATE_GET_MINUTE(self);
5002 int ss = DATE_GET_SECOND(self);
5003 int us = DATE_GET_MICROSECOND(self);
5004 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005005 int fold = DATE_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00005006
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005007 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 datetime_kws,
5009 &y, &m, &d, &hh, &mm, &ss, &us,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005010 &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 return NULL;
5012 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
5013 if (tuple == NULL)
5014 return NULL;
5015 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005016
5017 if (clone != NULL) {
5018 if (fold != 0 && fold != 1) {
5019 PyErr_SetString(PyExc_ValueError,
5020 "fold must be either 0 or 1");
5021 return NULL;
5022 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005023 DATE_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005024 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 Py_DECREF(tuple);
5026 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00005027}
5028
5029static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005030local_timezone_from_timestamp(time_t timestamp)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005031{
5032 PyObject *result = NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005033 PyObject *delta;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005034 struct tm *local_time_tm;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005035 PyObject *nameo = NULL;
5036 const char *zone = NULL;
5037
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005038 local_time_tm = localtime(&timestamp);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005039#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005040 zone = local_time_tm->tm_zone;
5041 delta = new_delta(0, local_time_tm->tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005042#else /* HAVE_STRUCT_TM_TM_ZONE */
5043 {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005044 PyObject *local_time, *utc_time;
5045 struct tm *utc_time_tm;
5046 char buf[100];
5047 strftime(buf, sizeof(buf), "%Z", local_time_tm);
5048 zone = buf;
5049 local_time = new_datetime(local_time_tm->tm_year + 1900,
5050 local_time_tm->tm_mon + 1,
5051 local_time_tm->tm_mday,
5052 local_time_tm->tm_hour,
5053 local_time_tm->tm_min,
5054 local_time_tm->tm_sec, 0, Py_None, 0);
5055 if (local_time == NULL) {
5056 return NULL;
5057 }
5058 utc_time_tm = gmtime(&timestamp);
5059 utc_time = new_datetime(utc_time_tm->tm_year + 1900,
5060 utc_time_tm->tm_mon + 1,
5061 utc_time_tm->tm_mday,
5062 utc_time_tm->tm_hour,
5063 utc_time_tm->tm_min,
5064 utc_time_tm->tm_sec, 0, Py_None, 0);
5065 if (utc_time == NULL) {
5066 Py_DECREF(local_time);
5067 return NULL;
5068 }
5069 delta = datetime_subtract(local_time, utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005070 Py_DECREF(local_time);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005071 Py_DECREF(utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005072 }
5073#endif /* HAVE_STRUCT_TM_TM_ZONE */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005074 if (delta == NULL) {
5075 return NULL;
5076 }
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005077 if (zone != NULL) {
5078 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
5079 if (nameo == NULL)
5080 goto error;
5081 }
5082 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02005083 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005084 error:
5085 Py_DECREF(delta);
5086 return result;
5087}
5088
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005089static PyObject *
5090local_timezone(PyDateTime_DateTime *utc_time)
5091{
5092 time_t timestamp;
5093 PyObject *delta;
5094 PyObject *one_second;
5095 PyObject *seconds;
5096
5097 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
5098 if (delta == NULL)
5099 return NULL;
5100 one_second = new_delta(0, 1, 0, 0);
5101 if (one_second == NULL) {
5102 Py_DECREF(delta);
5103 return NULL;
5104 }
5105 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
5106 (PyDateTime_Delta *)one_second);
5107 Py_DECREF(one_second);
5108 Py_DECREF(delta);
5109 if (seconds == NULL)
5110 return NULL;
5111 timestamp = _PyLong_AsTime_t(seconds);
5112 Py_DECREF(seconds);
5113 if (timestamp == -1 && PyErr_Occurred())
5114 return NULL;
5115 return local_timezone_from_timestamp(timestamp);
5116}
5117
5118static PY_LONG_LONG
5119local_to_seconds(int year, int month, int day,
5120 int hour, int minute, int second, int fold);
5121
5122static PyObject *
5123local_timezone_from_local(PyDateTime_DateTime *local_dt)
5124{
5125 PY_LONG_LONG seconds;
5126 time_t timestamp;
5127 seconds = local_to_seconds(GET_YEAR(local_dt),
5128 GET_MONTH(local_dt),
5129 GET_DAY(local_dt),
5130 DATE_GET_HOUR(local_dt),
5131 DATE_GET_MINUTE(local_dt),
5132 DATE_GET_SECOND(local_dt),
5133 DATE_GET_FOLD(local_dt));
5134 if (seconds == -1)
5135 return NULL;
5136 /* XXX: add bounds check */
5137 timestamp = seconds - epoch;
5138 return local_timezone_from_timestamp(timestamp);
5139}
5140
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005141static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00005142datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00005143{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005144 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005145 PyObject *offset;
5146 PyObject *temp;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005147 PyObject *self_tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005148 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00005150
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005151 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07005152 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005153 return NULL;
5154
5155 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00005157
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005158 if (!HASTZINFO(self) || self->tzinfo == Py_None) {
5159 self_tzinfo = local_timezone_from_local(self);
5160 if (self_tzinfo == NULL)
5161 return NULL;
5162 } else {
5163 self_tzinfo = self->tzinfo;
5164 Py_INCREF(self_tzinfo);
5165 }
Tim Peters521fc152002-12-31 17:36:56 +00005166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 /* Conversion to self's own time zone is a NOP. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005168 if (self_tzinfo == tzinfo) {
5169 Py_DECREF(self_tzinfo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005171 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005172 }
Tim Peters521fc152002-12-31 17:36:56 +00005173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 /* Convert self to UTC. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005175 offset = call_utcoffset(self_tzinfo, (PyObject *)self);
5176 Py_DECREF(self_tzinfo);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005177 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005179 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005180 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5181 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005182 Py_DECREF(offset);
5183 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00005185
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005186 /* Make sure result is aware and UTC. */
5187 if (!HASTZINFO(result)) {
5188 temp = (PyObject *)result;
5189 result = (PyDateTime_DateTime *)
5190 new_datetime_ex2(GET_YEAR(result),
5191 GET_MONTH(result),
5192 GET_DAY(result),
5193 DATE_GET_HOUR(result),
5194 DATE_GET_MINUTE(result),
5195 DATE_GET_SECOND(result),
5196 DATE_GET_MICROSECOND(result),
5197 PyDateTime_TimeZone_UTC,
5198 DATE_GET_FOLD(result),
5199 Py_TYPE(result));
5200 Py_DECREF(temp);
5201 if (result == NULL)
5202 return NULL;
5203 }
5204 else {
5205 /* Result is already aware - just replace tzinfo. */
5206 temp = result->tzinfo;
5207 result->tzinfo = PyDateTime_TimeZone_UTC;
5208 Py_INCREF(result->tzinfo);
5209 Py_DECREF(temp);
5210 }
5211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005212 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005213 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005214 if (tzinfo == Py_None) {
5215 tzinfo = local_timezone(result);
5216 if (tzinfo == NULL) {
5217 Py_DECREF(result);
5218 return NULL;
5219 }
5220 }
5221 else
5222 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005223 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005224 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00005225
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005226 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005227 result = (PyDateTime_DateTime *)
5228 _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", temp);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005229 Py_DECREF(temp);
5230
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005231 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00005232}
5233
5234static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005235datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005237 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00005238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005239 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005240 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00005241
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005242 dst = call_dst(self->tzinfo, (PyObject *)self);
5243 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005245
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005246 if (dst != Py_None)
5247 dstflag = delta_bool((PyDateTime_Delta *)dst);
5248 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005249 }
5250 return build_struct_time(GET_YEAR(self),
5251 GET_MONTH(self),
5252 GET_DAY(self),
5253 DATE_GET_HOUR(self),
5254 DATE_GET_MINUTE(self),
5255 DATE_GET_SECOND(self),
5256 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00005257}
5258
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005259static PY_LONG_LONG
5260local_to_seconds(int year, int month, int day,
5261 int hour, int minute, int second, int fold)
5262{
5263 PY_LONG_LONG t, a, b, u1, u2, t1, t2, lt;
5264 t = utc_to_seconds(year, month, day, hour, minute, second);
5265 /* Our goal is to solve t = local(u) for u. */
5266 lt = local(t);
5267 if (lt == -1)
5268 return -1;
5269 a = lt - t;
5270 u1 = t - a;
5271 t1 = local(u1);
5272 if (t1 == -1)
5273 return -1;
5274 if (t1 == t) {
5275 /* We found one solution, but it may not be the one we need.
5276 * Look for an earlier solution (if `fold` is 0), or a
5277 * later one (if `fold` is 1). */
5278 if (fold)
5279 u2 = u1 + max_fold_seconds;
5280 else
5281 u2 = u1 - max_fold_seconds;
5282 lt = local(u2);
5283 if (lt == -1)
5284 return -1;
5285 b = lt - u2;
5286 if (a == b)
5287 return u1;
5288 }
5289 else {
5290 b = t1 - u1;
5291 assert(a != b);
5292 }
5293 u2 = t - b;
5294 t2 = local(u2);
5295 if (t2 == -1)
5296 return -1;
5297 if (t2 == t)
5298 return u2;
5299 if (t1 == t)
5300 return u1;
5301 /* We have found both offsets a and b, but neither t - a nor t - b is
5302 * a solution. This means t is in the gap. */
5303 return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
5304}
5305
5306/* date(1970,1,1).toordinal() == 719163 */
5307#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
5308
Tim Peters2a799bf2002-12-16 20:18:38 +00005309static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04005310datetime_timestamp(PyDateTime_DateTime *self)
5311{
5312 PyObject *result;
5313
5314 if (HASTZINFO(self) && self->tzinfo != Py_None) {
5315 PyObject *delta;
5316 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
5317 if (delta == NULL)
5318 return NULL;
5319 result = delta_total_seconds(delta);
5320 Py_DECREF(delta);
5321 }
5322 else {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005323 PY_LONG_LONG seconds;
5324 seconds = local_to_seconds(GET_YEAR(self),
5325 GET_MONTH(self),
5326 GET_DAY(self),
5327 DATE_GET_HOUR(self),
5328 DATE_GET_MINUTE(self),
5329 DATE_GET_SECOND(self),
5330 DATE_GET_FOLD(self));
5331 if (seconds == -1)
Alexander Belopolskya4415142012-06-08 12:33:09 -04005332 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005333 result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
5334 DATE_GET_MICROSECOND(self) / 1e6);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005335 }
5336 return result;
5337}
5338
5339static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005340datetime_getdate(PyDateTime_DateTime *self)
5341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 return new_date(GET_YEAR(self),
5343 GET_MONTH(self),
5344 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005345}
5346
5347static PyObject *
5348datetime_gettime(PyDateTime_DateTime *self)
5349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 return new_time(DATE_GET_HOUR(self),
5351 DATE_GET_MINUTE(self),
5352 DATE_GET_SECOND(self),
5353 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005354 Py_None,
5355 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005356}
5357
5358static PyObject *
5359datetime_gettimetz(PyDateTime_DateTime *self)
5360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 return new_time(DATE_GET_HOUR(self),
5362 DATE_GET_MINUTE(self),
5363 DATE_GET_SECOND(self),
5364 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005365 GET_DT_TZINFO(self),
5366 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005367}
5368
5369static PyObject *
5370datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005371{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005372 int y, m, d, hh, mm, ss;
5373 PyObject *tzinfo;
5374 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00005375
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005376 tzinfo = GET_DT_TZINFO(self);
5377 if (tzinfo == Py_None) {
5378 utcself = self;
5379 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005381 else {
5382 PyObject *offset;
5383 offset = call_utcoffset(tzinfo, (PyObject *)self);
5384 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00005385 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005386 if (offset == Py_None) {
5387 Py_DECREF(offset);
5388 utcself = self;
5389 Py_INCREF(utcself);
5390 }
5391 else {
5392 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5393 (PyDateTime_Delta *)offset, -1);
5394 Py_DECREF(offset);
5395 if (utcself == NULL)
5396 return NULL;
5397 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005398 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005399 y = GET_YEAR(utcself);
5400 m = GET_MONTH(utcself);
5401 d = GET_DAY(utcself);
5402 hh = DATE_GET_HOUR(utcself);
5403 mm = DATE_GET_MINUTE(utcself);
5404 ss = DATE_GET_SECOND(utcself);
5405
5406 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005408}
5409
Tim Peters371935f2003-02-01 01:52:50 +00005410/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00005411
Tim Petersa9bc1682003-01-11 03:39:11 +00005412/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00005413 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5414 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00005415 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00005416 */
5417static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005418datetime_getstate(PyDateTime_DateTime *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00005419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 PyObject *basestate;
5421 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 basestate = PyBytes_FromStringAndSize((char *)self->data,
5424 _PyDateTime_DATETIME_DATASIZE);
5425 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005426 if (proto > 3 && DATE_GET_FOLD(self))
5427 /* Set the first bit of the third byte */
5428 PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5430 result = PyTuple_Pack(1, basestate);
5431 else
5432 result = PyTuple_Pack(2, basestate, self->tzinfo);
5433 Py_DECREF(basestate);
5434 }
5435 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005436}
5437
5438static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005439datetime_reduce(PyDateTime_DateTime *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00005440{
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005441 int proto = 0;
5442 if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
5443 return NULL;
5444
5445 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00005446}
5447
Tim Petersa9bc1682003-01-11 03:39:11 +00005448static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005450 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005451
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005452 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005454 {"utcnow", (PyCFunction)datetime_utcnow,
5455 METH_NOARGS | METH_CLASS,
5456 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5459 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5460 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5463 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05005464 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 {"strptime", (PyCFunction)datetime_strptime,
5467 METH_VARARGS | METH_CLASS,
5468 PyDoc_STR("string, format -> new datetime parsed from a string "
5469 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 {"combine", (PyCFunction)datetime_combine,
5472 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5473 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005477 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5478 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5481 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005483 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5484 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005486 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5487 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5490 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005491
Alexander Belopolskya4415142012-06-08 12:33:09 -04005492 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5493 PyDoc_STR("Return POSIX timestamp as float.")},
5494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005495 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5496 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5499 PyDoc_STR("[sep] -> string in ISO 8601 format, "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005500 "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 "sep is used to separate the year from the time, and "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005502 "defaults to 'T'.\n"
5503 "timespec specifies what components of the time to include"
5504 " (allowed values are 'auto', 'hours', 'minutes', 'seconds',"
5505 " 'milliseconds', and 'microseconds').\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5508 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5511 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5514 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5517 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5520 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005521
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005522 {"__reduce_ex__", (PyCFunction)datetime_reduce, METH_VARARGS,
5523 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005526};
5527
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02005528static const char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005529PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5530\n\
5531The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005532instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005533
Tim Petersa9bc1682003-01-11 03:39:11 +00005534static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 datetime_add, /* nb_add */
5536 datetime_subtract, /* nb_subtract */
5537 0, /* nb_multiply */
5538 0, /* nb_remainder */
5539 0, /* nb_divmod */
5540 0, /* nb_power */
5541 0, /* nb_negative */
5542 0, /* nb_positive */
5543 0, /* nb_absolute */
5544 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005545};
5546
Neal Norwitz227b5332006-03-22 09:28:35 +00005547static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 PyVarObject_HEAD_INIT(NULL, 0)
5549 "datetime.datetime", /* tp_name */
5550 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5551 0, /* tp_itemsize */
5552 (destructor)datetime_dealloc, /* tp_dealloc */
5553 0, /* tp_print */
5554 0, /* tp_getattr */
5555 0, /* tp_setattr */
5556 0, /* tp_reserved */
5557 (reprfunc)datetime_repr, /* tp_repr */
5558 &datetime_as_number, /* tp_as_number */
5559 0, /* tp_as_sequence */
5560 0, /* tp_as_mapping */
5561 (hashfunc)datetime_hash, /* tp_hash */
5562 0, /* tp_call */
5563 (reprfunc)datetime_str, /* tp_str */
5564 PyObject_GenericGetAttr, /* tp_getattro */
5565 0, /* tp_setattro */
5566 0, /* tp_as_buffer */
5567 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5568 datetime_doc, /* tp_doc */
5569 0, /* tp_traverse */
5570 0, /* tp_clear */
5571 datetime_richcompare, /* tp_richcompare */
5572 0, /* tp_weaklistoffset */
5573 0, /* tp_iter */
5574 0, /* tp_iternext */
5575 datetime_methods, /* tp_methods */
5576 0, /* tp_members */
5577 datetime_getset, /* tp_getset */
5578 &PyDateTime_DateType, /* tp_base */
5579 0, /* tp_dict */
5580 0, /* tp_descr_get */
5581 0, /* tp_descr_set */
5582 0, /* tp_dictoffset */
5583 0, /* tp_init */
5584 datetime_alloc, /* tp_alloc */
5585 datetime_new, /* tp_new */
5586 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005587};
5588
5589/* ---------------------------------------------------------------------------
5590 * Module methods and initialization.
5591 */
5592
5593static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005595};
5596
Tim Peters9ddf40b2004-06-20 22:41:32 +00005597/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5598 * datetime.h.
5599 */
5600static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005601 &PyDateTime_DateType,
5602 &PyDateTime_DateTimeType,
5603 &PyDateTime_TimeType,
5604 &PyDateTime_DeltaType,
5605 &PyDateTime_TZInfoType,
5606 new_date_ex,
5607 new_datetime_ex,
5608 new_time_ex,
5609 new_delta_ex,
5610 datetime_fromtimestamp,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005611 date_fromtimestamp,
5612 new_datetime_ex2,
5613 new_time_ex2
Tim Peters9ddf40b2004-06-20 22:41:32 +00005614};
5615
5616
Martin v. Löwis1a214512008-06-11 05:26:20 +00005617
5618static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005620 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005621 "Fast implementation of the datetime type.",
5622 -1,
5623 module_methods,
5624 NULL,
5625 NULL,
5626 NULL,
5627 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005628};
5629
Tim Peters2a799bf2002-12-16 20:18:38 +00005630PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005631PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 PyObject *m; /* a module object */
5634 PyObject *d; /* its dict */
5635 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005636 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005638 m = PyModule_Create(&datetimemodule);
5639 if (m == NULL)
5640 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 if (PyType_Ready(&PyDateTime_DateType) < 0)
5643 return NULL;
5644 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5645 return NULL;
5646 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5647 return NULL;
5648 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5649 return NULL;
5650 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5651 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005652 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5653 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005655 /* timedelta values */
5656 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 x = new_delta(0, 0, 1, 0);
5659 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5660 return NULL;
5661 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5664 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5665 return NULL;
5666 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5669 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5670 return NULL;
5671 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 /* date values */
5674 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005676 x = new_date(1, 1, 1);
5677 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5678 return NULL;
5679 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 x = new_date(MAXYEAR, 12, 31);
5682 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5683 return NULL;
5684 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 x = new_delta(1, 0, 0, 0);
5687 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5688 return NULL;
5689 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 /* time values */
5692 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005693
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005694 x = new_time(0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5696 return NULL;
5697 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005698
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005699 x = new_time(23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5701 return NULL;
5702 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 x = new_delta(0, 0, 1, 0);
5705 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5706 return NULL;
5707 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 /* datetime values */
5710 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005711
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005712 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5714 return NULL;
5715 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005716
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005717 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5719 return NULL;
5720 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 x = new_delta(0, 0, 1, 0);
5723 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5724 return NULL;
5725 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005726
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005727 /* timezone values */
5728 d = PyDateTime_TimeZoneType.tp_dict;
5729
5730 delta = new_delta(0, 0, 0, 0);
5731 if (delta == NULL)
5732 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005733 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005734 Py_DECREF(delta);
5735 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5736 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005737 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005738
5739 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5740 if (delta == NULL)
5741 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005742 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005743 Py_DECREF(delta);
5744 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5745 return NULL;
5746 Py_DECREF(x);
5747
5748 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5749 if (delta == NULL)
5750 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005751 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005752 Py_DECREF(delta);
5753 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5754 return NULL;
5755 Py_DECREF(x);
5756
Alexander Belopolskya4415142012-06-08 12:33:09 -04005757 /* Epoch */
5758 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005759 PyDateTime_TimeZone_UTC, 0);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005760 if (PyDateTime_Epoch == NULL)
5761 return NULL;
5762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005764 PyModule_AddIntMacro(m, MINYEAR);
5765 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005767 Py_INCREF(&PyDateTime_DateType);
5768 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 Py_INCREF(&PyDateTime_DateTimeType);
5771 PyModule_AddObject(m, "datetime",
5772 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 Py_INCREF(&PyDateTime_TimeType);
5775 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 Py_INCREF(&PyDateTime_DeltaType);
5778 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005780 Py_INCREF(&PyDateTime_TZInfoType);
5781 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005782
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005783 Py_INCREF(&PyDateTime_TimeZoneType);
5784 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005786 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5787 if (x == NULL)
5788 return NULL;
5789 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 /* A 4-year cycle has an extra leap day over what we'd get from
5792 * pasting together 4 single years.
5793 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005794 Py_BUILD_ASSERT(DI4Y == 4 * 365 + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005795 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5798 * get from pasting together 4 100-year cycles.
5799 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005800 Py_BUILD_ASSERT(DI400Y == 4 * DI100Y + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5804 * pasting together 25 4-year cycles.
5805 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005806 Py_BUILD_ASSERT(DI100Y == 25 * DI4Y - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005808
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005809 one = PyLong_FromLong(1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810 us_per_ms = PyLong_FromLong(1000);
5811 us_per_second = PyLong_FromLong(1000000);
5812 us_per_minute = PyLong_FromLong(60000000);
5813 seconds_per_day = PyLong_FromLong(24 * 3600);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005814 if (one == NULL || us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005815 us_per_minute == NULL || seconds_per_day == NULL)
5816 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 /* The rest are too big for 32-bit ints, but even
5819 * us_per_week fits in 40 bits, so doubles should be exact.
5820 */
5821 us_per_hour = PyLong_FromDouble(3600000000.0);
5822 us_per_day = PyLong_FromDouble(86400000000.0);
5823 us_per_week = PyLong_FromDouble(604800000000.0);
5824 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5825 return NULL;
5826 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005827}
Tim Petersf3615152003-01-01 21:51:37 +00005828
5829/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005830Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005831 x.n = x stripped of its timezone -- its naive time.
5832 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 return None
Tim Petersf3615152003-01-01 21:51:37 +00005834 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 return None
Tim Petersf3615152003-01-01 21:51:37 +00005836 x.s = x's standard offset, x.o - x.d
5837
5838Now some derived rules, where k is a duration (timedelta).
5839
58401. x.o = x.s + x.d
5841 This follows from the definition of x.s.
5842
Tim Petersc5dc4da2003-01-02 17:55:03 +000058432. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005844 This is actually a requirement, an assumption we need to make about
5845 sane tzinfo classes.
5846
58473. The naive UTC time corresponding to x is x.n - x.o.
5848 This is again a requirement for a sane tzinfo class.
5849
58504. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005851 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005852
Tim Petersc5dc4da2003-01-02 17:55:03 +000058535. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005854 Again follows from how arithmetic is defined.
5855
Tim Peters8bb5ad22003-01-24 02:44:45 +00005856Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005857(meaning that the various tzinfo methods exist, and don't blow up or return
5858None when called).
5859
Tim Petersa9bc1682003-01-11 03:39:11 +00005860The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005861x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005862
5863By #3, we want
5864
Tim Peters8bb5ad22003-01-24 02:44:45 +00005865 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005866
5867The algorithm starts by attaching tz to x.n, and calling that y. So
5868x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5869becomes true; in effect, we want to solve [2] for k:
5870
Tim Peters8bb5ad22003-01-24 02:44:45 +00005871 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005872
5873By #1, this is the same as
5874
Tim Peters8bb5ad22003-01-24 02:44:45 +00005875 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005876
5877By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5878Substituting that into [3],
5879
Tim Peters8bb5ad22003-01-24 02:44:45 +00005880 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5881 k - (y+k).s - (y+k).d = 0; rearranging,
5882 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5883 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005884
Tim Peters8bb5ad22003-01-24 02:44:45 +00005885On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5886approximate k by ignoring the (y+k).d term at first. Note that k can't be
5887very large, since all offset-returning methods return a duration of magnitude
5888less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5889be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005890
5891In any case, the new value is
5892
Tim Peters8bb5ad22003-01-24 02:44:45 +00005893 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005894
Tim Peters8bb5ad22003-01-24 02:44:45 +00005895It's helpful to step back at look at [4] from a higher level: it's simply
5896mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005897
5898At this point, if
5899
Tim Peters8bb5ad22003-01-24 02:44:45 +00005900 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005901
5902we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005903at the start of daylight time. Picture US Eastern for concreteness. The wall
5904time 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 +00005905sense then. The docs ask that an Eastern tzinfo class consider such a time to
5906be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5907on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005908the only spelling that makes sense on the local wall clock.
5909
Tim Petersc5dc4da2003-01-02 17:55:03 +00005910In fact, if [5] holds at this point, we do have the standard-time spelling,
5911but that takes a bit of proof. We first prove a stronger result. What's the
5912difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005913
Tim Peters8bb5ad22003-01-24 02:44:45 +00005914 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005915
Tim Petersc5dc4da2003-01-02 17:55:03 +00005916Now
5917 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005918 (y + y.s).n = by #5
5919 y.n + y.s = since y.n = x.n
5920 x.n + y.s = since z and y are have the same tzinfo member,
5921 y.s = z.s by #2
5922 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005923
Tim Petersc5dc4da2003-01-02 17:55:03 +00005924Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005925
Tim Petersc5dc4da2003-01-02 17:55:03 +00005926 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005927 x.n - ((x.n + z.s) - z.o) = expanding
5928 x.n - x.n - z.s + z.o = cancelling
5929 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005930 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005931
Tim Petersc5dc4da2003-01-02 17:55:03 +00005932So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005933
Tim Petersc5dc4da2003-01-02 17:55:03 +00005934If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005935spelling we wanted in the endcase described above. We're done. Contrarily,
5936if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005937
Tim Petersc5dc4da2003-01-02 17:55:03 +00005938If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5939add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005940local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005941
Tim Petersc5dc4da2003-01-02 17:55:03 +00005942Let
Tim Petersf3615152003-01-01 21:51:37 +00005943
Tim Peters4fede1a2003-01-04 00:26:59 +00005944 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005945
Tim Peters4fede1a2003-01-04 00:26:59 +00005946and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005947
Tim Peters8bb5ad22003-01-24 02:44:45 +00005948 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005949
Tim Peters8bb5ad22003-01-24 02:44:45 +00005950If so, we're done. If not, the tzinfo class is insane, according to the
5951assumptions we've made. This also requires a bit of proof. As before, let's
5952compute the difference between the LHS and RHS of [8] (and skipping some of
5953the justifications for the kinds of substitutions we've done several times
5954already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005955
Tim Peters8bb5ad22003-01-24 02:44:45 +00005956 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5958 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5959 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5960 - z.n + z.n - z.o + z'.o = cancel z.n
5961 - z.o + z'.o = #1 twice
5962 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5963 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005964
5965So 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 +00005966we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5967return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005968
Tim Peters8bb5ad22003-01-24 02:44:45 +00005969How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5970a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5971would have to change the result dst() returns: we start in DST, and moving
5972a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005973
Tim Peters8bb5ad22003-01-24 02:44:45 +00005974There isn't a sane case where this can happen. The closest it gets is at
5975the end of DST, where there's an hour in UTC with no spelling in a hybrid
5976tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5977that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5978UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5979time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5980clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5981standard time. Since that's what the local clock *does*, we want to map both
5982UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005983in local time, but so it goes -- it's the way the local clock works.
5984
Tim Peters8bb5ad22003-01-24 02:44:45 +00005985When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5986so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5987z' = 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 +00005988(correctly) concludes that z' is not UTC-equivalent to x.
5989
5990Because we know z.d said z was in daylight time (else [5] would have held and
5991we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005992and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005993return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5994but the reasoning doesn't depend on the example -- it depends on there being
5995two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005996z' must be in standard time, and is the spelling we want in this case.
5997
5998Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5999concerned (because it takes z' as being in standard time rather than the
6000daylight time we intend here), but returning it gives the real-life "local
6001clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
6002tz.
6003
6004When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
6005the 1:MM standard time spelling we want.
6006
6007So how can this break? One of the assumptions must be violated. Two
6008possibilities:
6009
60101) [2] effectively says that y.s is invariant across all y belong to a given
6011 time zone. This isn't true if, for political reasons or continental drift,
6012 a region decides to change its base offset from UTC.
6013
60142) There may be versions of "double daylight" time where the tail end of
6015 the analysis gives up a step too early. I haven't thought about that
6016 enough to say.
6017
6018In any case, it's clear that the default fromutc() is strong enough to handle
6019"almost all" time zones: so long as the standard offset is invariant, it
6020doesn't matter if daylight time transition points change from year to year, or
6021if daylight time is skipped in some years; it doesn't matter how large or
6022small dst() may get within its bounds; and it doesn't even matter if some
6023perverse time zone returns a negative dst()). So a breaking case must be
6024pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00006025--------------------------------------------------------------------------- */