blob: 1803d85a7123f1dae7bb38192c54dbd3f1faf1c2 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
Tim Peters2a799bf2002-12-16 20:18:38 +00006#include "structmember.h"
7
8#include <time.h>
9
Victor Stinner09e5cf22015-03-30 00:09:18 +020010#ifdef MS_WINDOWS
11# include <winsock2.h> /* struct timeval */
12#endif
13
Tim Peters9ddf40b2004-06-20 22:41:32 +000014/* Differentiate between building the core module and building extension
15 * modules.
16 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000017#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000018#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000019#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000020#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000021#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000022
Larry Hastings61272b72014-01-07 12:41:53 -080023/*[clinic input]
Larry Hastings44e2eaa2013-11-23 15:37:55 -080024module datetime
Larry Hastingsc2047262014-01-25 20:43:29 -080025class datetime.datetime "PyDateTime_DateTime *" "&PyDateTime_DateTimeType"
Larry Hastings61272b72014-01-07 12:41:53 -080026[clinic start generated code]*/
Larry Hastings581ee362014-01-28 05:00:08 -080027/*[clinic end generated code: output=da39a3ee5e6b4b0d input=78142cb64b9e98bc]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080028
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030029#include "clinic/_datetimemodule.c.h"
30
Tim Peters2a799bf2002-12-16 20:18:38 +000031/* We require that C int be at least 32 bits, and use int virtually
32 * everywhere. In just a few cases we use a temp long, where a Python
33 * API returns a C long. In such cases, we have to ensure that the
34 * final result fits in a C int (this can be an issue on 64-bit boxes).
35 */
36#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000037# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000038#endif
39
40#define MINYEAR 1
41#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000042#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000043
44/* Nine decimal digits is easy to communicate, and leaves enough room
45 * so that two delta days can be added w/o fear of overflowing a signed
46 * 32-bit int, and with plenty of room left over to absorb any possible
47 * carries from adding seconds.
48 */
49#define MAX_DELTA_DAYS 999999999
50
51/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052#define GET_YEAR PyDateTime_GET_YEAR
53#define GET_MONTH PyDateTime_GET_MONTH
54#define GET_DAY PyDateTime_GET_DAY
55#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
56#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
57#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
58#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040059#define DATE_GET_FOLD PyDateTime_DATE_GET_FOLD
Tim Peters2a799bf2002-12-16 20:18:38 +000060
61/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
63 ((o)->data[1] = ((v) & 0x00ff)))
64#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
65#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000066
67/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
69#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
70#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
71#define DATE_SET_MICROSECOND(o, v) \
72 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
73 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
74 ((o)->data[9] = ((v) & 0x0000ff)))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040075#define DATE_SET_FOLD(o, v) (PyDateTime_DATE_GET_FOLD(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000076
77/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
79#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
80#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
81#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040082#define TIME_GET_FOLD PyDateTime_TIME_GET_FOLD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
84#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
85#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
86#define TIME_SET_MICROSECOND(o, v) \
87 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
88 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
89 ((o)->data[5] = ((v) & 0x0000ff)))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -040090#define TIME_SET_FOLD(o, v) (PyDateTime_TIME_GET_FOLD(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000091
92/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
94#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
95#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097#define SET_TD_DAYS(o, v) ((o)->days = (v))
98#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000099#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
100
Tim Petersa032d2e2003-01-11 00:15:54 +0000101/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
102 * p->hastzinfo.
103 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000104#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
105#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
106 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
107#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
108 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +0000109/* M is a char or int claiming to be a valid month. The macro is equivalent
110 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +0000112 */
113#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
114
Tim Peters2a799bf2002-12-16 20:18:38 +0000115/* Forward declarations. */
116static PyTypeObject PyDateTime_DateType;
117static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000118static PyTypeObject PyDateTime_DeltaType;
119static PyTypeObject PyDateTime_TimeType;
120static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000121static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000122
Victor Stinnerb67f0962017-02-10 10:34:02 +0100123static int check_tzinfo_subclass(PyObject *p);
124
Martin v. Löwise75fc142013-11-07 18:46:53 +0100125_Py_IDENTIFIER(as_integer_ratio);
126_Py_IDENTIFIER(fromutc);
127_Py_IDENTIFIER(isoformat);
128_Py_IDENTIFIER(strftime);
129
Tim Peters2a799bf2002-12-16 20:18:38 +0000130/* ---------------------------------------------------------------------------
131 * Math utilities.
132 */
133
134/* k = i+j overflows iff k differs in sign from both inputs,
135 * iff k^i has sign bit set and k^j has sign bit set,
136 * iff (k^i)&(k^j) has sign bit set.
137 */
138#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000140
141/* Compute Python divmod(x, y), returning the quotient and storing the
142 * remainder into *r. The quotient is the floor of x/y, and that's
143 * the real point of this. C will probably truncate instead (C99
144 * requires truncation; C89 left it implementation-defined).
145 * Simplification: we *require* that y > 0 here. That's appropriate
146 * for all the uses made of it. This simplifies the code and makes
147 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
148 * overflow case).
149 */
150static int
151divmod(int x, int y, int *r)
152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 assert(y > 0);
156 quo = x / y;
157 *r = x - quo * y;
158 if (*r < 0) {
159 --quo;
160 *r += y;
161 }
162 assert(0 <= *r && *r < y);
163 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000164}
165
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000166/* Nearest integer to m / n for integers m and n. Half-integer results
167 * are rounded to even.
168 */
169static PyObject *
170divide_nearest(PyObject *m, PyObject *n)
171{
172 PyObject *result;
173 PyObject *temp;
174
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000175 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000176 if (temp == NULL)
177 return NULL;
178 result = PyTuple_GET_ITEM(temp, 0);
179 Py_INCREF(result);
180 Py_DECREF(temp);
181
182 return result;
183}
184
Tim Peters2a799bf2002-12-16 20:18:38 +0000185/* ---------------------------------------------------------------------------
186 * General calendrical helper functions
187 */
188
189/* For each month ordinal in 1..12, the number of days in that month,
190 * and the number of days before that month in the same year. These
191 * are correct for non-leap years only.
192 */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200193static const int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 0, /* unused; this vector uses 1-based indexing */
195 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000196};
197
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200198static const int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 0, /* unused; this vector uses 1-based indexing */
200 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000201};
202
203/* year -> 1 if leap year, else 0. */
204static int
205is_leap(int year)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 /* Cast year to unsigned. The result is the same either way, but
208 * C can generate faster code for unsigned mod than for signed
209 * mod (especially for % 4 -- a good compiler should just grab
210 * the last 2 bits when the LHS is unsigned).
211 */
212 const unsigned int ayear = (unsigned int)year;
213 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000214}
215
216/* year, month -> number of days in that month in that year */
217static int
218days_in_month(int year, int month)
219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 assert(month >= 1);
221 assert(month <= 12);
222 if (month == 2 && is_leap(year))
223 return 29;
224 else
225 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000226}
227
Martin Panter46f50722016-05-26 05:35:26 +0000228/* year, month -> number of days in year preceding first day of month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000229static int
230days_before_month(int year, int month)
231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 assert(month >= 1);
235 assert(month <= 12);
236 days = _days_before_month[month];
237 if (month > 2 && is_leap(year))
238 ++days;
239 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000240}
241
242/* year -> number of days before January 1st of year. Remember that we
243 * start with year 1, so days_before_year(1) == 0.
244 */
245static int
246days_before_year(int year)
247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 int y = year - 1;
249 /* This is incorrect if year <= 0; we really want the floor
250 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000251 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000253 assert (year >= 1);
254 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000255}
256
257/* Number of days in 4, 100, and 400 year cycles. That these have
258 * the correct values is asserted in the module init function.
259 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260#define DI4Y 1461 /* days_before_year(5); days in 4 years */
261#define DI100Y 36524 /* days_before_year(101); days in 100 years */
262#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000263
264/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
265static void
266ord_to_ymd(int ordinal, int *year, int *month, int *day)
267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
271 * leap years repeats exactly every 400 years. The basic strategy is
272 * to find the closest 400-year boundary at or before ordinal, then
273 * work with the offset from that boundary to ordinal. Life is much
274 * clearer if we subtract 1 from ordinal first -- then the values
275 * of ordinal at 400-year boundaries are exactly those divisible
276 * by DI400Y:
277 *
278 * D M Y n n-1
279 * -- --- ---- ---------- ----------------
280 * 31 Dec -400 -DI400Y -DI400Y -1
281 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
282 * ...
283 * 30 Dec 000 -1 -2
284 * 31 Dec 000 0 -1
285 * 1 Jan 001 1 0 400-year boundary
286 * 2 Jan 001 2 1
287 * 3 Jan 001 3 2
288 * ...
289 * 31 Dec 400 DI400Y DI400Y -1
290 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
291 */
292 assert(ordinal >= 1);
293 --ordinal;
294 n400 = ordinal / DI400Y;
295 n = ordinal % DI400Y;
296 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* Now n is the (non-negative) offset, in days, from January 1 of
299 * year, to the desired date. Now compute how many 100-year cycles
300 * precede n.
301 * Note that it's possible for n100 to equal 4! In that case 4 full
302 * 100-year cycles precede the desired day, which implies the
303 * desired day is December 31 at the end of a 400-year cycle.
304 */
305 n100 = n / DI100Y;
306 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 /* Now compute how many 4-year cycles precede it. */
309 n4 = n / DI4Y;
310 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 /* And now how many single years. Again n1 can be 4, and again
313 * meaning that the desired day is December 31 at the end of the
314 * 4-year cycle.
315 */
316 n1 = n / 365;
317 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 *year += n100 * 100 + n4 * 4 + n1;
320 if (n1 == 4 || n100 == 4) {
321 assert(n == 0);
322 *year -= 1;
323 *month = 12;
324 *day = 31;
325 return;
326 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 /* Now the year is correct, and n is the offset from January 1. We
329 * find the month via an estimate that's either exact or one too
330 * large.
331 */
332 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
333 assert(leapyear == is_leap(*year));
334 *month = (n + 50) >> 5;
335 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
336 if (preceding > n) {
337 /* estimate is too large */
338 *month -= 1;
339 preceding -= days_in_month(*year, *month);
340 }
341 n -= preceding;
342 assert(0 <= n);
343 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000346}
347
348/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
349static int
350ymd_to_ord(int year, int month, int day)
351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000353}
354
355/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
356static int
357weekday(int year, int month, int day)
358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000360}
361
362/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
363 * first calendar week containing a Thursday.
364 */
365static int
366iso_week1_monday(int year)
367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
369 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
370 int first_weekday = (first_day + 6) % 7;
371 /* ordinal of closest Monday at or before 1/1 */
372 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
375 week1_monday += 7;
376 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000377}
378
379/* ---------------------------------------------------------------------------
380 * Range checkers.
381 */
382
383/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
384 * If not, raise OverflowError and return -1.
385 */
386static int
387check_delta_day_range(int days)
388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
390 return 0;
391 PyErr_Format(PyExc_OverflowError,
392 "days=%d; must have magnitude <= %d",
393 days, MAX_DELTA_DAYS);
394 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000395}
396
397/* Check that date arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_date_args(int year, int month, int day)
402{
403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (year < MINYEAR || year > MAXYEAR) {
Victor Stinnerb67f0962017-02-10 10:34:02 +0100405 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return -1;
407 }
408 if (month < 1 || month > 12) {
409 PyErr_SetString(PyExc_ValueError,
410 "month must be in 1..12");
411 return -1;
412 }
413 if (day < 1 || day > days_in_month(year, month)) {
414 PyErr_SetString(PyExc_ValueError,
415 "day is out of range for month");
416 return -1;
417 }
418 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000419}
420
421/* Check that time arguments are in range. Return 0 if they are. If they
422 * aren't, raise ValueError and return -1.
423 */
424static int
Alexander Belopolsky47649ab2016-08-08 17:05:40 -0400425check_time_args(int h, int m, int s, int us, int fold)
Tim Peters2a799bf2002-12-16 20:18:38 +0000426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (h < 0 || h > 23) {
428 PyErr_SetString(PyExc_ValueError,
429 "hour must be in 0..23");
430 return -1;
431 }
432 if (m < 0 || m > 59) {
433 PyErr_SetString(PyExc_ValueError,
434 "minute must be in 0..59");
435 return -1;
436 }
437 if (s < 0 || s > 59) {
438 PyErr_SetString(PyExc_ValueError,
439 "second must be in 0..59");
440 return -1;
441 }
442 if (us < 0 || us > 999999) {
443 PyErr_SetString(PyExc_ValueError,
444 "microsecond must be in 0..999999");
445 return -1;
446 }
Alexander Belopolsky47649ab2016-08-08 17:05:40 -0400447 if (fold != 0 && fold != 1) {
448 PyErr_SetString(PyExc_ValueError,
449 "fold must be either 0 or 1");
450 return -1;
451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000453}
454
455/* ---------------------------------------------------------------------------
456 * Normalization utilities.
457 */
458
459/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
460 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
461 * at least factor, enough of *lo is converted into "hi" units so that
462 * 0 <= *lo < factor. The input values must be such that int overflow
463 * is impossible.
464 */
465static void
466normalize_pair(int *hi, int *lo, int factor)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 assert(factor > 0);
469 assert(lo != hi);
470 if (*lo < 0 || *lo >= factor) {
471 const int num_hi = divmod(*lo, factor, lo);
472 const int new_hi = *hi + num_hi;
473 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
474 *hi = new_hi;
475 }
476 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000477}
478
479/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 * 0 <= *s < 24*3600
481 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000482 * The input values must be such that the internals don't overflow.
483 * The way this routine is used, we don't get close.
484 */
485static void
486normalize_d_s_us(int *d, int *s, int *us)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (*us < 0 || *us >= 1000000) {
489 normalize_pair(s, us, 1000000);
490 /* |s| can't be bigger than about
491 * |original s| + |original us|/1000000 now.
492 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 }
495 if (*s < 0 || *s >= 24*3600) {
496 normalize_pair(d, s, 24*3600);
497 /* |d| can't be bigger than about
498 * |original d| +
499 * (|original s| + |original us|/1000000) / (24*3600) now.
500 */
501 }
502 assert(0 <= *s && *s < 24*3600);
503 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000504}
505
506/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 * 1 <= *m <= 12
508 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000509 * The input values must be such that the internals don't overflow.
510 * The way this routine is used, we don't get close.
511 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000512static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000513normalize_y_m_d(int *y, int *m, int *d)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000516
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000517 /* In actual use, m is always the month component extracted from a
518 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 /* Now only day can be out of bounds (year may also be out of bounds
524 * for a datetime object, but we don't care about that here).
525 * If day is out of bounds, what to do is arguable, but at least the
526 * method here is principled and explainable.
527 */
528 dim = days_in_month(*y, *m);
529 if (*d < 1 || *d > dim) {
530 /* Move day-1 days from the first of the month. First try to
531 * get off cheap if we're only one day out of range
532 * (adjustments for timezone alone can't be worse than that).
533 */
534 if (*d == 0) {
535 --*m;
536 if (*m > 0)
537 *d = days_in_month(*y, *m);
538 else {
539 --*y;
540 *m = 12;
541 *d = 31;
542 }
543 }
544 else if (*d == dim + 1) {
545 /* move forward a day */
546 ++*m;
547 *d = 1;
548 if (*m > 12) {
549 *m = 1;
550 ++*y;
551 }
552 }
553 else {
554 int ordinal = ymd_to_ord(*y, *m, 1) +
555 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000556 if (ordinal < 1 || ordinal > MAXORDINAL) {
557 goto error;
558 } else {
559 ord_to_ymd(ordinal, y, m, d);
560 return 0;
561 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 }
563 }
564 assert(*m > 0);
565 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000566 if (MINYEAR <= *y && *y <= MAXYEAR)
567 return 0;
568 error:
569 PyErr_SetString(PyExc_OverflowError,
570 "date value out of range");
571 return -1;
572
Tim Peters2a799bf2002-12-16 20:18:38 +0000573}
574
575/* Fiddle out-of-bounds months and days so that the result makes some kind
576 * of sense. The parameters are both inputs and outputs. Returns < 0 on
577 * failure, where failure means the adjusted year is out of bounds.
578 */
579static int
580normalize_date(int *year, int *month, int *day)
581{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000582 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000583}
584
585/* Force all the datetime fields into range. The parameters are both
586 * inputs and outputs. Returns < 0 on error.
587 */
588static int
589normalize_datetime(int *year, int *month, int *day,
590 int *hour, int *minute, int *second,
591 int *microsecond)
592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 normalize_pair(second, microsecond, 1000000);
594 normalize_pair(minute, second, 60);
595 normalize_pair(hour, minute, 60);
596 normalize_pair(day, hour, 24);
597 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000598}
599
600/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000601 * Basic object allocation: tp_alloc implementations. These allocate
602 * Python objects of the right size and type, and do the Python object-
603 * initialization bit. If there's not enough memory, they return NULL after
604 * setting MemoryError. All data members remain uninitialized trash.
605 *
606 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000607 * member is needed. This is ugly, imprecise, and possibly insecure.
608 * tp_basicsize for the time and datetime types is set to the size of the
609 * struct that has room for the tzinfo member, so subclasses in Python will
610 * allocate enough space for a tzinfo member whether or not one is actually
611 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
612 * part is that PyType_GenericAlloc() (which subclasses in Python end up
613 * using) just happens today to effectively ignore the nitems argument
614 * when tp_itemsize is 0, which it is for these type objects. If that
615 * changes, perhaps the callers of tp_alloc slots in this file should
616 * be changed to force a 0 nitems argument unless the type being allocated
617 * is a base type implemented in this file (so that tp_alloc is time_alloc
618 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000619 */
620
621static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000622time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 self = (PyObject *)
627 PyObject_MALLOC(aware ?
628 sizeof(PyDateTime_Time) :
629 sizeof(_PyDateTime_BaseTime));
630 if (self == NULL)
631 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100632 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000634}
635
636static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000637datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 self = (PyObject *)
642 PyObject_MALLOC(aware ?
643 sizeof(PyDateTime_DateTime) :
644 sizeof(_PyDateTime_BaseDateTime));
645 if (self == NULL)
646 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100647 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000649}
650
651/* ---------------------------------------------------------------------------
652 * Helpers for setting object fields. These work on pointers to the
653 * appropriate base class.
654 */
655
656/* For date and datetime. */
657static void
658set_date_fields(PyDateTime_Date *self, int y, int m, int d)
659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 self->hashcode = -1;
661 SET_YEAR(self, y);
662 SET_MONTH(self, m);
663 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000664}
665
666/* ---------------------------------------------------------------------------
667 * Create various objects, mostly without range checking.
668 */
669
670/* Create a date instance with no range checking. */
671static PyObject *
672new_date_ex(int year, int month, int day, PyTypeObject *type)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000675
Victor Stinnerb67f0962017-02-10 10:34:02 +0100676 if (check_date_args(year, month, day) < 0) {
677 return NULL;
678 }
679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
681 if (self != NULL)
682 set_date_fields(self, year, month, day);
683 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000684}
685
686#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000688
689/* Create a datetime instance with no range checking. */
690static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400691new_datetime_ex2(int year, int month, int day, int hour, int minute,
692 int second, int usecond, PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyDateTime_DateTime *self;
695 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000696
Victor Stinnerb67f0962017-02-10 10:34:02 +0100697 if (check_date_args(year, month, day) < 0) {
698 return NULL;
699 }
700 if (check_time_args(hour, minute, second, usecond, fold) < 0) {
701 return NULL;
702 }
703 if (check_tzinfo_subclass(tzinfo) < 0) {
704 return NULL;
705 }
706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
708 if (self != NULL) {
709 self->hastzinfo = aware;
710 set_date_fields((PyDateTime_Date *)self, year, month, day);
711 DATE_SET_HOUR(self, hour);
712 DATE_SET_MINUTE(self, minute);
713 DATE_SET_SECOND(self, second);
714 DATE_SET_MICROSECOND(self, usecond);
715 if (aware) {
716 Py_INCREF(tzinfo);
717 self->tzinfo = tzinfo;
718 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400719 DATE_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 }
721 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000722}
723
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400724static PyObject *
725new_datetime_ex(int year, int month, int day, int hour, int minute,
726 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
727{
728 return new_datetime_ex2(year, month, day, hour, minute, second, usecond,
729 tzinfo, 0, type);
730}
731
732#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo, fold) \
733 new_datetime_ex2(y, m, d, hh, mm, ss, us, tzinfo, fold, \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000735
736/* Create a time instance with no range checking. */
737static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400738new_time_ex2(int hour, int minute, int second, int usecond,
739 PyObject *tzinfo, int fold, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyDateTime_Time *self;
742 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000743
Victor Stinnerb67f0962017-02-10 10:34:02 +0100744 if (check_time_args(hour, minute, second, usecond, fold) < 0) {
745 return NULL;
746 }
747 if (check_tzinfo_subclass(tzinfo) < 0) {
748 return NULL;
749 }
750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
752 if (self != NULL) {
753 self->hastzinfo = aware;
754 self->hashcode = -1;
755 TIME_SET_HOUR(self, hour);
756 TIME_SET_MINUTE(self, minute);
757 TIME_SET_SECOND(self, second);
758 TIME_SET_MICROSECOND(self, usecond);
759 if (aware) {
760 Py_INCREF(tzinfo);
761 self->tzinfo = tzinfo;
762 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400763 TIME_SET_FOLD(self, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 }
765 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000766}
767
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400768static PyObject *
769new_time_ex(int hour, int minute, int second, int usecond,
770 PyObject *tzinfo, PyTypeObject *type)
771{
772 return new_time_ex2(hour, minute, second, usecond, tzinfo, 0, type);
773}
774
775#define new_time(hh, mm, ss, us, tzinfo, fold) \
776 new_time_ex2(hh, mm, ss, us, tzinfo, fold, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000777
778/* Create a timedelta instance. Normalize the members iff normalize is
779 * true. Passing false is a speed optimization, if you know for sure
780 * that seconds and microseconds are already in their proper ranges. In any
781 * case, raises OverflowError and returns NULL if the normalized days is out
782 * of range).
783 */
784static PyObject *
785new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (normalize)
791 normalize_d_s_us(&days, &seconds, &microseconds);
792 assert(0 <= seconds && seconds < 24*3600);
793 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 if (check_delta_day_range(days) < 0)
796 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
799 if (self != NULL) {
800 self->hashcode = -1;
801 SET_TD_DAYS(self, days);
802 SET_TD_SECONDS(self, seconds);
803 SET_TD_MICROSECONDS(self, microseconds);
804 }
805 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000806}
807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808#define new_delta(d, s, us, normalize) \
809 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000810
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000811
812typedef struct
813{
814 PyObject_HEAD
815 PyObject *offset;
816 PyObject *name;
817} PyDateTime_TimeZone;
818
Victor Stinner6ced7c42011-03-21 18:15:42 +0100819/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000820static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya4415142012-06-08 12:33:09 -0400821/* The interned Epoch datetime instance */
822static PyObject *PyDateTime_Epoch;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +0000823
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000824/* Create new timezone instance checking offset range. This
825 function does not check the name argument. Caller must assure
826 that offset is a timedelta instance and name is either NULL
827 or a unicode object. */
828static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000829create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000830{
831 PyDateTime_TimeZone *self;
832 PyTypeObject *type = &PyDateTime_TimeZoneType;
833
834 assert(offset != NULL);
835 assert(PyDelta_Check(offset));
836 assert(name == NULL || PyUnicode_Check(name));
837
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000838 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
839 if (self == NULL) {
840 return NULL;
841 }
842 Py_INCREF(offset);
843 self->offset = offset;
844 Py_XINCREF(name);
845 self->name = name;
846 return (PyObject *)self;
847}
848
849static int delta_bool(PyDateTime_Delta *self);
850
851static PyObject *
852new_timezone(PyObject *offset, PyObject *name)
853{
854 assert(offset != NULL);
855 assert(PyDelta_Check(offset));
856 assert(name == NULL || PyUnicode_Check(name));
857
858 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
859 Py_INCREF(PyDateTime_TimeZone_UTC);
860 return PyDateTime_TimeZone_UTC;
861 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000862 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
863 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400864 " representing a whole number of minutes,"
865 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000866 return NULL;
867 }
868 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
869 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
870 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
871 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400872 " timedelta(hours=24),"
873 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000874 return NULL;
875 }
876
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000877 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000878}
879
Tim Petersb0c854d2003-05-17 15:57:00 +0000880/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000881 * tzinfo helpers.
882 */
883
Tim Peters855fe882002-12-22 03:43:39 +0000884/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
885 * raise TypeError and return -1.
886 */
887static int
888check_tzinfo_subclass(PyObject *p)
889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 if (p == Py_None || PyTZInfo_Check(p))
891 return 0;
892 PyErr_Format(PyExc_TypeError,
893 "tzinfo argument must be None or of a tzinfo subclass, "
894 "not type '%s'",
895 Py_TYPE(p)->tp_name);
896 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000897}
898
Tim Peters2a799bf2002-12-16 20:18:38 +0000899/* If self has a tzinfo member, return a BORROWED reference to it. Else
900 * return NULL, which is NOT AN ERROR. There are no error returns here,
901 * and the caller must not decref the result.
902 */
903static PyObject *
904get_tzinfo_member(PyObject *self)
905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (PyDateTime_Check(self) && HASTZINFO(self))
909 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
910 else if (PyTime_Check(self) && HASTZINFO(self))
911 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000914}
915
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000916/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
917 * be an instance of the tzinfo class. If the method returns None, this
918 * returns None. If the method doesn't return None or timedelta, TypeError is
919 * raised and this returns NULL. If it returns a timedelta and the value is
920 * out of range or isn't a whole number of minutes, ValueError is raised and
921 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000922 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000923static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200924call_tzinfo_method(PyObject *tzinfo, const char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000925{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000926 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000929 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000931
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000932 if (tzinfo == Py_None)
933 Py_RETURN_NONE;
934 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
935 if (offset == Py_None || offset == NULL)
936 return offset;
937 if (PyDelta_Check(offset)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400938 if (GET_TD_MICROSECONDS(offset) != 0) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000939 Py_DECREF(offset);
940 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400941 " representing a whole number of seconds");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000942 return NULL;
943 }
944 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
945 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
946 Py_DECREF(offset);
947 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
948 " strictly between -timedelta(hours=24) and"
949 " timedelta(hours=24).");
950 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 }
952 }
953 else {
954 PyErr_Format(PyExc_TypeError,
955 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000956 "timedelta, not '%.200s'",
957 name, Py_TYPE(offset)->tp_name);
Raymond Hettinger5a2146a2014-07-25 14:59:48 -0700958 Py_DECREF(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000959 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000961
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000962 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000963}
964
965/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
966 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
967 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000968 * doesn't return None or timedelta, TypeError is raised and this returns -1.
969 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
970 * # of minutes), ValueError is raised and this returns -1. Else *none is
971 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000972 */
Tim Peters855fe882002-12-22 03:43:39 +0000973static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000974call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
975{
976 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000977}
978
Tim Peters2a799bf2002-12-16 20:18:38 +0000979/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
980 * result. tzinfo must be an instance of the tzinfo class. If dst()
981 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000982 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000983 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000984 * ValueError is raised and this returns -1. Else *none is set to 0 and
985 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000986 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000987static PyObject *
988call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000989{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000990 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000991}
992
Tim Petersbad8ff02002-12-30 20:52:32 +0000993/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000994 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000995 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000996 * returns NULL. If the result is a string, we ensure it is a Unicode
997 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000998 */
999static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001000call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001003 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 assert(tzinfo != NULL);
1006 assert(check_tzinfo_subclass(tzinfo) >= 0);
1007 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001010 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001011
Victor Stinner20401de2016-12-09 15:24:31 +01001012 result = _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_tzname,
1013 tzinfoarg, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001014
1015 if (result == NULL || result == Py_None)
1016 return result;
1017
1018 if (!PyUnicode_Check(result)) {
1019 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
1020 "return None or a string, not '%s'",
1021 Py_TYPE(result)->tp_name);
1022 Py_DECREF(result);
1023 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001025
1026 return result;
Tim Peters00237032002-12-27 02:21:51 +00001027}
1028
Tim Peters2a799bf2002-12-16 20:18:38 +00001029/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1030 * stuff
1031 * ", tzinfo=" + repr(tzinfo)
1032 * before the closing ")".
1033 */
1034static PyObject *
1035append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 assert(PyUnicode_Check(repr));
1040 assert(tzinfo);
1041 if (tzinfo == Py_None)
1042 return repr;
1043 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1045 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 Py_DECREF(repr);
1047 if (temp == NULL)
1048 return NULL;
1049 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1050 Py_DECREF(temp);
1051 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001052}
1053
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001054/* repr is like "someclass(arg1, arg2)". If fold isn't 0,
1055 * stuff
1056 * ", fold=" + repr(tzinfo)
1057 * before the closing ")".
1058 */
1059static PyObject *
1060append_keyword_fold(PyObject *repr, int fold)
1061{
1062 PyObject *temp;
1063
1064 assert(PyUnicode_Check(repr));
1065 if (fold == 0)
1066 return repr;
1067 /* Get rid of the trailing ')'. */
1068 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
1069 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
1070 Py_DECREF(repr);
1071 if (temp == NULL)
1072 return NULL;
1073 repr = PyUnicode_FromFormat("%U, fold=%d)", temp, fold);
1074 Py_DECREF(temp);
1075 return repr;
1076}
1077
Tim Peters2a799bf2002-12-16 20:18:38 +00001078/* ---------------------------------------------------------------------------
1079 * String format helpers.
1080 */
1081
1082static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001083format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001084{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001085 static const char * const DayNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1087 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02001088 static const char * const MonthNames[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1090 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1091 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1096 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1097 GET_DAY(date), hours, minutes, seconds,
1098 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001099}
1100
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001101static PyObject *delta_negative(PyDateTime_Delta *self);
1102
Tim Peters2a799bf2002-12-16 20:18:38 +00001103/* Add an hours & minutes UTC offset string to buf. buf has no more than
1104 * buflen bytes remaining. The UTC offset is gotten by calling
1105 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1106 * *buf, and that's all. Else the returned value is checked for sanity (an
1107 * integer in range), and if that's OK it's converted to an hours & minutes
1108 * string of the form
1109 * sign HH sep MM
1110 * Returns 0 if everything is OK. If the return value from utcoffset() is
1111 * bogus, an appropriate exception is set and -1 is returned.
1112 */
1113static int
Tim Peters328fff72002-12-20 01:31:27 +00001114format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001116{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001117 PyObject *offset;
1118 int hours, minutes, seconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001122
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001123 offset = call_utcoffset(tzinfo, tzinfoarg);
1124 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001126 if (offset == Py_None) {
1127 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 *buf = '\0';
1129 return 0;
1130 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001131 /* Offset is normalized, so it is negative if days < 0 */
1132 if (GET_TD_DAYS(offset) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 sign = '-';
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03001134 Py_SETREF(offset, delta_negative((PyDateTime_Delta *)offset));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001135 if (offset == NULL)
1136 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001138 else {
1139 sign = '+';
1140 }
1141 /* Offset is not negative here. */
1142 seconds = GET_TD_SECONDS(offset);
1143 Py_DECREF(offset);
1144 minutes = divmod(seconds, 60, &seconds);
1145 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04001146 if (seconds == 0)
1147 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1148 else
1149 PyOS_snprintf(buf, buflen, "%c%02d%s%02d%s%02d", sign, hours,
1150 sep, minutes, sep, seconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001152}
1153
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001154static PyObject *
1155make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 PyObject *temp;
1158 PyObject *tzinfo = get_tzinfo_member(object);
1159 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001160 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (Zreplacement == NULL)
1163 return NULL;
1164 if (tzinfo == Py_None || tzinfo == NULL)
1165 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 assert(tzinfoarg != NULL);
1168 temp = call_tzname(tzinfo, tzinfoarg);
1169 if (temp == NULL)
1170 goto Error;
1171 if (temp == Py_None) {
1172 Py_DECREF(temp);
1173 return Zreplacement;
1174 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 assert(PyUnicode_Check(temp));
1177 /* Since the tzname is getting stuffed into the
1178 * format, we have to double any % signs so that
1179 * strftime doesn't treat them as format codes.
1180 */
1181 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001182 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 Py_DECREF(temp);
1184 if (Zreplacement == NULL)
1185 return NULL;
1186 if (!PyUnicode_Check(Zreplacement)) {
1187 PyErr_SetString(PyExc_TypeError,
1188 "tzname.replace() did not return a string");
1189 goto Error;
1190 }
1191 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001192
1193 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 Py_DECREF(Zreplacement);
1195 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001196}
1197
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001198static PyObject *
1199make_freplacement(PyObject *object)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 char freplacement[64];
1202 if (PyTime_Check(object))
1203 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1204 else if (PyDateTime_Check(object))
1205 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1206 else
1207 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001210}
1211
Tim Peters2a799bf2002-12-16 20:18:38 +00001212/* I sure don't want to reproduce the strftime code from the time module,
1213 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001214 * giving special meanings to the %z, %Z and %f format codes via a
1215 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001216 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1217 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001218 */
1219static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001220wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1226 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1227 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 const char *pin; /* pointer to next char in input format */
1230 Py_ssize_t flen; /* length of input format */
1231 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 PyObject *newfmt = NULL; /* py string, the output format */
1234 char *pnew; /* pointer to available byte in output format */
1235 size_t totalnew; /* number bytes total in output format buffer,
1236 exclusive of trailing \0 */
1237 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 const char *ptoappend; /* ptr to string to append to output buffer */
1240 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 assert(object && format && timetuple);
1243 assert(PyUnicode_Check(format));
1244 /* Convert the input format to a C string and size */
Serhiy Storchaka06515832016-11-20 09:13:07 +02001245 pin = PyUnicode_AsUTF8AndSize(format, &flen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (!pin)
1247 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 /* Scan the input format, looking for %z/%Z/%f escapes, building
1250 * a new format. Since computing the replacements for those codes
1251 * is expensive, don't unless they're actually used.
1252 */
1253 if (flen > INT_MAX - 1) {
1254 PyErr_NoMemory();
1255 goto Done;
1256 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 totalnew = flen + 1; /* realistic if no %z/%Z */
1259 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1260 if (newfmt == NULL) goto Done;
1261 pnew = PyBytes_AsString(newfmt);
1262 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 while ((ch = *pin++) != '\0') {
1265 if (ch != '%') {
1266 ptoappend = pin - 1;
1267 ntoappend = 1;
1268 }
1269 else if ((ch = *pin++) == '\0') {
1270 /* There's a lone trailing %; doesn't make sense. */
1271 PyErr_SetString(PyExc_ValueError, "strftime format "
1272 "ends with raw %");
1273 goto Done;
1274 }
1275 /* A % has been seen and ch is the character after it. */
1276 else if (ch == 'z') {
1277 if (zreplacement == NULL) {
1278 /* format utcoffset */
1279 char buf[100];
1280 PyObject *tzinfo = get_tzinfo_member(object);
1281 zreplacement = PyBytes_FromStringAndSize("", 0);
1282 if (zreplacement == NULL) goto Done;
1283 if (tzinfo != Py_None && tzinfo != NULL) {
1284 assert(tzinfoarg != NULL);
1285 if (format_utcoffset(buf,
1286 sizeof(buf),
1287 "",
1288 tzinfo,
1289 tzinfoarg) < 0)
1290 goto Done;
1291 Py_DECREF(zreplacement);
1292 zreplacement =
1293 PyBytes_FromStringAndSize(buf,
1294 strlen(buf));
1295 if (zreplacement == NULL)
1296 goto Done;
1297 }
1298 }
1299 assert(zreplacement != NULL);
1300 ptoappend = PyBytes_AS_STRING(zreplacement);
1301 ntoappend = PyBytes_GET_SIZE(zreplacement);
1302 }
1303 else if (ch == 'Z') {
1304 /* format tzname */
1305 if (Zreplacement == NULL) {
1306 Zreplacement = make_Zreplacement(object,
1307 tzinfoarg);
1308 if (Zreplacement == NULL)
1309 goto Done;
1310 }
1311 assert(Zreplacement != NULL);
1312 assert(PyUnicode_Check(Zreplacement));
Serhiy Storchaka06515832016-11-20 09:13:07 +02001313 ptoappend = PyUnicode_AsUTF8AndSize(Zreplacement,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001315 if (ptoappend == NULL)
1316 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 }
1318 else if (ch == 'f') {
1319 /* format microseconds */
1320 if (freplacement == NULL) {
1321 freplacement = make_freplacement(object);
1322 if (freplacement == NULL)
1323 goto Done;
1324 }
1325 assert(freplacement != NULL);
1326 assert(PyBytes_Check(freplacement));
1327 ptoappend = PyBytes_AS_STRING(freplacement);
1328 ntoappend = PyBytes_GET_SIZE(freplacement);
1329 }
1330 else {
1331 /* percent followed by neither z nor Z */
1332 ptoappend = pin - 2;
1333 ntoappend = 2;
1334 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /* Append the ntoappend chars starting at ptoappend to
1337 * the new format.
1338 */
1339 if (ntoappend == 0)
1340 continue;
1341 assert(ptoappend != NULL);
1342 assert(ntoappend > 0);
1343 while (usednew + ntoappend > totalnew) {
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001344 if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 PyErr_NoMemory();
1346 goto Done;
1347 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001348 totalnew <<= 1;
1349 if (_PyBytes_Resize(&newfmt, totalnew) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 pnew = PyBytes_AsString(newfmt) + usednew;
1352 }
1353 memcpy(pnew, ptoappend, ntoappend);
1354 pnew += ntoappend;
1355 usednew += ntoappend;
1356 assert(usednew <= totalnew);
1357 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1360 goto Done;
1361 {
1362 PyObject *format;
1363 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 if (time == NULL)
1366 goto Done;
1367 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1368 if (format != NULL) {
Victor Stinner20401de2016-12-09 15:24:31 +01001369 result = _PyObject_CallMethodIdObjArgs(time, &PyId_strftime,
1370 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 Py_DECREF(format);
1372 }
1373 Py_DECREF(time);
1374 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001375 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 Py_XDECREF(freplacement);
1377 Py_XDECREF(zreplacement);
1378 Py_XDECREF(Zreplacement);
1379 Py_XDECREF(newfmt);
1380 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001381}
1382
Tim Peters2a799bf2002-12-16 20:18:38 +00001383/* ---------------------------------------------------------------------------
1384 * Wrap functions from the time module. These aren't directly available
1385 * from C. Perhaps they should be.
1386 */
1387
1388/* Call time.time() and return its result (a Python float). */
1389static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001390time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 PyObject *result = NULL;
1393 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001396 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001397
Victor Stinnerad8c83a2016-09-05 17:53:15 -07001398 result = _PyObject_CallMethodId(time, &PyId_time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_DECREF(time);
1400 }
1401 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001402}
1403
1404/* Build a time.struct_time. The weekday and day number are automatically
1405 * computed from the y,m,d args.
1406 */
1407static PyObject *
1408build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyObject *time;
Victor Stinner2b635972016-12-09 00:38:16 +01001411 PyObject *result;
1412 _Py_IDENTIFIER(struct_time);
1413 PyObject *args;
1414
Tim Peters2a799bf2002-12-16 20:18:38 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 time = PyImport_ImportModuleNoBlock("time");
Victor Stinner2b635972016-12-09 00:38:16 +01001417 if (time == NULL) {
1418 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 }
Victor Stinner2b635972016-12-09 00:38:16 +01001420
1421 args = Py_BuildValue("iiiiiiiii",
1422 y, m, d,
1423 hh, mm, ss,
1424 weekday(y, m, d),
1425 days_before_month(y, m) + d,
1426 dstflag);
1427 if (args == NULL) {
1428 Py_DECREF(time);
1429 return NULL;
1430 }
1431
1432 result = _PyObject_CallMethodIdObjArgs(time, &PyId_struct_time,
1433 args, NULL);
1434 Py_DECREF(time);
Victor Stinnerddc120f2016-12-09 15:35:40 +01001435 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001437}
1438
1439/* ---------------------------------------------------------------------------
1440 * Miscellaneous helpers.
1441 */
1442
Mark Dickinsone94c6792009-02-02 20:36:42 +00001443/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001444 * The comparisons here all most naturally compute a cmp()-like result.
1445 * This little helper turns that into a bool result for rich comparisons.
1446 */
1447static PyObject *
1448diff_to_bool(int diff, int op)
1449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 PyObject *result;
1451 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 switch (op) {
1454 case Py_EQ: istrue = diff == 0; break;
1455 case Py_NE: istrue = diff != 0; break;
1456 case Py_LE: istrue = diff <= 0; break;
1457 case Py_GE: istrue = diff >= 0; break;
1458 case Py_LT: istrue = diff < 0; break;
1459 case Py_GT: istrue = diff > 0; break;
1460 default:
1461 assert(! "op unknown");
1462 istrue = 0; /* To shut up compiler */
1463 }
1464 result = istrue ? Py_True : Py_False;
1465 Py_INCREF(result);
1466 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001467}
1468
Tim Peters07534a62003-02-07 22:50:28 +00001469/* Raises a "can't compare" TypeError and returns NULL. */
1470static PyObject *
1471cmperror(PyObject *a, PyObject *b)
1472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 PyErr_Format(PyExc_TypeError,
1474 "can't compare %s to %s",
1475 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1476 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001477}
1478
Tim Peters2a799bf2002-12-16 20:18:38 +00001479/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001480 * Cached Python objects; these are set by the module init function.
1481 */
1482
1483/* Conversion factors. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04001484static PyObject *one = NULL; /* 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485static PyObject *us_per_ms = NULL; /* 1000 */
1486static PyObject *us_per_second = NULL; /* 1000000 */
1487static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001488static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
1489static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
1490static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
Tim Peters2a799bf2002-12-16 20:18:38 +00001491static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1492
Tim Peters2a799bf2002-12-16 20:18:38 +00001493/* ---------------------------------------------------------------------------
1494 * Class implementations.
1495 */
1496
1497/*
1498 * PyDateTime_Delta implementation.
1499 */
1500
1501/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Serhiy Storchaka95949422013-08-27 19:40:23 +03001503 * as a Python int.
Tim Peters2a799bf2002-12-16 20:18:38 +00001504 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1505 * due to ubiquitous overflow possibilities.
1506 */
1507static PyObject *
1508delta_to_microseconds(PyDateTime_Delta *self)
1509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 PyObject *x1 = NULL;
1511 PyObject *x2 = NULL;
1512 PyObject *x3 = NULL;
1513 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1516 if (x1 == NULL)
1517 goto Done;
1518 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1519 if (x2 == NULL)
1520 goto Done;
1521 Py_DECREF(x1);
1522 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 /* x2 has days in seconds */
1525 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1526 if (x1 == NULL)
1527 goto Done;
1528 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1529 if (x3 == NULL)
1530 goto Done;
1531 Py_DECREF(x1);
1532 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001533 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 /* x3 has days+seconds in seconds */
1536 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1537 if (x1 == NULL)
1538 goto Done;
1539 Py_DECREF(x3);
1540 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 /* x1 has days+seconds in us */
1543 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1544 if (x2 == NULL)
1545 goto Done;
1546 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001547
1548Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 Py_XDECREF(x1);
1550 Py_XDECREF(x2);
1551 Py_XDECREF(x3);
1552 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001553}
1554
Serhiy Storchaka95949422013-08-27 19:40:23 +03001555/* Convert a number of us (as a Python int) to a timedelta.
Tim Peters2a799bf2002-12-16 20:18:38 +00001556 */
1557static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001558microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 int us;
1561 int s;
1562 int d;
1563 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyObject *tuple = NULL;
1566 PyObject *num = NULL;
1567 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 tuple = PyNumber_Divmod(pyus, us_per_second);
1570 if (tuple == NULL)
1571 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 num = PyTuple_GetItem(tuple, 1); /* us */
1574 if (num == NULL)
1575 goto Done;
1576 temp = PyLong_AsLong(num);
1577 num = NULL;
1578 if (temp == -1 && PyErr_Occurred())
1579 goto Done;
1580 assert(0 <= temp && temp < 1000000);
1581 us = (int)temp;
1582 if (us < 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 seconds */
1589 if (num == NULL)
1590 goto Done;
1591 Py_INCREF(num);
1592 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 tuple = PyNumber_Divmod(num, seconds_per_day);
1595 if (tuple == NULL)
1596 goto Done;
1597 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 num = PyTuple_GetItem(tuple, 1); /* seconds */
1600 if (num == NULL)
1601 goto Done;
1602 temp = PyLong_AsLong(num);
1603 num = NULL;
1604 if (temp == -1 && PyErr_Occurred())
1605 goto Done;
1606 assert(0 <= temp && temp < 24*3600);
1607 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (s < 0) {
1610 /* The divisor was positive, so this must be an error. */
1611 assert(PyErr_Occurred());
1612 goto Done;
1613 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1616 if (num == NULL)
1617 goto Done;
1618 Py_INCREF(num);
1619 temp = PyLong_AsLong(num);
1620 if (temp == -1 && PyErr_Occurred())
1621 goto Done;
1622 d = (int)temp;
1623 if ((long)d != temp) {
1624 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1625 "large to fit in a C int");
1626 goto Done;
1627 }
1628 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001629
1630Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 Py_XDECREF(tuple);
1632 Py_XDECREF(num);
1633 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001634}
1635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636#define microseconds_to_delta(pymicros) \
1637 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001638
Tim Peters2a799bf2002-12-16 20:18:38 +00001639static PyObject *
1640multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyObject *pyus_in;
1643 PyObject *pyus_out;
1644 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 pyus_in = delta_to_microseconds(delta);
1647 if (pyus_in == NULL)
1648 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1651 Py_DECREF(pyus_in);
1652 if (pyus_out == NULL)
1653 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 result = microseconds_to_delta(pyus_out);
1656 Py_DECREF(pyus_out);
1657 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001658}
1659
1660static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001661multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1662{
1663 PyObject *result = NULL;
1664 PyObject *pyus_in = NULL, *temp, *pyus_out;
1665 PyObject *ratio = NULL;
1666
1667 pyus_in = delta_to_microseconds(delta);
1668 if (pyus_in == NULL)
1669 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001670 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001671 if (ratio == NULL)
1672 goto error;
1673 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1674 Py_DECREF(pyus_in);
1675 pyus_in = NULL;
1676 if (temp == NULL)
1677 goto error;
1678 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1679 Py_DECREF(temp);
1680 if (pyus_out == NULL)
1681 goto error;
1682 result = microseconds_to_delta(pyus_out);
1683 Py_DECREF(pyus_out);
1684 error:
1685 Py_XDECREF(pyus_in);
1686 Py_XDECREF(ratio);
1687
1688 return result;
1689}
1690
1691static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001692divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyObject *pyus_in;
1695 PyObject *pyus_out;
1696 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 pyus_in = delta_to_microseconds(delta);
1699 if (pyus_in == NULL)
1700 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1703 Py_DECREF(pyus_in);
1704 if (pyus_out == NULL)
1705 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 result = microseconds_to_delta(pyus_out);
1708 Py_DECREF(pyus_out);
1709 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001710}
1711
1712static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001713divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyObject *pyus_left;
1716 PyObject *pyus_right;
1717 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 pyus_left = delta_to_microseconds(left);
1720 if (pyus_left == NULL)
1721 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 pyus_right = delta_to_microseconds(right);
1724 if (pyus_right == NULL) {
1725 Py_DECREF(pyus_left);
1726 return NULL;
1727 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1730 Py_DECREF(pyus_left);
1731 Py_DECREF(pyus_right);
1732 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001733}
1734
1735static PyObject *
1736truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 PyObject *pyus_left;
1739 PyObject *pyus_right;
1740 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 pyus_left = delta_to_microseconds(left);
1743 if (pyus_left == NULL)
1744 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 pyus_right = delta_to_microseconds(right);
1747 if (pyus_right == NULL) {
1748 Py_DECREF(pyus_left);
1749 return NULL;
1750 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1753 Py_DECREF(pyus_left);
1754 Py_DECREF(pyus_right);
1755 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001756}
1757
1758static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001759truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1760{
1761 PyObject *result = NULL;
1762 PyObject *pyus_in = NULL, *temp, *pyus_out;
1763 PyObject *ratio = NULL;
1764
1765 pyus_in = delta_to_microseconds(delta);
1766 if (pyus_in == NULL)
1767 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001768 ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001769 if (ratio == NULL)
1770 goto error;
1771 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1772 Py_DECREF(pyus_in);
1773 pyus_in = NULL;
1774 if (temp == NULL)
1775 goto error;
1776 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1777 Py_DECREF(temp);
1778 if (pyus_out == NULL)
1779 goto error;
1780 result = microseconds_to_delta(pyus_out);
1781 Py_DECREF(pyus_out);
1782 error:
1783 Py_XDECREF(pyus_in);
1784 Py_XDECREF(ratio);
1785
1786 return result;
1787}
1788
1789static PyObject *
1790truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1791{
1792 PyObject *result;
1793 PyObject *pyus_in, *pyus_out;
1794 pyus_in = delta_to_microseconds(delta);
1795 if (pyus_in == NULL)
1796 return NULL;
1797 pyus_out = divide_nearest(pyus_in, i);
1798 Py_DECREF(pyus_in);
1799 if (pyus_out == NULL)
1800 return NULL;
1801 result = microseconds_to_delta(pyus_out);
1802 Py_DECREF(pyus_out);
1803
1804 return result;
1805}
1806
1807static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001808delta_add(PyObject *left, PyObject *right)
1809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1813 /* delta + delta */
1814 /* The C-level additions can't overflow because of the
1815 * invariant bounds.
1816 */
1817 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1818 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1819 int microseconds = GET_TD_MICROSECONDS(left) +
1820 GET_TD_MICROSECONDS(right);
1821 result = new_delta(days, seconds, microseconds, 1);
1822 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 if (result == Py_NotImplemented)
1825 Py_INCREF(result);
1826 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001827}
1828
1829static PyObject *
1830delta_negative(PyDateTime_Delta *self)
1831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 return new_delta(-GET_TD_DAYS(self),
1833 -GET_TD_SECONDS(self),
1834 -GET_TD_MICROSECONDS(self),
1835 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001836}
1837
1838static PyObject *
1839delta_positive(PyDateTime_Delta *self)
1840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 /* Could optimize this (by returning self) if this isn't a
1842 * subclass -- but who uses unary + ? Approximately nobody.
1843 */
1844 return new_delta(GET_TD_DAYS(self),
1845 GET_TD_SECONDS(self),
1846 GET_TD_MICROSECONDS(self),
1847 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001848}
1849
1850static PyObject *
1851delta_abs(PyDateTime_Delta *self)
1852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 assert(GET_TD_MICROSECONDS(self) >= 0);
1856 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (GET_TD_DAYS(self) < 0)
1859 result = delta_negative(self);
1860 else
1861 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001864}
1865
1866static PyObject *
1867delta_subtract(PyObject *left, PyObject *right)
1868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1872 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04001873 /* The C-level additions can't overflow because of the
1874 * invariant bounds.
1875 */
1876 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1877 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1878 int microseconds = GET_TD_MICROSECONDS(left) -
1879 GET_TD_MICROSECONDS(right);
1880 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (result == Py_NotImplemented)
1884 Py_INCREF(result);
1885 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001886}
1887
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001888static int
1889delta_cmp(PyObject *self, PyObject *other)
1890{
1891 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1892 if (diff == 0) {
1893 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1894 if (diff == 0)
1895 diff = GET_TD_MICROSECONDS(self) -
1896 GET_TD_MICROSECONDS(other);
1897 }
1898 return diff;
1899}
1900
Tim Peters2a799bf2002-12-16 20:18:38 +00001901static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001902delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001905 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 return diff_to_bool(diff, op);
1907 }
1908 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05001909 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001911}
1912
1913static PyObject *delta_getstate(PyDateTime_Delta *self);
1914
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001915static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001916delta_hash(PyDateTime_Delta *self)
1917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 if (self->hashcode == -1) {
1919 PyObject *temp = delta_getstate(self);
1920 if (temp != NULL) {
1921 self->hashcode = PyObject_Hash(temp);
1922 Py_DECREF(temp);
1923 }
1924 }
1925 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001926}
1927
1928static PyObject *
1929delta_multiply(PyObject *left, PyObject *right)
1930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 if (PyDelta_Check(left)) {
1934 /* delta * ??? */
1935 if (PyLong_Check(right))
1936 result = multiply_int_timedelta(right,
1937 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001938 else if (PyFloat_Check(right))
1939 result = multiply_float_timedelta(right,
1940 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 }
1942 else if (PyLong_Check(left))
1943 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001944 (PyDateTime_Delta *) right);
1945 else if (PyFloat_Check(left))
1946 result = multiply_float_timedelta(left,
1947 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 if (result == Py_NotImplemented)
1950 Py_INCREF(result);
1951 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001952}
1953
1954static PyObject *
1955delta_divide(PyObject *left, PyObject *right)
1956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 if (PyDelta_Check(left)) {
1960 /* delta * ??? */
1961 if (PyLong_Check(right))
1962 result = divide_timedelta_int(
1963 (PyDateTime_Delta *)left,
1964 right);
1965 else if (PyDelta_Check(right))
1966 result = divide_timedelta_timedelta(
1967 (PyDateTime_Delta *)left,
1968 (PyDateTime_Delta *)right);
1969 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (result == Py_NotImplemented)
1972 Py_INCREF(result);
1973 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001974}
1975
Mark Dickinson7c186e22010-04-20 22:32:49 +00001976static PyObject *
1977delta_truedivide(PyObject *left, PyObject *right)
1978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 if (PyDelta_Check(left)) {
1982 if (PyDelta_Check(right))
1983 result = truedivide_timedelta_timedelta(
1984 (PyDateTime_Delta *)left,
1985 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001986 else if (PyFloat_Check(right))
1987 result = truedivide_timedelta_float(
1988 (PyDateTime_Delta *)left, right);
1989 else if (PyLong_Check(right))
1990 result = truedivide_timedelta_int(
1991 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 if (result == Py_NotImplemented)
1995 Py_INCREF(result);
1996 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001997}
1998
1999static PyObject *
2000delta_remainder(PyObject *left, PyObject *right)
2001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyObject *pyus_left;
2003 PyObject *pyus_right;
2004 PyObject *pyus_remainder;
2005 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002006
Brian Curtindfc80e32011-08-10 20:28:54 -05002007 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2008 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2011 if (pyus_left == NULL)
2012 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2015 if (pyus_right == NULL) {
2016 Py_DECREF(pyus_left);
2017 return NULL;
2018 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
2021 Py_DECREF(pyus_left);
2022 Py_DECREF(pyus_right);
2023 if (pyus_remainder == NULL)
2024 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 remainder = microseconds_to_delta(pyus_remainder);
2027 Py_DECREF(pyus_remainder);
2028 if (remainder == NULL)
2029 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002032}
2033
2034static PyObject *
2035delta_divmod(PyObject *left, PyObject *right)
2036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 PyObject *pyus_left;
2038 PyObject *pyus_right;
2039 PyObject *divmod;
2040 PyObject *delta;
2041 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002042
Brian Curtindfc80e32011-08-10 20:28:54 -05002043 if (!PyDelta_Check(left) || !PyDelta_Check(right))
2044 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2047 if (pyus_left == NULL)
2048 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2051 if (pyus_right == NULL) {
2052 Py_DECREF(pyus_left);
2053 return NULL;
2054 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 divmod = PyNumber_Divmod(pyus_left, pyus_right);
2057 Py_DECREF(pyus_left);
2058 Py_DECREF(pyus_right);
2059 if (divmod == NULL)
2060 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 assert(PyTuple_Size(divmod) == 2);
2063 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
2064 if (delta == NULL) {
2065 Py_DECREF(divmod);
2066 return NULL;
2067 }
2068 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
2069 Py_DECREF(delta);
2070 Py_DECREF(divmod);
2071 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002072}
2073
Tim Peters2a799bf2002-12-16 20:18:38 +00002074/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2075 * timedelta constructor. sofar is the # of microseconds accounted for
2076 * so far, and there are factor microseconds per current unit, the number
2077 * of which is given by num. num * factor is added to sofar in a
2078 * numerically careful way, and that's the result. Any fractional
2079 * microseconds left over (this can happen if num is a float type) are
2080 * added into *leftover.
2081 * Note that there are many ways this can give an error (NULL) return.
2082 */
2083static PyObject *
2084accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2085 double *leftover)
2086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 PyObject *prod;
2088 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (PyLong_Check(num)) {
2093 prod = PyNumber_Multiply(num, factor);
2094 if (prod == NULL)
2095 return NULL;
2096 sum = PyNumber_Add(sofar, prod);
2097 Py_DECREF(prod);
2098 return sum;
2099 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (PyFloat_Check(num)) {
2102 double dnum;
2103 double fracpart;
2104 double intpart;
2105 PyObject *x;
2106 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 /* The Plan: decompose num into an integer part and a
2109 * fractional part, num = intpart + fracpart.
2110 * Then num * factor ==
2111 * intpart * factor + fracpart * factor
2112 * and the LHS can be computed exactly in long arithmetic.
2113 * The RHS is again broken into an int part and frac part.
2114 * and the frac part is added into *leftover.
2115 */
2116 dnum = PyFloat_AsDouble(num);
2117 if (dnum == -1.0 && PyErr_Occurred())
2118 return NULL;
2119 fracpart = modf(dnum, &intpart);
2120 x = PyLong_FromDouble(intpart);
2121 if (x == NULL)
2122 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 prod = PyNumber_Multiply(x, factor);
2125 Py_DECREF(x);
2126 if (prod == NULL)
2127 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 sum = PyNumber_Add(sofar, prod);
2130 Py_DECREF(prod);
2131 if (sum == NULL)
2132 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if (fracpart == 0.0)
2135 return sum;
2136 /* So far we've lost no information. Dealing with the
2137 * fractional part requires float arithmetic, and may
2138 * lose a little info.
2139 */
2140 assert(PyLong_Check(factor));
2141 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 dnum *= fracpart;
2144 fracpart = modf(dnum, &intpart);
2145 x = PyLong_FromDouble(intpart);
2146 if (x == NULL) {
2147 Py_DECREF(sum);
2148 return NULL;
2149 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 y = PyNumber_Add(sum, x);
2152 Py_DECREF(sum);
2153 Py_DECREF(x);
2154 *leftover += fracpart;
2155 return y;
2156 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 PyErr_Format(PyExc_TypeError,
2159 "unsupported type for timedelta %s component: %s",
2160 tag, Py_TYPE(num)->tp_name);
2161 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002162}
2163
2164static PyObject *
2165delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 /* Argument objects. */
2170 PyObject *day = NULL;
2171 PyObject *second = NULL;
2172 PyObject *us = NULL;
2173 PyObject *ms = NULL;
2174 PyObject *minute = NULL;
2175 PyObject *hour = NULL;
2176 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyObject *x = NULL; /* running sum of microseconds */
2179 PyObject *y = NULL; /* temp sum of microseconds */
2180 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 static char *keywords[] = {
2183 "days", "seconds", "microseconds", "milliseconds",
2184 "minutes", "hours", "weeks", NULL
2185 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2188 keywords,
2189 &day, &second, &us,
2190 &ms, &minute, &hour, &week) == 0)
2191 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 x = PyLong_FromLong(0);
2194 if (x == NULL)
2195 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197#define CLEANUP \
2198 Py_DECREF(x); \
2199 x = y; \
2200 if (x == NULL) \
2201 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 if (us) {
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002204 y = accum("microseconds", x, us, one, &leftover_us);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 CLEANUP;
2206 }
2207 if (ms) {
2208 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2209 CLEANUP;
2210 }
2211 if (second) {
2212 y = accum("seconds", x, second, us_per_second, &leftover_us);
2213 CLEANUP;
2214 }
2215 if (minute) {
2216 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2217 CLEANUP;
2218 }
2219 if (hour) {
2220 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2221 CLEANUP;
2222 }
2223 if (day) {
2224 y = accum("days", x, day, us_per_day, &leftover_us);
2225 CLEANUP;
2226 }
2227 if (week) {
2228 y = accum("weeks", x, week, us_per_week, &leftover_us);
2229 CLEANUP;
2230 }
2231 if (leftover_us) {
2232 /* Round to nearest whole # of us, and add into x. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002233 double whole_us = round(leftover_us);
Victor Stinner69cc4872015-09-08 23:58:54 +02002234 int x_is_odd;
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002235 PyObject *temp;
2236
Victor Stinner69cc4872015-09-08 23:58:54 +02002237 whole_us = round(leftover_us);
2238 if (fabs(whole_us - leftover_us) == 0.5) {
2239 /* We're exactly halfway between two integers. In order
2240 * to do round-half-to-even, we must determine whether x
2241 * is odd. Note that x is odd when it's last bit is 1. The
2242 * code below uses bitwise and operation to check the last
2243 * bit. */
2244 temp = PyNumber_And(x, one); /* temp <- x & 1 */
2245 if (temp == NULL) {
2246 Py_DECREF(x);
2247 goto Done;
2248 }
2249 x_is_odd = PyObject_IsTrue(temp);
2250 Py_DECREF(temp);
2251 if (x_is_odd == -1) {
2252 Py_DECREF(x);
2253 goto Done;
2254 }
2255 whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2256 }
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002257
Victor Stinner36a5a062013-08-28 01:53:39 +02002258 temp = PyLong_FromLong((long)whole_us);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 if (temp == NULL) {
2261 Py_DECREF(x);
2262 goto Done;
2263 }
2264 y = PyNumber_Add(x, temp);
2265 Py_DECREF(temp);
2266 CLEANUP;
2267 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 self = microseconds_to_delta_ex(x, type);
2270 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002271Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002273
2274#undef CLEANUP
2275}
2276
2277static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002278delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 return (GET_TD_DAYS(self) != 0
2281 || GET_TD_SECONDS(self) != 0
2282 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002283}
2284
2285static PyObject *
2286delta_repr(PyDateTime_Delta *self)
2287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (GET_TD_MICROSECONDS(self) != 0)
2289 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2290 Py_TYPE(self)->tp_name,
2291 GET_TD_DAYS(self),
2292 GET_TD_SECONDS(self),
2293 GET_TD_MICROSECONDS(self));
2294 if (GET_TD_SECONDS(self) != 0)
2295 return PyUnicode_FromFormat("%s(%d, %d)",
2296 Py_TYPE(self)->tp_name,
2297 GET_TD_DAYS(self),
2298 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 return PyUnicode_FromFormat("%s(%d)",
2301 Py_TYPE(self)->tp_name,
2302 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002303}
2304
2305static PyObject *
2306delta_str(PyDateTime_Delta *self)
2307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 int us = GET_TD_MICROSECONDS(self);
2309 int seconds = GET_TD_SECONDS(self);
2310 int minutes = divmod(seconds, 60, &seconds);
2311 int hours = divmod(minutes, 60, &minutes);
2312 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 if (days) {
2315 if (us)
2316 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2317 days, (days == 1 || days == -1) ? "" : "s",
2318 hours, minutes, seconds, us);
2319 else
2320 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2321 days, (days == 1 || days == -1) ? "" : "s",
2322 hours, minutes, seconds);
2323 } else {
2324 if (us)
2325 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2326 hours, minutes, seconds, us);
2327 else
2328 return PyUnicode_FromFormat("%d:%02d:%02d",
2329 hours, minutes, seconds);
2330 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002331
Tim Peters2a799bf2002-12-16 20:18:38 +00002332}
2333
Tim Peters371935f2003-02-01 01:52:50 +00002334/* Pickle support, a simple use of __reduce__. */
2335
Tim Petersb57f8f02003-02-01 02:54:15 +00002336/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002337static PyObject *
2338delta_getstate(PyDateTime_Delta *self)
2339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 return Py_BuildValue("iii", GET_TD_DAYS(self),
2341 GET_TD_SECONDS(self),
2342 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002343}
2344
Tim Peters2a799bf2002-12-16 20:18:38 +00002345static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002346delta_total_seconds(PyObject *self)
2347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 PyObject *total_seconds;
2349 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2352 if (total_microseconds == NULL)
2353 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002354
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002355 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002359}
2360
2361static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002362delta_reduce(PyDateTime_Delta* self)
2363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002365}
2366
2367#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2368
2369static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 {"days", T_INT, OFFSET(days), READONLY,
2372 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 {"seconds", T_INT, OFFSET(seconds), READONLY,
2375 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2378 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2379 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002380};
2381
2382static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2384 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2387 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002390};
2391
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002392static const char delta_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00002393PyDoc_STR("Difference between two datetime values.");
2394
2395static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 delta_add, /* nb_add */
2397 delta_subtract, /* nb_subtract */
2398 delta_multiply, /* nb_multiply */
2399 delta_remainder, /* nb_remainder */
2400 delta_divmod, /* nb_divmod */
2401 0, /* nb_power */
2402 (unaryfunc)delta_negative, /* nb_negative */
2403 (unaryfunc)delta_positive, /* nb_positive */
2404 (unaryfunc)delta_abs, /* nb_absolute */
2405 (inquiry)delta_bool, /* nb_bool */
2406 0, /*nb_invert*/
2407 0, /*nb_lshift*/
2408 0, /*nb_rshift*/
2409 0, /*nb_and*/
2410 0, /*nb_xor*/
2411 0, /*nb_or*/
2412 0, /*nb_int*/
2413 0, /*nb_reserved*/
2414 0, /*nb_float*/
2415 0, /*nb_inplace_add*/
2416 0, /*nb_inplace_subtract*/
2417 0, /*nb_inplace_multiply*/
2418 0, /*nb_inplace_remainder*/
2419 0, /*nb_inplace_power*/
2420 0, /*nb_inplace_lshift*/
2421 0, /*nb_inplace_rshift*/
2422 0, /*nb_inplace_and*/
2423 0, /*nb_inplace_xor*/
2424 0, /*nb_inplace_or*/
2425 delta_divide, /* nb_floor_divide */
2426 delta_truedivide, /* nb_true_divide */
2427 0, /* nb_inplace_floor_divide */
2428 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002429};
2430
2431static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 PyVarObject_HEAD_INIT(NULL, 0)
2433 "datetime.timedelta", /* tp_name */
2434 sizeof(PyDateTime_Delta), /* tp_basicsize */
2435 0, /* tp_itemsize */
2436 0, /* tp_dealloc */
2437 0, /* tp_print */
2438 0, /* tp_getattr */
2439 0, /* tp_setattr */
2440 0, /* tp_reserved */
2441 (reprfunc)delta_repr, /* tp_repr */
2442 &delta_as_number, /* tp_as_number */
2443 0, /* tp_as_sequence */
2444 0, /* tp_as_mapping */
2445 (hashfunc)delta_hash, /* tp_hash */
2446 0, /* tp_call */
2447 (reprfunc)delta_str, /* tp_str */
2448 PyObject_GenericGetAttr, /* tp_getattro */
2449 0, /* tp_setattro */
2450 0, /* tp_as_buffer */
2451 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2452 delta_doc, /* tp_doc */
2453 0, /* tp_traverse */
2454 0, /* tp_clear */
2455 delta_richcompare, /* tp_richcompare */
2456 0, /* tp_weaklistoffset */
2457 0, /* tp_iter */
2458 0, /* tp_iternext */
2459 delta_methods, /* tp_methods */
2460 delta_members, /* tp_members */
2461 0, /* tp_getset */
2462 0, /* tp_base */
2463 0, /* tp_dict */
2464 0, /* tp_descr_get */
2465 0, /* tp_descr_set */
2466 0, /* tp_dictoffset */
2467 0, /* tp_init */
2468 0, /* tp_alloc */
2469 delta_new, /* tp_new */
2470 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002471};
2472
2473/*
2474 * PyDateTime_Date implementation.
2475 */
2476
2477/* Accessor properties. */
2478
2479static PyObject *
2480date_year(PyDateTime_Date *self, void *unused)
2481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002483}
2484
2485static PyObject *
2486date_month(PyDateTime_Date *self, void *unused)
2487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002489}
2490
2491static PyObject *
2492date_day(PyDateTime_Date *self, void *unused)
2493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002495}
2496
2497static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 {"year", (getter)date_year},
2499 {"month", (getter)date_month},
2500 {"day", (getter)date_day},
2501 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002502};
2503
2504/* Constructors. */
2505
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002506static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002507
Tim Peters2a799bf2002-12-16 20:18:38 +00002508static PyObject *
2509date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 PyObject *self = NULL;
2512 PyObject *state;
2513 int year;
2514 int month;
2515 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 /* Check for invocation from pickle with __getstate__ state */
2518 if (PyTuple_GET_SIZE(args) == 1 &&
2519 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2520 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2521 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2522 {
2523 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2526 if (me != NULL) {
2527 char *pdata = PyBytes_AS_STRING(state);
2528 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2529 me->hashcode = -1;
2530 }
2531 return (PyObject *)me;
2532 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2535 &year, &month, &day)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 self = new_date_ex(year, month, day, type);
2537 }
2538 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002539}
2540
2541/* Return new date from localtime(t). */
2542static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002543date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002544{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002545 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002547
Victor Stinnere4a994d2015-03-30 01:10:14 +02002548 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002550
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04002551 if (_PyTime_localtime(t, &tm) != 0)
Victor Stinner21f58932012-03-14 00:15:40 +01002552 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01002553
2554 return PyObject_CallFunction(cls, "iii",
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04002555 tm.tm_year + 1900,
2556 tm.tm_mon + 1,
2557 tm.tm_mday);
Tim Peters2a799bf2002-12-16 20:18:38 +00002558}
2559
2560/* Return new date from current time.
2561 * We say this is equivalent to fromtimestamp(time.time()), and the
2562 * only way to be sure of that is to *call* time.time(). That's not
2563 * generally the same as calling C's time.
2564 */
2565static PyObject *
2566date_today(PyObject *cls, PyObject *dummy)
2567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 PyObject *time;
2569 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002570 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 time = time_time();
2573 if (time == NULL)
2574 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 /* Note well: today() is a class method, so this may not call
2577 * date.fromtimestamp. For example, it may call
2578 * datetime.fromtimestamp. That's why we need all the accuracy
2579 * time.time() delivers; if someone were gonzo about optimization,
2580 * date.today() could get away with plain C time().
2581 */
Victor Stinner20401de2016-12-09 15:24:31 +01002582 result = _PyObject_CallMethodIdObjArgs(cls, &PyId_fromtimestamp,
2583 time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 Py_DECREF(time);
2585 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002586}
2587
2588/* Return new date from given timestamp (Python timestamp -- a double). */
2589static PyObject *
2590date_fromtimestamp(PyObject *cls, PyObject *args)
2591{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002592 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002594
Victor Stinner5d272cc2012-03-13 13:35:55 +01002595 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2596 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002598}
2599
2600/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2601 * the ordinal is out of range.
2602 */
2603static PyObject *
2604date_fromordinal(PyObject *cls, PyObject *args)
2605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 PyObject *result = NULL;
2607 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2610 int year;
2611 int month;
2612 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 if (ordinal < 1)
2615 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2616 ">= 1");
2617 else {
2618 ord_to_ymd(ordinal, &year, &month, &day);
2619 result = PyObject_CallFunction(cls, "iii",
2620 year, month, day);
2621 }
2622 }
2623 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002624}
2625
2626/*
2627 * Date arithmetic.
2628 */
2629
2630/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2631 * instead.
2632 */
2633static PyObject *
2634add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 PyObject *result = NULL;
2637 int year = GET_YEAR(date);
2638 int month = GET_MONTH(date);
2639 int deltadays = GET_TD_DAYS(delta);
2640 /* C-level overflow is impossible because |deltadays| < 1e9. */
2641 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 if (normalize_date(&year, &month, &day) >= 0)
2644 result = new_date(year, month, day);
2645 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002646}
2647
2648static PyObject *
2649date_add(PyObject *left, PyObject *right)
2650{
Brian Curtindfc80e32011-08-10 20:28:54 -05002651 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2652 Py_RETURN_NOTIMPLEMENTED;
2653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 if (PyDate_Check(left)) {
2655 /* date + ??? */
2656 if (PyDelta_Check(right))
2657 /* date + delta */
2658 return add_date_timedelta((PyDateTime_Date *) left,
2659 (PyDateTime_Delta *) right,
2660 0);
2661 }
2662 else {
2663 /* ??? + date
2664 * 'right' must be one of us, or we wouldn't have been called
2665 */
2666 if (PyDelta_Check(left))
2667 /* delta + date */
2668 return add_date_timedelta((PyDateTime_Date *) right,
2669 (PyDateTime_Delta *) left,
2670 0);
2671 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002672 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002673}
2674
2675static PyObject *
2676date_subtract(PyObject *left, PyObject *right)
2677{
Brian Curtindfc80e32011-08-10 20:28:54 -05002678 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2679 Py_RETURN_NOTIMPLEMENTED;
2680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 if (PyDate_Check(left)) {
2682 if (PyDate_Check(right)) {
2683 /* date - date */
2684 int left_ord = ymd_to_ord(GET_YEAR(left),
2685 GET_MONTH(left),
2686 GET_DAY(left));
2687 int right_ord = ymd_to_ord(GET_YEAR(right),
2688 GET_MONTH(right),
2689 GET_DAY(right));
2690 return new_delta(left_ord - right_ord, 0, 0, 0);
2691 }
2692 if (PyDelta_Check(right)) {
2693 /* date - delta */
2694 return add_date_timedelta((PyDateTime_Date *) left,
2695 (PyDateTime_Delta *) right,
2696 1);
2697 }
2698 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002699 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002700}
2701
2702
2703/* Various ways to turn a date into a string. */
2704
2705static PyObject *
2706date_repr(PyDateTime_Date *self)
2707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2709 Py_TYPE(self)->tp_name,
2710 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002711}
2712
2713static PyObject *
2714date_isoformat(PyDateTime_Date *self)
2715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 return PyUnicode_FromFormat("%04d-%02d-%02d",
2717 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002718}
2719
Tim Peterse2df5ff2003-05-02 18:39:55 +00002720/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002721static PyObject *
2722date_str(PyDateTime_Date *self)
2723{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002724 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002725}
2726
2727
2728static PyObject *
2729date_ctime(PyDateTime_Date *self)
2730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002732}
2733
2734static PyObject *
2735date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 /* This method can be inherited, and needs to call the
2738 * timetuple() method appropriate to self's class.
2739 */
2740 PyObject *result;
2741 PyObject *tuple;
2742 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002743 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2747 &format))
2748 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002749
Victor Stinnerad8c83a2016-09-05 17:53:15 -07002750 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 if (tuple == NULL)
2752 return NULL;
2753 result = wrap_strftime((PyObject *)self, format, tuple,
2754 (PyObject *)self);
2755 Py_DECREF(tuple);
2756 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002757}
2758
Eric Smith1ba31142007-09-11 18:06:02 +00002759static PyObject *
2760date_format(PyDateTime_Date *self, PyObject *args)
2761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2765 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002768 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002770
Victor Stinner20401de2016-12-09 15:24:31 +01002771 return _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_strftime,
2772 format, NULL);
Eric Smith1ba31142007-09-11 18:06:02 +00002773}
2774
Tim Peters2a799bf2002-12-16 20:18:38 +00002775/* ISO methods. */
2776
2777static PyObject *
2778date_isoweekday(PyDateTime_Date *self)
2779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002783}
2784
2785static PyObject *
2786date_isocalendar(PyDateTime_Date *self)
2787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 int year = GET_YEAR(self);
2789 int week1_monday = iso_week1_monday(year);
2790 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2791 int week;
2792 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 week = divmod(today - week1_monday, 7, &day);
2795 if (week < 0) {
2796 --year;
2797 week1_monday = iso_week1_monday(year);
2798 week = divmod(today - week1_monday, 7, &day);
2799 }
2800 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2801 ++year;
2802 week = 0;
2803 }
2804 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002805}
2806
2807/* Miscellaneous methods. */
2808
Tim Peters2a799bf2002-12-16 20:18:38 +00002809static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002810date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 if (PyDate_Check(other)) {
2813 int diff = memcmp(((PyDateTime_Date *)self)->data,
2814 ((PyDateTime_Date *)other)->data,
2815 _PyDateTime_DATE_DATASIZE);
2816 return diff_to_bool(diff, op);
2817 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002818 else
2819 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002820}
2821
2822static PyObject *
2823date_timetuple(PyDateTime_Date *self)
2824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 return build_struct_time(GET_YEAR(self),
2826 GET_MONTH(self),
2827 GET_DAY(self),
2828 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002829}
2830
Tim Peters12bf3392002-12-24 05:41:27 +00002831static PyObject *
2832date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 PyObject *clone;
2835 PyObject *tuple;
2836 int year = GET_YEAR(self);
2837 int month = GET_MONTH(self);
2838 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2841 &year, &month, &day))
2842 return NULL;
2843 tuple = Py_BuildValue("iii", year, month, day);
2844 if (tuple == NULL)
2845 return NULL;
2846 clone = date_new(Py_TYPE(self), tuple, NULL);
2847 Py_DECREF(tuple);
2848 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002849}
2850
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002851static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002852generic_hash(unsigned char *data, int len)
2853{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002854 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002855}
2856
2857
2858static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002859
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002860static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002861date_hash(PyDateTime_Date *self)
2862{
Benjamin Petersondec2df32016-09-09 17:46:24 -07002863 if (self->hashcode == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 self->hashcode = generic_hash(
2865 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Benjamin Petersondec2df32016-09-09 17:46:24 -07002866 }
Guido van Rossum254348e2007-11-21 19:29:53 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002869}
2870
2871static PyObject *
2872date_toordinal(PyDateTime_Date *self)
2873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2875 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002876}
2877
2878static PyObject *
2879date_weekday(PyDateTime_Date *self)
2880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002884}
2885
Tim Peters371935f2003-02-01 01:52:50 +00002886/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002887
Tim Petersb57f8f02003-02-01 02:54:15 +00002888/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002889static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002890date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 PyObject* field;
2893 field = PyBytes_FromStringAndSize((char*)self->data,
2894 _PyDateTime_DATE_DATASIZE);
2895 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002896}
2897
2898static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002899date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002902}
2903
2904static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2909 METH_CLASS,
2910 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2911 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2914 METH_CLASS,
2915 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2916 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2919 PyDoc_STR("Current date or datetime: same as "
2920 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2925 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2928 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2931 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2934 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2937 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2938 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2941 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2944 PyDoc_STR("Return the day of the week represented by the date.\n"
2945 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2948 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2949 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2952 PyDoc_STR("Return the day of the week represented by the date.\n"
2953 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2956 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2959 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002962};
2963
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002964static const char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002965PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002966
2967static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 date_add, /* nb_add */
2969 date_subtract, /* nb_subtract */
2970 0, /* nb_multiply */
2971 0, /* nb_remainder */
2972 0, /* nb_divmod */
2973 0, /* nb_power */
2974 0, /* nb_negative */
2975 0, /* nb_positive */
2976 0, /* nb_absolute */
2977 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002978};
2979
2980static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 PyVarObject_HEAD_INIT(NULL, 0)
2982 "datetime.date", /* tp_name */
2983 sizeof(PyDateTime_Date), /* tp_basicsize */
2984 0, /* tp_itemsize */
2985 0, /* tp_dealloc */
2986 0, /* tp_print */
2987 0, /* tp_getattr */
2988 0, /* tp_setattr */
2989 0, /* tp_reserved */
2990 (reprfunc)date_repr, /* tp_repr */
2991 &date_as_number, /* tp_as_number */
2992 0, /* tp_as_sequence */
2993 0, /* tp_as_mapping */
2994 (hashfunc)date_hash, /* tp_hash */
2995 0, /* tp_call */
2996 (reprfunc)date_str, /* tp_str */
2997 PyObject_GenericGetAttr, /* tp_getattro */
2998 0, /* tp_setattro */
2999 0, /* tp_as_buffer */
3000 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3001 date_doc, /* tp_doc */
3002 0, /* tp_traverse */
3003 0, /* tp_clear */
3004 date_richcompare, /* tp_richcompare */
3005 0, /* tp_weaklistoffset */
3006 0, /* tp_iter */
3007 0, /* tp_iternext */
3008 date_methods, /* tp_methods */
3009 0, /* tp_members */
3010 date_getset, /* tp_getset */
3011 0, /* tp_base */
3012 0, /* tp_dict */
3013 0, /* tp_descr_get */
3014 0, /* tp_descr_set */
3015 0, /* tp_dictoffset */
3016 0, /* tp_init */
3017 0, /* tp_alloc */
3018 date_new, /* tp_new */
3019 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003020};
3021
3022/*
Tim Peters2a799bf2002-12-16 20:18:38 +00003023 * PyDateTime_TZInfo implementation.
3024 */
3025
3026/* This is a pure abstract base class, so doesn't do anything beyond
3027 * raising NotImplemented exceptions. Real tzinfo classes need
3028 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00003029 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00003030 * be subclasses of this tzinfo class, which is easy and quick to check).
3031 *
3032 * Note: For reasons having to do with pickling of subclasses, we have
3033 * to allow tzinfo objects to be instantiated. This wasn't an issue
3034 * in the Python implementation (__init__() could raise NotImplementedError
3035 * there without ill effect), but doing so in the C implementation hit a
3036 * brick wall.
3037 */
3038
3039static PyObject *
3040tzinfo_nogo(const char* methodname)
3041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 PyErr_Format(PyExc_NotImplementedError,
3043 "a tzinfo subclass must implement %s()",
3044 methodname);
3045 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003046}
3047
3048/* Methods. A subclass must implement these. */
3049
Tim Peters52dcce22003-01-23 16:36:11 +00003050static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003051tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00003054}
3055
Tim Peters52dcce22003-01-23 16:36:11 +00003056static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003057tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00003060}
3061
Tim Peters52dcce22003-01-23 16:36:11 +00003062static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003063tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003066}
3067
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003068
3069static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
3070 PyDateTime_Delta *delta,
3071 int factor);
3072static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
3073static PyObject *datetime_dst(PyObject *self, PyObject *);
3074
Tim Peters52dcce22003-01-23 16:36:11 +00003075static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003076tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003077{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003078 PyObject *result = NULL;
3079 PyObject *off = NULL, *dst = NULL;
3080 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003081
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003082 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 PyErr_SetString(PyExc_TypeError,
3084 "fromutc: argument must be a datetime");
3085 return NULL;
3086 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003087 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3089 "is not self");
3090 return NULL;
3091 }
Tim Peters52dcce22003-01-23 16:36:11 +00003092
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003093 off = datetime_utcoffset(dt, NULL);
3094 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003096 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3098 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003099 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 }
Tim Peters52dcce22003-01-23 16:36:11 +00003101
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003102 dst = datetime_dst(dt, NULL);
3103 if (dst == NULL)
3104 goto Fail;
3105 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3107 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003108 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 }
Tim Peters52dcce22003-01-23 16:36:11 +00003110
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003111 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3112 if (delta == NULL)
3113 goto Fail;
3114 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003117
3118 Py_DECREF(dst);
3119 dst = call_dst(GET_DT_TZINFO(dt), result);
3120 if (dst == NULL)
3121 goto Fail;
3122 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 goto Inconsistent;
Alexander Belopolskyc79447b2015-09-27 21:41:55 -04003124 if (delta_bool((PyDateTime_Delta *)dst) != 0) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03003125 Py_SETREF(result, add_datetime_timedelta((PyDateTime_DateTime *)result,
Serhiy Storchaka576f1322016-01-05 21:27:54 +02003126 (PyDateTime_Delta *)dst, 1));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003127 if (result == NULL)
3128 goto Fail;
3129 }
3130 Py_DECREF(delta);
3131 Py_DECREF(dst);
3132 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003134
3135Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3137 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003140Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003141 Py_XDECREF(off);
3142 Py_XDECREF(dst);
3143 Py_XDECREF(delta);
3144 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003146}
3147
Tim Peters2a799bf2002-12-16 20:18:38 +00003148/*
3149 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003150 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003151 */
3152
Guido van Rossum177e41a2003-01-30 22:06:23 +00003153static PyObject *
3154tzinfo_reduce(PyObject *self)
3155{
Victor Stinnerd1584d32016-08-23 00:11:04 +02003156 PyObject *args, *state;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003158 _Py_IDENTIFIER(__getinitargs__);
3159 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003160
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003161 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 if (getinitargs != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003163 args = _PyObject_CallNoArg(getinitargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 Py_DECREF(getinitargs);
3165 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 return NULL;
3167 }
3168 }
3169 else {
3170 PyErr_Clear();
Victor Stinnerd1584d32016-08-23 00:11:04 +02003171
3172 args = PyTuple_New(0);
3173 if (args == NULL) {
3174 return NULL;
3175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003177
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003178 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 if (getstate != NULL) {
Victor Stinnerd1584d32016-08-23 00:11:04 +02003180 state = _PyObject_CallNoArg(getstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 Py_DECREF(getstate);
3182 if (state == NULL) {
3183 Py_DECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 return NULL;
3185 }
3186 }
3187 else {
3188 PyObject **dictptr;
3189 PyErr_Clear();
3190 state = Py_None;
3191 dictptr = _PyObject_GetDictPtr(self);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02003192 if (dictptr && *dictptr && PyDict_GET_SIZE(*dictptr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 state = *dictptr;
Victor Stinnerd1584d32016-08-23 00:11:04 +02003194 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 Py_INCREF(state);
3196 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 if (state == Py_None) {
3199 Py_DECREF(state);
3200 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3201 }
3202 else
3203 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003204}
Tim Peters2a799bf2002-12-16 20:18:38 +00003205
3206static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3209 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003212 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3213 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3216 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003219 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3222 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003225};
3226
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003227static const char tzinfo_doc[] =
Tim Peters2a799bf2002-12-16 20:18:38 +00003228PyDoc_STR("Abstract base class for time zone info objects.");
3229
Neal Norwitz227b5332006-03-22 09:28:35 +00003230static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 PyVarObject_HEAD_INIT(NULL, 0)
3232 "datetime.tzinfo", /* tp_name */
3233 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3234 0, /* tp_itemsize */
3235 0, /* tp_dealloc */
3236 0, /* tp_print */
3237 0, /* tp_getattr */
3238 0, /* tp_setattr */
3239 0, /* tp_reserved */
3240 0, /* tp_repr */
3241 0, /* tp_as_number */
3242 0, /* tp_as_sequence */
3243 0, /* tp_as_mapping */
3244 0, /* tp_hash */
3245 0, /* tp_call */
3246 0, /* tp_str */
3247 PyObject_GenericGetAttr, /* tp_getattro */
3248 0, /* tp_setattro */
3249 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003250 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 tzinfo_doc, /* tp_doc */
3252 0, /* tp_traverse */
3253 0, /* tp_clear */
3254 0, /* tp_richcompare */
3255 0, /* tp_weaklistoffset */
3256 0, /* tp_iter */
3257 0, /* tp_iternext */
3258 tzinfo_methods, /* tp_methods */
3259 0, /* tp_members */
3260 0, /* tp_getset */
3261 0, /* tp_base */
3262 0, /* tp_dict */
3263 0, /* tp_descr_get */
3264 0, /* tp_descr_set */
3265 0, /* tp_dictoffset */
3266 0, /* tp_init */
3267 0, /* tp_alloc */
3268 PyType_GenericNew, /* tp_new */
3269 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003270};
3271
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003272static char *timezone_kws[] = {"offset", "name", NULL};
3273
3274static PyObject *
3275timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3276{
3277 PyObject *offset;
3278 PyObject *name = NULL;
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03003279 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|U:timezone", timezone_kws,
3280 &PyDateTime_DeltaType, &offset, &name))
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003281 return new_timezone(offset, name);
3282
3283 return NULL;
3284}
3285
3286static void
3287timezone_dealloc(PyDateTime_TimeZone *self)
3288{
3289 Py_CLEAR(self->offset);
3290 Py_CLEAR(self->name);
3291 Py_TYPE(self)->tp_free((PyObject *)self);
3292}
3293
3294static PyObject *
3295timezone_richcompare(PyDateTime_TimeZone *self,
3296 PyDateTime_TimeZone *other, int op)
3297{
Brian Curtindfc80e32011-08-10 20:28:54 -05003298 if (op != Py_EQ && op != Py_NE)
3299 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003300 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003301 if (op == Py_EQ)
3302 Py_RETURN_FALSE;
3303 else
3304 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003305 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003306 return delta_richcompare(self->offset, other->offset, op);
3307}
3308
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003309static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003310timezone_hash(PyDateTime_TimeZone *self)
3311{
3312 return delta_hash((PyDateTime_Delta *)self->offset);
3313}
3314
3315/* Check argument type passed to tzname, utcoffset, or dst methods.
3316 Returns 0 for good argument. Returns -1 and sets exception info
3317 otherwise.
3318 */
3319static int
3320_timezone_check_argument(PyObject *dt, const char *meth)
3321{
3322 if (dt == Py_None || PyDateTime_Check(dt))
3323 return 0;
3324 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3325 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3326 return -1;
3327}
3328
3329static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003330timezone_repr(PyDateTime_TimeZone *self)
3331{
3332 /* Note that although timezone is not subclassable, it is convenient
3333 to use Py_TYPE(self)->tp_name here. */
3334 const char *type_name = Py_TYPE(self)->tp_name;
3335
3336 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3337 return PyUnicode_FromFormat("%s.utc", type_name);
3338
3339 if (self->name == NULL)
3340 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3341
3342 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3343 self->name);
3344}
3345
3346
3347static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003348timezone_str(PyDateTime_TimeZone *self)
3349{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003350 int hours, minutes, seconds;
3351 PyObject *offset;
3352 char sign;
3353
3354 if (self->name != NULL) {
3355 Py_INCREF(self->name);
3356 return self->name;
3357 }
Victor Stinner90fd8952015-09-08 00:12:49 +02003358 if ((PyObject *)self == PyDateTime_TimeZone_UTC ||
Alexander Belopolsky7827a5b2015-09-06 13:07:21 -04003359 (GET_TD_DAYS(self->offset) == 0 &&
3360 GET_TD_SECONDS(self->offset) == 0 &&
3361 GET_TD_MICROSECONDS(self->offset) == 0))
3362 return PyUnicode_FromString("UTC");
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003363 /* Offset is normalized, so it is negative if days < 0 */
3364 if (GET_TD_DAYS(self->offset) < 0) {
3365 sign = '-';
3366 offset = delta_negative((PyDateTime_Delta *)self->offset);
3367 if (offset == NULL)
3368 return NULL;
3369 }
3370 else {
3371 sign = '+';
3372 offset = self->offset;
3373 Py_INCREF(offset);
3374 }
3375 /* Offset is not negative here. */
3376 seconds = GET_TD_SECONDS(offset);
3377 Py_DECREF(offset);
3378 minutes = divmod(seconds, 60, &seconds);
3379 hours = divmod(minutes, 60, &minutes);
Martin Pantere26da7c2016-06-02 10:07:09 +00003380 /* XXX ignore sub-minute data, currently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003381 assert(seconds == 0);
3382 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003383}
3384
3385static PyObject *
3386timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3387{
3388 if (_timezone_check_argument(dt, "tzname") == -1)
3389 return NULL;
3390
3391 return timezone_str(self);
3392}
3393
3394static PyObject *
3395timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3396{
3397 if (_timezone_check_argument(dt, "utcoffset") == -1)
3398 return NULL;
3399
3400 Py_INCREF(self->offset);
3401 return self->offset;
3402}
3403
3404static PyObject *
3405timezone_dst(PyObject *self, PyObject *dt)
3406{
3407 if (_timezone_check_argument(dt, "dst") == -1)
3408 return NULL;
3409
3410 Py_RETURN_NONE;
3411}
3412
3413static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003414timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3415{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003416 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003417 PyErr_SetString(PyExc_TypeError,
3418 "fromutc: argument must be a datetime");
3419 return NULL;
3420 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003421 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003422 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3423 "is not self");
3424 return NULL;
3425 }
3426
3427 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3428}
3429
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003430static PyObject *
3431timezone_getinitargs(PyDateTime_TimeZone *self)
3432{
3433 if (self->name == NULL)
3434 return Py_BuildValue("(O)", self->offset);
3435 return Py_BuildValue("(OO)", self->offset, self->name);
3436}
3437
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003438static PyMethodDef timezone_methods[] = {
3439 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3440 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003441 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003442
3443 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003444 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003445
3446 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003447 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003448
3449 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3450 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3451
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003452 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3453 PyDoc_STR("pickle support")},
3454
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003455 {NULL, NULL}
3456};
3457
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02003458static const char timezone_doc[] =
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003459PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3460
3461static PyTypeObject PyDateTime_TimeZoneType = {
3462 PyVarObject_HEAD_INIT(NULL, 0)
3463 "datetime.timezone", /* tp_name */
3464 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3465 0, /* tp_itemsize */
3466 (destructor)timezone_dealloc, /* tp_dealloc */
3467 0, /* tp_print */
3468 0, /* tp_getattr */
3469 0, /* tp_setattr */
3470 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003471 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003472 0, /* tp_as_number */
3473 0, /* tp_as_sequence */
3474 0, /* tp_as_mapping */
3475 (hashfunc)timezone_hash, /* tp_hash */
3476 0, /* tp_call */
3477 (reprfunc)timezone_str, /* tp_str */
3478 0, /* tp_getattro */
3479 0, /* tp_setattro */
3480 0, /* tp_as_buffer */
3481 Py_TPFLAGS_DEFAULT, /* tp_flags */
3482 timezone_doc, /* tp_doc */
3483 0, /* tp_traverse */
3484 0, /* tp_clear */
3485 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3486 0, /* tp_weaklistoffset */
3487 0, /* tp_iter */
3488 0, /* tp_iternext */
3489 timezone_methods, /* tp_methods */
3490 0, /* tp_members */
3491 0, /* tp_getset */
3492 &PyDateTime_TZInfoType, /* tp_base */
3493 0, /* tp_dict */
3494 0, /* tp_descr_get */
3495 0, /* tp_descr_set */
3496 0, /* tp_dictoffset */
3497 0, /* tp_init */
3498 0, /* tp_alloc */
3499 timezone_new, /* tp_new */
3500};
3501
Tim Peters2a799bf2002-12-16 20:18:38 +00003502/*
Tim Peters37f39822003-01-10 03:49:02 +00003503 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003504 */
3505
Tim Peters37f39822003-01-10 03:49:02 +00003506/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003507 */
3508
3509static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003510time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003513}
3514
Tim Peters37f39822003-01-10 03:49:02 +00003515static PyObject *
3516time_minute(PyDateTime_Time *self, void *unused)
3517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003519}
3520
3521/* The name time_second conflicted with some platform header file. */
3522static PyObject *
3523py_time_second(PyDateTime_Time *self, void *unused)
3524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003526}
3527
3528static PyObject *
3529time_microsecond(PyDateTime_Time *self, void *unused)
3530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003532}
3533
3534static PyObject *
3535time_tzinfo(PyDateTime_Time *self, void *unused)
3536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3538 Py_INCREF(result);
3539 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003540}
3541
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003542static PyObject *
3543time_fold(PyDateTime_Time *self, void *unused)
3544{
3545 return PyLong_FromLong(TIME_GET_FOLD(self));
3546}
3547
Tim Peters37f39822003-01-10 03:49:02 +00003548static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 {"hour", (getter)time_hour},
3550 {"minute", (getter)time_minute},
3551 {"second", (getter)py_time_second},
3552 {"microsecond", (getter)time_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003553 {"tzinfo", (getter)time_tzinfo},
3554 {"fold", (getter)time_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003556};
3557
3558/*
3559 * Constructors.
3560 */
3561
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003562static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003563 "tzinfo", "fold", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003564
Tim Peters2a799bf2002-12-16 20:18:38 +00003565static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003566time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 PyObject *self = NULL;
3569 PyObject *state;
3570 int hour = 0;
3571 int minute = 0;
3572 int second = 0;
3573 int usecond = 0;
3574 PyObject *tzinfo = Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003575 int fold = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 /* Check for invocation from pickle with __getstate__ state */
3578 if (PyTuple_GET_SIZE(args) >= 1 &&
3579 PyTuple_GET_SIZE(args) <= 2 &&
3580 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3581 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003582 (0x7F & ((unsigned char) (PyBytes_AS_STRING(state)[0]))) < 24)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 {
3584 PyDateTime_Time *me;
3585 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 if (PyTuple_GET_SIZE(args) == 2) {
3588 tzinfo = PyTuple_GET_ITEM(args, 1);
3589 if (check_tzinfo_subclass(tzinfo) < 0) {
3590 PyErr_SetString(PyExc_TypeError, "bad "
3591 "tzinfo state arg");
3592 return NULL;
3593 }
3594 }
3595 aware = (char)(tzinfo != Py_None);
3596 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3597 if (me != NULL) {
3598 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3601 me->hashcode = -1;
3602 me->hastzinfo = aware;
3603 if (aware) {
3604 Py_INCREF(tzinfo);
3605 me->tzinfo = tzinfo;
3606 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003607 if (pdata[0] & (1 << 7)) {
3608 me->data[0] -= 128;
3609 me->fold = 1;
3610 }
3611 else {
3612 me->fold = 0;
3613 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 }
3615 return (PyObject *)me;
3616 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003617
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003618 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i", time_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 &hour, &minute, &second, &usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003620 &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003621 self = new_time_ex2(hour, minute, second, usecond, tzinfo, fold,
3622 type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 }
3624 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003625}
3626
3627/*
3628 * Destructor.
3629 */
3630
3631static void
Tim Peters37f39822003-01-10 03:49:02 +00003632time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 if (HASTZINFO(self)) {
3635 Py_XDECREF(self->tzinfo);
3636 }
3637 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003638}
3639
3640/*
Tim Peters855fe882002-12-22 03:43:39 +00003641 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003642 */
3643
Tim Peters2a799bf2002-12-16 20:18:38 +00003644/* These are all METH_NOARGS, so don't need to check the arglist. */
3645static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003646time_utcoffset(PyObject *self, PyObject *unused) {
3647 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003648}
3649
3650static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003651time_dst(PyObject *self, PyObject *unused) {
3652 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003653}
3654
3655static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003656time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003657 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003658}
3659
3660/*
Tim Peters37f39822003-01-10 03:49:02 +00003661 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003662 */
3663
3664static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003665time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 const char *type_name = Py_TYPE(self)->tp_name;
3668 int h = TIME_GET_HOUR(self);
3669 int m = TIME_GET_MINUTE(self);
3670 int s = TIME_GET_SECOND(self);
3671 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003672 int fold = TIME_GET_FOLD(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 if (us)
3676 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3677 type_name, h, m, s, us);
3678 else if (s)
3679 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3680 type_name, h, m, s);
3681 else
3682 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3683 if (result != NULL && HASTZINFO(self))
3684 result = append_keyword_tzinfo(result, self->tzinfo);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003685 if (result != NULL && fold)
3686 result = append_keyword_fold(result, fold);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003688}
3689
Tim Peters37f39822003-01-10 03:49:02 +00003690static PyObject *
3691time_str(PyDateTime_Time *self)
3692{
Victor Stinnerad8c83a2016-09-05 17:53:15 -07003693 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, NULL);
Tim Peters37f39822003-01-10 03:49:02 +00003694}
Tim Peters2a799bf2002-12-16 20:18:38 +00003695
3696static PyObject *
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003697time_isoformat(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 char buf[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003700 char *timespec = NULL;
3701 static char *keywords[] = {"timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02003703 int us = TIME_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003704 static char *specs[][2] = {
3705 {"hours", "%02d"},
3706 {"minutes", "%02d:%02d"},
3707 {"seconds", "%02d:%02d:%02d"},
3708 {"milliseconds", "%02d:%02d:%02d.%03d"},
3709 {"microseconds", "%02d:%02d:%02d.%06d"},
3710 };
3711 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00003712
Alexander Belopolskya2998a62016-03-06 14:58:43 -05003713 if (!PyArg_ParseTupleAndKeywords(args, kw, "|s:isoformat", keywords, &timespec))
3714 return NULL;
3715
3716 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
3717 if (us == 0) {
3718 /* seconds */
3719 given_spec = 2;
3720 }
3721 else {
3722 /* microseconds */
3723 given_spec = 4;
3724 }
3725 }
3726 else {
3727 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
3728 if (strcmp(timespec, specs[given_spec][0]) == 0) {
3729 if (given_spec == 3) {
3730 /* milliseconds */
3731 us = us / 1000;
3732 }
3733 break;
3734 }
3735 }
3736 }
3737
3738 if (given_spec == Py_ARRAY_LENGTH(specs)) {
3739 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
3740 return NULL;
3741 }
3742 else {
3743 result = PyUnicode_FromFormat(specs[given_spec][1],
3744 TIME_GET_HOUR(self), TIME_GET_MINUTE(self),
3745 TIME_GET_SECOND(self), us);
3746 }
Tim Peters37f39822003-01-10 03:49:02 +00003747
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003748 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 /* We need to append the UTC offset. */
3752 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3753 Py_None) < 0) {
3754 Py_DECREF(result);
3755 return NULL;
3756 }
3757 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3758 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003759}
3760
Tim Peters37f39822003-01-10 03:49:02 +00003761static PyObject *
3762time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 PyObject *result;
3765 PyObject *tuple;
3766 PyObject *format;
3767 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3770 &format))
3771 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 /* Python's strftime does insane things with the year part of the
3774 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003775 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 */
3777 tuple = Py_BuildValue("iiiiiiiii",
3778 1900, 1, 1, /* year, month, day */
3779 TIME_GET_HOUR(self),
3780 TIME_GET_MINUTE(self),
3781 TIME_GET_SECOND(self),
3782 0, 1, -1); /* weekday, daynum, dst */
3783 if (tuple == NULL)
3784 return NULL;
3785 assert(PyTuple_Size(tuple) == 9);
3786 result = wrap_strftime((PyObject *)self, format, tuple,
3787 Py_None);
3788 Py_DECREF(tuple);
3789 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003790}
Tim Peters2a799bf2002-12-16 20:18:38 +00003791
3792/*
3793 * Miscellaneous methods.
3794 */
3795
Tim Peters37f39822003-01-10 03:49:02 +00003796static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003797time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003798{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003799 PyObject *result = NULL;
3800 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003802
Brian Curtindfc80e32011-08-10 20:28:54 -05003803 if (! PyTime_Check(other))
3804 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003805
3806 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 diff = memcmp(((PyDateTime_Time *)self)->data,
3808 ((PyDateTime_Time *)other)->data,
3809 _PyDateTime_TIME_DATASIZE);
3810 return diff_to_bool(diff, op);
3811 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003812 offset1 = time_utcoffset(self, NULL);
3813 if (offset1 == NULL)
3814 return NULL;
3815 offset2 = time_utcoffset(other, NULL);
3816 if (offset2 == NULL)
3817 goto done;
3818 /* If they're both naive, or both aware and have the same offsets,
3819 * we get off cheap. Note that if they're both naive, offset1 ==
3820 * offset2 == Py_None at this point.
3821 */
3822 if ((offset1 == offset2) ||
3823 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3824 delta_cmp(offset1, offset2) == 0)) {
3825 diff = memcmp(((PyDateTime_Time *)self)->data,
3826 ((PyDateTime_Time *)other)->data,
3827 _PyDateTime_TIME_DATASIZE);
3828 result = diff_to_bool(diff, op);
3829 }
3830 /* The hard case: both aware with different UTC offsets */
3831 else if (offset1 != Py_None && offset2 != Py_None) {
3832 int offsecs1, offsecs2;
3833 assert(offset1 != offset2); /* else last "if" handled it */
3834 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3835 TIME_GET_MINUTE(self) * 60 +
3836 TIME_GET_SECOND(self) -
3837 GET_TD_DAYS(offset1) * 86400 -
3838 GET_TD_SECONDS(offset1);
3839 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3840 TIME_GET_MINUTE(other) * 60 +
3841 TIME_GET_SECOND(other) -
3842 GET_TD_DAYS(offset2) * 86400 -
3843 GET_TD_SECONDS(offset2);
3844 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 if (diff == 0)
3846 diff = TIME_GET_MICROSECOND(self) -
3847 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003848 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003850 else if (op == Py_EQ) {
3851 result = Py_False;
3852 Py_INCREF(result);
3853 }
3854 else if (op == Py_NE) {
3855 result = Py_True;
3856 Py_INCREF(result);
3857 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003858 else {
3859 PyErr_SetString(PyExc_TypeError,
3860 "can't compare offset-naive and "
3861 "offset-aware times");
3862 }
3863 done:
3864 Py_DECREF(offset1);
3865 Py_XDECREF(offset2);
3866 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003867}
3868
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003869static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003870time_hash(PyDateTime_Time *self)
3871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003873 PyObject *offset, *self0;
Victor Stinner423c16b2017-01-03 23:47:12 +01003874 if (TIME_GET_FOLD(self)) {
3875 self0 = new_time_ex2(TIME_GET_HOUR(self),
3876 TIME_GET_MINUTE(self),
3877 TIME_GET_SECOND(self),
3878 TIME_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003879 HASTZINFO(self) ? self->tzinfo : Py_None,
3880 0, Py_TYPE(self));
3881 if (self0 == NULL)
3882 return -1;
3883 }
3884 else {
3885 self0 = (PyObject *)self;
3886 Py_INCREF(self0);
3887 }
3888 offset = time_utcoffset(self0, NULL);
3889 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003890
3891 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003895 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 self->hashcode = generic_hash(
3897 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003899 PyObject *temp1, *temp2;
3900 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003901 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003902 seconds = TIME_GET_HOUR(self) * 3600 +
3903 TIME_GET_MINUTE(self) * 60 +
3904 TIME_GET_SECOND(self);
3905 microseconds = TIME_GET_MICROSECOND(self);
3906 temp1 = new_delta(0, seconds, microseconds, 1);
3907 if (temp1 == NULL) {
3908 Py_DECREF(offset);
3909 return -1;
3910 }
3911 temp2 = delta_subtract(temp1, offset);
3912 Py_DECREF(temp1);
3913 if (temp2 == NULL) {
3914 Py_DECREF(offset);
3915 return -1;
3916 }
3917 self->hashcode = PyObject_Hash(temp2);
3918 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003919 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003920 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 }
3922 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003923}
Tim Peters2a799bf2002-12-16 20:18:38 +00003924
Tim Peters12bf3392002-12-24 05:41:27 +00003925static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003926time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 PyObject *clone;
3929 PyObject *tuple;
3930 int hh = TIME_GET_HOUR(self);
3931 int mm = TIME_GET_MINUTE(self);
3932 int ss = TIME_GET_SECOND(self);
3933 int us = TIME_GET_MICROSECOND(self);
3934 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003935 int fold = TIME_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00003936
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003937 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 time_kws,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003939 &hh, &mm, &ss, &us, &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 return NULL;
3941 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3942 if (tuple == NULL)
3943 return NULL;
3944 clone = time_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003945 if (clone != NULL) {
3946 if (fold != 0 && fold != 1) {
3947 PyErr_SetString(PyExc_ValueError,
3948 "fold must be either 0 or 1");
3949 return NULL;
3950 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003951 TIME_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04003952 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 Py_DECREF(tuple);
3954 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003955}
3956
Tim Peters371935f2003-02-01 01:52:50 +00003957/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003958
Tim Peters33e0f382003-01-10 02:05:14 +00003959/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003960 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3961 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003962 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003963 */
3964static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003965time_getstate(PyDateTime_Time *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00003966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 PyObject *basestate;
3968 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 basestate = PyBytes_FromStringAndSize((char *)self->data,
3971 _PyDateTime_TIME_DATASIZE);
3972 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003973 if (proto > 3 && TIME_GET_FOLD(self))
3974 /* Set the first bit of the first byte */
3975 PyBytes_AS_STRING(basestate)[0] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3977 result = PyTuple_Pack(1, basestate);
3978 else
3979 result = PyTuple_Pack(2, basestate, self->tzinfo);
3980 Py_DECREF(basestate);
3981 }
3982 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003983}
3984
3985static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02003986time_reduce_ex(PyDateTime_Time *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00003987{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02003988 int proto;
3989 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04003990 return NULL;
3991
3992 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00003993}
3994
Serhiy Storchaka546ce652016-11-22 00:29:42 +02003995static PyObject *
3996time_reduce(PyDateTime_Time *self, PyObject *arg)
3997{
3998 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self, 2));
3999}
4000
Tim Peters37f39822003-01-10 03:49:02 +00004001static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004002
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004003 {"isoformat", (PyCFunction)time_isoformat, METH_VARARGS | METH_KEYWORDS,
4004 PyDoc_STR("Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]]"
4005 "[+HH:MM].\n\n"
4006 "timespec specifies what components of the time to include.\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
4009 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00004010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 {"__format__", (PyCFunction)date_format, METH_VARARGS,
4012 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00004013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
4015 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
4018 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 {"dst", (PyCFunction)time_dst, METH_NOARGS,
4021 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
4024 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004025
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004026 {"__reduce_ex__", (PyCFunction)time_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004027 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004028
Serhiy Storchaka546ce652016-11-22 00:29:42 +02004029 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
4030 PyDoc_STR("__reduce__() -> (cls, state)")},
4031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004033};
4034
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02004035static const char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004036PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
4037\n\
4038All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03004039a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004040
Neal Norwitz227b5332006-03-22 09:28:35 +00004041static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 PyVarObject_HEAD_INIT(NULL, 0)
4043 "datetime.time", /* tp_name */
4044 sizeof(PyDateTime_Time), /* tp_basicsize */
4045 0, /* tp_itemsize */
4046 (destructor)time_dealloc, /* tp_dealloc */
4047 0, /* tp_print */
4048 0, /* tp_getattr */
4049 0, /* tp_setattr */
4050 0, /* tp_reserved */
4051 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05004052 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 0, /* tp_as_sequence */
4054 0, /* tp_as_mapping */
4055 (hashfunc)time_hash, /* tp_hash */
4056 0, /* tp_call */
4057 (reprfunc)time_str, /* tp_str */
4058 PyObject_GenericGetAttr, /* tp_getattro */
4059 0, /* tp_setattro */
4060 0, /* tp_as_buffer */
4061 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4062 time_doc, /* tp_doc */
4063 0, /* tp_traverse */
4064 0, /* tp_clear */
4065 time_richcompare, /* tp_richcompare */
4066 0, /* tp_weaklistoffset */
4067 0, /* tp_iter */
4068 0, /* tp_iternext */
4069 time_methods, /* tp_methods */
4070 0, /* tp_members */
4071 time_getset, /* tp_getset */
4072 0, /* tp_base */
4073 0, /* tp_dict */
4074 0, /* tp_descr_get */
4075 0, /* tp_descr_set */
4076 0, /* tp_dictoffset */
4077 0, /* tp_init */
4078 time_alloc, /* tp_alloc */
4079 time_new, /* tp_new */
4080 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004081};
4082
4083/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004084 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00004085 */
4086
Tim Petersa9bc1682003-01-11 03:39:11 +00004087/* Accessor properties. Properties for day, month, and year are inherited
4088 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004089 */
4090
4091static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004092datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00004093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004095}
4096
Tim Petersa9bc1682003-01-11 03:39:11 +00004097static PyObject *
4098datetime_minute(PyDateTime_DateTime *self, void *unused)
4099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004101}
4102
4103static PyObject *
4104datetime_second(PyDateTime_DateTime *self, void *unused)
4105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004107}
4108
4109static PyObject *
4110datetime_microsecond(PyDateTime_DateTime *self, void *unused)
4111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004113}
4114
4115static PyObject *
4116datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
4117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4119 Py_INCREF(result);
4120 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004121}
4122
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004123static PyObject *
4124datetime_fold(PyDateTime_DateTime *self, void *unused)
4125{
4126 return PyLong_FromLong(DATE_GET_FOLD(self));
4127}
4128
Tim Petersa9bc1682003-01-11 03:39:11 +00004129static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 {"hour", (getter)datetime_hour},
4131 {"minute", (getter)datetime_minute},
4132 {"second", (getter)datetime_second},
4133 {"microsecond", (getter)datetime_microsecond},
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004134 {"tzinfo", (getter)datetime_tzinfo},
4135 {"fold", (getter)datetime_fold},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004137};
4138
4139/*
4140 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004141 */
4142
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004143static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 "year", "month", "day", "hour", "minute", "second",
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004145 "microsecond", "tzinfo", "fold", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004146};
4147
Tim Peters2a799bf2002-12-16 20:18:38 +00004148static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004149datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 PyObject *self = NULL;
4152 PyObject *state;
4153 int year;
4154 int month;
4155 int day;
4156 int hour = 0;
4157 int minute = 0;
4158 int second = 0;
4159 int usecond = 0;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004160 int fold = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 /* Check for invocation from pickle with __getstate__ state */
4164 if (PyTuple_GET_SIZE(args) >= 1 &&
4165 PyTuple_GET_SIZE(args) <= 2 &&
4166 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4167 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004168 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2] & 0x7F))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004169 {
4170 PyDateTime_DateTime *me;
4171 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 if (PyTuple_GET_SIZE(args) == 2) {
4174 tzinfo = PyTuple_GET_ITEM(args, 1);
4175 if (check_tzinfo_subclass(tzinfo) < 0) {
4176 PyErr_SetString(PyExc_TypeError, "bad "
4177 "tzinfo state arg");
4178 return NULL;
4179 }
4180 }
4181 aware = (char)(tzinfo != Py_None);
4182 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4183 if (me != NULL) {
4184 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4187 me->hashcode = -1;
4188 me->hastzinfo = aware;
4189 if (aware) {
4190 Py_INCREF(tzinfo);
4191 me->tzinfo = tzinfo;
4192 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004193 if (pdata[2] & (1 << 7)) {
4194 me->data[2] -= 128;
4195 me->fold = 1;
4196 }
4197 else {
4198 me->fold = 0;
4199 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 }
4201 return (PyObject *)me;
4202 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004203
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004204 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO$i", datetime_kws,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 &year, &month, &day, &hour, &minute,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004206 &second, &usecond, &tzinfo, &fold)) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004207 self = new_datetime_ex2(year, month, day,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 hour, minute, second, usecond,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004209 tzinfo, fold, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 }
4211 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004212}
4213
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004214/* TM_FUNC is the shared type of _PyTime_localtime() and
4215 * _PyTime_gmtime(). */
4216typedef int (*TM_FUNC)(time_t timer, struct tm*);
Tim Petersa9bc1682003-01-11 03:39:11 +00004217
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004218/* As of version 2015f max fold in IANA database is
4219 * 23 hours at 1969-09-30 13:00:00 in Kwajalein. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004220static long long max_fold_seconds = 24 * 3600;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004221/* NB: date(1970,1,1).toordinal() == 719163 */
Benjamin Petersonac965ca2016-09-18 18:12:21 -07004222static long long epoch = 719163LL * 24 * 60 * 60;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004223
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004224static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004225utc_to_seconds(int year, int month, int day,
4226 int hour, int minute, int second)
4227{
Victor Stinnerb67f0962017-02-10 10:34:02 +01004228 long long ordinal;
4229
4230 /* ymd_to_ord() doesn't support year <= 0 */
4231 if (year < MINYEAR || year > MAXYEAR) {
4232 PyErr_Format(PyExc_ValueError, "year %i is out of range", year);
4233 return -1;
4234 }
4235
4236 ordinal = ymd_to_ord(year, month, day);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004237 return ((ordinal * 24 + hour) * 60 + minute) * 60 + second;
4238}
4239
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004240static long long
4241local(long long u)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004242{
4243 struct tm local_time;
Alexander Belopolsky8e1d3a22016-07-25 13:54:51 -04004244 time_t t;
4245 u -= epoch;
4246 t = u;
4247 if (t != u) {
4248 PyErr_SetString(PyExc_OverflowError,
4249 "timestamp out of range for platform time_t");
4250 return -1;
4251 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004252 if (_PyTime_localtime(t, &local_time) != 0)
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004253 return -1;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004254 return utc_to_seconds(local_time.tm_year + 1900,
4255 local_time.tm_mon + 1,
4256 local_time.tm_mday,
4257 local_time.tm_hour,
4258 local_time.tm_min,
4259 local_time.tm_sec);
4260}
4261
Tim Petersa9bc1682003-01-11 03:39:11 +00004262/* Internal helper.
4263 * Build datetime from a time_t and a distinct count of microseconds.
4264 * Pass localtime or gmtime for f, to control the interpretation of timet.
4265 */
4266static PyObject *
4267datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004269{
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004270 struct tm tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004271 int year, month, day, hour, minute, second, fold = 0;
Tim Petersa9bc1682003-01-11 03:39:11 +00004272
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004273 if (f(timet, &tm) != 0)
4274 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01004275
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004276 year = tm.tm_year + 1900;
4277 month = tm.tm_mon + 1;
4278 day = tm.tm_mday;
4279 hour = tm.tm_hour;
4280 minute = tm.tm_min;
Victor Stinner21f58932012-03-14 00:15:40 +01004281 /* The platform localtime/gmtime may insert leap seconds,
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004282 * indicated by tm.tm_sec > 59. We don't care about them,
Victor Stinner21f58932012-03-14 00:15:40 +01004283 * except to the extent that passing them on to the datetime
4284 * constructor would raise ValueError for a reason that
4285 * made no sense to the user.
4286 */
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04004287 second = Py_MIN(59, tm.tm_sec);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004288
Victor Stinnerb67f0962017-02-10 10:34:02 +01004289 /* local timezone requires to compute fold */
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004290 if (tzinfo == Py_None && f == _PyTime_localtime) {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07004291 long long probe_seconds, result_seconds, transition;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004292
4293 result_seconds = utc_to_seconds(year, month, day,
4294 hour, minute, second);
4295 /* Probe max_fold_seconds to detect a fold. */
4296 probe_seconds = local(epoch + timet - max_fold_seconds);
4297 if (probe_seconds == -1)
4298 return NULL;
4299 transition = result_seconds - probe_seconds - max_fold_seconds;
4300 if (transition < 0) {
4301 probe_seconds = local(epoch + timet + transition);
4302 if (probe_seconds == -1)
4303 return NULL;
4304 if (probe_seconds == result_seconds)
4305 fold = 1;
4306 }
4307 }
4308 return new_datetime_ex2(year, month, day, hour,
4309 minute, second, us, tzinfo, fold,
4310 (PyTypeObject *)cls);
Tim Petersa9bc1682003-01-11 03:39:11 +00004311}
4312
4313/* Internal helper.
4314 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4315 * to control the interpretation of the timestamp. Since a double doesn't
4316 * have enough bits to cover a datetime's full range of precision, it's
4317 * better to call datetime_from_timet_and_us provided you have a way
4318 * to get that much precision (e.g., C time() isn't good enough).
4319 */
4320static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004321datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004325 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004326
Victor Stinnere4a994d2015-03-30 01:10:14 +02004327 if (_PyTime_ObjectToTimeval(timestamp,
Victor Stinner7667f582015-09-09 01:02:23 +02004328 &timet, &us, _PyTime_ROUND_HALF_EVEN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004330
Victor Stinner21f58932012-03-14 00:15:40 +01004331 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004332}
4333
4334/* Internal helper.
4335 * Build most accurate possible datetime for current time. Pass localtime or
4336 * gmtime for f as appropriate.
4337 */
4338static PyObject *
4339datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4340{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004341 _PyTime_t ts = _PyTime_GetSystemClock();
Victor Stinner1e2b6882015-09-18 13:23:02 +02004342 time_t secs;
4343 int us;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004344
Victor Stinner1e2b6882015-09-18 13:23:02 +02004345 if (_PyTime_AsTimevalTime_t(ts, &secs, &us, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner09e5cf22015-03-30 00:09:18 +02004346 return NULL;
Victor Stinner1e2b6882015-09-18 13:23:02 +02004347 assert(0 <= us && us <= 999999);
Victor Stinner09e5cf22015-03-30 00:09:18 +02004348
Victor Stinner1e2b6882015-09-18 13:23:02 +02004349 return datetime_from_timet_and_us(cls, f, secs, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004350}
4351
Larry Hastings61272b72014-01-07 12:41:53 -08004352/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004353
4354@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004355datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004356
4357 tz: object = None
4358 Timezone object.
4359
4360Returns new datetime object representing current time local to tz.
4361
4362If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004363[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004364
Larry Hastings31826802013-10-19 00:09:25 -07004365static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004366datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03004367/*[clinic end generated code: output=b3386e5345e2b47a input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004370
Larry Hastings31826802013-10-19 00:09:25 -07004371 /* Return best possible local time -- this isn't constrained by the
4372 * precision of a timestamp.
4373 */
4374 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004376
Larry Hastings5c661892014-01-24 06:17:25 -08004377 self = datetime_best_possible((PyObject *)type,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004378 tz == Py_None ? _PyTime_localtime :
4379 _PyTime_gmtime,
Larry Hastings31826802013-10-19 00:09:25 -07004380 tz);
4381 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004383 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 }
4385 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004386}
4387
Tim Petersa9bc1682003-01-11 03:39:11 +00004388/* Return best possible UTC time -- this isn't constrained by the
4389 * precision of a timestamp.
4390 */
4391static PyObject *
4392datetime_utcnow(PyObject *cls, PyObject *dummy)
4393{
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004394 return datetime_best_possible(cls, _PyTime_gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004395}
4396
Tim Peters2a799bf2002-12-16 20:18:38 +00004397/* Return new local datetime from timestamp (Python timestamp -- a double). */
4398static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004399datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004402 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 PyObject *tzinfo = Py_None;
4404 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004405
Victor Stinner5d272cc2012-03-13 13:35:55 +01004406 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 keywords, &timestamp, &tzinfo))
4408 return NULL;
4409 if (check_tzinfo_subclass(tzinfo) < 0)
4410 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 self = datetime_from_timestamp(cls,
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004413 tzinfo == Py_None ? _PyTime_localtime :
4414 _PyTime_gmtime,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 timestamp,
4416 tzinfo);
4417 if (self != NULL && tzinfo != Py_None) {
4418 /* Convert UTC to tzinfo's zone. */
Serhiy Storchaka576f1322016-01-05 21:27:54 +02004419 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "N", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 }
4421 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004422}
4423
Tim Petersa9bc1682003-01-11 03:39:11 +00004424/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4425static PyObject *
4426datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4427{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004428 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004430
Victor Stinner5d272cc2012-03-13 13:35:55 +01004431 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04004432 result = datetime_from_timestamp(cls, _PyTime_gmtime, timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 Py_None);
4434 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004435}
4436
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004437/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004438static PyObject *
4439datetime_strptime(PyObject *cls, PyObject *args)
4440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004442 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004443 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004444
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004445 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004447
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004448 if (module == NULL) {
4449 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004450 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004451 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 }
Victor Stinner20401de2016-12-09 15:24:31 +01004453 return _PyObject_CallMethodIdObjArgs(module, &PyId__strptime_datetime,
4454 cls, string, format, NULL);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004455}
4456
Tim Petersa9bc1682003-01-11 03:39:11 +00004457/* Return new datetime from date/datetime and time arguments. */
4458static PyObject *
4459datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4460{
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004461 static char *keywords[] = {"date", "time", "tzinfo", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 PyObject *date;
4463 PyObject *time;
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004464 PyObject *tzinfo = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004466
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004467 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!|O:combine", keywords,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 &PyDateTime_DateType, &date,
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004469 &PyDateTime_TimeType, &time, &tzinfo)) {
4470 if (tzinfo == NULL) {
4471 if (HASTZINFO(time))
4472 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4473 else
4474 tzinfo = Py_None;
4475 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 result = PyObject_CallFunction(cls, "iiiiiiiO",
Alexander Belopolsky43746c32016-08-02 17:49:30 -04004477 GET_YEAR(date),
4478 GET_MONTH(date),
4479 GET_DAY(date),
4480 TIME_GET_HOUR(time),
4481 TIME_GET_MINUTE(time),
4482 TIME_GET_SECOND(time),
4483 TIME_GET_MICROSECOND(time),
4484 tzinfo);
4485 if (result)
4486 DATE_SET_FOLD(result, TIME_GET_FOLD(time));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 }
4488 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004489}
Tim Peters2a799bf2002-12-16 20:18:38 +00004490
4491/*
4492 * Destructor.
4493 */
4494
4495static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004496datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 if (HASTZINFO(self)) {
4499 Py_XDECREF(self->tzinfo);
4500 }
4501 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004502}
4503
4504/*
4505 * Indirect access to tzinfo methods.
4506 */
4507
Tim Peters2a799bf2002-12-16 20:18:38 +00004508/* These are all METH_NOARGS, so don't need to check the arglist. */
4509static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004510datetime_utcoffset(PyObject *self, PyObject *unused) {
4511 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004512}
4513
4514static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004515datetime_dst(PyObject *self, PyObject *unused) {
4516 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004517}
4518
4519static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004520datetime_tzname(PyObject *self, PyObject *unused) {
4521 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004522}
4523
4524/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004525 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004526 */
4527
Tim Petersa9bc1682003-01-11 03:39:11 +00004528/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4529 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004530 */
4531static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004532add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004535 /* Note that the C-level additions can't overflow, because of
4536 * invariant bounds on the member values.
4537 */
4538 int year = GET_YEAR(date);
4539 int month = GET_MONTH(date);
4540 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4541 int hour = DATE_GET_HOUR(date);
4542 int minute = DATE_GET_MINUTE(date);
4543 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4544 int microsecond = DATE_GET_MICROSECOND(date) +
4545 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 assert(factor == 1 || factor == -1);
4548 if (normalize_datetime(&year, &month, &day,
Victor Stinnerb67f0962017-02-10 10:34:02 +01004549 &hour, &minute, &second, &microsecond) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 return NULL;
Victor Stinnerb67f0962017-02-10 10:34:02 +01004551 }
4552
4553 return new_datetime(year, month, day,
4554 hour, minute, second, microsecond,
4555 HASTZINFO(date) ? date->tzinfo : Py_None, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004556}
4557
4558static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004559datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 if (PyDateTime_Check(left)) {
4562 /* datetime + ??? */
4563 if (PyDelta_Check(right))
4564 /* datetime + delta */
4565 return add_datetime_timedelta(
4566 (PyDateTime_DateTime *)left,
4567 (PyDateTime_Delta *)right,
4568 1);
4569 }
4570 else if (PyDelta_Check(left)) {
4571 /* delta + datetime */
4572 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4573 (PyDateTime_Delta *) left,
4574 1);
4575 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004576 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004577}
4578
4579static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004580datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 if (PyDateTime_Check(left)) {
4585 /* datetime - ??? */
4586 if (PyDateTime_Check(right)) {
4587 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004588 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004590
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004591 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4592 offset2 = offset1 = Py_None;
4593 Py_INCREF(offset1);
4594 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004596 else {
4597 offset1 = datetime_utcoffset(left, NULL);
4598 if (offset1 == NULL)
4599 return NULL;
4600 offset2 = datetime_utcoffset(right, NULL);
4601 if (offset2 == NULL) {
4602 Py_DECREF(offset1);
4603 return NULL;
4604 }
4605 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4606 PyErr_SetString(PyExc_TypeError,
4607 "can't subtract offset-naive and "
4608 "offset-aware datetimes");
4609 Py_DECREF(offset1);
4610 Py_DECREF(offset2);
4611 return NULL;
4612 }
4613 }
4614 if ((offset1 != offset2) &&
4615 delta_cmp(offset1, offset2) != 0) {
4616 offdiff = delta_subtract(offset1, offset2);
4617 if (offdiff == NULL) {
4618 Py_DECREF(offset1);
4619 Py_DECREF(offset2);
4620 return NULL;
4621 }
4622 }
4623 Py_DECREF(offset1);
4624 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 delta_d = ymd_to_ord(GET_YEAR(left),
4626 GET_MONTH(left),
4627 GET_DAY(left)) -
4628 ymd_to_ord(GET_YEAR(right),
4629 GET_MONTH(right),
4630 GET_DAY(right));
4631 /* These can't overflow, since the values are
4632 * normalized. At most this gives the number of
4633 * seconds in one day.
4634 */
4635 delta_s = (DATE_GET_HOUR(left) -
4636 DATE_GET_HOUR(right)) * 3600 +
4637 (DATE_GET_MINUTE(left) -
4638 DATE_GET_MINUTE(right)) * 60 +
4639 (DATE_GET_SECOND(left) -
4640 DATE_GET_SECOND(right));
4641 delta_us = DATE_GET_MICROSECOND(left) -
4642 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004644 if (result == NULL)
4645 return NULL;
4646
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004647 if (offdiff != NULL) {
Serhiy Storchakaf01e4082016-04-10 18:12:01 +03004648 Py_SETREF(result, delta_subtract(result, offdiff));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004649 Py_DECREF(offdiff);
4650 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 }
4652 else if (PyDelta_Check(right)) {
4653 /* datetime - delta */
4654 result = add_datetime_timedelta(
4655 (PyDateTime_DateTime *)left,
4656 (PyDateTime_Delta *)right,
4657 -1);
4658 }
4659 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 if (result == Py_NotImplemented)
4662 Py_INCREF(result);
4663 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004664}
4665
4666/* Various ways to turn a datetime into a string. */
4667
4668static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004669datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 const char *type_name = Py_TYPE(self)->tp_name;
4672 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 if (DATE_GET_MICROSECOND(self)) {
4675 baserepr = PyUnicode_FromFormat(
4676 "%s(%d, %d, %d, %d, %d, %d, %d)",
4677 type_name,
4678 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4679 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4680 DATE_GET_SECOND(self),
4681 DATE_GET_MICROSECOND(self));
4682 }
4683 else if (DATE_GET_SECOND(self)) {
4684 baserepr = PyUnicode_FromFormat(
4685 "%s(%d, %d, %d, %d, %d, %d)",
4686 type_name,
4687 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4688 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4689 DATE_GET_SECOND(self));
4690 }
4691 else {
4692 baserepr = PyUnicode_FromFormat(
4693 "%s(%d, %d, %d, %d, %d)",
4694 type_name,
4695 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4696 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4697 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004698 if (baserepr != NULL && DATE_GET_FOLD(self) != 0)
4699 baserepr = append_keyword_fold(baserepr, DATE_GET_FOLD(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 if (baserepr == NULL || ! HASTZINFO(self))
4701 return baserepr;
4702 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004703}
4704
Tim Petersa9bc1682003-01-11 03:39:11 +00004705static PyObject *
4706datetime_str(PyDateTime_DateTime *self)
4707{
Victor Stinner4c381542016-12-09 00:33:39 +01004708 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "s", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004709}
Tim Peters2a799bf2002-12-16 20:18:38 +00004710
4711static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004712datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 int sep = 'T';
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004715 char *timespec = NULL;
4716 static char *keywords[] = {"sep", "timespec", NULL};
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 char buffer[100];
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004718 PyObject *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 int us = DATE_GET_MICROSECOND(self);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004720 static char *specs[][2] = {
4721 {"hours", "%04d-%02d-%02d%c%02d"},
4722 {"minutes", "%04d-%02d-%02d%c%02d:%02d"},
4723 {"seconds", "%04d-%02d-%02d%c%02d:%02d:%02d"},
4724 {"milliseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%03d"},
4725 {"microseconds", "%04d-%02d-%02d%c%02d:%02d:%02d.%06d"},
4726 };
4727 size_t given_spec;
Tim Peters2a799bf2002-12-16 20:18:38 +00004728
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004729 if (!PyArg_ParseTupleAndKeywords(args, kw, "|Cs:isoformat", keywords, &sep, &timespec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 return NULL;
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004731
4732 if (timespec == NULL || strcmp(timespec, "auto") == 0) {
4733 if (us == 0) {
4734 /* seconds */
4735 given_spec = 2;
4736 }
4737 else {
4738 /* microseconds */
4739 given_spec = 4;
4740 }
4741 }
4742 else {
4743 for (given_spec = 0; given_spec < Py_ARRAY_LENGTH(specs); given_spec++) {
4744 if (strcmp(timespec, specs[given_spec][0]) == 0) {
4745 if (given_spec == 3) {
4746 us = us / 1000;
4747 }
4748 break;
4749 }
4750 }
4751 }
4752
4753 if (given_spec == Py_ARRAY_LENGTH(specs)) {
4754 PyErr_Format(PyExc_ValueError, "Unknown timespec value");
4755 return NULL;
4756 }
4757 else {
4758 result = PyUnicode_FromFormat(specs[given_spec][1],
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 GET_YEAR(self), GET_MONTH(self),
4760 GET_DAY(self), (int)sep,
4761 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4762 DATE_GET_SECOND(self), us);
Alexander Belopolskya2998a62016-03-06 14:58:43 -05004763 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 if (!result || !HASTZINFO(self))
4766 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 /* We need to append the UTC offset. */
4769 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4770 (PyObject *)self) < 0) {
4771 Py_DECREF(result);
4772 return NULL;
4773 }
4774 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4775 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004776}
4777
Tim Petersa9bc1682003-01-11 03:39:11 +00004778static PyObject *
4779datetime_ctime(PyDateTime_DateTime *self)
4780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 return format_ctime((PyDateTime_Date *)self,
4782 DATE_GET_HOUR(self),
4783 DATE_GET_MINUTE(self),
4784 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004785}
4786
Tim Peters2a799bf2002-12-16 20:18:38 +00004787/* Miscellaneous methods. */
4788
Tim Petersa9bc1682003-01-11 03:39:11 +00004789static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004790flip_fold(PyObject *dt)
4791{
4792 return new_datetime_ex2(GET_YEAR(dt),
4793 GET_MONTH(dt),
4794 GET_DAY(dt),
4795 DATE_GET_HOUR(dt),
4796 DATE_GET_MINUTE(dt),
4797 DATE_GET_SECOND(dt),
4798 DATE_GET_MICROSECOND(dt),
4799 HASTZINFO(dt) ?
4800 ((PyDateTime_DateTime *)dt)->tzinfo : Py_None,
4801 !DATE_GET_FOLD(dt),
4802 Py_TYPE(dt));
4803}
4804
4805static PyObject *
4806get_flip_fold_offset(PyObject *dt)
4807{
4808 PyObject *result, *flip_dt;
4809
4810 flip_dt = flip_fold(dt);
4811 if (flip_dt == NULL)
4812 return NULL;
4813 result = datetime_utcoffset(flip_dt, NULL);
4814 Py_DECREF(flip_dt);
4815 return result;
4816}
4817
4818/* PEP 495 exception: Whenever one or both of the operands in
4819 * inter-zone comparison is such that its utcoffset() depends
4820 * on the value of its fold fold attribute, the result is False.
4821 *
4822 * Return 1 if exception applies, 0 if not, and -1 on error.
4823 */
4824static int
4825pep495_eq_exception(PyObject *self, PyObject *other,
4826 PyObject *offset_self, PyObject *offset_other)
4827{
4828 int result = 0;
4829 PyObject *flip_offset;
4830
4831 flip_offset = get_flip_fold_offset(self);
4832 if (flip_offset == NULL)
4833 return -1;
4834 if (flip_offset != offset_self &&
4835 delta_cmp(flip_offset, offset_self))
4836 {
4837 result = 1;
4838 goto done;
4839 }
4840 Py_DECREF(flip_offset);
4841
4842 flip_offset = get_flip_fold_offset(other);
4843 if (flip_offset == NULL)
4844 return -1;
4845 if (flip_offset != offset_other &&
4846 delta_cmp(flip_offset, offset_other))
4847 result = 1;
4848 done:
4849 Py_DECREF(flip_offset);
4850 return result;
4851}
4852
4853static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004854datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004855{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004856 PyObject *result = NULL;
4857 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 if (! PyDateTime_Check(other)) {
4861 if (PyDate_Check(other)) {
4862 /* Prevent invocation of date_richcompare. We want to
4863 return NotImplemented here to give the other object
4864 a chance. But since DateTime is a subclass of
4865 Date, if the other object is a Date, it would
4866 compute an ordering based on the date part alone,
4867 and we don't want that. So force unequal or
4868 uncomparable here in that case. */
4869 if (op == Py_EQ)
4870 Py_RETURN_FALSE;
4871 if (op == Py_NE)
4872 Py_RETURN_TRUE;
4873 return cmperror(self, other);
4874 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004875 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004877
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004878 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4880 ((PyDateTime_DateTime *)other)->data,
4881 _PyDateTime_DATETIME_DATASIZE);
4882 return diff_to_bool(diff, op);
4883 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004884 offset1 = datetime_utcoffset(self, NULL);
4885 if (offset1 == NULL)
4886 return NULL;
4887 offset2 = datetime_utcoffset(other, NULL);
4888 if (offset2 == NULL)
4889 goto done;
4890 /* If they're both naive, or both aware and have the same offsets,
4891 * we get off cheap. Note that if they're both naive, offset1 ==
4892 * offset2 == Py_None at this point.
4893 */
4894 if ((offset1 == offset2) ||
4895 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4896 delta_cmp(offset1, offset2) == 0)) {
4897 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4898 ((PyDateTime_DateTime *)other)->data,
4899 _PyDateTime_DATETIME_DATASIZE);
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);
4908 }
4909 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004911
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004912 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004913 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4914 other);
4915 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004916 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 diff = GET_TD_DAYS(delta);
4918 if (diff == 0)
4919 diff = GET_TD_SECONDS(delta) |
4920 GET_TD_MICROSECONDS(delta);
4921 Py_DECREF(delta);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004922 if ((op == Py_EQ || op == Py_NE) && diff == 0) {
4923 int ex = pep495_eq_exception(self, other, offset1, offset2);
4924 if (ex == -1)
4925 goto done;
4926 if (ex)
4927 diff = 1;
4928 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004929 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004930 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004931 else if (op == Py_EQ) {
4932 result = Py_False;
4933 Py_INCREF(result);
4934 }
4935 else if (op == Py_NE) {
4936 result = Py_True;
4937 Py_INCREF(result);
4938 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004939 else {
4940 PyErr_SetString(PyExc_TypeError,
4941 "can't compare offset-naive and "
4942 "offset-aware datetimes");
4943 }
4944 done:
4945 Py_DECREF(offset1);
4946 Py_XDECREF(offset2);
4947 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004948}
4949
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004950static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004951datetime_hash(PyDateTime_DateTime *self)
4952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004953 if (self->hashcode == -1) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04004954 PyObject *offset, *self0;
4955 if (DATE_GET_FOLD(self)) {
4956 self0 = new_datetime_ex2(GET_YEAR(self),
4957 GET_MONTH(self),
4958 GET_DAY(self),
4959 DATE_GET_HOUR(self),
4960 DATE_GET_MINUTE(self),
4961 DATE_GET_SECOND(self),
4962 DATE_GET_MICROSECOND(self),
4963 HASTZINFO(self) ? self->tzinfo : Py_None,
4964 0, Py_TYPE(self));
4965 if (self0 == NULL)
4966 return -1;
4967 }
4968 else {
4969 self0 = (PyObject *)self;
4970 Py_INCREF(self0);
4971 }
4972 offset = datetime_utcoffset(self0, NULL);
4973 Py_DECREF(self0);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004974
4975 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004979 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 self->hashcode = generic_hash(
4981 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004983 PyObject *temp1, *temp2;
4984 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 assert(HASTZINFO(self));
4987 days = ymd_to_ord(GET_YEAR(self),
4988 GET_MONTH(self),
4989 GET_DAY(self));
4990 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004991 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004993 temp1 = new_delta(days, seconds,
4994 DATE_GET_MICROSECOND(self),
4995 1);
4996 if (temp1 == NULL) {
4997 Py_DECREF(offset);
4998 return -1;
4999 }
5000 temp2 = delta_subtract(temp1, offset);
5001 Py_DECREF(temp1);
5002 if (temp2 == NULL) {
5003 Py_DECREF(offset);
5004 return -1;
5005 }
5006 self->hashcode = PyObject_Hash(temp2);
5007 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005009 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 }
5011 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00005012}
Tim Peters2a799bf2002-12-16 20:18:38 +00005013
5014static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005015datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00005016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 PyObject *clone;
5018 PyObject *tuple;
5019 int y = GET_YEAR(self);
5020 int m = GET_MONTH(self);
5021 int d = GET_DAY(self);
5022 int hh = DATE_GET_HOUR(self);
5023 int mm = DATE_GET_MINUTE(self);
5024 int ss = DATE_GET_SECOND(self);
5025 int us = DATE_GET_MICROSECOND(self);
5026 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005027 int fold = DATE_GET_FOLD(self);
Tim Peters12bf3392002-12-24 05:41:27 +00005028
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005029 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO$i:replace",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 datetime_kws,
5031 &y, &m, &d, &hh, &mm, &ss, &us,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005032 &tzinfo, &fold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 return NULL;
5034 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
5035 if (tuple == NULL)
5036 return NULL;
5037 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005038
5039 if (clone != NULL) {
5040 if (fold != 0 && fold != 1) {
5041 PyErr_SetString(PyExc_ValueError,
5042 "fold must be either 0 or 1");
5043 return NULL;
5044 }
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005045 DATE_SET_FOLD(clone, fold);
Alexander Belopolsky47649ab2016-08-08 17:05:40 -04005046 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 Py_DECREF(tuple);
5048 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00005049}
5050
5051static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005052local_timezone_from_timestamp(time_t timestamp)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005053{
5054 PyObject *result = NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005055 PyObject *delta;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005056 struct tm local_time_tm;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005057 PyObject *nameo = NULL;
5058 const char *zone = NULL;
5059
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005060 if (_PyTime_localtime(timestamp, &local_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005061 return NULL;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005062#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005063 zone = local_time_tm.tm_zone;
5064 delta = new_delta(0, local_time_tm.tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005065#else /* HAVE_STRUCT_TM_TM_ZONE */
5066 {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005067 PyObject *local_time, *utc_time;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005068 struct tm utc_time_tm;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005069 char buf[100];
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005070 strftime(buf, sizeof(buf), "%Z", &local_time_tm);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005071 zone = buf;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005072 local_time = new_datetime(local_time_tm.tm_year + 1900,
5073 local_time_tm.tm_mon + 1,
5074 local_time_tm.tm_mday,
5075 local_time_tm.tm_hour,
5076 local_time_tm.tm_min,
5077 local_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005078 if (local_time == NULL) {
5079 return NULL;
5080 }
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -04005081 if (_PyTime_gmtime(timestamp, &utc_time_tm) != 0)
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005082 return NULL;
Alexander Belopolsky6d88fa52016-09-10 15:58:31 -04005083 utc_time = new_datetime(utc_time_tm.tm_year + 1900,
5084 utc_time_tm.tm_mon + 1,
5085 utc_time_tm.tm_mday,
5086 utc_time_tm.tm_hour,
5087 utc_time_tm.tm_min,
5088 utc_time_tm.tm_sec, 0, Py_None, 0);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005089 if (utc_time == NULL) {
5090 Py_DECREF(local_time);
5091 return NULL;
5092 }
5093 delta = datetime_subtract(local_time, utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005094 Py_DECREF(local_time);
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005095 Py_DECREF(utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005096 }
5097#endif /* HAVE_STRUCT_TM_TM_ZONE */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005098 if (delta == NULL) {
5099 return NULL;
5100 }
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005101 if (zone != NULL) {
5102 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
5103 if (nameo == NULL)
5104 goto error;
5105 }
5106 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02005107 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005108 error:
5109 Py_DECREF(delta);
5110 return result;
5111}
5112
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005113static PyObject *
5114local_timezone(PyDateTime_DateTime *utc_time)
5115{
5116 time_t timestamp;
5117 PyObject *delta;
5118 PyObject *one_second;
5119 PyObject *seconds;
5120
5121 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
5122 if (delta == NULL)
5123 return NULL;
5124 one_second = new_delta(0, 1, 0, 0);
5125 if (one_second == NULL) {
5126 Py_DECREF(delta);
5127 return NULL;
5128 }
5129 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
5130 (PyDateTime_Delta *)one_second);
5131 Py_DECREF(one_second);
5132 Py_DECREF(delta);
5133 if (seconds == NULL)
5134 return NULL;
5135 timestamp = _PyLong_AsTime_t(seconds);
5136 Py_DECREF(seconds);
5137 if (timestamp == -1 && PyErr_Occurred())
5138 return NULL;
5139 return local_timezone_from_timestamp(timestamp);
5140}
5141
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005142static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005143local_to_seconds(int year, int month, int day,
5144 int hour, int minute, int second, int fold);
5145
5146static PyObject *
5147local_timezone_from_local(PyDateTime_DateTime *local_dt)
5148{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005149 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005150 time_t timestamp;
5151 seconds = local_to_seconds(GET_YEAR(local_dt),
5152 GET_MONTH(local_dt),
5153 GET_DAY(local_dt),
5154 DATE_GET_HOUR(local_dt),
5155 DATE_GET_MINUTE(local_dt),
5156 DATE_GET_SECOND(local_dt),
5157 DATE_GET_FOLD(local_dt));
5158 if (seconds == -1)
5159 return NULL;
5160 /* XXX: add bounds check */
5161 timestamp = seconds - epoch;
5162 return local_timezone_from_timestamp(timestamp);
5163}
5164
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005165static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00005166datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00005167{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005168 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005169 PyObject *offset;
5170 PyObject *temp;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005171 PyObject *self_tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005172 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005173 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00005174
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005175 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07005176 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005177 return NULL;
5178
5179 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00005181
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005182 if (!HASTZINFO(self) || self->tzinfo == Py_None) {
5183 self_tzinfo = local_timezone_from_local(self);
5184 if (self_tzinfo == NULL)
5185 return NULL;
5186 } else {
5187 self_tzinfo = self->tzinfo;
5188 Py_INCREF(self_tzinfo);
5189 }
Tim Peters521fc152002-12-31 17:36:56 +00005190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005191 /* Conversion to self's own time zone is a NOP. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005192 if (self_tzinfo == tzinfo) {
5193 Py_DECREF(self_tzinfo);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005195 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 }
Tim Peters521fc152002-12-31 17:36:56 +00005197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 /* Convert self to UTC. */
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005199 offset = call_utcoffset(self_tzinfo, (PyObject *)self);
5200 Py_DECREF(self_tzinfo);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005201 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005203 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005204 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5205 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005206 Py_DECREF(offset);
5207 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00005209
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005210 /* Make sure result is aware and UTC. */
5211 if (!HASTZINFO(result)) {
5212 temp = (PyObject *)result;
5213 result = (PyDateTime_DateTime *)
5214 new_datetime_ex2(GET_YEAR(result),
5215 GET_MONTH(result),
5216 GET_DAY(result),
5217 DATE_GET_HOUR(result),
5218 DATE_GET_MINUTE(result),
5219 DATE_GET_SECOND(result),
5220 DATE_GET_MICROSECOND(result),
5221 PyDateTime_TimeZone_UTC,
5222 DATE_GET_FOLD(result),
5223 Py_TYPE(result));
5224 Py_DECREF(temp);
5225 if (result == NULL)
5226 return NULL;
5227 }
5228 else {
5229 /* Result is already aware - just replace tzinfo. */
5230 temp = result->tzinfo;
5231 result->tzinfo = PyDateTime_TimeZone_UTC;
5232 Py_INCREF(result->tzinfo);
5233 Py_DECREF(temp);
5234 }
5235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005236 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005237 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04005238 if (tzinfo == Py_None) {
5239 tzinfo = local_timezone(result);
5240 if (tzinfo == NULL) {
5241 Py_DECREF(result);
5242 return NULL;
5243 }
5244 }
5245 else
5246 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005247 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005248 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00005249
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04005250 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005251 result = (PyDateTime_DateTime *)
Victor Stinner20401de2016-12-09 15:24:31 +01005252 _PyObject_CallMethodIdObjArgs(tzinfo, &PyId_fromutc, temp, NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005253 Py_DECREF(temp);
5254
Alexander Belopolsky878054e2012-06-22 14:11:58 -04005255 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00005256}
5257
5258static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005259datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00005262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005264 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00005265
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005266 dst = call_dst(self->tzinfo, (PyObject *)self);
5267 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005269
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005270 if (dst != Py_None)
5271 dstflag = delta_bool((PyDateTime_Delta *)dst);
5272 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 }
5274 return build_struct_time(GET_YEAR(self),
5275 GET_MONTH(self),
5276 GET_DAY(self),
5277 DATE_GET_HOUR(self),
5278 DATE_GET_MINUTE(self),
5279 DATE_GET_SECOND(self),
5280 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00005281}
5282
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005283static long long
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005284local_to_seconds(int year, int month, int day,
5285 int hour, int minute, int second, int fold)
5286{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005287 long long t, a, b, u1, u2, t1, t2, lt;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005288 t = utc_to_seconds(year, month, day, hour, minute, second);
5289 /* Our goal is to solve t = local(u) for u. */
5290 lt = local(t);
5291 if (lt == -1)
5292 return -1;
5293 a = lt - t;
5294 u1 = t - a;
5295 t1 = local(u1);
5296 if (t1 == -1)
5297 return -1;
5298 if (t1 == t) {
5299 /* We found one solution, but it may not be the one we need.
5300 * Look for an earlier solution (if `fold` is 0), or a
5301 * later one (if `fold` is 1). */
5302 if (fold)
5303 u2 = u1 + max_fold_seconds;
5304 else
5305 u2 = u1 - max_fold_seconds;
5306 lt = local(u2);
5307 if (lt == -1)
5308 return -1;
5309 b = lt - u2;
5310 if (a == b)
5311 return u1;
5312 }
5313 else {
5314 b = t1 - u1;
5315 assert(a != b);
5316 }
5317 u2 = t - b;
5318 t2 = local(u2);
5319 if (t2 == -1)
5320 return -1;
5321 if (t2 == t)
5322 return u2;
5323 if (t1 == t)
5324 return u1;
5325 /* We have found both offsets a and b, but neither t - a nor t - b is
5326 * a solution. This means t is in the gap. */
5327 return fold?Py_MIN(u1, u2):Py_MAX(u1, u2);
5328}
5329
5330/* date(1970,1,1).toordinal() == 719163 */
5331#define EPOCH_SECONDS (719163LL * 24 * 60 * 60)
5332
Tim Peters2a799bf2002-12-16 20:18:38 +00005333static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04005334datetime_timestamp(PyDateTime_DateTime *self)
5335{
5336 PyObject *result;
5337
5338 if (HASTZINFO(self) && self->tzinfo != Py_None) {
5339 PyObject *delta;
5340 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
5341 if (delta == NULL)
5342 return NULL;
5343 result = delta_total_seconds(delta);
5344 Py_DECREF(delta);
5345 }
5346 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07005347 long long seconds;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005348 seconds = local_to_seconds(GET_YEAR(self),
5349 GET_MONTH(self),
5350 GET_DAY(self),
5351 DATE_GET_HOUR(self),
5352 DATE_GET_MINUTE(self),
5353 DATE_GET_SECOND(self),
5354 DATE_GET_FOLD(self));
5355 if (seconds == -1)
Alexander Belopolskya4415142012-06-08 12:33:09 -04005356 return NULL;
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005357 result = PyFloat_FromDouble(seconds - EPOCH_SECONDS +
5358 DATE_GET_MICROSECOND(self) / 1e6);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005359 }
5360 return result;
5361}
5362
5363static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00005364datetime_getdate(PyDateTime_DateTime *self)
5365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 return new_date(GET_YEAR(self),
5367 GET_MONTH(self),
5368 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005369}
5370
5371static PyObject *
5372datetime_gettime(PyDateTime_DateTime *self)
5373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 return new_time(DATE_GET_HOUR(self),
5375 DATE_GET_MINUTE(self),
5376 DATE_GET_SECOND(self),
5377 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005378 Py_None,
5379 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005380}
5381
5382static PyObject *
5383datetime_gettimetz(PyDateTime_DateTime *self)
5384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 return new_time(DATE_GET_HOUR(self),
5386 DATE_GET_MINUTE(self),
5387 DATE_GET_SECOND(self),
5388 DATE_GET_MICROSECOND(self),
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005389 GET_DT_TZINFO(self),
5390 DATE_GET_FOLD(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00005391}
5392
5393static PyObject *
5394datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00005395{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005396 int y, m, d, hh, mm, ss;
5397 PyObject *tzinfo;
5398 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00005399
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005400 tzinfo = GET_DT_TZINFO(self);
5401 if (tzinfo == Py_None) {
5402 utcself = self;
5403 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005405 else {
5406 PyObject *offset;
5407 offset = call_utcoffset(tzinfo, (PyObject *)self);
5408 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00005409 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005410 if (offset == Py_None) {
5411 Py_DECREF(offset);
5412 utcself = self;
5413 Py_INCREF(utcself);
5414 }
5415 else {
5416 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
5417 (PyDateTime_Delta *)offset, -1);
5418 Py_DECREF(offset);
5419 if (utcself == NULL)
5420 return NULL;
5421 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005422 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00005423 y = GET_YEAR(utcself);
5424 m = GET_MONTH(utcself);
5425 d = GET_DAY(utcself);
5426 hh = DATE_GET_HOUR(utcself);
5427 mm = DATE_GET_MINUTE(utcself);
5428 ss = DATE_GET_SECOND(utcself);
5429
5430 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00005432}
5433
Tim Peters371935f2003-02-01 01:52:50 +00005434/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00005435
Tim Petersa9bc1682003-01-11 03:39:11 +00005436/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00005437 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
5438 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00005439 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00005440 */
5441static PyObject *
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005442datetime_getstate(PyDateTime_DateTime *self, int proto)
Tim Peters2a799bf2002-12-16 20:18:38 +00005443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 PyObject *basestate;
5445 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 basestate = PyBytes_FromStringAndSize((char *)self->data,
5448 _PyDateTime_DATETIME_DATASIZE);
5449 if (basestate != NULL) {
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005450 if (proto > 3 && DATE_GET_FOLD(self))
5451 /* Set the first bit of the third byte */
5452 PyBytes_AS_STRING(basestate)[2] |= (1 << 7);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005453 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5454 result = PyTuple_Pack(1, basestate);
5455 else
5456 result = PyTuple_Pack(2, basestate, self->tzinfo);
5457 Py_DECREF(basestate);
5458 }
5459 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005460}
5461
5462static PyObject *
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005463datetime_reduce_ex(PyDateTime_DateTime *self, PyObject *args)
Tim Peters2a799bf2002-12-16 20:18:38 +00005464{
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005465 int proto;
5466 if (!PyArg_ParseTuple(args, "i:__reduce_ex__", &proto))
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005467 return NULL;
5468
5469 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, proto));
Tim Peters2a799bf2002-12-16 20:18:38 +00005470}
5471
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005472static PyObject *
5473datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
5474{
5475 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self, 2));
5476}
5477
Tim Petersa9bc1682003-01-11 03:39:11 +00005478static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005480 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005481
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005482 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005484 {"utcnow", (PyCFunction)datetime_utcnow,
5485 METH_NOARGS | METH_CLASS,
5486 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005488 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5489 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5490 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005492 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5493 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05005494 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005496 {"strptime", (PyCFunction)datetime_strptime,
5497 METH_VARARGS | METH_CLASS,
5498 PyDoc_STR("string, format -> new datetime parsed from a string "
5499 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 {"combine", (PyCFunction)datetime_combine,
5502 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5503 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5508 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5511 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5514 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5517 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5520 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005521
Alexander Belopolskya4415142012-06-08 12:33:09 -04005522 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5523 PyDoc_STR("Return POSIX timestamp as float.")},
5524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5526 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005528 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5529 PyDoc_STR("[sep] -> string in ISO 8601 format, "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005530 "YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].\n"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 "sep is used to separate the year from the time, and "
Alexander Belopolskya2998a62016-03-06 14:58:43 -05005532 "defaults to 'T'.\n"
5533 "timespec specifies what components of the time to include"
5534 " (allowed values are 'auto', 'hours', 'minutes', 'seconds',"
5535 " 'milliseconds', and 'microseconds').\n")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5538 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5541 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5544 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5547 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5550 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005551
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005552 {"__reduce_ex__", (PyCFunction)datetime_reduce_ex, METH_VARARGS,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005553 PyDoc_STR("__reduce_ex__(proto) -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005554
Serhiy Storchaka546ce652016-11-22 00:29:42 +02005555 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
5556 PyDoc_STR("__reduce__() -> (cls, state)")},
5557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005559};
5560
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02005561static const char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005562PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5563\n\
5564The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005565instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005566
Tim Petersa9bc1682003-01-11 03:39:11 +00005567static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 datetime_add, /* nb_add */
5569 datetime_subtract, /* nb_subtract */
5570 0, /* nb_multiply */
5571 0, /* nb_remainder */
5572 0, /* nb_divmod */
5573 0, /* nb_power */
5574 0, /* nb_negative */
5575 0, /* nb_positive */
5576 0, /* nb_absolute */
5577 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005578};
5579
Neal Norwitz227b5332006-03-22 09:28:35 +00005580static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005581 PyVarObject_HEAD_INIT(NULL, 0)
5582 "datetime.datetime", /* tp_name */
5583 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5584 0, /* tp_itemsize */
5585 (destructor)datetime_dealloc, /* tp_dealloc */
5586 0, /* tp_print */
5587 0, /* tp_getattr */
5588 0, /* tp_setattr */
5589 0, /* tp_reserved */
5590 (reprfunc)datetime_repr, /* tp_repr */
5591 &datetime_as_number, /* tp_as_number */
5592 0, /* tp_as_sequence */
5593 0, /* tp_as_mapping */
5594 (hashfunc)datetime_hash, /* tp_hash */
5595 0, /* tp_call */
5596 (reprfunc)datetime_str, /* tp_str */
5597 PyObject_GenericGetAttr, /* tp_getattro */
5598 0, /* tp_setattro */
5599 0, /* tp_as_buffer */
5600 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5601 datetime_doc, /* tp_doc */
5602 0, /* tp_traverse */
5603 0, /* tp_clear */
5604 datetime_richcompare, /* tp_richcompare */
5605 0, /* tp_weaklistoffset */
5606 0, /* tp_iter */
5607 0, /* tp_iternext */
5608 datetime_methods, /* tp_methods */
5609 0, /* tp_members */
5610 datetime_getset, /* tp_getset */
5611 &PyDateTime_DateType, /* tp_base */
5612 0, /* tp_dict */
5613 0, /* tp_descr_get */
5614 0, /* tp_descr_set */
5615 0, /* tp_dictoffset */
5616 0, /* tp_init */
5617 datetime_alloc, /* tp_alloc */
5618 datetime_new, /* tp_new */
5619 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005620};
5621
5622/* ---------------------------------------------------------------------------
5623 * Module methods and initialization.
5624 */
5625
5626static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005628};
5629
Tim Peters9ddf40b2004-06-20 22:41:32 +00005630/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5631 * datetime.h.
5632 */
5633static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005634 &PyDateTime_DateType,
5635 &PyDateTime_DateTimeType,
5636 &PyDateTime_TimeType,
5637 &PyDateTime_DeltaType,
5638 &PyDateTime_TZInfoType,
5639 new_date_ex,
5640 new_datetime_ex,
5641 new_time_ex,
5642 new_delta_ex,
5643 datetime_fromtimestamp,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005644 date_fromtimestamp,
5645 new_datetime_ex2,
5646 new_time_ex2
Tim Peters9ddf40b2004-06-20 22:41:32 +00005647};
5648
5649
Martin v. Löwis1a214512008-06-11 05:26:20 +00005650
5651static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005653 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 "Fast implementation of the datetime type.",
5655 -1,
5656 module_methods,
5657 NULL,
5658 NULL,
5659 NULL,
5660 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005661};
5662
Tim Peters2a799bf2002-12-16 20:18:38 +00005663PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005664PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 PyObject *m; /* a module object */
5667 PyObject *d; /* its dict */
5668 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005669 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 m = PyModule_Create(&datetimemodule);
5672 if (m == NULL)
5673 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 if (PyType_Ready(&PyDateTime_DateType) < 0)
5676 return NULL;
5677 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5678 return NULL;
5679 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5680 return NULL;
5681 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5682 return NULL;
5683 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5684 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005685 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5686 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 /* timedelta values */
5689 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 x = new_delta(0, 0, 1, 0);
5692 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5693 return NULL;
5694 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005696 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5697 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5698 return NULL;
5699 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5702 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5703 return NULL;
5704 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 /* date values */
5707 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 x = new_date(1, 1, 1);
5710 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5711 return NULL;
5712 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 x = new_date(MAXYEAR, 12, 31);
5715 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5716 return NULL;
5717 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005719 x = new_delta(1, 0, 0, 0);
5720 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5721 return NULL;
5722 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 /* time values */
5725 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005726
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005727 x = new_time(0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005728 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5729 return NULL;
5730 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005731
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005732 x = new_time(23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005733 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5734 return NULL;
5735 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005737 x = new_delta(0, 0, 1, 0);
5738 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5739 return NULL;
5740 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005742 /* datetime values */
5743 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005744
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005745 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5747 return NULL;
5748 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005749
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005750 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005751 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5752 return NULL;
5753 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 x = new_delta(0, 0, 1, 0);
5756 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5757 return NULL;
5758 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005759
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005760 /* timezone values */
5761 d = PyDateTime_TimeZoneType.tp_dict;
5762
5763 delta = new_delta(0, 0, 0, 0);
5764 if (delta == NULL)
5765 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005766 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005767 Py_DECREF(delta);
5768 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5769 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005770 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005771
5772 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5773 if (delta == NULL)
5774 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005775 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005776 Py_DECREF(delta);
5777 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5778 return NULL;
5779 Py_DECREF(x);
5780
5781 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5782 if (delta == NULL)
5783 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005784 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005785 Py_DECREF(delta);
5786 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5787 return NULL;
5788 Py_DECREF(x);
5789
Alexander Belopolskya4415142012-06-08 12:33:09 -04005790 /* Epoch */
5791 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -04005792 PyDateTime_TimeZone_UTC, 0);
Alexander Belopolskya4415142012-06-08 12:33:09 -04005793 if (PyDateTime_Epoch == NULL)
5794 return NULL;
5795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005796 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005797 PyModule_AddIntMacro(m, MINYEAR);
5798 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 Py_INCREF(&PyDateTime_DateType);
5801 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005803 Py_INCREF(&PyDateTime_DateTimeType);
5804 PyModule_AddObject(m, "datetime",
5805 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 Py_INCREF(&PyDateTime_TimeType);
5808 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810 Py_INCREF(&PyDateTime_DeltaType);
5811 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005813 Py_INCREF(&PyDateTime_TZInfoType);
5814 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005815
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005816 Py_INCREF(&PyDateTime_TimeZoneType);
5817 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5820 if (x == NULL)
5821 return NULL;
5822 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 /* A 4-year cycle has an extra leap day over what we'd get from
5825 * pasting together 4 single years.
5826 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005827 Py_BUILD_ASSERT(DI4Y == 4 * 365 + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5831 * get from pasting together 4 100-year cycles.
5832 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005833 Py_BUILD_ASSERT(DI400Y == 4 * DI100Y + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005834 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005836 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5837 * pasting together 25 4-year cycles.
5838 */
Serhiy Storchakafad85aa2015-11-07 15:42:38 +02005839 Py_BUILD_ASSERT(DI100Y == 25 * DI4Y - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005840 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005841
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005842 one = PyLong_FromLong(1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 us_per_ms = PyLong_FromLong(1000);
5844 us_per_second = PyLong_FromLong(1000000);
5845 us_per_minute = PyLong_FromLong(60000000);
5846 seconds_per_day = PyLong_FromLong(24 * 3600);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005847 if (one == NULL || us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005848 us_per_minute == NULL || seconds_per_day == NULL)
5849 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 /* The rest are too big for 32-bit ints, but even
5852 * us_per_week fits in 40 bits, so doubles should be exact.
5853 */
5854 us_per_hour = PyLong_FromDouble(3600000000.0);
5855 us_per_day = PyLong_FromDouble(86400000000.0);
5856 us_per_week = PyLong_FromDouble(604800000000.0);
5857 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5858 return NULL;
5859 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005860}
Tim Petersf3615152003-01-01 21:51:37 +00005861
5862/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005863Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005864 x.n = x stripped of its timezone -- its naive time.
5865 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005866 return None
Tim Petersf3615152003-01-01 21:51:37 +00005867 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 return None
Tim Petersf3615152003-01-01 21:51:37 +00005869 x.s = x's standard offset, x.o - x.d
5870
5871Now some derived rules, where k is a duration (timedelta).
5872
58731. x.o = x.s + x.d
5874 This follows from the definition of x.s.
5875
Tim Petersc5dc4da2003-01-02 17:55:03 +000058762. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005877 This is actually a requirement, an assumption we need to make about
5878 sane tzinfo classes.
5879
58803. The naive UTC time corresponding to x is x.n - x.o.
5881 This is again a requirement for a sane tzinfo class.
5882
58834. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005884 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005885
Tim Petersc5dc4da2003-01-02 17:55:03 +000058865. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005887 Again follows from how arithmetic is defined.
5888
Tim Peters8bb5ad22003-01-24 02:44:45 +00005889Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005890(meaning that the various tzinfo methods exist, and don't blow up or return
5891None when called).
5892
Tim Petersa9bc1682003-01-11 03:39:11 +00005893The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005894x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005895
5896By #3, we want
5897
Tim Peters8bb5ad22003-01-24 02:44:45 +00005898 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005899
5900The algorithm starts by attaching tz to x.n, and calling that y. So
5901x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5902becomes true; in effect, we want to solve [2] for k:
5903
Tim Peters8bb5ad22003-01-24 02:44:45 +00005904 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005905
5906By #1, this is the same as
5907
Tim Peters8bb5ad22003-01-24 02:44:45 +00005908 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005909
5910By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5911Substituting that into [3],
5912
Tim Peters8bb5ad22003-01-24 02:44:45 +00005913 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5914 k - (y+k).s - (y+k).d = 0; rearranging,
5915 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5916 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005917
Tim Peters8bb5ad22003-01-24 02:44:45 +00005918On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5919approximate k by ignoring the (y+k).d term at first. Note that k can't be
5920very large, since all offset-returning methods return a duration of magnitude
5921less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5922be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005923
5924In any case, the new value is
5925
Tim Peters8bb5ad22003-01-24 02:44:45 +00005926 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005927
Tim Peters8bb5ad22003-01-24 02:44:45 +00005928It's helpful to step back at look at [4] from a higher level: it's simply
5929mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005930
5931At this point, if
5932
Tim Peters8bb5ad22003-01-24 02:44:45 +00005933 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005934
5935we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005936at the start of daylight time. Picture US Eastern for concreteness. The wall
5937time 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 +00005938sense then. The docs ask that an Eastern tzinfo class consider such a time to
5939be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5940on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005941the only spelling that makes sense on the local wall clock.
5942
Tim Petersc5dc4da2003-01-02 17:55:03 +00005943In fact, if [5] holds at this point, we do have the standard-time spelling,
5944but that takes a bit of proof. We first prove a stronger result. What's the
5945difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005946
Tim Peters8bb5ad22003-01-24 02:44:45 +00005947 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005948
Tim Petersc5dc4da2003-01-02 17:55:03 +00005949Now
5950 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005951 (y + y.s).n = by #5
5952 y.n + y.s = since y.n = x.n
5953 x.n + y.s = since z and y are have the same tzinfo member,
5954 y.s = z.s by #2
5955 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005956
Tim Petersc5dc4da2003-01-02 17:55:03 +00005957Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005958
Tim Petersc5dc4da2003-01-02 17:55:03 +00005959 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005960 x.n - ((x.n + z.s) - z.o) = expanding
5961 x.n - x.n - z.s + z.o = cancelling
5962 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005963 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005964
Tim Petersc5dc4da2003-01-02 17:55:03 +00005965So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005966
Tim Petersc5dc4da2003-01-02 17:55:03 +00005967If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005968spelling we wanted in the endcase described above. We're done. Contrarily,
5969if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005970
Tim Petersc5dc4da2003-01-02 17:55:03 +00005971If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5972add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005973local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005974
Tim Petersc5dc4da2003-01-02 17:55:03 +00005975Let
Tim Petersf3615152003-01-01 21:51:37 +00005976
Tim Peters4fede1a2003-01-04 00:26:59 +00005977 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005978
Tim Peters4fede1a2003-01-04 00:26:59 +00005979and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005980
Tim Peters8bb5ad22003-01-24 02:44:45 +00005981 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005982
Tim Peters8bb5ad22003-01-24 02:44:45 +00005983If so, we're done. If not, the tzinfo class is insane, according to the
5984assumptions we've made. This also requires a bit of proof. As before, let's
5985compute the difference between the LHS and RHS of [8] (and skipping some of
5986the justifications for the kinds of substitutions we've done several times
5987already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005988
Tim Peters8bb5ad22003-01-24 02:44:45 +00005989 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5991 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5992 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5993 - z.n + z.n - z.o + z'.o = cancel z.n
5994 - z.o + z'.o = #1 twice
5995 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5996 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005997
5998So 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 +00005999we've found the UTC-equivalent so are done. In fact, we stop with [7] and
6000return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00006001
Tim Peters8bb5ad22003-01-24 02:44:45 +00006002How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
6003a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
6004would have to change the result dst() returns: we start in DST, and moving
6005a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00006006
Tim Peters8bb5ad22003-01-24 02:44:45 +00006007There isn't a sane case where this can happen. The closest it gets is at
6008the end of DST, where there's an hour in UTC with no spelling in a hybrid
6009tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
6010that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
6011UTC) because the docs insist on that, but 0:MM is taken as being in daylight
6012time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
6013clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
6014standard time. Since that's what the local clock *does*, we want to map both
6015UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00006016in local time, but so it goes -- it's the way the local clock works.
6017
Tim Peters8bb5ad22003-01-24 02:44:45 +00006018When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
6019so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
6020z' = 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 +00006021(correctly) concludes that z' is not UTC-equivalent to x.
6022
6023Because we know z.d said z was in daylight time (else [5] would have held and
6024we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00006025and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00006026return in Eastern, it follows that z'.d must be 0 (which it is in the example,
6027but the reasoning doesn't depend on the example -- it depends on there being
6028two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00006029z' must be in standard time, and is the spelling we want in this case.
6030
6031Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
6032concerned (because it takes z' as being in standard time rather than the
6033daylight time we intend here), but returning it gives the real-life "local
6034clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
6035tz.
6036
6037When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
6038the 1:MM standard time spelling we want.
6039
6040So how can this break? One of the assumptions must be violated. Two
6041possibilities:
6042
60431) [2] effectively says that y.s is invariant across all y belong to a given
6044 time zone. This isn't true if, for political reasons or continental drift,
6045 a region decides to change its base offset from UTC.
6046
60472) There may be versions of "double daylight" time where the tail end of
6048 the analysis gives up a step too early. I haven't thought about that
6049 enough to say.
6050
6051In any case, it's clear that the default fromutc() is strong enough to handle
6052"almost all" time zones: so long as the standard offset is invariant, it
6053doesn't matter if daylight time transition points change from year to year, or
6054if daylight time is skipped in some years; it doesn't matter how large or
6055small dst() may get within its bounds; and it doesn't even matter if some
6056perverse time zone returns a negative dst()). So a breaking case must be
6057pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00006058--------------------------------------------------------------------------- */