blob: ab2acae662e883fa759ddd55ea9b79f154d636d4 [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
Tim Peters2a799bf2002-12-16 20:18:38 +000029/* We require that C int be at least 32 bits, and use int virtually
30 * everywhere. In just a few cases we use a temp long, where a Python
31 * API returns a C long. In such cases, we have to ensure that the
32 * final result fits in a C int (this can be an issue on 64-bit boxes).
33 */
34#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000035# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000036#endif
37
38#define MINYEAR 1
39#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000040#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000041
42/* Nine decimal digits is easy to communicate, and leaves enough room
43 * so that two delta days can be added w/o fear of overflowing a signed
44 * 32-bit int, and with plenty of room left over to absorb any possible
45 * carries from adding seconds.
46 */
47#define MAX_DELTA_DAYS 999999999
48
49/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050#define GET_YEAR PyDateTime_GET_YEAR
51#define GET_MONTH PyDateTime_GET_MONTH
52#define GET_DAY PyDateTime_GET_DAY
53#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
54#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
55#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
56#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000057
58/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
60 ((o)->data[1] = ((v) & 0x00ff)))
61#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
62#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000063
64/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
66#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
67#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
68#define DATE_SET_MICROSECOND(o, v) \
69 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
70 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
71 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000072
73/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
75#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
76#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
77#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
78#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
79#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
80#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
81#define TIME_SET_MICROSECOND(o, v) \
82 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
83 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
84 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000085
86/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
88#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
89#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091#define SET_TD_DAYS(o, v) ((o)->days = (v))
92#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000093#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
94
Tim Petersa032d2e2003-01-11 00:15:54 +000095/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
96 * p->hastzinfo.
97 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +000098#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
99#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
100 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
101#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
102 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +0000103/* M is a char or int claiming to be a valid month. The macro is equivalent
104 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +0000106 */
107#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
108
Tim Peters2a799bf2002-12-16 20:18:38 +0000109/* Forward declarations. */
110static PyTypeObject PyDateTime_DateType;
111static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000112static PyTypeObject PyDateTime_DeltaType;
113static PyTypeObject PyDateTime_TimeType;
114static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000115static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000116
Martin v. Löwise75fc142013-11-07 18:46:53 +0100117_Py_IDENTIFIER(as_integer_ratio);
118_Py_IDENTIFIER(fromutc);
119_Py_IDENTIFIER(isoformat);
120_Py_IDENTIFIER(strftime);
121
Tim Peters2a799bf2002-12-16 20:18:38 +0000122/* ---------------------------------------------------------------------------
123 * Math utilities.
124 */
125
126/* k = i+j overflows iff k differs in sign from both inputs,
127 * iff k^i has sign bit set and k^j has sign bit set,
128 * iff (k^i)&(k^j) has sign bit set.
129 */
130#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000132
133/* Compute Python divmod(x, y), returning the quotient and storing the
134 * remainder into *r. The quotient is the floor of x/y, and that's
135 * the real point of this. C will probably truncate instead (C99
136 * requires truncation; C89 left it implementation-defined).
137 * Simplification: we *require* that y > 0 here. That's appropriate
138 * for all the uses made of it. This simplifies the code and makes
139 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
140 * overflow case).
141 */
142static int
143divmod(int x, int y, int *r)
144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 assert(y > 0);
148 quo = x / y;
149 *r = x - quo * y;
150 if (*r < 0) {
151 --quo;
152 *r += y;
153 }
154 assert(0 <= *r && *r < y);
155 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000156}
157
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000158/* Nearest integer to m / n for integers m and n. Half-integer results
159 * are rounded to even.
160 */
161static PyObject *
162divide_nearest(PyObject *m, PyObject *n)
163{
164 PyObject *result;
165 PyObject *temp;
166
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000167 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000168 if (temp == NULL)
169 return NULL;
170 result = PyTuple_GET_ITEM(temp, 0);
171 Py_INCREF(result);
172 Py_DECREF(temp);
173
174 return result;
175}
176
Tim Peters2a799bf2002-12-16 20:18:38 +0000177/* ---------------------------------------------------------------------------
178 * General calendrical helper functions
179 */
180
181/* For each month ordinal in 1..12, the number of days in that month,
182 * and the number of days before that month in the same year. These
183 * are correct for non-leap years only.
184 */
185static int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 0, /* unused; this vector uses 1-based indexing */
187 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000188};
189
190static int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 0, /* unused; this vector uses 1-based indexing */
192 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000193};
194
195/* year -> 1 if leap year, else 0. */
196static int
197is_leap(int year)
198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 /* Cast year to unsigned. The result is the same either way, but
200 * C can generate faster code for unsigned mod than for signed
201 * mod (especially for % 4 -- a good compiler should just grab
202 * the last 2 bits when the LHS is unsigned).
203 */
204 const unsigned int ayear = (unsigned int)year;
205 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000206}
207
208/* year, month -> number of days in that month in that year */
209static int
210days_in_month(int year, int month)
211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 assert(month >= 1);
213 assert(month <= 12);
214 if (month == 2 && is_leap(year))
215 return 29;
216 else
217 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000218}
219
220/* year, month -> number of days in year preceeding first day of month */
221static int
222days_before_month(int year, int month)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 assert(month >= 1);
227 assert(month <= 12);
228 days = _days_before_month[month];
229 if (month > 2 && is_leap(year))
230 ++days;
231 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000232}
233
234/* year -> number of days before January 1st of year. Remember that we
235 * start with year 1, so days_before_year(1) == 0.
236 */
237static int
238days_before_year(int year)
239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 int y = year - 1;
241 /* This is incorrect if year <= 0; we really want the floor
242 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000243 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000245 assert (year >= 1);
246 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000247}
248
249/* Number of days in 4, 100, and 400 year cycles. That these have
250 * the correct values is asserted in the module init function.
251 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252#define DI4Y 1461 /* days_before_year(5); days in 4 years */
253#define DI100Y 36524 /* days_before_year(101); days in 100 years */
254#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000255
256/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
257static void
258ord_to_ymd(int ordinal, int *year, int *month, int *day)
259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
263 * leap years repeats exactly every 400 years. The basic strategy is
264 * to find the closest 400-year boundary at or before ordinal, then
265 * work with the offset from that boundary to ordinal. Life is much
266 * clearer if we subtract 1 from ordinal first -- then the values
267 * of ordinal at 400-year boundaries are exactly those divisible
268 * by DI400Y:
269 *
270 * D M Y n n-1
271 * -- --- ---- ---------- ----------------
272 * 31 Dec -400 -DI400Y -DI400Y -1
273 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
274 * ...
275 * 30 Dec 000 -1 -2
276 * 31 Dec 000 0 -1
277 * 1 Jan 001 1 0 400-year boundary
278 * 2 Jan 001 2 1
279 * 3 Jan 001 3 2
280 * ...
281 * 31 Dec 400 DI400Y DI400Y -1
282 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
283 */
284 assert(ordinal >= 1);
285 --ordinal;
286 n400 = ordinal / DI400Y;
287 n = ordinal % DI400Y;
288 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 /* Now n is the (non-negative) offset, in days, from January 1 of
291 * year, to the desired date. Now compute how many 100-year cycles
292 * precede n.
293 * Note that it's possible for n100 to equal 4! In that case 4 full
294 * 100-year cycles precede the desired day, which implies the
295 * desired day is December 31 at the end of a 400-year cycle.
296 */
297 n100 = n / DI100Y;
298 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 /* Now compute how many 4-year cycles precede it. */
301 n4 = n / DI4Y;
302 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 /* And now how many single years. Again n1 can be 4, and again
305 * meaning that the desired day is December 31 at the end of the
306 * 4-year cycle.
307 */
308 n1 = n / 365;
309 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 *year += n100 * 100 + n4 * 4 + n1;
312 if (n1 == 4 || n100 == 4) {
313 assert(n == 0);
314 *year -= 1;
315 *month = 12;
316 *day = 31;
317 return;
318 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 /* Now the year is correct, and n is the offset from January 1. We
321 * find the month via an estimate that's either exact or one too
322 * large.
323 */
324 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
325 assert(leapyear == is_leap(*year));
326 *month = (n + 50) >> 5;
327 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
328 if (preceding > n) {
329 /* estimate is too large */
330 *month -= 1;
331 preceding -= days_in_month(*year, *month);
332 }
333 n -= preceding;
334 assert(0 <= n);
335 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000338}
339
340/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
341static int
342ymd_to_ord(int year, int month, int day)
343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000345}
346
347/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
348static int
349weekday(int year, int month, int day)
350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000352}
353
354/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
355 * first calendar week containing a Thursday.
356 */
357static int
358iso_week1_monday(int year)
359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
361 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
362 int first_weekday = (first_day + 6) % 7;
363 /* ordinal of closest Monday at or before 1/1 */
364 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
367 week1_monday += 7;
368 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000369}
370
371/* ---------------------------------------------------------------------------
372 * Range checkers.
373 */
374
375/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
376 * If not, raise OverflowError and return -1.
377 */
378static int
379check_delta_day_range(int days)
380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
382 return 0;
383 PyErr_Format(PyExc_OverflowError,
384 "days=%d; must have magnitude <= %d",
385 days, MAX_DELTA_DAYS);
386 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000387}
388
389/* Check that date arguments are in range. Return 0 if they are. If they
390 * aren't, raise ValueError and return -1.
391 */
392static int
393check_date_args(int year, int month, int day)
394{
395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (year < MINYEAR || year > MAXYEAR) {
397 PyErr_SetString(PyExc_ValueError,
398 "year is out of range");
399 return -1;
400 }
401 if (month < 1 || month > 12) {
402 PyErr_SetString(PyExc_ValueError,
403 "month must be in 1..12");
404 return -1;
405 }
406 if (day < 1 || day > days_in_month(year, month)) {
407 PyErr_SetString(PyExc_ValueError,
408 "day is out of range for month");
409 return -1;
410 }
411 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000412}
413
414/* Check that time arguments are in range. Return 0 if they are. If they
415 * aren't, raise ValueError and return -1.
416 */
417static int
418check_time_args(int h, int m, int s, int us)
419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (h < 0 || h > 23) {
421 PyErr_SetString(PyExc_ValueError,
422 "hour must be in 0..23");
423 return -1;
424 }
425 if (m < 0 || m > 59) {
426 PyErr_SetString(PyExc_ValueError,
427 "minute must be in 0..59");
428 return -1;
429 }
430 if (s < 0 || s > 59) {
431 PyErr_SetString(PyExc_ValueError,
432 "second must be in 0..59");
433 return -1;
434 }
435 if (us < 0 || us > 999999) {
436 PyErr_SetString(PyExc_ValueError,
437 "microsecond must be in 0..999999");
438 return -1;
439 }
440 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000441}
442
443/* ---------------------------------------------------------------------------
444 * Normalization utilities.
445 */
446
447/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
448 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
449 * at least factor, enough of *lo is converted into "hi" units so that
450 * 0 <= *lo < factor. The input values must be such that int overflow
451 * is impossible.
452 */
453static void
454normalize_pair(int *hi, int *lo, int factor)
455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 assert(factor > 0);
457 assert(lo != hi);
458 if (*lo < 0 || *lo >= factor) {
459 const int num_hi = divmod(*lo, factor, lo);
460 const int new_hi = *hi + num_hi;
461 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
462 *hi = new_hi;
463 }
464 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000465}
466
467/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 * 0 <= *s < 24*3600
469 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000470 * The input values must be such that the internals don't overflow.
471 * The way this routine is used, we don't get close.
472 */
473static void
474normalize_d_s_us(int *d, int *s, int *us)
475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 if (*us < 0 || *us >= 1000000) {
477 normalize_pair(s, us, 1000000);
478 /* |s| can't be bigger than about
479 * |original s| + |original us|/1000000 now.
480 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 }
483 if (*s < 0 || *s >= 24*3600) {
484 normalize_pair(d, s, 24*3600);
485 /* |d| can't be bigger than about
486 * |original d| +
487 * (|original s| + |original us|/1000000) / (24*3600) now.
488 */
489 }
490 assert(0 <= *s && *s < 24*3600);
491 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000492}
493
494/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 * 1 <= *m <= 12
496 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000497 * The input values must be such that the internals don't overflow.
498 * The way this routine is used, we don't get close.
499 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000500static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000501normalize_y_m_d(int *y, int *m, int *d)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000504
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000505 /* In actual use, m is always the month component extracted from a
506 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 /* Now only day can be out of bounds (year may also be out of bounds
512 * for a datetime object, but we don't care about that here).
513 * If day is out of bounds, what to do is arguable, but at least the
514 * method here is principled and explainable.
515 */
516 dim = days_in_month(*y, *m);
517 if (*d < 1 || *d > dim) {
518 /* Move day-1 days from the first of the month. First try to
519 * get off cheap if we're only one day out of range
520 * (adjustments for timezone alone can't be worse than that).
521 */
522 if (*d == 0) {
523 --*m;
524 if (*m > 0)
525 *d = days_in_month(*y, *m);
526 else {
527 --*y;
528 *m = 12;
529 *d = 31;
530 }
531 }
532 else if (*d == dim + 1) {
533 /* move forward a day */
534 ++*m;
535 *d = 1;
536 if (*m > 12) {
537 *m = 1;
538 ++*y;
539 }
540 }
541 else {
542 int ordinal = ymd_to_ord(*y, *m, 1) +
543 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000544 if (ordinal < 1 || ordinal > MAXORDINAL) {
545 goto error;
546 } else {
547 ord_to_ymd(ordinal, y, m, d);
548 return 0;
549 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 }
551 }
552 assert(*m > 0);
553 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000554 if (MINYEAR <= *y && *y <= MAXYEAR)
555 return 0;
556 error:
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 return -1;
560
Tim Peters2a799bf2002-12-16 20:18:38 +0000561}
562
563/* Fiddle out-of-bounds months and days so that the result makes some kind
564 * of sense. The parameters are both inputs and outputs. Returns < 0 on
565 * failure, where failure means the adjusted year is out of bounds.
566 */
567static int
568normalize_date(int *year, int *month, int *day)
569{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000570 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000571}
572
573/* Force all the datetime fields into range. The parameters are both
574 * inputs and outputs. Returns < 0 on error.
575 */
576static int
577normalize_datetime(int *year, int *month, int *day,
578 int *hour, int *minute, int *second,
579 int *microsecond)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 normalize_pair(second, microsecond, 1000000);
582 normalize_pair(minute, second, 60);
583 normalize_pair(hour, minute, 60);
584 normalize_pair(day, hour, 24);
585 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000586}
587
588/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000589 * Basic object allocation: tp_alloc implementations. These allocate
590 * Python objects of the right size and type, and do the Python object-
591 * initialization bit. If there's not enough memory, they return NULL after
592 * setting MemoryError. All data members remain uninitialized trash.
593 *
594 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000595 * member is needed. This is ugly, imprecise, and possibly insecure.
596 * tp_basicsize for the time and datetime types is set to the size of the
597 * struct that has room for the tzinfo member, so subclasses in Python will
598 * allocate enough space for a tzinfo member whether or not one is actually
599 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
600 * part is that PyType_GenericAlloc() (which subclasses in Python end up
601 * using) just happens today to effectively ignore the nitems argument
602 * when tp_itemsize is 0, which it is for these type objects. If that
603 * changes, perhaps the callers of tp_alloc slots in this file should
604 * be changed to force a 0 nitems argument unless the type being allocated
605 * is a base type implemented in this file (so that tp_alloc is time_alloc
606 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000607 */
608
609static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000610time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 self = (PyObject *)
615 PyObject_MALLOC(aware ?
616 sizeof(PyDateTime_Time) :
617 sizeof(_PyDateTime_BaseTime));
618 if (self == NULL)
619 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100620 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000622}
623
624static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000625datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 self = (PyObject *)
630 PyObject_MALLOC(aware ?
631 sizeof(PyDateTime_DateTime) :
632 sizeof(_PyDateTime_BaseDateTime));
633 if (self == NULL)
634 return (PyObject *)PyErr_NoMemory();
Christian Heimesecb4e6a2013-12-04 09:34:29 +0100635 (void)PyObject_INIT(self, type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000637}
638
639/* ---------------------------------------------------------------------------
640 * Helpers for setting object fields. These work on pointers to the
641 * appropriate base class.
642 */
643
644/* For date and datetime. */
645static void
646set_date_fields(PyDateTime_Date *self, int y, int m, int d)
647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 self->hashcode = -1;
649 SET_YEAR(self, y);
650 SET_MONTH(self, m);
651 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000652}
653
654/* ---------------------------------------------------------------------------
655 * Create various objects, mostly without range checking.
656 */
657
658/* Create a date instance with no range checking. */
659static PyObject *
660new_date_ex(int year, int month, int day, PyTypeObject *type)
661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
665 if (self != NULL)
666 set_date_fields(self, year, month, day);
667 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000668}
669
670#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000672
673/* Create a datetime instance with no range checking. */
674static PyObject *
675new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyDateTime_DateTime *self;
679 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
682 if (self != NULL) {
683 self->hastzinfo = aware;
684 set_date_fields((PyDateTime_Date *)self, year, month, day);
685 DATE_SET_HOUR(self, hour);
686 DATE_SET_MINUTE(self, minute);
687 DATE_SET_SECOND(self, second);
688 DATE_SET_MICROSECOND(self, usecond);
689 if (aware) {
690 Py_INCREF(tzinfo);
691 self->tzinfo = tzinfo;
692 }
693 }
694 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000695}
696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
698 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
699 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000700
701/* Create a time instance with no range checking. */
702static PyObject *
703new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 PyDateTime_Time *self;
707 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
710 if (self != NULL) {
711 self->hastzinfo = aware;
712 self->hashcode = -1;
713 TIME_SET_HOUR(self, hour);
714 TIME_SET_MINUTE(self, minute);
715 TIME_SET_SECOND(self, second);
716 TIME_SET_MICROSECOND(self, usecond);
717 if (aware) {
718 Py_INCREF(tzinfo);
719 self->tzinfo = tzinfo;
720 }
721 }
722 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000723}
724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725#define new_time(hh, mm, ss, us, tzinfo) \
726 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000727
728/* Create a timedelta instance. Normalize the members iff normalize is
729 * true. Passing false is a speed optimization, if you know for sure
730 * that seconds and microseconds are already in their proper ranges. In any
731 * case, raises OverflowError and returns NULL if the normalized days is out
732 * of range).
733 */
734static PyObject *
735new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (normalize)
741 normalize_d_s_us(&days, &seconds, &microseconds);
742 assert(0 <= seconds && seconds < 24*3600);
743 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (check_delta_day_range(days) < 0)
746 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
749 if (self != NULL) {
750 self->hashcode = -1;
751 SET_TD_DAYS(self, days);
752 SET_TD_SECONDS(self, seconds);
753 SET_TD_MICROSECONDS(self, microseconds);
754 }
755 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000756}
757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758#define new_delta(d, s, us, normalize) \
759 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000760
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000761
762typedef struct
763{
764 PyObject_HEAD
765 PyObject *offset;
766 PyObject *name;
767} PyDateTime_TimeZone;
768
Victor Stinner6ced7c42011-03-21 18:15:42 +0100769/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000770static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya4415142012-06-08 12:33:09 -0400771/* The interned Epoch datetime instance */
772static PyObject *PyDateTime_Epoch;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +0000773
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000774/* Create new timezone instance checking offset range. This
775 function does not check the name argument. Caller must assure
776 that offset is a timedelta instance and name is either NULL
777 or a unicode object. */
778static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000779create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000780{
781 PyDateTime_TimeZone *self;
782 PyTypeObject *type = &PyDateTime_TimeZoneType;
783
784 assert(offset != NULL);
785 assert(PyDelta_Check(offset));
786 assert(name == NULL || PyUnicode_Check(name));
787
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000788 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
789 if (self == NULL) {
790 return NULL;
791 }
792 Py_INCREF(offset);
793 self->offset = offset;
794 Py_XINCREF(name);
795 self->name = name;
796 return (PyObject *)self;
797}
798
799static int delta_bool(PyDateTime_Delta *self);
800
801static PyObject *
802new_timezone(PyObject *offset, PyObject *name)
803{
804 assert(offset != NULL);
805 assert(PyDelta_Check(offset));
806 assert(name == NULL || PyUnicode_Check(name));
807
808 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
809 Py_INCREF(PyDateTime_TimeZone_UTC);
810 return PyDateTime_TimeZone_UTC;
811 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000812 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
813 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400814 " representing a whole number of minutes,"
815 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000816 return NULL;
817 }
818 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
819 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
820 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
821 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400822 " timedelta(hours=24),"
823 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000824 return NULL;
825 }
826
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000827 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000828}
829
Tim Petersb0c854d2003-05-17 15:57:00 +0000830/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000831 * tzinfo helpers.
832 */
833
Tim Peters855fe882002-12-22 03:43:39 +0000834/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
835 * raise TypeError and return -1.
836 */
837static int
838check_tzinfo_subclass(PyObject *p)
839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (p == Py_None || PyTZInfo_Check(p))
841 return 0;
842 PyErr_Format(PyExc_TypeError,
843 "tzinfo argument must be None or of a tzinfo subclass, "
844 "not type '%s'",
845 Py_TYPE(p)->tp_name);
846 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000847}
848
Tim Peters2a799bf2002-12-16 20:18:38 +0000849/* If self has a tzinfo member, return a BORROWED reference to it. Else
850 * return NULL, which is NOT AN ERROR. There are no error returns here,
851 * and the caller must not decref the result.
852 */
853static PyObject *
854get_tzinfo_member(PyObject *self)
855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (PyDateTime_Check(self) && HASTZINFO(self))
859 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
860 else if (PyTime_Check(self) && HASTZINFO(self))
861 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000864}
865
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000866/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
867 * be an instance of the tzinfo class. If the method returns None, this
868 * returns None. If the method doesn't return None or timedelta, TypeError is
869 * raised and this returns NULL. If it returns a timedelta and the value is
870 * out of range or isn't a whole number of minutes, ValueError is raised and
871 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000872 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000873static PyObject *
874call_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000875{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000876 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000879 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000881
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000882 if (tzinfo == Py_None)
883 Py_RETURN_NONE;
884 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
885 if (offset == Py_None || offset == NULL)
886 return offset;
887 if (PyDelta_Check(offset)) {
888 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
889 Py_DECREF(offset);
890 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
891 " representing a whole number of minutes");
892 return NULL;
893 }
894 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
895 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
896 Py_DECREF(offset);
897 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
898 " strictly between -timedelta(hours=24) and"
899 " timedelta(hours=24).");
900 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 }
902 }
903 else {
904 PyErr_Format(PyExc_TypeError,
905 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000906 "timedelta, not '%.200s'",
907 name, Py_TYPE(offset)->tp_name);
Raymond Hettinger5a2146a2014-07-25 14:59:48 -0700908 Py_DECREF(offset);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000909 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000911
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000912 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000913}
914
915/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
916 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
917 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000918 * doesn't return None or timedelta, TypeError is raised and this returns -1.
919 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
920 * # of minutes), ValueError is raised and this returns -1. Else *none is
921 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000922 */
Tim Peters855fe882002-12-22 03:43:39 +0000923static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000924call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
925{
926 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000927}
928
Tim Peters2a799bf2002-12-16 20:18:38 +0000929/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
930 * result. tzinfo must be an instance of the tzinfo class. If dst()
931 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000932 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000933 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000934 * ValueError is raised and this returns -1. Else *none is set to 0 and
935 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000936 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000937static PyObject *
938call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000939{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000940 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000941}
942
Tim Petersbad8ff02002-12-30 20:52:32 +0000943/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000944 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000945 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000946 * returns NULL. If the result is a string, we ensure it is a Unicode
947 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000948 */
949static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000950call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200953 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 assert(tzinfo != NULL);
956 assert(check_tzinfo_subclass(tzinfo) >= 0);
957 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000960 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +0000961
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200962 result = _PyObject_CallMethodId(tzinfo, &PyId_tzname, "O", tzinfoarg);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000963
964 if (result == NULL || result == Py_None)
965 return result;
966
967 if (!PyUnicode_Check(result)) {
968 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
969 "return None or a string, not '%s'",
970 Py_TYPE(result)->tp_name);
971 Py_DECREF(result);
972 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000974
975 return result;
Tim Peters00237032002-12-27 02:21:51 +0000976}
977
Tim Peters2a799bf2002-12-16 20:18:38 +0000978/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
979 * stuff
980 * ", tzinfo=" + repr(tzinfo)
981 * before the closing ")".
982 */
983static PyObject *
984append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 assert(PyUnicode_Check(repr));
989 assert(tzinfo);
990 if (tzinfo == Py_None)
991 return repr;
992 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
994 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 Py_DECREF(repr);
996 if (temp == NULL)
997 return NULL;
998 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
999 Py_DECREF(temp);
1000 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001001}
1002
1003/* ---------------------------------------------------------------------------
1004 * String format helpers.
1005 */
1006
1007static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001008format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 static const char *DayNames[] = {
1011 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1012 };
1013 static const char *MonthNames[] = {
1014 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1015 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1016 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1021 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1022 GET_DAY(date), hours, minutes, seconds,
1023 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001024}
1025
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001026static PyObject *delta_negative(PyDateTime_Delta *self);
1027
Tim Peters2a799bf2002-12-16 20:18:38 +00001028/* Add an hours & minutes UTC offset string to buf. buf has no more than
1029 * buflen bytes remaining. The UTC offset is gotten by calling
1030 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1031 * *buf, and that's all. Else the returned value is checked for sanity (an
1032 * integer in range), and if that's OK it's converted to an hours & minutes
1033 * string of the form
1034 * sign HH sep MM
1035 * Returns 0 if everything is OK. If the return value from utcoffset() is
1036 * bogus, an appropriate exception is set and -1 is returned.
1037 */
1038static int
Tim Peters328fff72002-12-20 01:31:27 +00001039format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001041{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001042 PyObject *offset;
1043 int hours, minutes, seconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001047
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001048 offset = call_utcoffset(tzinfo, tzinfoarg);
1049 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001051 if (offset == Py_None) {
1052 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 *buf = '\0';
1054 return 0;
1055 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001056 /* Offset is normalized, so it is negative if days < 0 */
1057 if (GET_TD_DAYS(offset) < 0) {
1058 PyObject *temp = offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 sign = '-';
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001060 offset = delta_negative((PyDateTime_Delta *)offset);
1061 Py_DECREF(temp);
1062 if (offset == NULL)
1063 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001065 else {
1066 sign = '+';
1067 }
1068 /* Offset is not negative here. */
1069 seconds = GET_TD_SECONDS(offset);
1070 Py_DECREF(offset);
1071 minutes = divmod(seconds, 60, &seconds);
1072 hours = divmod(minutes, 60, &minutes);
1073 assert(seconds == 0);
1074 /* XXX ignore sub-minute data, curently not allowed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001078}
1079
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001080static PyObject *
1081make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyObject *temp;
1084 PyObject *tzinfo = get_tzinfo_member(object);
1085 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001086 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (Zreplacement == NULL)
1089 return NULL;
1090 if (tzinfo == Py_None || tzinfo == NULL)
1091 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 assert(tzinfoarg != NULL);
1094 temp = call_tzname(tzinfo, tzinfoarg);
1095 if (temp == NULL)
1096 goto Error;
1097 if (temp == Py_None) {
1098 Py_DECREF(temp);
1099 return Zreplacement;
1100 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 assert(PyUnicode_Check(temp));
1103 /* Since the tzname is getting stuffed into the
1104 * format, we have to double any % signs so that
1105 * strftime doesn't treat them as format codes.
1106 */
1107 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001108 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 Py_DECREF(temp);
1110 if (Zreplacement == NULL)
1111 return NULL;
1112 if (!PyUnicode_Check(Zreplacement)) {
1113 PyErr_SetString(PyExc_TypeError,
1114 "tzname.replace() did not return a string");
1115 goto Error;
1116 }
1117 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001118
1119 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 Py_DECREF(Zreplacement);
1121 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001122}
1123
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001124static PyObject *
1125make_freplacement(PyObject *object)
1126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 char freplacement[64];
1128 if (PyTime_Check(object))
1129 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1130 else if (PyDateTime_Check(object))
1131 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1132 else
1133 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001136}
1137
Tim Peters2a799bf2002-12-16 20:18:38 +00001138/* I sure don't want to reproduce the strftime code from the time module,
1139 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001140 * giving special meanings to the %z, %Z and %f format codes via a
1141 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001142 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1143 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001144 */
1145static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001146wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1152 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1153 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 const char *pin; /* pointer to next char in input format */
1156 Py_ssize_t flen; /* length of input format */
1157 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyObject *newfmt = NULL; /* py string, the output format */
1160 char *pnew; /* pointer to available byte in output format */
1161 size_t totalnew; /* number bytes total in output format buffer,
1162 exclusive of trailing \0 */
1163 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 const char *ptoappend; /* ptr to string to append to output buffer */
1166 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 assert(object && format && timetuple);
1169 assert(PyUnicode_Check(format));
1170 /* Convert the input format to a C string and size */
1171 pin = _PyUnicode_AsStringAndSize(format, &flen);
1172 if (!pin)
1173 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 /* Scan the input format, looking for %z/%Z/%f escapes, building
1176 * a new format. Since computing the replacements for those codes
1177 * is expensive, don't unless they're actually used.
1178 */
1179 if (flen > INT_MAX - 1) {
1180 PyErr_NoMemory();
1181 goto Done;
1182 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 totalnew = flen + 1; /* realistic if no %z/%Z */
1185 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1186 if (newfmt == NULL) goto Done;
1187 pnew = PyBytes_AsString(newfmt);
1188 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 while ((ch = *pin++) != '\0') {
1191 if (ch != '%') {
1192 ptoappend = pin - 1;
1193 ntoappend = 1;
1194 }
1195 else if ((ch = *pin++) == '\0') {
1196 /* There's a lone trailing %; doesn't make sense. */
1197 PyErr_SetString(PyExc_ValueError, "strftime format "
1198 "ends with raw %");
1199 goto Done;
1200 }
1201 /* A % has been seen and ch is the character after it. */
1202 else if (ch == 'z') {
1203 if (zreplacement == NULL) {
1204 /* format utcoffset */
1205 char buf[100];
1206 PyObject *tzinfo = get_tzinfo_member(object);
1207 zreplacement = PyBytes_FromStringAndSize("", 0);
1208 if (zreplacement == NULL) goto Done;
1209 if (tzinfo != Py_None && tzinfo != NULL) {
1210 assert(tzinfoarg != NULL);
1211 if (format_utcoffset(buf,
1212 sizeof(buf),
1213 "",
1214 tzinfo,
1215 tzinfoarg) < 0)
1216 goto Done;
1217 Py_DECREF(zreplacement);
1218 zreplacement =
1219 PyBytes_FromStringAndSize(buf,
1220 strlen(buf));
1221 if (zreplacement == NULL)
1222 goto Done;
1223 }
1224 }
1225 assert(zreplacement != NULL);
1226 ptoappend = PyBytes_AS_STRING(zreplacement);
1227 ntoappend = PyBytes_GET_SIZE(zreplacement);
1228 }
1229 else if (ch == 'Z') {
1230 /* format tzname */
1231 if (Zreplacement == NULL) {
1232 Zreplacement = make_Zreplacement(object,
1233 tzinfoarg);
1234 if (Zreplacement == NULL)
1235 goto Done;
1236 }
1237 assert(Zreplacement != NULL);
1238 assert(PyUnicode_Check(Zreplacement));
1239 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1240 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001241 if (ptoappend == NULL)
1242 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 }
1244 else if (ch == 'f') {
1245 /* format microseconds */
1246 if (freplacement == NULL) {
1247 freplacement = make_freplacement(object);
1248 if (freplacement == NULL)
1249 goto Done;
1250 }
1251 assert(freplacement != NULL);
1252 assert(PyBytes_Check(freplacement));
1253 ptoappend = PyBytes_AS_STRING(freplacement);
1254 ntoappend = PyBytes_GET_SIZE(freplacement);
1255 }
1256 else {
1257 /* percent followed by neither z nor Z */
1258 ptoappend = pin - 2;
1259 ntoappend = 2;
1260 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 /* Append the ntoappend chars starting at ptoappend to
1263 * the new format.
1264 */
1265 if (ntoappend == 0)
1266 continue;
1267 assert(ptoappend != NULL);
1268 assert(ntoappend > 0);
1269 while (usednew + ntoappend > totalnew) {
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001270 if (totalnew > (PY_SSIZE_T_MAX >> 1)) { /* overflow */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 PyErr_NoMemory();
1272 goto Done;
1273 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01001274 totalnew <<= 1;
1275 if (_PyBytes_Resize(&newfmt, totalnew) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 pnew = PyBytes_AsString(newfmt) + usednew;
1278 }
1279 memcpy(pnew, ptoappend, ntoappend);
1280 pnew += ntoappend;
1281 usednew += ntoappend;
1282 assert(usednew <= totalnew);
1283 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1286 goto Done;
1287 {
1288 PyObject *format;
1289 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 if (time == NULL)
1292 goto Done;
1293 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1294 if (format != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001295 result = _PyObject_CallMethodId(time, &PyId_strftime, "OO",
1296 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 Py_DECREF(format);
1298 }
1299 Py_DECREF(time);
1300 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001301 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 Py_XDECREF(freplacement);
1303 Py_XDECREF(zreplacement);
1304 Py_XDECREF(Zreplacement);
1305 Py_XDECREF(newfmt);
1306 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001307}
1308
Tim Peters2a799bf2002-12-16 20:18:38 +00001309/* ---------------------------------------------------------------------------
1310 * Wrap functions from the time module. These aren't directly available
1311 * from C. Perhaps they should be.
1312 */
1313
1314/* Call time.time() and return its result (a Python float). */
1315static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001316time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 PyObject *result = NULL;
1319 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001322 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001323
1324 result = _PyObject_CallMethodId(time, &PyId_time, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 Py_DECREF(time);
1326 }
1327 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001328}
1329
1330/* Build a time.struct_time. The weekday and day number are automatically
1331 * computed from the y,m,d args.
1332 */
1333static PyObject *
1334build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyObject *time;
1337 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 time = PyImport_ImportModuleNoBlock("time");
1340 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001341 _Py_IDENTIFIER(struct_time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001342
1343 result = _PyObject_CallMethodId(time, &PyId_struct_time,
1344 "((iiiiiiiii))",
1345 y, m, d,
1346 hh, mm, ss,
1347 weekday(y, m, d),
1348 days_before_month(y, m) + d,
1349 dstflag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 Py_DECREF(time);
1351 }
1352 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001353}
1354
1355/* ---------------------------------------------------------------------------
1356 * Miscellaneous helpers.
1357 */
1358
Mark Dickinsone94c6792009-02-02 20:36:42 +00001359/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001360 * The comparisons here all most naturally compute a cmp()-like result.
1361 * This little helper turns that into a bool result for rich comparisons.
1362 */
1363static PyObject *
1364diff_to_bool(int diff, int op)
1365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 PyObject *result;
1367 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 switch (op) {
1370 case Py_EQ: istrue = diff == 0; break;
1371 case Py_NE: istrue = diff != 0; break;
1372 case Py_LE: istrue = diff <= 0; break;
1373 case Py_GE: istrue = diff >= 0; break;
1374 case Py_LT: istrue = diff < 0; break;
1375 case Py_GT: istrue = diff > 0; break;
1376 default:
1377 assert(! "op unknown");
1378 istrue = 0; /* To shut up compiler */
1379 }
1380 result = istrue ? Py_True : Py_False;
1381 Py_INCREF(result);
1382 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001383}
1384
Tim Peters07534a62003-02-07 22:50:28 +00001385/* Raises a "can't compare" TypeError and returns NULL. */
1386static PyObject *
1387cmperror(PyObject *a, PyObject *b)
1388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyErr_Format(PyExc_TypeError,
1390 "can't compare %s to %s",
1391 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1392 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001393}
1394
Tim Peters2a799bf2002-12-16 20:18:38 +00001395/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001396 * Cached Python objects; these are set by the module init function.
1397 */
1398
1399/* Conversion factors. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04001400static PyObject *one = NULL; /* 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401static PyObject *us_per_ms = NULL; /* 1000 */
1402static PyObject *us_per_second = NULL; /* 1000000 */
1403static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
Serhiy Storchaka95949422013-08-27 19:40:23 +03001404static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python int */
1405static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python int */
1406static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python int */
Tim Peters2a799bf2002-12-16 20:18:38 +00001407static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1408
Tim Peters2a799bf2002-12-16 20:18:38 +00001409/* ---------------------------------------------------------------------------
1410 * Class implementations.
1411 */
1412
1413/*
1414 * PyDateTime_Delta implementation.
1415 */
1416
1417/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Serhiy Storchaka95949422013-08-27 19:40:23 +03001419 * as a Python int.
Tim Peters2a799bf2002-12-16 20:18:38 +00001420 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1421 * due to ubiquitous overflow possibilities.
1422 */
1423static PyObject *
1424delta_to_microseconds(PyDateTime_Delta *self)
1425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 PyObject *x1 = NULL;
1427 PyObject *x2 = NULL;
1428 PyObject *x3 = NULL;
1429 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1432 if (x1 == NULL)
1433 goto Done;
1434 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1435 if (x2 == NULL)
1436 goto Done;
1437 Py_DECREF(x1);
1438 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 /* x2 has days in seconds */
1441 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1442 if (x1 == NULL)
1443 goto Done;
1444 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1445 if (x3 == NULL)
1446 goto Done;
1447 Py_DECREF(x1);
1448 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001449 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 /* x3 has days+seconds in seconds */
1452 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1453 if (x1 == NULL)
1454 goto Done;
1455 Py_DECREF(x3);
1456 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 /* x1 has days+seconds in us */
1459 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1460 if (x2 == NULL)
1461 goto Done;
1462 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001463
1464Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 Py_XDECREF(x1);
1466 Py_XDECREF(x2);
1467 Py_XDECREF(x3);
1468 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001469}
1470
Serhiy Storchaka95949422013-08-27 19:40:23 +03001471/* Convert a number of us (as a Python int) to a timedelta.
Tim Peters2a799bf2002-12-16 20:18:38 +00001472 */
1473static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001474microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 int us;
1477 int s;
1478 int d;
1479 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 PyObject *tuple = NULL;
1482 PyObject *num = NULL;
1483 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 tuple = PyNumber_Divmod(pyus, us_per_second);
1486 if (tuple == NULL)
1487 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 num = PyTuple_GetItem(tuple, 1); /* us */
1490 if (num == NULL)
1491 goto Done;
1492 temp = PyLong_AsLong(num);
1493 num = NULL;
1494 if (temp == -1 && PyErr_Occurred())
1495 goto Done;
1496 assert(0 <= temp && temp < 1000000);
1497 us = (int)temp;
1498 if (us < 0) {
1499 /* The divisor was positive, so this must be an error. */
1500 assert(PyErr_Occurred());
1501 goto Done;
1502 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1505 if (num == NULL)
1506 goto Done;
1507 Py_INCREF(num);
1508 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 tuple = PyNumber_Divmod(num, seconds_per_day);
1511 if (tuple == NULL)
1512 goto Done;
1513 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 num = PyTuple_GetItem(tuple, 1); /* seconds */
1516 if (num == NULL)
1517 goto Done;
1518 temp = PyLong_AsLong(num);
1519 num = NULL;
1520 if (temp == -1 && PyErr_Occurred())
1521 goto Done;
1522 assert(0 <= temp && temp < 24*3600);
1523 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (s < 0) {
1526 /* The divisor was positive, so this must be an error. */
1527 assert(PyErr_Occurred());
1528 goto Done;
1529 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1532 if (num == NULL)
1533 goto Done;
1534 Py_INCREF(num);
1535 temp = PyLong_AsLong(num);
1536 if (temp == -1 && PyErr_Occurred())
1537 goto Done;
1538 d = (int)temp;
1539 if ((long)d != temp) {
1540 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1541 "large to fit in a C int");
1542 goto Done;
1543 }
1544 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001545
1546Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 Py_XDECREF(tuple);
1548 Py_XDECREF(num);
1549 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001550}
1551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552#define microseconds_to_delta(pymicros) \
1553 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001554
Tim Peters2a799bf2002-12-16 20:18:38 +00001555static PyObject *
1556multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyObject *pyus_in;
1559 PyObject *pyus_out;
1560 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 pyus_in = delta_to_microseconds(delta);
1563 if (pyus_in == NULL)
1564 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1567 Py_DECREF(pyus_in);
1568 if (pyus_out == NULL)
1569 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 result = microseconds_to_delta(pyus_out);
1572 Py_DECREF(pyus_out);
1573 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001574}
1575
1576static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001577multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1578{
1579 PyObject *result = NULL;
1580 PyObject *pyus_in = NULL, *temp, *pyus_out;
1581 PyObject *ratio = NULL;
1582
1583 pyus_in = delta_to_microseconds(delta);
1584 if (pyus_in == NULL)
1585 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001586 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001587 if (ratio == NULL)
1588 goto error;
1589 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1590 Py_DECREF(pyus_in);
1591 pyus_in = NULL;
1592 if (temp == NULL)
1593 goto error;
1594 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1595 Py_DECREF(temp);
1596 if (pyus_out == NULL)
1597 goto error;
1598 result = microseconds_to_delta(pyus_out);
1599 Py_DECREF(pyus_out);
1600 error:
1601 Py_XDECREF(pyus_in);
1602 Py_XDECREF(ratio);
1603
1604 return result;
1605}
1606
1607static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001608divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 PyObject *pyus_in;
1611 PyObject *pyus_out;
1612 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 pyus_in = delta_to_microseconds(delta);
1615 if (pyus_in == NULL)
1616 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1619 Py_DECREF(pyus_in);
1620 if (pyus_out == NULL)
1621 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 result = microseconds_to_delta(pyus_out);
1624 Py_DECREF(pyus_out);
1625 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001626}
1627
1628static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001629divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 PyObject *pyus_left;
1632 PyObject *pyus_right;
1633 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 pyus_left = delta_to_microseconds(left);
1636 if (pyus_left == NULL)
1637 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 pyus_right = delta_to_microseconds(right);
1640 if (pyus_right == NULL) {
1641 Py_DECREF(pyus_left);
1642 return NULL;
1643 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1646 Py_DECREF(pyus_left);
1647 Py_DECREF(pyus_right);
1648 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001649}
1650
1651static PyObject *
1652truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 PyObject *pyus_left;
1655 PyObject *pyus_right;
1656 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 pyus_left = delta_to_microseconds(left);
1659 if (pyus_left == NULL)
1660 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 pyus_right = delta_to_microseconds(right);
1663 if (pyus_right == NULL) {
1664 Py_DECREF(pyus_left);
1665 return NULL;
1666 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1669 Py_DECREF(pyus_left);
1670 Py_DECREF(pyus_right);
1671 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001672}
1673
1674static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001675truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1676{
1677 PyObject *result = NULL;
1678 PyObject *pyus_in = NULL, *temp, *pyus_out;
1679 PyObject *ratio = NULL;
1680
1681 pyus_in = delta_to_microseconds(delta);
1682 if (pyus_in == NULL)
1683 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001684 ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001685 if (ratio == NULL)
1686 goto error;
1687 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1688 Py_DECREF(pyus_in);
1689 pyus_in = NULL;
1690 if (temp == NULL)
1691 goto error;
1692 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1693 Py_DECREF(temp);
1694 if (pyus_out == NULL)
1695 goto error;
1696 result = microseconds_to_delta(pyus_out);
1697 Py_DECREF(pyus_out);
1698 error:
1699 Py_XDECREF(pyus_in);
1700 Py_XDECREF(ratio);
1701
1702 return result;
1703}
1704
1705static PyObject *
1706truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1707{
1708 PyObject *result;
1709 PyObject *pyus_in, *pyus_out;
1710 pyus_in = delta_to_microseconds(delta);
1711 if (pyus_in == NULL)
1712 return NULL;
1713 pyus_out = divide_nearest(pyus_in, i);
1714 Py_DECREF(pyus_in);
1715 if (pyus_out == NULL)
1716 return NULL;
1717 result = microseconds_to_delta(pyus_out);
1718 Py_DECREF(pyus_out);
1719
1720 return result;
1721}
1722
1723static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001724delta_add(PyObject *left, PyObject *right)
1725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1729 /* delta + delta */
1730 /* The C-level additions can't overflow because of the
1731 * invariant bounds.
1732 */
1733 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1734 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1735 int microseconds = GET_TD_MICROSECONDS(left) +
1736 GET_TD_MICROSECONDS(right);
1737 result = new_delta(days, seconds, microseconds, 1);
1738 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (result == Py_NotImplemented)
1741 Py_INCREF(result);
1742 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001743}
1744
1745static PyObject *
1746delta_negative(PyDateTime_Delta *self)
1747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 return new_delta(-GET_TD_DAYS(self),
1749 -GET_TD_SECONDS(self),
1750 -GET_TD_MICROSECONDS(self),
1751 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001752}
1753
1754static PyObject *
1755delta_positive(PyDateTime_Delta *self)
1756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 /* Could optimize this (by returning self) if this isn't a
1758 * subclass -- but who uses unary + ? Approximately nobody.
1759 */
1760 return new_delta(GET_TD_DAYS(self),
1761 GET_TD_SECONDS(self),
1762 GET_TD_MICROSECONDS(self),
1763 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001764}
1765
1766static PyObject *
1767delta_abs(PyDateTime_Delta *self)
1768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 assert(GET_TD_MICROSECONDS(self) >= 0);
1772 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (GET_TD_DAYS(self) < 0)
1775 result = delta_negative(self);
1776 else
1777 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001780}
1781
1782static PyObject *
1783delta_subtract(PyObject *left, PyObject *right)
1784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1788 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04001789 /* The C-level additions can't overflow because of the
1790 * invariant bounds.
1791 */
1792 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1793 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1794 int microseconds = GET_TD_MICROSECONDS(left) -
1795 GET_TD_MICROSECONDS(right);
1796 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 if (result == Py_NotImplemented)
1800 Py_INCREF(result);
1801 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001802}
1803
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001804static int
1805delta_cmp(PyObject *self, PyObject *other)
1806{
1807 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1808 if (diff == 0) {
1809 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1810 if (diff == 0)
1811 diff = GET_TD_MICROSECONDS(self) -
1812 GET_TD_MICROSECONDS(other);
1813 }
1814 return diff;
1815}
1816
Tim Peters2a799bf2002-12-16 20:18:38 +00001817static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001818delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001821 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 return diff_to_bool(diff, op);
1823 }
1824 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05001825 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001827}
1828
1829static PyObject *delta_getstate(PyDateTime_Delta *self);
1830
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001831static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001832delta_hash(PyDateTime_Delta *self)
1833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (self->hashcode == -1) {
1835 PyObject *temp = delta_getstate(self);
1836 if (temp != NULL) {
1837 self->hashcode = PyObject_Hash(temp);
1838 Py_DECREF(temp);
1839 }
1840 }
1841 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001842}
1843
1844static PyObject *
1845delta_multiply(PyObject *left, PyObject *right)
1846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (PyDelta_Check(left)) {
1850 /* delta * ??? */
1851 if (PyLong_Check(right))
1852 result = multiply_int_timedelta(right,
1853 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001854 else if (PyFloat_Check(right))
1855 result = multiply_float_timedelta(right,
1856 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 }
1858 else if (PyLong_Check(left))
1859 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001860 (PyDateTime_Delta *) right);
1861 else if (PyFloat_Check(left))
1862 result = multiply_float_timedelta(left,
1863 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if (result == Py_NotImplemented)
1866 Py_INCREF(result);
1867 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001868}
1869
1870static PyObject *
1871delta_divide(PyObject *left, PyObject *right)
1872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 if (PyDelta_Check(left)) {
1876 /* delta * ??? */
1877 if (PyLong_Check(right))
1878 result = divide_timedelta_int(
1879 (PyDateTime_Delta *)left,
1880 right);
1881 else if (PyDelta_Check(right))
1882 result = divide_timedelta_timedelta(
1883 (PyDateTime_Delta *)left,
1884 (PyDateTime_Delta *)right);
1885 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (result == Py_NotImplemented)
1888 Py_INCREF(result);
1889 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001890}
1891
Mark Dickinson7c186e22010-04-20 22:32:49 +00001892static PyObject *
1893delta_truedivide(PyObject *left, PyObject *right)
1894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 if (PyDelta_Check(left)) {
1898 if (PyDelta_Check(right))
1899 result = truedivide_timedelta_timedelta(
1900 (PyDateTime_Delta *)left,
1901 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001902 else if (PyFloat_Check(right))
1903 result = truedivide_timedelta_float(
1904 (PyDateTime_Delta *)left, right);
1905 else if (PyLong_Check(right))
1906 result = truedivide_timedelta_int(
1907 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 if (result == Py_NotImplemented)
1911 Py_INCREF(result);
1912 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001913}
1914
1915static PyObject *
1916delta_remainder(PyObject *left, PyObject *right)
1917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 PyObject *pyus_left;
1919 PyObject *pyus_right;
1920 PyObject *pyus_remainder;
1921 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001922
Brian Curtindfc80e32011-08-10 20:28:54 -05001923 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1924 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1927 if (pyus_left == NULL)
1928 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1931 if (pyus_right == NULL) {
1932 Py_DECREF(pyus_left);
1933 return NULL;
1934 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
1937 Py_DECREF(pyus_left);
1938 Py_DECREF(pyus_right);
1939 if (pyus_remainder == NULL)
1940 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 remainder = microseconds_to_delta(pyus_remainder);
1943 Py_DECREF(pyus_remainder);
1944 if (remainder == NULL)
1945 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001948}
1949
1950static PyObject *
1951delta_divmod(PyObject *left, PyObject *right)
1952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 PyObject *pyus_left;
1954 PyObject *pyus_right;
1955 PyObject *divmod;
1956 PyObject *delta;
1957 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001958
Brian Curtindfc80e32011-08-10 20:28:54 -05001959 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1960 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1963 if (pyus_left == NULL)
1964 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1967 if (pyus_right == NULL) {
1968 Py_DECREF(pyus_left);
1969 return NULL;
1970 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 divmod = PyNumber_Divmod(pyus_left, pyus_right);
1973 Py_DECREF(pyus_left);
1974 Py_DECREF(pyus_right);
1975 if (divmod == NULL)
1976 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 assert(PyTuple_Size(divmod) == 2);
1979 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
1980 if (delta == NULL) {
1981 Py_DECREF(divmod);
1982 return NULL;
1983 }
1984 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
1985 Py_DECREF(delta);
1986 Py_DECREF(divmod);
1987 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001988}
1989
Tim Peters2a799bf2002-12-16 20:18:38 +00001990/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1991 * timedelta constructor. sofar is the # of microseconds accounted for
1992 * so far, and there are factor microseconds per current unit, the number
1993 * of which is given by num. num * factor is added to sofar in a
1994 * numerically careful way, and that's the result. Any fractional
1995 * microseconds left over (this can happen if num is a float type) are
1996 * added into *leftover.
1997 * Note that there are many ways this can give an error (NULL) return.
1998 */
1999static PyObject *
2000accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2001 double *leftover)
2002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PyObject *prod;
2004 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 if (PyLong_Check(num)) {
2009 prod = PyNumber_Multiply(num, factor);
2010 if (prod == NULL)
2011 return NULL;
2012 sum = PyNumber_Add(sofar, prod);
2013 Py_DECREF(prod);
2014 return sum;
2015 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if (PyFloat_Check(num)) {
2018 double dnum;
2019 double fracpart;
2020 double intpart;
2021 PyObject *x;
2022 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 /* The Plan: decompose num into an integer part and a
2025 * fractional part, num = intpart + fracpart.
2026 * Then num * factor ==
2027 * intpart * factor + fracpart * factor
2028 * and the LHS can be computed exactly in long arithmetic.
2029 * The RHS is again broken into an int part and frac part.
2030 * and the frac part is added into *leftover.
2031 */
2032 dnum = PyFloat_AsDouble(num);
2033 if (dnum == -1.0 && PyErr_Occurred())
2034 return NULL;
2035 fracpart = modf(dnum, &intpart);
2036 x = PyLong_FromDouble(intpart);
2037 if (x == NULL)
2038 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 prod = PyNumber_Multiply(x, factor);
2041 Py_DECREF(x);
2042 if (prod == NULL)
2043 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 sum = PyNumber_Add(sofar, prod);
2046 Py_DECREF(prod);
2047 if (sum == NULL)
2048 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (fracpart == 0.0)
2051 return sum;
2052 /* So far we've lost no information. Dealing with the
2053 * fractional part requires float arithmetic, and may
2054 * lose a little info.
2055 */
2056 assert(PyLong_Check(factor));
2057 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 dnum *= fracpart;
2060 fracpart = modf(dnum, &intpart);
2061 x = PyLong_FromDouble(intpart);
2062 if (x == NULL) {
2063 Py_DECREF(sum);
2064 return NULL;
2065 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 y = PyNumber_Add(sum, x);
2068 Py_DECREF(sum);
2069 Py_DECREF(x);
2070 *leftover += fracpart;
2071 return y;
2072 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyErr_Format(PyExc_TypeError,
2075 "unsupported type for timedelta %s component: %s",
2076 tag, Py_TYPE(num)->tp_name);
2077 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002078}
2079
2080static PyObject *
2081delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 /* Argument objects. */
2086 PyObject *day = NULL;
2087 PyObject *second = NULL;
2088 PyObject *us = NULL;
2089 PyObject *ms = NULL;
2090 PyObject *minute = NULL;
2091 PyObject *hour = NULL;
2092 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 PyObject *x = NULL; /* running sum of microseconds */
2095 PyObject *y = NULL; /* temp sum of microseconds */
2096 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 static char *keywords[] = {
2099 "days", "seconds", "microseconds", "milliseconds",
2100 "minutes", "hours", "weeks", NULL
2101 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2104 keywords,
2105 &day, &second, &us,
2106 &ms, &minute, &hour, &week) == 0)
2107 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 x = PyLong_FromLong(0);
2110 if (x == NULL)
2111 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113#define CLEANUP \
2114 Py_DECREF(x); \
2115 x = y; \
2116 if (x == NULL) \
2117 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 if (us) {
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002120 y = accum("microseconds", x, us, one, &leftover_us);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 CLEANUP;
2122 }
2123 if (ms) {
2124 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2125 CLEANUP;
2126 }
2127 if (second) {
2128 y = accum("seconds", x, second, us_per_second, &leftover_us);
2129 CLEANUP;
2130 }
2131 if (minute) {
2132 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2133 CLEANUP;
2134 }
2135 if (hour) {
2136 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2137 CLEANUP;
2138 }
2139 if (day) {
2140 y = accum("days", x, day, us_per_day, &leftover_us);
2141 CLEANUP;
2142 }
2143 if (week) {
2144 y = accum("weeks", x, week, us_per_week, &leftover_us);
2145 CLEANUP;
2146 }
2147 if (leftover_us) {
2148 /* Round to nearest whole # of us, and add into x. */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002149 double whole_us = round(leftover_us);
2150 int x_is_odd;
2151 PyObject *temp;
2152
2153 whole_us = round(leftover_us);
2154 if (fabs(whole_us - leftover_us) == 0.5) {
2155 /* We're exactly halfway between two integers. In order
2156 * to do round-half-to-even, we must determine whether x
2157 * is odd. Note that x is odd when it's last bit is 1. The
2158 * code below uses bitwise and operation to check the last
2159 * bit. */
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07002160 temp = PyNumber_And(x, one); /* temp <- x & 1 */
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002161 if (temp == NULL) {
2162 Py_DECREF(x);
2163 goto Done;
2164 }
2165 x_is_odd = PyObject_IsTrue(temp);
2166 Py_DECREF(temp);
2167 if (x_is_odd == -1) {
2168 Py_DECREF(x);
2169 goto Done;
2170 }
2171 whole_us = 2.0 * round((leftover_us + x_is_odd) * 0.5) - x_is_odd;
2172 }
2173
Victor Stinner36a5a062013-08-28 01:53:39 +02002174 temp = PyLong_FromLong((long)whole_us);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (temp == NULL) {
2177 Py_DECREF(x);
2178 goto Done;
2179 }
2180 y = PyNumber_Add(x, temp);
2181 Py_DECREF(temp);
2182 CLEANUP;
2183 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 self = microseconds_to_delta_ex(x, type);
2186 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002187Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002189
2190#undef CLEANUP
2191}
2192
2193static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002194delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 return (GET_TD_DAYS(self) != 0
2197 || GET_TD_SECONDS(self) != 0
2198 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002199}
2200
2201static PyObject *
2202delta_repr(PyDateTime_Delta *self)
2203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 if (GET_TD_MICROSECONDS(self) != 0)
2205 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2206 Py_TYPE(self)->tp_name,
2207 GET_TD_DAYS(self),
2208 GET_TD_SECONDS(self),
2209 GET_TD_MICROSECONDS(self));
2210 if (GET_TD_SECONDS(self) != 0)
2211 return PyUnicode_FromFormat("%s(%d, %d)",
2212 Py_TYPE(self)->tp_name,
2213 GET_TD_DAYS(self),
2214 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 return PyUnicode_FromFormat("%s(%d)",
2217 Py_TYPE(self)->tp_name,
2218 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002219}
2220
2221static PyObject *
2222delta_str(PyDateTime_Delta *self)
2223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 int us = GET_TD_MICROSECONDS(self);
2225 int seconds = GET_TD_SECONDS(self);
2226 int minutes = divmod(seconds, 60, &seconds);
2227 int hours = divmod(minutes, 60, &minutes);
2228 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 if (days) {
2231 if (us)
2232 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2233 days, (days == 1 || days == -1) ? "" : "s",
2234 hours, minutes, seconds, us);
2235 else
2236 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2237 days, (days == 1 || days == -1) ? "" : "s",
2238 hours, minutes, seconds);
2239 } else {
2240 if (us)
2241 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2242 hours, minutes, seconds, us);
2243 else
2244 return PyUnicode_FromFormat("%d:%02d:%02d",
2245 hours, minutes, seconds);
2246 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002247
Tim Peters2a799bf2002-12-16 20:18:38 +00002248}
2249
Tim Peters371935f2003-02-01 01:52:50 +00002250/* Pickle support, a simple use of __reduce__. */
2251
Tim Petersb57f8f02003-02-01 02:54:15 +00002252/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002253static PyObject *
2254delta_getstate(PyDateTime_Delta *self)
2255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 return Py_BuildValue("iii", GET_TD_DAYS(self),
2257 GET_TD_SECONDS(self),
2258 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002259}
2260
Tim Peters2a799bf2002-12-16 20:18:38 +00002261static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002262delta_total_seconds(PyObject *self)
2263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 PyObject *total_seconds;
2265 PyObject *total_microseconds;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2268 if (total_microseconds == NULL)
2269 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002270
Alexander Belopolskydf7027b2013-08-04 15:18:58 -04002271 total_seconds = PyNumber_TrueDivide(total_microseconds, us_per_second);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 Py_DECREF(total_microseconds);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002275}
2276
2277static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002278delta_reduce(PyDateTime_Delta* self)
2279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002281}
2282
2283#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2284
2285static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 {"days", T_INT, OFFSET(days), READONLY,
2288 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 {"seconds", T_INT, OFFSET(seconds), READONLY,
2291 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2294 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2295 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002296};
2297
2298static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2300 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2303 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002306};
2307
2308static char delta_doc[] =
2309PyDoc_STR("Difference between two datetime values.");
2310
2311static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 delta_add, /* nb_add */
2313 delta_subtract, /* nb_subtract */
2314 delta_multiply, /* nb_multiply */
2315 delta_remainder, /* nb_remainder */
2316 delta_divmod, /* nb_divmod */
2317 0, /* nb_power */
2318 (unaryfunc)delta_negative, /* nb_negative */
2319 (unaryfunc)delta_positive, /* nb_positive */
2320 (unaryfunc)delta_abs, /* nb_absolute */
2321 (inquiry)delta_bool, /* nb_bool */
2322 0, /*nb_invert*/
2323 0, /*nb_lshift*/
2324 0, /*nb_rshift*/
2325 0, /*nb_and*/
2326 0, /*nb_xor*/
2327 0, /*nb_or*/
2328 0, /*nb_int*/
2329 0, /*nb_reserved*/
2330 0, /*nb_float*/
2331 0, /*nb_inplace_add*/
2332 0, /*nb_inplace_subtract*/
2333 0, /*nb_inplace_multiply*/
2334 0, /*nb_inplace_remainder*/
2335 0, /*nb_inplace_power*/
2336 0, /*nb_inplace_lshift*/
2337 0, /*nb_inplace_rshift*/
2338 0, /*nb_inplace_and*/
2339 0, /*nb_inplace_xor*/
2340 0, /*nb_inplace_or*/
2341 delta_divide, /* nb_floor_divide */
2342 delta_truedivide, /* nb_true_divide */
2343 0, /* nb_inplace_floor_divide */
2344 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002345};
2346
2347static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 PyVarObject_HEAD_INIT(NULL, 0)
2349 "datetime.timedelta", /* tp_name */
2350 sizeof(PyDateTime_Delta), /* tp_basicsize */
2351 0, /* tp_itemsize */
2352 0, /* tp_dealloc */
2353 0, /* tp_print */
2354 0, /* tp_getattr */
2355 0, /* tp_setattr */
2356 0, /* tp_reserved */
2357 (reprfunc)delta_repr, /* tp_repr */
2358 &delta_as_number, /* tp_as_number */
2359 0, /* tp_as_sequence */
2360 0, /* tp_as_mapping */
2361 (hashfunc)delta_hash, /* tp_hash */
2362 0, /* tp_call */
2363 (reprfunc)delta_str, /* tp_str */
2364 PyObject_GenericGetAttr, /* tp_getattro */
2365 0, /* tp_setattro */
2366 0, /* tp_as_buffer */
2367 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2368 delta_doc, /* tp_doc */
2369 0, /* tp_traverse */
2370 0, /* tp_clear */
2371 delta_richcompare, /* tp_richcompare */
2372 0, /* tp_weaklistoffset */
2373 0, /* tp_iter */
2374 0, /* tp_iternext */
2375 delta_methods, /* tp_methods */
2376 delta_members, /* tp_members */
2377 0, /* tp_getset */
2378 0, /* tp_base */
2379 0, /* tp_dict */
2380 0, /* tp_descr_get */
2381 0, /* tp_descr_set */
2382 0, /* tp_dictoffset */
2383 0, /* tp_init */
2384 0, /* tp_alloc */
2385 delta_new, /* tp_new */
2386 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002387};
2388
2389/*
2390 * PyDateTime_Date implementation.
2391 */
2392
2393/* Accessor properties. */
2394
2395static PyObject *
2396date_year(PyDateTime_Date *self, void *unused)
2397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002399}
2400
2401static PyObject *
2402date_month(PyDateTime_Date *self, void *unused)
2403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002405}
2406
2407static PyObject *
2408date_day(PyDateTime_Date *self, void *unused)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002411}
2412
2413static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 {"year", (getter)date_year},
2415 {"month", (getter)date_month},
2416 {"day", (getter)date_day},
2417 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002418};
2419
2420/* Constructors. */
2421
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002422static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002423
Tim Peters2a799bf2002-12-16 20:18:38 +00002424static PyObject *
2425date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 PyObject *self = NULL;
2428 PyObject *state;
2429 int year;
2430 int month;
2431 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 /* Check for invocation from pickle with __getstate__ state */
2434 if (PyTuple_GET_SIZE(args) == 1 &&
2435 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2436 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2437 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2438 {
2439 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2442 if (me != NULL) {
2443 char *pdata = PyBytes_AS_STRING(state);
2444 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2445 me->hashcode = -1;
2446 }
2447 return (PyObject *)me;
2448 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2451 &year, &month, &day)) {
2452 if (check_date_args(year, month, day) < 0)
2453 return NULL;
2454 self = new_date_ex(year, month, day, type);
2455 }
2456 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002457}
2458
2459/* Return new date from localtime(t). */
2460static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002461date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 struct tm *tm;
2464 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002465
Victor Stinnere4a994d2015-03-30 01:10:14 +02002466 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 tm = localtime(&t);
Victor Stinner21f58932012-03-14 00:15:40 +01002470 if (tm == NULL) {
2471 /* unconvertible time */
2472#ifdef EINVAL
2473 if (errno == 0)
2474 errno = EINVAL;
2475#endif
2476 PyErr_SetFromErrno(PyExc_OSError);
2477 return NULL;
2478 }
2479
2480 return PyObject_CallFunction(cls, "iii",
2481 tm->tm_year + 1900,
2482 tm->tm_mon + 1,
2483 tm->tm_mday);
Tim Peters2a799bf2002-12-16 20:18:38 +00002484}
2485
2486/* Return new date from current time.
2487 * We say this is equivalent to fromtimestamp(time.time()), and the
2488 * only way to be sure of that is to *call* time.time(). That's not
2489 * generally the same as calling C's time.
2490 */
2491static PyObject *
2492date_today(PyObject *cls, PyObject *dummy)
2493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 PyObject *time;
2495 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002496 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 time = time_time();
2499 if (time == NULL)
2500 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* Note well: today() is a class method, so this may not call
2503 * date.fromtimestamp. For example, it may call
2504 * datetime.fromtimestamp. That's why we need all the accuracy
2505 * time.time() delivers; if someone were gonzo about optimization,
2506 * date.today() could get away with plain C time().
2507 */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002508 result = _PyObject_CallMethodId(cls, &PyId_fromtimestamp, "O", time);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 Py_DECREF(time);
2510 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002511}
2512
2513/* Return new date from given timestamp (Python timestamp -- a double). */
2514static PyObject *
2515date_fromtimestamp(PyObject *cls, PyObject *args)
2516{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002517 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002519
Victor Stinner5d272cc2012-03-13 13:35:55 +01002520 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2521 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002523}
2524
2525/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2526 * the ordinal is out of range.
2527 */
2528static PyObject *
2529date_fromordinal(PyObject *cls, PyObject *args)
2530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 PyObject *result = NULL;
2532 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2535 int year;
2536 int month;
2537 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (ordinal < 1)
2540 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2541 ">= 1");
2542 else {
2543 ord_to_ymd(ordinal, &year, &month, &day);
2544 result = PyObject_CallFunction(cls, "iii",
2545 year, month, day);
2546 }
2547 }
2548 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002549}
2550
2551/*
2552 * Date arithmetic.
2553 */
2554
2555/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2556 * instead.
2557 */
2558static PyObject *
2559add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 PyObject *result = NULL;
2562 int year = GET_YEAR(date);
2563 int month = GET_MONTH(date);
2564 int deltadays = GET_TD_DAYS(delta);
2565 /* C-level overflow is impossible because |deltadays| < 1e9. */
2566 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 if (normalize_date(&year, &month, &day) >= 0)
2569 result = new_date(year, month, day);
2570 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002571}
2572
2573static PyObject *
2574date_add(PyObject *left, PyObject *right)
2575{
Brian Curtindfc80e32011-08-10 20:28:54 -05002576 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2577 Py_RETURN_NOTIMPLEMENTED;
2578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 if (PyDate_Check(left)) {
2580 /* date + ??? */
2581 if (PyDelta_Check(right))
2582 /* date + delta */
2583 return add_date_timedelta((PyDateTime_Date *) left,
2584 (PyDateTime_Delta *) right,
2585 0);
2586 }
2587 else {
2588 /* ??? + date
2589 * 'right' must be one of us, or we wouldn't have been called
2590 */
2591 if (PyDelta_Check(left))
2592 /* delta + date */
2593 return add_date_timedelta((PyDateTime_Date *) right,
2594 (PyDateTime_Delta *) left,
2595 0);
2596 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002597 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002598}
2599
2600static PyObject *
2601date_subtract(PyObject *left, PyObject *right)
2602{
Brian Curtindfc80e32011-08-10 20:28:54 -05002603 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2604 Py_RETURN_NOTIMPLEMENTED;
2605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 if (PyDate_Check(left)) {
2607 if (PyDate_Check(right)) {
2608 /* date - date */
2609 int left_ord = ymd_to_ord(GET_YEAR(left),
2610 GET_MONTH(left),
2611 GET_DAY(left));
2612 int right_ord = ymd_to_ord(GET_YEAR(right),
2613 GET_MONTH(right),
2614 GET_DAY(right));
2615 return new_delta(left_ord - right_ord, 0, 0, 0);
2616 }
2617 if (PyDelta_Check(right)) {
2618 /* date - delta */
2619 return add_date_timedelta((PyDateTime_Date *) left,
2620 (PyDateTime_Delta *) right,
2621 1);
2622 }
2623 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002624 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002625}
2626
2627
2628/* Various ways to turn a date into a string. */
2629
2630static PyObject *
2631date_repr(PyDateTime_Date *self)
2632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2634 Py_TYPE(self)->tp_name,
2635 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002636}
2637
2638static PyObject *
2639date_isoformat(PyDateTime_Date *self)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 return PyUnicode_FromFormat("%04d-%02d-%02d",
2642 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002643}
2644
Tim Peterse2df5ff2003-05-02 18:39:55 +00002645/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002646static PyObject *
2647date_str(PyDateTime_Date *self)
2648{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002649 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002650}
2651
2652
2653static PyObject *
2654date_ctime(PyDateTime_Date *self)
2655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002657}
2658
2659static PyObject *
2660date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 /* This method can be inherited, and needs to call the
2663 * timetuple() method appropriate to self's class.
2664 */
2665 PyObject *result;
2666 PyObject *tuple;
2667 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002668 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2672 &format))
2673 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002674
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002675 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 if (tuple == NULL)
2677 return NULL;
2678 result = wrap_strftime((PyObject *)self, format, tuple,
2679 (PyObject *)self);
2680 Py_DECREF(tuple);
2681 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002682}
2683
Eric Smith1ba31142007-09-11 18:06:02 +00002684static PyObject *
2685date_format(PyDateTime_Date *self, PyObject *args)
2686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2690 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002693 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002695
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002696 return _PyObject_CallMethodId((PyObject *)self, &PyId_strftime, "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002697}
2698
Tim Peters2a799bf2002-12-16 20:18:38 +00002699/* ISO methods. */
2700
2701static PyObject *
2702date_isoweekday(PyDateTime_Date *self)
2703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002707}
2708
2709static PyObject *
2710date_isocalendar(PyDateTime_Date *self)
2711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 int year = GET_YEAR(self);
2713 int week1_monday = iso_week1_monday(year);
2714 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2715 int week;
2716 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 week = divmod(today - week1_monday, 7, &day);
2719 if (week < 0) {
2720 --year;
2721 week1_monday = iso_week1_monday(year);
2722 week = divmod(today - week1_monday, 7, &day);
2723 }
2724 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2725 ++year;
2726 week = 0;
2727 }
2728 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002729}
2730
2731/* Miscellaneous methods. */
2732
Tim Peters2a799bf2002-12-16 20:18:38 +00002733static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002734date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 if (PyDate_Check(other)) {
2737 int diff = memcmp(((PyDateTime_Date *)self)->data,
2738 ((PyDateTime_Date *)other)->data,
2739 _PyDateTime_DATE_DATASIZE);
2740 return diff_to_bool(diff, op);
2741 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002742 else
2743 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002744}
2745
2746static PyObject *
2747date_timetuple(PyDateTime_Date *self)
2748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 return build_struct_time(GET_YEAR(self),
2750 GET_MONTH(self),
2751 GET_DAY(self),
2752 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002753}
2754
Tim Peters12bf3392002-12-24 05:41:27 +00002755static PyObject *
2756date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 PyObject *clone;
2759 PyObject *tuple;
2760 int year = GET_YEAR(self);
2761 int month = GET_MONTH(self);
2762 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2765 &year, &month, &day))
2766 return NULL;
2767 tuple = Py_BuildValue("iii", year, month, day);
2768 if (tuple == NULL)
2769 return NULL;
2770 clone = date_new(Py_TYPE(self), tuple, NULL);
2771 Py_DECREF(tuple);
2772 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002773}
2774
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002775static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002776generic_hash(unsigned char *data, int len)
2777{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002778 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002779}
2780
2781
2782static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002783
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002784static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002785date_hash(PyDateTime_Date *self)
2786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 if (self->hashcode == -1)
2788 self->hashcode = generic_hash(
2789 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002792}
2793
2794static PyObject *
2795date_toordinal(PyDateTime_Date *self)
2796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2798 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002799}
2800
2801static PyObject *
2802date_weekday(PyDateTime_Date *self)
2803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002807}
2808
Tim Peters371935f2003-02-01 01:52:50 +00002809/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002810
Tim Petersb57f8f02003-02-01 02:54:15 +00002811/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002812static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002813date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 PyObject* field;
2816 field = PyBytes_FromStringAndSize((char*)self->data,
2817 _PyDateTime_DATE_DATASIZE);
2818 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002819}
2820
2821static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002822date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002825}
2826
2827static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2832 METH_CLASS,
2833 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2834 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2837 METH_CLASS,
2838 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2839 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2842 PyDoc_STR("Current date or datetime: same as "
2843 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2848 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2851 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2854 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2857 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2860 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2861 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2864 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2867 PyDoc_STR("Return the day of the week represented by the date.\n"
2868 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2871 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2872 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2875 PyDoc_STR("Return the day of the week represented by the date.\n"
2876 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2879 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2882 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002885};
2886
2887static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002888PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002889
2890static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 date_add, /* nb_add */
2892 date_subtract, /* nb_subtract */
2893 0, /* nb_multiply */
2894 0, /* nb_remainder */
2895 0, /* nb_divmod */
2896 0, /* nb_power */
2897 0, /* nb_negative */
2898 0, /* nb_positive */
2899 0, /* nb_absolute */
2900 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002901};
2902
2903static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 PyVarObject_HEAD_INIT(NULL, 0)
2905 "datetime.date", /* tp_name */
2906 sizeof(PyDateTime_Date), /* tp_basicsize */
2907 0, /* tp_itemsize */
2908 0, /* tp_dealloc */
2909 0, /* tp_print */
2910 0, /* tp_getattr */
2911 0, /* tp_setattr */
2912 0, /* tp_reserved */
2913 (reprfunc)date_repr, /* tp_repr */
2914 &date_as_number, /* tp_as_number */
2915 0, /* tp_as_sequence */
2916 0, /* tp_as_mapping */
2917 (hashfunc)date_hash, /* tp_hash */
2918 0, /* tp_call */
2919 (reprfunc)date_str, /* tp_str */
2920 PyObject_GenericGetAttr, /* tp_getattro */
2921 0, /* tp_setattro */
2922 0, /* tp_as_buffer */
2923 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2924 date_doc, /* tp_doc */
2925 0, /* tp_traverse */
2926 0, /* tp_clear */
2927 date_richcompare, /* tp_richcompare */
2928 0, /* tp_weaklistoffset */
2929 0, /* tp_iter */
2930 0, /* tp_iternext */
2931 date_methods, /* tp_methods */
2932 0, /* tp_members */
2933 date_getset, /* tp_getset */
2934 0, /* tp_base */
2935 0, /* tp_dict */
2936 0, /* tp_descr_get */
2937 0, /* tp_descr_set */
2938 0, /* tp_dictoffset */
2939 0, /* tp_init */
2940 0, /* tp_alloc */
2941 date_new, /* tp_new */
2942 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002943};
2944
2945/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002946 * PyDateTime_TZInfo implementation.
2947 */
2948
2949/* This is a pure abstract base class, so doesn't do anything beyond
2950 * raising NotImplemented exceptions. Real tzinfo classes need
2951 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002952 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002953 * be subclasses of this tzinfo class, which is easy and quick to check).
2954 *
2955 * Note: For reasons having to do with pickling of subclasses, we have
2956 * to allow tzinfo objects to be instantiated. This wasn't an issue
2957 * in the Python implementation (__init__() could raise NotImplementedError
2958 * there without ill effect), but doing so in the C implementation hit a
2959 * brick wall.
2960 */
2961
2962static PyObject *
2963tzinfo_nogo(const char* methodname)
2964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 PyErr_Format(PyExc_NotImplementedError,
2966 "a tzinfo subclass must implement %s()",
2967 methodname);
2968 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002969}
2970
2971/* Methods. A subclass must implement these. */
2972
Tim Peters52dcce22003-01-23 16:36:11 +00002973static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002974tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002977}
2978
Tim Peters52dcce22003-01-23 16:36:11 +00002979static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002980tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002983}
2984
Tim Peters52dcce22003-01-23 16:36:11 +00002985static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002986tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00002989}
2990
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002991
2992static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
2993 PyDateTime_Delta *delta,
2994 int factor);
2995static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
2996static PyObject *datetime_dst(PyObject *self, PyObject *);
2997
Tim Peters52dcce22003-01-23 16:36:11 +00002998static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002999tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003000{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003001 PyObject *result = NULL;
3002 PyObject *off = NULL, *dst = NULL;
3003 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003004
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003005 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 PyErr_SetString(PyExc_TypeError,
3007 "fromutc: argument must be a datetime");
3008 return NULL;
3009 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003010 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3012 "is not self");
3013 return NULL;
3014 }
Tim Peters52dcce22003-01-23 16:36:11 +00003015
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003016 off = datetime_utcoffset(dt, NULL);
3017 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003019 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3021 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003022 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 }
Tim Peters52dcce22003-01-23 16:36:11 +00003024
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003025 dst = datetime_dst(dt, NULL);
3026 if (dst == NULL)
3027 goto Fail;
3028 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3030 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003031 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 }
Tim Peters52dcce22003-01-23 16:36:11 +00003033
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003034 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3035 if (delta == NULL)
3036 goto Fail;
3037 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003040
3041 Py_DECREF(dst);
3042 dst = call_dst(GET_DT_TZINFO(dt), result);
3043 if (dst == NULL)
3044 goto Fail;
3045 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 goto Inconsistent;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003047 if (delta_bool(delta) != 0) {
3048 PyObject *temp = result;
3049 result = add_datetime_timedelta((PyDateTime_DateTime *)result,
3050 (PyDateTime_Delta *)dst, 1);
3051 Py_DECREF(temp);
3052 if (result == NULL)
3053 goto Fail;
3054 }
3055 Py_DECREF(delta);
3056 Py_DECREF(dst);
3057 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003059
3060Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3062 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003065Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003066 Py_XDECREF(off);
3067 Py_XDECREF(dst);
3068 Py_XDECREF(delta);
3069 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003071}
3072
Tim Peters2a799bf2002-12-16 20:18:38 +00003073/*
3074 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003075 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003076 */
3077
Guido van Rossum177e41a2003-01-30 22:06:23 +00003078static PyObject *
3079tzinfo_reduce(PyObject *self)
3080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 PyObject *args, *state, *tmp;
3082 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003083 _Py_IDENTIFIER(__getinitargs__);
3084 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 tmp = PyTuple_New(0);
3087 if (tmp == NULL)
3088 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003089
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003090 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 if (getinitargs != NULL) {
3092 args = PyObject_CallObject(getinitargs, tmp);
3093 Py_DECREF(getinitargs);
3094 if (args == NULL) {
3095 Py_DECREF(tmp);
3096 return NULL;
3097 }
3098 }
3099 else {
3100 PyErr_Clear();
3101 args = tmp;
3102 Py_INCREF(args);
3103 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003104
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003105 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 if (getstate != NULL) {
3107 state = PyObject_CallObject(getstate, tmp);
3108 Py_DECREF(getstate);
3109 if (state == NULL) {
3110 Py_DECREF(args);
3111 Py_DECREF(tmp);
3112 return NULL;
3113 }
3114 }
3115 else {
3116 PyObject **dictptr;
3117 PyErr_Clear();
3118 state = Py_None;
3119 dictptr = _PyObject_GetDictPtr(self);
3120 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3121 state = *dictptr;
3122 Py_INCREF(state);
3123 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 if (state == Py_None) {
3128 Py_DECREF(state);
3129 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3130 }
3131 else
3132 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003133}
Tim Peters2a799bf2002-12-16 20:18:38 +00003134
3135static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3138 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003141 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3142 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3145 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003148 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3151 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003154};
3155
3156static char tzinfo_doc[] =
3157PyDoc_STR("Abstract base class for time zone info objects.");
3158
Neal Norwitz227b5332006-03-22 09:28:35 +00003159static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 PyVarObject_HEAD_INIT(NULL, 0)
3161 "datetime.tzinfo", /* tp_name */
3162 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3163 0, /* tp_itemsize */
3164 0, /* tp_dealloc */
3165 0, /* tp_print */
3166 0, /* tp_getattr */
3167 0, /* tp_setattr */
3168 0, /* tp_reserved */
3169 0, /* tp_repr */
3170 0, /* tp_as_number */
3171 0, /* tp_as_sequence */
3172 0, /* tp_as_mapping */
3173 0, /* tp_hash */
3174 0, /* tp_call */
3175 0, /* tp_str */
3176 PyObject_GenericGetAttr, /* tp_getattro */
3177 0, /* tp_setattro */
3178 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003179 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 tzinfo_doc, /* tp_doc */
3181 0, /* tp_traverse */
3182 0, /* tp_clear */
3183 0, /* tp_richcompare */
3184 0, /* tp_weaklistoffset */
3185 0, /* tp_iter */
3186 0, /* tp_iternext */
3187 tzinfo_methods, /* tp_methods */
3188 0, /* tp_members */
3189 0, /* tp_getset */
3190 0, /* tp_base */
3191 0, /* tp_dict */
3192 0, /* tp_descr_get */
3193 0, /* tp_descr_set */
3194 0, /* tp_dictoffset */
3195 0, /* tp_init */
3196 0, /* tp_alloc */
3197 PyType_GenericNew, /* tp_new */
3198 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003199};
3200
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003201static char *timezone_kws[] = {"offset", "name", NULL};
3202
3203static PyObject *
3204timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3205{
3206 PyObject *offset;
3207 PyObject *name = NULL;
3208 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
3209 &PyDateTime_DeltaType, &offset,
3210 &PyUnicode_Type, &name))
3211 return new_timezone(offset, name);
3212
3213 return NULL;
3214}
3215
3216static void
3217timezone_dealloc(PyDateTime_TimeZone *self)
3218{
3219 Py_CLEAR(self->offset);
3220 Py_CLEAR(self->name);
3221 Py_TYPE(self)->tp_free((PyObject *)self);
3222}
3223
3224static PyObject *
3225timezone_richcompare(PyDateTime_TimeZone *self,
3226 PyDateTime_TimeZone *other, int op)
3227{
Brian Curtindfc80e32011-08-10 20:28:54 -05003228 if (op != Py_EQ && op != Py_NE)
3229 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003230 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07003231 if (op == Py_EQ)
3232 Py_RETURN_FALSE;
3233 else
3234 Py_RETURN_TRUE;
Georg Brandl0085a242012-09-22 09:23:12 +02003235 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003236 return delta_richcompare(self->offset, other->offset, op);
3237}
3238
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003239static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003240timezone_hash(PyDateTime_TimeZone *self)
3241{
3242 return delta_hash((PyDateTime_Delta *)self->offset);
3243}
3244
3245/* Check argument type passed to tzname, utcoffset, or dst methods.
3246 Returns 0 for good argument. Returns -1 and sets exception info
3247 otherwise.
3248 */
3249static int
3250_timezone_check_argument(PyObject *dt, const char *meth)
3251{
3252 if (dt == Py_None || PyDateTime_Check(dt))
3253 return 0;
3254 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3255 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3256 return -1;
3257}
3258
3259static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003260timezone_repr(PyDateTime_TimeZone *self)
3261{
3262 /* Note that although timezone is not subclassable, it is convenient
3263 to use Py_TYPE(self)->tp_name here. */
3264 const char *type_name = Py_TYPE(self)->tp_name;
3265
3266 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3267 return PyUnicode_FromFormat("%s.utc", type_name);
3268
3269 if (self->name == NULL)
3270 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3271
3272 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3273 self->name);
3274}
3275
3276
3277static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003278timezone_str(PyDateTime_TimeZone *self)
3279{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003280 int hours, minutes, seconds;
3281 PyObject *offset;
3282 char sign;
3283
3284 if (self->name != NULL) {
3285 Py_INCREF(self->name);
3286 return self->name;
3287 }
3288 /* Offset is normalized, so it is negative if days < 0 */
3289 if (GET_TD_DAYS(self->offset) < 0) {
3290 sign = '-';
3291 offset = delta_negative((PyDateTime_Delta *)self->offset);
3292 if (offset == NULL)
3293 return NULL;
3294 }
3295 else {
3296 sign = '+';
3297 offset = self->offset;
3298 Py_INCREF(offset);
3299 }
3300 /* Offset is not negative here. */
3301 seconds = GET_TD_SECONDS(offset);
3302 Py_DECREF(offset);
3303 minutes = divmod(seconds, 60, &seconds);
3304 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003305 /* XXX ignore sub-minute data, curently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003306 assert(seconds == 0);
3307 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003308}
3309
3310static PyObject *
3311timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3312{
3313 if (_timezone_check_argument(dt, "tzname") == -1)
3314 return NULL;
3315
3316 return timezone_str(self);
3317}
3318
3319static PyObject *
3320timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3321{
3322 if (_timezone_check_argument(dt, "utcoffset") == -1)
3323 return NULL;
3324
3325 Py_INCREF(self->offset);
3326 return self->offset;
3327}
3328
3329static PyObject *
3330timezone_dst(PyObject *self, PyObject *dt)
3331{
3332 if (_timezone_check_argument(dt, "dst") == -1)
3333 return NULL;
3334
3335 Py_RETURN_NONE;
3336}
3337
3338static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003339timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3340{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003341 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003342 PyErr_SetString(PyExc_TypeError,
3343 "fromutc: argument must be a datetime");
3344 return NULL;
3345 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003346 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003347 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3348 "is not self");
3349 return NULL;
3350 }
3351
3352 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3353}
3354
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003355static PyObject *
3356timezone_getinitargs(PyDateTime_TimeZone *self)
3357{
3358 if (self->name == NULL)
3359 return Py_BuildValue("(O)", self->offset);
3360 return Py_BuildValue("(OO)", self->offset, self->name);
3361}
3362
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003363static PyMethodDef timezone_methods[] = {
3364 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3365 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003366 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003367
3368 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003369 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003370
3371 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003372 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003373
3374 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3375 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3376
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003377 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3378 PyDoc_STR("pickle support")},
3379
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003380 {NULL, NULL}
3381};
3382
3383static char timezone_doc[] =
3384PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3385
3386static PyTypeObject PyDateTime_TimeZoneType = {
3387 PyVarObject_HEAD_INIT(NULL, 0)
3388 "datetime.timezone", /* tp_name */
3389 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3390 0, /* tp_itemsize */
3391 (destructor)timezone_dealloc, /* tp_dealloc */
3392 0, /* tp_print */
3393 0, /* tp_getattr */
3394 0, /* tp_setattr */
3395 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003396 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003397 0, /* tp_as_number */
3398 0, /* tp_as_sequence */
3399 0, /* tp_as_mapping */
3400 (hashfunc)timezone_hash, /* tp_hash */
3401 0, /* tp_call */
3402 (reprfunc)timezone_str, /* tp_str */
3403 0, /* tp_getattro */
3404 0, /* tp_setattro */
3405 0, /* tp_as_buffer */
3406 Py_TPFLAGS_DEFAULT, /* tp_flags */
3407 timezone_doc, /* tp_doc */
3408 0, /* tp_traverse */
3409 0, /* tp_clear */
3410 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3411 0, /* tp_weaklistoffset */
3412 0, /* tp_iter */
3413 0, /* tp_iternext */
3414 timezone_methods, /* tp_methods */
3415 0, /* tp_members */
3416 0, /* tp_getset */
3417 &PyDateTime_TZInfoType, /* tp_base */
3418 0, /* tp_dict */
3419 0, /* tp_descr_get */
3420 0, /* tp_descr_set */
3421 0, /* tp_dictoffset */
3422 0, /* tp_init */
3423 0, /* tp_alloc */
3424 timezone_new, /* tp_new */
3425};
3426
Tim Peters2a799bf2002-12-16 20:18:38 +00003427/*
Tim Peters37f39822003-01-10 03:49:02 +00003428 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003429 */
3430
Tim Peters37f39822003-01-10 03:49:02 +00003431/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003432 */
3433
3434static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003435time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003438}
3439
Tim Peters37f39822003-01-10 03:49:02 +00003440static PyObject *
3441time_minute(PyDateTime_Time *self, void *unused)
3442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003444}
3445
3446/* The name time_second conflicted with some platform header file. */
3447static PyObject *
3448py_time_second(PyDateTime_Time *self, void *unused)
3449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003451}
3452
3453static PyObject *
3454time_microsecond(PyDateTime_Time *self, void *unused)
3455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003457}
3458
3459static PyObject *
3460time_tzinfo(PyDateTime_Time *self, void *unused)
3461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3463 Py_INCREF(result);
3464 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003465}
3466
3467static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 {"hour", (getter)time_hour},
3469 {"minute", (getter)time_minute},
3470 {"second", (getter)py_time_second},
3471 {"microsecond", (getter)time_microsecond},
3472 {"tzinfo", (getter)time_tzinfo},
3473 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003474};
3475
3476/*
3477 * Constructors.
3478 */
3479
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003480static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003482
Tim Peters2a799bf2002-12-16 20:18:38 +00003483static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003484time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 PyObject *self = NULL;
3487 PyObject *state;
3488 int hour = 0;
3489 int minute = 0;
3490 int second = 0;
3491 int usecond = 0;
3492 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 /* Check for invocation from pickle with __getstate__ state */
3495 if (PyTuple_GET_SIZE(args) >= 1 &&
3496 PyTuple_GET_SIZE(args) <= 2 &&
3497 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3498 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3499 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
3500 {
3501 PyDateTime_Time *me;
3502 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 if (PyTuple_GET_SIZE(args) == 2) {
3505 tzinfo = PyTuple_GET_ITEM(args, 1);
3506 if (check_tzinfo_subclass(tzinfo) < 0) {
3507 PyErr_SetString(PyExc_TypeError, "bad "
3508 "tzinfo state arg");
3509 return NULL;
3510 }
3511 }
3512 aware = (char)(tzinfo != Py_None);
3513 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3514 if (me != NULL) {
3515 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3518 me->hashcode = -1;
3519 me->hastzinfo = aware;
3520 if (aware) {
3521 Py_INCREF(tzinfo);
3522 me->tzinfo = tzinfo;
3523 }
3524 }
3525 return (PyObject *)me;
3526 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3529 &hour, &minute, &second, &usecond,
3530 &tzinfo)) {
3531 if (check_time_args(hour, minute, second, usecond) < 0)
3532 return NULL;
3533 if (check_tzinfo_subclass(tzinfo) < 0)
3534 return NULL;
3535 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3536 type);
3537 }
3538 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003539}
3540
3541/*
3542 * Destructor.
3543 */
3544
3545static void
Tim Peters37f39822003-01-10 03:49:02 +00003546time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 if (HASTZINFO(self)) {
3549 Py_XDECREF(self->tzinfo);
3550 }
3551 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003552}
3553
3554/*
Tim Peters855fe882002-12-22 03:43:39 +00003555 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003556 */
3557
Tim Peters2a799bf2002-12-16 20:18:38 +00003558/* These are all METH_NOARGS, so don't need to check the arglist. */
3559static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003560time_utcoffset(PyObject *self, PyObject *unused) {
3561 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003562}
3563
3564static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003565time_dst(PyObject *self, PyObject *unused) {
3566 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003567}
3568
3569static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003570time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003571 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003572}
3573
3574/*
Tim Peters37f39822003-01-10 03:49:02 +00003575 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003576 */
3577
3578static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003579time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 const char *type_name = Py_TYPE(self)->tp_name;
3582 int h = TIME_GET_HOUR(self);
3583 int m = TIME_GET_MINUTE(self);
3584 int s = TIME_GET_SECOND(self);
3585 int us = TIME_GET_MICROSECOND(self);
3586 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 if (us)
3589 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3590 type_name, h, m, s, us);
3591 else if (s)
3592 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3593 type_name, h, m, s);
3594 else
3595 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3596 if (result != NULL && HASTZINFO(self))
3597 result = append_keyword_tzinfo(result, self->tzinfo);
3598 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003599}
3600
Tim Peters37f39822003-01-10 03:49:02 +00003601static PyObject *
3602time_str(PyDateTime_Time *self)
3603{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003604 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters37f39822003-01-10 03:49:02 +00003605}
Tim Peters2a799bf2002-12-16 20:18:38 +00003606
3607static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003608time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 char buf[100];
3611 PyObject *result;
Ezio Melotti3f5db392013-01-27 06:20:14 +02003612 int us = TIME_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 if (us)
3615 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3616 TIME_GET_HOUR(self),
3617 TIME_GET_MINUTE(self),
3618 TIME_GET_SECOND(self),
3619 us);
3620 else
3621 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3622 TIME_GET_HOUR(self),
3623 TIME_GET_MINUTE(self),
3624 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003625
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003626 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 /* We need to append the UTC offset. */
3630 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3631 Py_None) < 0) {
3632 Py_DECREF(result);
3633 return NULL;
3634 }
3635 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3636 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003637}
3638
Tim Peters37f39822003-01-10 03:49:02 +00003639static PyObject *
3640time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 PyObject *result;
3643 PyObject *tuple;
3644 PyObject *format;
3645 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3648 &format))
3649 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 /* Python's strftime does insane things with the year part of the
3652 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003653 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 */
3655 tuple = Py_BuildValue("iiiiiiiii",
3656 1900, 1, 1, /* year, month, day */
3657 TIME_GET_HOUR(self),
3658 TIME_GET_MINUTE(self),
3659 TIME_GET_SECOND(self),
3660 0, 1, -1); /* weekday, daynum, dst */
3661 if (tuple == NULL)
3662 return NULL;
3663 assert(PyTuple_Size(tuple) == 9);
3664 result = wrap_strftime((PyObject *)self, format, tuple,
3665 Py_None);
3666 Py_DECREF(tuple);
3667 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003668}
Tim Peters2a799bf2002-12-16 20:18:38 +00003669
3670/*
3671 * Miscellaneous methods.
3672 */
3673
Tim Peters37f39822003-01-10 03:49:02 +00003674static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003675time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003676{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003677 PyObject *result = NULL;
3678 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003680
Brian Curtindfc80e32011-08-10 20:28:54 -05003681 if (! PyTime_Check(other))
3682 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003683
3684 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 diff = memcmp(((PyDateTime_Time *)self)->data,
3686 ((PyDateTime_Time *)other)->data,
3687 _PyDateTime_TIME_DATASIZE);
3688 return diff_to_bool(diff, op);
3689 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003690 offset1 = time_utcoffset(self, NULL);
3691 if (offset1 == NULL)
3692 return NULL;
3693 offset2 = time_utcoffset(other, NULL);
3694 if (offset2 == NULL)
3695 goto done;
3696 /* If they're both naive, or both aware and have the same offsets,
3697 * we get off cheap. Note that if they're both naive, offset1 ==
3698 * offset2 == Py_None at this point.
3699 */
3700 if ((offset1 == offset2) ||
3701 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3702 delta_cmp(offset1, offset2) == 0)) {
3703 diff = memcmp(((PyDateTime_Time *)self)->data,
3704 ((PyDateTime_Time *)other)->data,
3705 _PyDateTime_TIME_DATASIZE);
3706 result = diff_to_bool(diff, op);
3707 }
3708 /* The hard case: both aware with different UTC offsets */
3709 else if (offset1 != Py_None && offset2 != Py_None) {
3710 int offsecs1, offsecs2;
3711 assert(offset1 != offset2); /* else last "if" handled it */
3712 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3713 TIME_GET_MINUTE(self) * 60 +
3714 TIME_GET_SECOND(self) -
3715 GET_TD_DAYS(offset1) * 86400 -
3716 GET_TD_SECONDS(offset1);
3717 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3718 TIME_GET_MINUTE(other) * 60 +
3719 TIME_GET_SECOND(other) -
3720 GET_TD_DAYS(offset2) * 86400 -
3721 GET_TD_SECONDS(offset2);
3722 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 if (diff == 0)
3724 diff = TIME_GET_MICROSECOND(self) -
3725 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003726 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003728 else if (op == Py_EQ) {
3729 result = Py_False;
3730 Py_INCREF(result);
3731 }
3732 else if (op == Py_NE) {
3733 result = Py_True;
3734 Py_INCREF(result);
3735 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003736 else {
3737 PyErr_SetString(PyExc_TypeError,
3738 "can't compare offset-naive and "
3739 "offset-aware times");
3740 }
3741 done:
3742 Py_DECREF(offset1);
3743 Py_XDECREF(offset2);
3744 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003745}
3746
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003747static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003748time_hash(PyDateTime_Time *self)
3749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003751 PyObject *offset;
Tim Peters37f39822003-01-10 03:49:02 +00003752
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003753 offset = time_utcoffset((PyObject *)self, NULL);
3754
3755 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003756 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003759 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 self->hashcode = generic_hash(
3761 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003763 PyObject *temp1, *temp2;
3764 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003766 seconds = TIME_GET_HOUR(self) * 3600 +
3767 TIME_GET_MINUTE(self) * 60 +
3768 TIME_GET_SECOND(self);
3769 microseconds = TIME_GET_MICROSECOND(self);
3770 temp1 = new_delta(0, seconds, microseconds, 1);
3771 if (temp1 == NULL) {
3772 Py_DECREF(offset);
3773 return -1;
3774 }
3775 temp2 = delta_subtract(temp1, offset);
3776 Py_DECREF(temp1);
3777 if (temp2 == NULL) {
3778 Py_DECREF(offset);
3779 return -1;
3780 }
3781 self->hashcode = PyObject_Hash(temp2);
3782 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003784 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 }
3786 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003787}
Tim Peters2a799bf2002-12-16 20:18:38 +00003788
Tim Peters12bf3392002-12-24 05:41:27 +00003789static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003790time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 PyObject *clone;
3793 PyObject *tuple;
3794 int hh = TIME_GET_HOUR(self);
3795 int mm = TIME_GET_MINUTE(self);
3796 int ss = TIME_GET_SECOND(self);
3797 int us = TIME_GET_MICROSECOND(self);
3798 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3801 time_kws,
3802 &hh, &mm, &ss, &us, &tzinfo))
3803 return NULL;
3804 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3805 if (tuple == NULL)
3806 return NULL;
3807 clone = time_new(Py_TYPE(self), tuple, NULL);
3808 Py_DECREF(tuple);
3809 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003810}
3811
Tim Peters371935f2003-02-01 01:52:50 +00003812/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003813
Tim Peters33e0f382003-01-10 02:05:14 +00003814/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003815 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3816 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003817 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003818 */
3819static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003820time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 PyObject *basestate;
3823 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 basestate = PyBytes_FromStringAndSize((char *)self->data,
3826 _PyDateTime_TIME_DATASIZE);
3827 if (basestate != NULL) {
3828 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3829 result = PyTuple_Pack(1, basestate);
3830 else
3831 result = PyTuple_Pack(2, basestate, self->tzinfo);
3832 Py_DECREF(basestate);
3833 }
3834 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003835}
3836
3837static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003838time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003841}
3842
Tim Peters37f39822003-01-10 03:49:02 +00003843static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3846 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3847 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3850 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3853 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3856 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3859 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003861 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3862 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3865 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3868 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003871};
3872
Tim Peters37f39822003-01-10 03:49:02 +00003873static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003874PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3875\n\
3876All arguments are optional. tzinfo may be None, or an instance of\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03003877a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003878
Neal Norwitz227b5332006-03-22 09:28:35 +00003879static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 PyVarObject_HEAD_INIT(NULL, 0)
3881 "datetime.time", /* tp_name */
3882 sizeof(PyDateTime_Time), /* tp_basicsize */
3883 0, /* tp_itemsize */
3884 (destructor)time_dealloc, /* tp_dealloc */
3885 0, /* tp_print */
3886 0, /* tp_getattr */
3887 0, /* tp_setattr */
3888 0, /* tp_reserved */
3889 (reprfunc)time_repr, /* tp_repr */
Benjamin Petersonee6bdc02014-03-20 18:00:35 -05003890 0, /* tp_as_number */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 0, /* tp_as_sequence */
3892 0, /* tp_as_mapping */
3893 (hashfunc)time_hash, /* tp_hash */
3894 0, /* tp_call */
3895 (reprfunc)time_str, /* tp_str */
3896 PyObject_GenericGetAttr, /* tp_getattro */
3897 0, /* tp_setattro */
3898 0, /* tp_as_buffer */
3899 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3900 time_doc, /* tp_doc */
3901 0, /* tp_traverse */
3902 0, /* tp_clear */
3903 time_richcompare, /* tp_richcompare */
3904 0, /* tp_weaklistoffset */
3905 0, /* tp_iter */
3906 0, /* tp_iternext */
3907 time_methods, /* tp_methods */
3908 0, /* tp_members */
3909 time_getset, /* tp_getset */
3910 0, /* tp_base */
3911 0, /* tp_dict */
3912 0, /* tp_descr_get */
3913 0, /* tp_descr_set */
3914 0, /* tp_dictoffset */
3915 0, /* tp_init */
3916 time_alloc, /* tp_alloc */
3917 time_new, /* tp_new */
3918 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003919};
3920
3921/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003922 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003923 */
3924
Tim Petersa9bc1682003-01-11 03:39:11 +00003925/* Accessor properties. Properties for day, month, and year are inherited
3926 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003927 */
3928
3929static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003930datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003933}
3934
Tim Petersa9bc1682003-01-11 03:39:11 +00003935static PyObject *
3936datetime_minute(PyDateTime_DateTime *self, void *unused)
3937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003939}
3940
3941static PyObject *
3942datetime_second(PyDateTime_DateTime *self, void *unused)
3943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003945}
3946
3947static PyObject *
3948datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003951}
3952
3953static PyObject *
3954datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3957 Py_INCREF(result);
3958 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003959}
3960
3961static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 {"hour", (getter)datetime_hour},
3963 {"minute", (getter)datetime_minute},
3964 {"second", (getter)datetime_second},
3965 {"microsecond", (getter)datetime_microsecond},
3966 {"tzinfo", (getter)datetime_tzinfo},
3967 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003968};
3969
3970/*
3971 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003972 */
3973
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003974static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 "year", "month", "day", "hour", "minute", "second",
3976 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00003977};
3978
Tim Peters2a799bf2002-12-16 20:18:38 +00003979static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003980datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 PyObject *self = NULL;
3983 PyObject *state;
3984 int year;
3985 int month;
3986 int day;
3987 int hour = 0;
3988 int minute = 0;
3989 int second = 0;
3990 int usecond = 0;
3991 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 /* Check for invocation from pickle with __getstate__ state */
3994 if (PyTuple_GET_SIZE(args) >= 1 &&
3995 PyTuple_GET_SIZE(args) <= 2 &&
3996 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3997 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3998 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
3999 {
4000 PyDateTime_DateTime *me;
4001 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 if (PyTuple_GET_SIZE(args) == 2) {
4004 tzinfo = PyTuple_GET_ITEM(args, 1);
4005 if (check_tzinfo_subclass(tzinfo) < 0) {
4006 PyErr_SetString(PyExc_TypeError, "bad "
4007 "tzinfo state arg");
4008 return NULL;
4009 }
4010 }
4011 aware = (char)(tzinfo != Py_None);
4012 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4013 if (me != NULL) {
4014 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4017 me->hashcode = -1;
4018 me->hastzinfo = aware;
4019 if (aware) {
4020 Py_INCREF(tzinfo);
4021 me->tzinfo = tzinfo;
4022 }
4023 }
4024 return (PyObject *)me;
4025 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
4028 &year, &month, &day, &hour, &minute,
4029 &second, &usecond, &tzinfo)) {
4030 if (check_date_args(year, month, day) < 0)
4031 return NULL;
4032 if (check_time_args(hour, minute, second, usecond) < 0)
4033 return NULL;
4034 if (check_tzinfo_subclass(tzinfo) < 0)
4035 return NULL;
4036 self = new_datetime_ex(year, month, day,
4037 hour, minute, second, usecond,
4038 tzinfo, type);
4039 }
4040 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004041}
4042
Tim Petersa9bc1682003-01-11 03:39:11 +00004043/* TM_FUNC is the shared type of localtime() and gmtime(). */
4044typedef struct tm *(*TM_FUNC)(const time_t *timer);
4045
4046/* Internal helper.
4047 * Build datetime from a time_t and a distinct count of microseconds.
4048 * Pass localtime or gmtime for f, to control the interpretation of timet.
4049 */
4050static PyObject *
4051datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 struct tm *tm;
Tim Petersa9bc1682003-01-11 03:39:11 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 tm = f(&timet);
Victor Stinner21f58932012-03-14 00:15:40 +01004057 if (tm == NULL) {
4058#ifdef EINVAL
4059 if (errno == 0)
4060 errno = EINVAL;
4061#endif
4062 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 }
Victor Stinner21f58932012-03-14 00:15:40 +01004064
4065 /* The platform localtime/gmtime may insert leap seconds,
4066 * indicated by tm->tm_sec > 59. We don't care about them,
4067 * except to the extent that passing them on to the datetime
4068 * constructor would raise ValueError for a reason that
4069 * made no sense to the user.
4070 */
4071 if (tm->tm_sec > 59)
4072 tm->tm_sec = 59;
4073 return PyObject_CallFunction(cls, "iiiiiiiO",
4074 tm->tm_year + 1900,
4075 tm->tm_mon + 1,
4076 tm->tm_mday,
4077 tm->tm_hour,
4078 tm->tm_min,
4079 tm->tm_sec,
4080 us,
4081 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004082}
4083
4084/* Internal helper.
4085 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4086 * to control the interpretation of the timestamp. Since a double doesn't
4087 * have enough bits to cover a datetime's full range of precision, it's
4088 * better to call datetime_from_timet_and_us provided you have a way
4089 * to get that much precision (e.g., C time() isn't good enough).
4090 */
4091static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004092datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004096 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004097
Victor Stinnere4a994d2015-03-30 01:10:14 +02004098 if (_PyTime_ObjectToTimeval(timestamp,
4099 &timet, &us, _PyTime_ROUND_FLOOR) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004101 assert(0 <= us && us <= 999999);
4102
Victor Stinner21f58932012-03-14 00:15:40 +01004103 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004104}
4105
4106/* Internal helper.
4107 * Build most accurate possible datetime for current time. Pass localtime or
4108 * gmtime for f as appropriate.
4109 */
4110static PyObject *
4111datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4112{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004113 _PyTime_t ts = _PyTime_GetSystemClock();
4114 struct timeval tv;
4115
4116 if (_PyTime_AsTimeval(ts, &tv, _PyTime_ROUND_FLOOR) < 0)
4117 return NULL;
4118 assert(0 <= tv.tv_usec && tv.tv_usec <= 999999);
4119
4120 return datetime_from_timet_and_us(cls, f, tv.tv_sec, tv.tv_usec, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004121}
4122
Larry Hastings61272b72014-01-07 12:41:53 -08004123/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004124
4125@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004126datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004127
4128 tz: object = None
4129 Timezone object.
4130
4131Returns new datetime object representing current time local to tz.
4132
4133If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004134[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004135
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004136PyDoc_STRVAR(datetime_datetime_now__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08004137"now($type, /, tz=None)\n"
4138"--\n"
4139"\n"
Larry Hastings31826802013-10-19 00:09:25 -07004140"Returns new datetime object representing current time local to tz.\n"
4141"\n"
Larry Hastings31826802013-10-19 00:09:25 -07004142" tz\n"
4143" Timezone object.\n"
4144"\n"
4145"If no tz is specified, uses local timezone.");
4146
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004147#define DATETIME_DATETIME_NOW_METHODDEF \
4148 {"now", (PyCFunction)datetime_datetime_now, METH_VARARGS|METH_KEYWORDS|METH_CLASS, datetime_datetime_now__doc__},
Larry Hastings31826802013-10-19 00:09:25 -07004149
Tim Peters2a799bf2002-12-16 20:18:38 +00004150static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004151datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz);
Larry Hastings31826802013-10-19 00:09:25 -07004152
4153static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004154datetime_datetime_now(PyTypeObject *type, PyObject *args, PyObject *kwargs)
Larry Hastings31826802013-10-19 00:09:25 -07004155{
4156 PyObject *return_value = NULL;
4157 static char *_keywords[] = {"tz", NULL};
4158 PyObject *tz = Py_None;
4159
4160 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
4161 "|O:now", _keywords,
4162 &tz))
4163 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -08004164 return_value = datetime_datetime_now_impl(type, tz);
Larry Hastings31826802013-10-19 00:09:25 -07004165
4166exit:
4167 return return_value;
4168}
4169
4170static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004171datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Larry Hastings2623c8c2014-02-08 22:15:29 -08004172/*[clinic end generated code: output=583c5637e3c843fa input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004175
Larry Hastings31826802013-10-19 00:09:25 -07004176 /* Return best possible local time -- this isn't constrained by the
4177 * precision of a timestamp.
4178 */
4179 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004181
Larry Hastings5c661892014-01-24 06:17:25 -08004182 self = datetime_best_possible((PyObject *)type,
Larry Hastings31826802013-10-19 00:09:25 -07004183 tz == Py_None ? localtime : gmtime,
4184 tz);
4185 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 /* Convert UTC to tzinfo's zone. */
4187 PyObject *temp = self;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004188
Larry Hastings31826802013-10-19 00:09:25 -07004189 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 Py_DECREF(temp);
4191 }
4192 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004193}
4194
Tim Petersa9bc1682003-01-11 03:39:11 +00004195/* Return best possible UTC time -- this isn't constrained by the
4196 * precision of a timestamp.
4197 */
4198static PyObject *
4199datetime_utcnow(PyObject *cls, PyObject *dummy)
4200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004202}
4203
Tim Peters2a799bf2002-12-16 20:18:38 +00004204/* Return new local datetime from timestamp (Python timestamp -- a double). */
4205static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004206datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004209 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 PyObject *tzinfo = Py_None;
4211 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004212
Victor Stinner5d272cc2012-03-13 13:35:55 +01004213 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 keywords, &timestamp, &tzinfo))
4215 return NULL;
4216 if (check_tzinfo_subclass(tzinfo) < 0)
4217 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 self = datetime_from_timestamp(cls,
4220 tzinfo == Py_None ? localtime : gmtime,
4221 timestamp,
4222 tzinfo);
4223 if (self != NULL && tzinfo != Py_None) {
4224 /* Convert UTC to tzinfo's zone. */
4225 PyObject *temp = self;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004226
4227 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 Py_DECREF(temp);
4229 }
4230 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004231}
4232
Tim Petersa9bc1682003-01-11 03:39:11 +00004233/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4234static PyObject *
4235datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4236{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004237 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004239
Victor Stinner5d272cc2012-03-13 13:35:55 +01004240 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 result = datetime_from_timestamp(cls, gmtime, timestamp,
4242 Py_None);
4243 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004244}
4245
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004246/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004247static PyObject *
4248datetime_strptime(PyObject *cls, PyObject *args)
4249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004250 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004251 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004252 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004254 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004256
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004257 if (module == NULL) {
4258 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004259 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004260 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004262 return _PyObject_CallMethodId(module, &PyId__strptime_datetime, "OOO",
4263 cls, string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004264}
4265
Tim Petersa9bc1682003-01-11 03:39:11 +00004266/* Return new datetime from date/datetime and time arguments. */
4267static PyObject *
4268datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 static char *keywords[] = {"date", "time", NULL};
4271 PyObject *date;
4272 PyObject *time;
4273 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4276 &PyDateTime_DateType, &date,
4277 &PyDateTime_TimeType, &time)) {
4278 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 if (HASTZINFO(time))
4281 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4282 result = PyObject_CallFunction(cls, "iiiiiiiO",
4283 GET_YEAR(date),
4284 GET_MONTH(date),
4285 GET_DAY(date),
4286 TIME_GET_HOUR(time),
4287 TIME_GET_MINUTE(time),
4288 TIME_GET_SECOND(time),
4289 TIME_GET_MICROSECOND(time),
4290 tzinfo);
4291 }
4292 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004293}
Tim Peters2a799bf2002-12-16 20:18:38 +00004294
4295/*
4296 * Destructor.
4297 */
4298
4299static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004300datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004302 if (HASTZINFO(self)) {
4303 Py_XDECREF(self->tzinfo);
4304 }
4305 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004306}
4307
4308/*
4309 * Indirect access to tzinfo methods.
4310 */
4311
Tim Peters2a799bf2002-12-16 20:18:38 +00004312/* These are all METH_NOARGS, so don't need to check the arglist. */
4313static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004314datetime_utcoffset(PyObject *self, PyObject *unused) {
4315 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004316}
4317
4318static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004319datetime_dst(PyObject *self, PyObject *unused) {
4320 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004321}
4322
4323static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004324datetime_tzname(PyObject *self, PyObject *unused) {
4325 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004326}
4327
4328/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004329 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004330 */
4331
Tim Petersa9bc1682003-01-11 03:39:11 +00004332/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4333 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004334 */
4335static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004336add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 /* Note that the C-level additions can't overflow, because of
4340 * invariant bounds on the member values.
4341 */
4342 int year = GET_YEAR(date);
4343 int month = GET_MONTH(date);
4344 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4345 int hour = DATE_GET_HOUR(date);
4346 int minute = DATE_GET_MINUTE(date);
4347 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4348 int microsecond = DATE_GET_MICROSECOND(date) +
4349 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 assert(factor == 1 || factor == -1);
4352 if (normalize_datetime(&year, &month, &day,
4353 &hour, &minute, &second, &microsecond) < 0)
4354 return NULL;
4355 else
4356 return new_datetime(year, month, day,
4357 hour, minute, second, microsecond,
4358 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004359}
4360
4361static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004362datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 if (PyDateTime_Check(left)) {
4365 /* datetime + ??? */
4366 if (PyDelta_Check(right))
4367 /* datetime + delta */
4368 return add_datetime_timedelta(
4369 (PyDateTime_DateTime *)left,
4370 (PyDateTime_Delta *)right,
4371 1);
4372 }
4373 else if (PyDelta_Check(left)) {
4374 /* delta + datetime */
4375 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4376 (PyDateTime_Delta *) left,
4377 1);
4378 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004379 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004380}
4381
4382static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004383datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 if (PyDateTime_Check(left)) {
4388 /* datetime - ??? */
4389 if (PyDateTime_Check(right)) {
4390 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004391 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004393
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004394 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4395 offset2 = offset1 = Py_None;
4396 Py_INCREF(offset1);
4397 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004399 else {
4400 offset1 = datetime_utcoffset(left, NULL);
4401 if (offset1 == NULL)
4402 return NULL;
4403 offset2 = datetime_utcoffset(right, NULL);
4404 if (offset2 == NULL) {
4405 Py_DECREF(offset1);
4406 return NULL;
4407 }
4408 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4409 PyErr_SetString(PyExc_TypeError,
4410 "can't subtract offset-naive and "
4411 "offset-aware datetimes");
4412 Py_DECREF(offset1);
4413 Py_DECREF(offset2);
4414 return NULL;
4415 }
4416 }
4417 if ((offset1 != offset2) &&
4418 delta_cmp(offset1, offset2) != 0) {
4419 offdiff = delta_subtract(offset1, offset2);
4420 if (offdiff == NULL) {
4421 Py_DECREF(offset1);
4422 Py_DECREF(offset2);
4423 return NULL;
4424 }
4425 }
4426 Py_DECREF(offset1);
4427 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 delta_d = ymd_to_ord(GET_YEAR(left),
4429 GET_MONTH(left),
4430 GET_DAY(left)) -
4431 ymd_to_ord(GET_YEAR(right),
4432 GET_MONTH(right),
4433 GET_DAY(right));
4434 /* These can't overflow, since the values are
4435 * normalized. At most this gives the number of
4436 * seconds in one day.
4437 */
4438 delta_s = (DATE_GET_HOUR(left) -
4439 DATE_GET_HOUR(right)) * 3600 +
4440 (DATE_GET_MINUTE(left) -
4441 DATE_GET_MINUTE(right)) * 60 +
4442 (DATE_GET_SECOND(left) -
4443 DATE_GET_SECOND(right));
4444 delta_us = DATE_GET_MICROSECOND(left) -
4445 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004447 if (result == NULL)
4448 return NULL;
4449
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004450 if (offdiff != NULL) {
4451 PyObject *temp = result;
4452 result = delta_subtract(result, offdiff);
4453 Py_DECREF(temp);
4454 Py_DECREF(offdiff);
4455 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 }
4457 else if (PyDelta_Check(right)) {
4458 /* datetime - delta */
4459 result = add_datetime_timedelta(
4460 (PyDateTime_DateTime *)left,
4461 (PyDateTime_Delta *)right,
4462 -1);
4463 }
4464 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 if (result == Py_NotImplemented)
4467 Py_INCREF(result);
4468 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004469}
4470
4471/* Various ways to turn a datetime into a string. */
4472
4473static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004474datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 const char *type_name = Py_TYPE(self)->tp_name;
4477 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 if (DATE_GET_MICROSECOND(self)) {
4480 baserepr = PyUnicode_FromFormat(
4481 "%s(%d, %d, %d, %d, %d, %d, %d)",
4482 type_name,
4483 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4484 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4485 DATE_GET_SECOND(self),
4486 DATE_GET_MICROSECOND(self));
4487 }
4488 else if (DATE_GET_SECOND(self)) {
4489 baserepr = PyUnicode_FromFormat(
4490 "%s(%d, %d, %d, %d, %d, %d)",
4491 type_name,
4492 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4493 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4494 DATE_GET_SECOND(self));
4495 }
4496 else {
4497 baserepr = PyUnicode_FromFormat(
4498 "%s(%d, %d, %d, %d, %d)",
4499 type_name,
4500 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4501 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4502 }
4503 if (baserepr == NULL || ! HASTZINFO(self))
4504 return baserepr;
4505 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004506}
4507
Tim Petersa9bc1682003-01-11 03:39:11 +00004508static PyObject *
4509datetime_str(PyDateTime_DateTime *self)
4510{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004511 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004512}
Tim Peters2a799bf2002-12-16 20:18:38 +00004513
4514static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004515datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 int sep = 'T';
4518 static char *keywords[] = {"sep", NULL};
4519 char buffer[100];
4520 PyObject *result;
4521 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004523 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4524 return NULL;
4525 if (us)
4526 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4527 GET_YEAR(self), GET_MONTH(self),
4528 GET_DAY(self), (int)sep,
4529 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4530 DATE_GET_SECOND(self), us);
4531 else
4532 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4533 GET_YEAR(self), GET_MONTH(self),
4534 GET_DAY(self), (int)sep,
4535 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4536 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 if (!result || !HASTZINFO(self))
4539 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 /* We need to append the UTC offset. */
4542 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4543 (PyObject *)self) < 0) {
4544 Py_DECREF(result);
4545 return NULL;
4546 }
4547 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4548 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004549}
4550
Tim Petersa9bc1682003-01-11 03:39:11 +00004551static PyObject *
4552datetime_ctime(PyDateTime_DateTime *self)
4553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004554 return format_ctime((PyDateTime_Date *)self,
4555 DATE_GET_HOUR(self),
4556 DATE_GET_MINUTE(self),
4557 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004558}
4559
Tim Peters2a799bf2002-12-16 20:18:38 +00004560/* Miscellaneous methods. */
4561
Tim Petersa9bc1682003-01-11 03:39:11 +00004562static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004563datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004564{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004565 PyObject *result = NULL;
4566 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 if (! PyDateTime_Check(other)) {
4570 if (PyDate_Check(other)) {
4571 /* Prevent invocation of date_richcompare. We want to
4572 return NotImplemented here to give the other object
4573 a chance. But since DateTime is a subclass of
4574 Date, if the other object is a Date, it would
4575 compute an ordering based on the date part alone,
4576 and we don't want that. So force unequal or
4577 uncomparable here in that case. */
4578 if (op == Py_EQ)
4579 Py_RETURN_FALSE;
4580 if (op == Py_NE)
4581 Py_RETURN_TRUE;
4582 return cmperror(self, other);
4583 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004584 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004586
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004587 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4589 ((PyDateTime_DateTime *)other)->data,
4590 _PyDateTime_DATETIME_DATASIZE);
4591 return diff_to_bool(diff, op);
4592 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004593 offset1 = datetime_utcoffset(self, NULL);
4594 if (offset1 == NULL)
4595 return NULL;
4596 offset2 = datetime_utcoffset(other, NULL);
4597 if (offset2 == NULL)
4598 goto done;
4599 /* If they're both naive, or both aware and have the same offsets,
4600 * we get off cheap. Note that if they're both naive, offset1 ==
4601 * offset2 == Py_None at this point.
4602 */
4603 if ((offset1 == offset2) ||
4604 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4605 delta_cmp(offset1, offset2) == 0)) {
4606 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4607 ((PyDateTime_DateTime *)other)->data,
4608 _PyDateTime_DATETIME_DATASIZE);
4609 result = diff_to_bool(diff, op);
4610 }
4611 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004613
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004614 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4616 other);
4617 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004618 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 diff = GET_TD_DAYS(delta);
4620 if (diff == 0)
4621 diff = GET_TD_SECONDS(delta) |
4622 GET_TD_MICROSECONDS(delta);
4623 Py_DECREF(delta);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004624 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004626 else if (op == Py_EQ) {
4627 result = Py_False;
4628 Py_INCREF(result);
4629 }
4630 else if (op == Py_NE) {
4631 result = Py_True;
4632 Py_INCREF(result);
4633 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004634 else {
4635 PyErr_SetString(PyExc_TypeError,
4636 "can't compare offset-naive and "
4637 "offset-aware datetimes");
4638 }
4639 done:
4640 Py_DECREF(offset1);
4641 Py_XDECREF(offset2);
4642 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004643}
4644
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004645static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004646datetime_hash(PyDateTime_DateTime *self)
4647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004649 PyObject *offset;
Tim Petersa9bc1682003-01-11 03:39:11 +00004650
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004651 offset = datetime_utcoffset((PyObject *)self, NULL);
4652
4653 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004657 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 self->hashcode = generic_hash(
4659 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004661 PyObject *temp1, *temp2;
4662 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 assert(HASTZINFO(self));
4665 days = ymd_to_ord(GET_YEAR(self),
4666 GET_MONTH(self),
4667 GET_DAY(self));
4668 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004669 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004671 temp1 = new_delta(days, seconds,
4672 DATE_GET_MICROSECOND(self),
4673 1);
4674 if (temp1 == NULL) {
4675 Py_DECREF(offset);
4676 return -1;
4677 }
4678 temp2 = delta_subtract(temp1, offset);
4679 Py_DECREF(temp1);
4680 if (temp2 == NULL) {
4681 Py_DECREF(offset);
4682 return -1;
4683 }
4684 self->hashcode = PyObject_Hash(temp2);
4685 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004687 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688 }
4689 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004690}
Tim Peters2a799bf2002-12-16 20:18:38 +00004691
4692static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004693datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 PyObject *clone;
4696 PyObject *tuple;
4697 int y = GET_YEAR(self);
4698 int m = GET_MONTH(self);
4699 int d = GET_DAY(self);
4700 int hh = DATE_GET_HOUR(self);
4701 int mm = DATE_GET_MINUTE(self);
4702 int ss = DATE_GET_SECOND(self);
4703 int us = DATE_GET_MICROSECOND(self);
4704 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4707 datetime_kws,
4708 &y, &m, &d, &hh, &mm, &ss, &us,
4709 &tzinfo))
4710 return NULL;
4711 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4712 if (tuple == NULL)
4713 return NULL;
4714 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4715 Py_DECREF(tuple);
4716 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004717}
4718
4719static PyObject *
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004720local_timezone(PyDateTime_DateTime *utc_time)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004721{
4722 PyObject *result = NULL;
4723 struct tm *timep;
4724 time_t timestamp;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004725 PyObject *delta;
4726 PyObject *one_second;
4727 PyObject *seconds;
4728 PyObject *nameo = NULL;
4729 const char *zone = NULL;
4730
4731 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
4732 if (delta == NULL)
4733 return NULL;
4734 one_second = new_delta(0, 1, 0, 0);
4735 if (one_second == NULL)
4736 goto error;
4737 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
4738 (PyDateTime_Delta *)one_second);
4739 Py_DECREF(one_second);
4740 if (seconds == NULL)
4741 goto error;
4742 Py_DECREF(delta);
4743 timestamp = PyLong_AsLong(seconds);
4744 Py_DECREF(seconds);
4745 if (timestamp == -1 && PyErr_Occurred())
4746 return NULL;
4747 timep = localtime(&timestamp);
4748#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky93c9cd02012-06-22 16:04:19 -04004749 zone = timep->tm_zone;
4750 delta = new_delta(0, timep->tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004751#else /* HAVE_STRUCT_TM_TM_ZONE */
4752 {
4753 PyObject *local_time;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004754 local_time = new_datetime(timep->tm_year + 1900, timep->tm_mon + 1,
4755 timep->tm_mday, timep->tm_hour, timep->tm_min,
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004756 timep->tm_sec, DATE_GET_MICROSECOND(utc_time),
4757 utc_time->tzinfo);
4758 if (local_time == NULL)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004759 goto error;
Alexander Belopolsky93c9cd02012-06-22 16:04:19 -04004760 delta = datetime_subtract(local_time, (PyObject*)utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004761 /* XXX: before relying on tzname, we should compare delta
4762 to the offset implied by timezone/altzone */
4763 if (daylight && timep->tm_isdst >= 0)
4764 zone = tzname[timep->tm_isdst % 2];
4765 else
4766 zone = tzname[0];
4767 Py_DECREF(local_time);
4768 }
4769#endif /* HAVE_STRUCT_TM_TM_ZONE */
4770 if (zone != NULL) {
4771 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
4772 if (nameo == NULL)
4773 goto error;
4774 }
4775 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02004776 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004777 error:
4778 Py_DECREF(delta);
4779 return result;
4780}
4781
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004782static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00004783datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004784{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004785 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004786 PyObject *offset;
4787 PyObject *temp;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004788 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004790
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004791 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07004792 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004793 return NULL;
4794
4795 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004798 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4799 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 /* Conversion to self's own time zone is a NOP. */
4802 if (self->tzinfo == tzinfo) {
4803 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004804 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 }
Tim Peters521fc152002-12-31 17:36:56 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 /* Convert self to UTC. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004808 offset = datetime_utcoffset((PyObject *)self, NULL);
4809 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004810 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004811 if (offset == Py_None) {
4812 Py_DECREF(offset);
4813 NeedAware:
4814 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4815 "a naive datetime");
4816 return NULL;
4817 }
Tim Petersf3615152003-01-01 21:51:37 +00004818
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004819 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004820 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4821 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004822 Py_DECREF(offset);
4823 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004827 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004828 if (tzinfo == Py_None) {
4829 tzinfo = local_timezone(result);
4830 if (tzinfo == NULL) {
4831 Py_DECREF(result);
4832 return NULL;
4833 }
4834 }
4835 else
4836 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004837 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004838 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00004839
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004840 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004841 result = (PyDateTime_DateTime *)
4842 _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", temp);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004843 Py_DECREF(temp);
4844
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004845 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00004846}
4847
4848static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004849datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004854 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00004855
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004856 dst = call_dst(self->tzinfo, (PyObject *)self);
4857 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004859
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004860 if (dst != Py_None)
4861 dstflag = delta_bool((PyDateTime_Delta *)dst);
4862 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 }
4864 return build_struct_time(GET_YEAR(self),
4865 GET_MONTH(self),
4866 GET_DAY(self),
4867 DATE_GET_HOUR(self),
4868 DATE_GET_MINUTE(self),
4869 DATE_GET_SECOND(self),
4870 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004871}
4872
4873static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04004874datetime_timestamp(PyDateTime_DateTime *self)
4875{
4876 PyObject *result;
4877
4878 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4879 PyObject *delta;
4880 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
4881 if (delta == NULL)
4882 return NULL;
4883 result = delta_total_seconds(delta);
4884 Py_DECREF(delta);
4885 }
4886 else {
4887 struct tm time;
4888 time_t timestamp;
4889 memset((void *) &time, '\0', sizeof(struct tm));
4890 time.tm_year = GET_YEAR(self) - 1900;
4891 time.tm_mon = GET_MONTH(self) - 1;
4892 time.tm_mday = GET_DAY(self);
4893 time.tm_hour = DATE_GET_HOUR(self);
4894 time.tm_min = DATE_GET_MINUTE(self);
4895 time.tm_sec = DATE_GET_SECOND(self);
4896 time.tm_wday = -1;
4897 time.tm_isdst = -1;
4898 timestamp = mktime(&time);
Victor Stinner93037492013-06-25 22:54:35 +02004899 if (timestamp == (time_t)(-1)
4900#ifndef _AIX
4901 /* Return value of -1 does not necessarily mean an error,
4902 * but tm_wday cannot remain set to -1 if mktime succeeded. */
4903 && time.tm_wday == -1
4904#else
4905 /* on AIX, tm_wday is always sets, even on error */
4906#endif
4907 )
4908 {
Alexander Belopolskya4415142012-06-08 12:33:09 -04004909 PyErr_SetString(PyExc_OverflowError,
4910 "timestamp out of range");
4911 return NULL;
4912 }
4913 result = PyFloat_FromDouble(timestamp + DATE_GET_MICROSECOND(self) / 1e6);
4914 }
4915 return result;
4916}
4917
4918static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004919datetime_getdate(PyDateTime_DateTime *self)
4920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004921 return new_date(GET_YEAR(self),
4922 GET_MONTH(self),
4923 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004924}
4925
4926static PyObject *
4927datetime_gettime(PyDateTime_DateTime *self)
4928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004929 return new_time(DATE_GET_HOUR(self),
4930 DATE_GET_MINUTE(self),
4931 DATE_GET_SECOND(self),
4932 DATE_GET_MICROSECOND(self),
4933 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004934}
4935
4936static PyObject *
4937datetime_gettimetz(PyDateTime_DateTime *self)
4938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 return new_time(DATE_GET_HOUR(self),
4940 DATE_GET_MINUTE(self),
4941 DATE_GET_SECOND(self),
4942 DATE_GET_MICROSECOND(self),
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004943 GET_DT_TZINFO(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004944}
4945
4946static PyObject *
4947datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004948{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004949 int y, m, d, hh, mm, ss;
4950 PyObject *tzinfo;
4951 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00004952
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004953 tzinfo = GET_DT_TZINFO(self);
4954 if (tzinfo == Py_None) {
4955 utcself = self;
4956 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004958 else {
4959 PyObject *offset;
4960 offset = call_utcoffset(tzinfo, (PyObject *)self);
4961 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00004962 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004963 if (offset == Py_None) {
4964 Py_DECREF(offset);
4965 utcself = self;
4966 Py_INCREF(utcself);
4967 }
4968 else {
4969 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4970 (PyDateTime_Delta *)offset, -1);
4971 Py_DECREF(offset);
4972 if (utcself == NULL)
4973 return NULL;
4974 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004976 y = GET_YEAR(utcself);
4977 m = GET_MONTH(utcself);
4978 d = GET_DAY(utcself);
4979 hh = DATE_GET_HOUR(utcself);
4980 mm = DATE_GET_MINUTE(utcself);
4981 ss = DATE_GET_SECOND(utcself);
4982
4983 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004985}
4986
Tim Peters371935f2003-02-01 01:52:50 +00004987/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004988
Tim Petersa9bc1682003-01-11 03:39:11 +00004989/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004990 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4991 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004992 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004993 */
4994static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004995datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 PyObject *basestate;
4998 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 basestate = PyBytes_FromStringAndSize((char *)self->data,
5001 _PyDateTime_DATETIME_DATASIZE);
5002 if (basestate != NULL) {
5003 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5004 result = PyTuple_Pack(1, basestate);
5005 else
5006 result = PyTuple_Pack(2, basestate, self->tzinfo);
5007 Py_DECREF(basestate);
5008 }
5009 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005010}
5011
5012static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00005013datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00005014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00005016}
5017
Tim Petersa9bc1682003-01-11 03:39:11 +00005018static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005021
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005022 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 {"utcnow", (PyCFunction)datetime_utcnow,
5025 METH_NOARGS | METH_CLASS,
5026 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5029 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5030 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5033 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05005034 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 {"strptime", (PyCFunction)datetime_strptime,
5037 METH_VARARGS | METH_CLASS,
5038 PyDoc_STR("string, format -> new datetime parsed from a string "
5039 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 {"combine", (PyCFunction)datetime_combine,
5042 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5043 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5048 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5051 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5054 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5057 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005059 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5060 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005061
Alexander Belopolskya4415142012-06-08 12:33:09 -04005062 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5063 PyDoc_STR("Return POSIX timestamp as float.")},
5064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5066 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005068 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5069 PyDoc_STR("[sep] -> string in ISO 8601 format, "
5070 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
5071 "sep is used to separate the year from the time, and "
5072 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5075 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5078 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5081 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5084 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005086 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5087 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
5090 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005093};
5094
Tim Petersa9bc1682003-01-11 03:39:11 +00005095static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005096PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5097\n\
5098The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005099instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005100
Tim Petersa9bc1682003-01-11 03:39:11 +00005101static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 datetime_add, /* nb_add */
5103 datetime_subtract, /* nb_subtract */
5104 0, /* nb_multiply */
5105 0, /* nb_remainder */
5106 0, /* nb_divmod */
5107 0, /* nb_power */
5108 0, /* nb_negative */
5109 0, /* nb_positive */
5110 0, /* nb_absolute */
5111 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005112};
5113
Neal Norwitz227b5332006-03-22 09:28:35 +00005114static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 PyVarObject_HEAD_INIT(NULL, 0)
5116 "datetime.datetime", /* tp_name */
5117 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5118 0, /* tp_itemsize */
5119 (destructor)datetime_dealloc, /* tp_dealloc */
5120 0, /* tp_print */
5121 0, /* tp_getattr */
5122 0, /* tp_setattr */
5123 0, /* tp_reserved */
5124 (reprfunc)datetime_repr, /* tp_repr */
5125 &datetime_as_number, /* tp_as_number */
5126 0, /* tp_as_sequence */
5127 0, /* tp_as_mapping */
5128 (hashfunc)datetime_hash, /* tp_hash */
5129 0, /* tp_call */
5130 (reprfunc)datetime_str, /* tp_str */
5131 PyObject_GenericGetAttr, /* tp_getattro */
5132 0, /* tp_setattro */
5133 0, /* tp_as_buffer */
5134 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5135 datetime_doc, /* tp_doc */
5136 0, /* tp_traverse */
5137 0, /* tp_clear */
5138 datetime_richcompare, /* tp_richcompare */
5139 0, /* tp_weaklistoffset */
5140 0, /* tp_iter */
5141 0, /* tp_iternext */
5142 datetime_methods, /* tp_methods */
5143 0, /* tp_members */
5144 datetime_getset, /* tp_getset */
5145 &PyDateTime_DateType, /* tp_base */
5146 0, /* tp_dict */
5147 0, /* tp_descr_get */
5148 0, /* tp_descr_set */
5149 0, /* tp_dictoffset */
5150 0, /* tp_init */
5151 datetime_alloc, /* tp_alloc */
5152 datetime_new, /* tp_new */
5153 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005154};
5155
5156/* ---------------------------------------------------------------------------
5157 * Module methods and initialization.
5158 */
5159
5160static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005162};
5163
Tim Peters9ddf40b2004-06-20 22:41:32 +00005164/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5165 * datetime.h.
5166 */
5167static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005168 &PyDateTime_DateType,
5169 &PyDateTime_DateTimeType,
5170 &PyDateTime_TimeType,
5171 &PyDateTime_DeltaType,
5172 &PyDateTime_TZInfoType,
5173 new_date_ex,
5174 new_datetime_ex,
5175 new_time_ex,
5176 new_delta_ex,
5177 datetime_fromtimestamp,
5178 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00005179};
5180
5181
Martin v. Löwis1a214512008-06-11 05:26:20 +00005182
5183static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005184 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005185 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005186 "Fast implementation of the datetime type.",
5187 -1,
5188 module_methods,
5189 NULL,
5190 NULL,
5191 NULL,
5192 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005193};
5194
Tim Peters2a799bf2002-12-16 20:18:38 +00005195PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005196PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 PyObject *m; /* a module object */
5199 PyObject *d; /* its dict */
5200 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005201 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 m = PyModule_Create(&datetimemodule);
5204 if (m == NULL)
5205 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 if (PyType_Ready(&PyDateTime_DateType) < 0)
5208 return NULL;
5209 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5210 return NULL;
5211 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5212 return NULL;
5213 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5214 return NULL;
5215 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5216 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005217 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5218 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 /* timedelta values */
5221 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 x = new_delta(0, 0, 1, 0);
5224 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5225 return NULL;
5226 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5229 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5230 return NULL;
5231 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5234 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5235 return NULL;
5236 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 /* date values */
5239 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 x = new_date(1, 1, 1);
5242 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5243 return NULL;
5244 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 x = new_date(MAXYEAR, 12, 31);
5247 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5248 return NULL;
5249 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 x = new_delta(1, 0, 0, 0);
5252 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5253 return NULL;
5254 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 /* time values */
5257 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005259 x = new_time(0, 0, 0, 0, Py_None);
5260 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5261 return NULL;
5262 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 x = new_time(23, 59, 59, 999999, Py_None);
5265 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5266 return NULL;
5267 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005269 x = new_delta(0, 0, 1, 0);
5270 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5271 return NULL;
5272 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 /* datetime values */
5275 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005277 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
5278 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5279 return NULL;
5280 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5283 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5284 return NULL;
5285 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005287 x = new_delta(0, 0, 1, 0);
5288 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5289 return NULL;
5290 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005291
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005292 /* timezone values */
5293 d = PyDateTime_TimeZoneType.tp_dict;
5294
5295 delta = new_delta(0, 0, 0, 0);
5296 if (delta == NULL)
5297 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005298 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005299 Py_DECREF(delta);
5300 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5301 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005302 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005303
5304 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5305 if (delta == NULL)
5306 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005307 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005308 Py_DECREF(delta);
5309 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5310 return NULL;
5311 Py_DECREF(x);
5312
5313 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5314 if (delta == NULL)
5315 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005316 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005317 Py_DECREF(delta);
5318 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5319 return NULL;
5320 Py_DECREF(x);
5321
Alexander Belopolskya4415142012-06-08 12:33:09 -04005322 /* Epoch */
5323 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
5324 PyDateTime_TimeZone_UTC);
5325 if (PyDateTime_Epoch == NULL)
5326 return NULL;
5327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005329 PyModule_AddIntMacro(m, MINYEAR);
5330 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 Py_INCREF(&PyDateTime_DateType);
5333 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 Py_INCREF(&PyDateTime_DateTimeType);
5336 PyModule_AddObject(m, "datetime",
5337 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 Py_INCREF(&PyDateTime_TimeType);
5340 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 Py_INCREF(&PyDateTime_DeltaType);
5343 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005345 Py_INCREF(&PyDateTime_TZInfoType);
5346 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005347
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005348 Py_INCREF(&PyDateTime_TimeZoneType);
5349 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5352 if (x == NULL)
5353 return NULL;
5354 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 /* A 4-year cycle has an extra leap day over what we'd get from
5357 * pasting together 4 single years.
5358 */
5359 assert(DI4Y == 4 * 365 + 1);
5360 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5363 * get from pasting together 4 100-year cycles.
5364 */
5365 assert(DI400Y == 4 * DI100Y + 1);
5366 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5369 * pasting together 25 4-year cycles.
5370 */
5371 assert(DI100Y == 25 * DI4Y - 1);
5372 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005373
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005374 one = PyLong_FromLong(1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 us_per_ms = PyLong_FromLong(1000);
5376 us_per_second = PyLong_FromLong(1000000);
5377 us_per_minute = PyLong_FromLong(60000000);
5378 seconds_per_day = PyLong_FromLong(24 * 3600);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005379 if (one == NULL || us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005380 us_per_minute == NULL || seconds_per_day == NULL)
5381 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 /* The rest are too big for 32-bit ints, but even
5384 * us_per_week fits in 40 bits, so doubles should be exact.
5385 */
5386 us_per_hour = PyLong_FromDouble(3600000000.0);
5387 us_per_day = PyLong_FromDouble(86400000000.0);
5388 us_per_week = PyLong_FromDouble(604800000000.0);
5389 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5390 return NULL;
5391 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005392}
Tim Petersf3615152003-01-01 21:51:37 +00005393
5394/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005395Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005396 x.n = x stripped of its timezone -- its naive time.
5397 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005398 return None
Tim Petersf3615152003-01-01 21:51:37 +00005399 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005400 return None
Tim Petersf3615152003-01-01 21:51:37 +00005401 x.s = x's standard offset, x.o - x.d
5402
5403Now some derived rules, where k is a duration (timedelta).
5404
54051. x.o = x.s + x.d
5406 This follows from the definition of x.s.
5407
Tim Petersc5dc4da2003-01-02 17:55:03 +000054082. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005409 This is actually a requirement, an assumption we need to make about
5410 sane tzinfo classes.
5411
54123. The naive UTC time corresponding to x is x.n - x.o.
5413 This is again a requirement for a sane tzinfo class.
5414
54154. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005416 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005417
Tim Petersc5dc4da2003-01-02 17:55:03 +000054185. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005419 Again follows from how arithmetic is defined.
5420
Tim Peters8bb5ad22003-01-24 02:44:45 +00005421Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005422(meaning that the various tzinfo methods exist, and don't blow up or return
5423None when called).
5424
Tim Petersa9bc1682003-01-11 03:39:11 +00005425The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005426x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005427
5428By #3, we want
5429
Tim Peters8bb5ad22003-01-24 02:44:45 +00005430 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005431
5432The algorithm starts by attaching tz to x.n, and calling that y. So
5433x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5434becomes true; in effect, we want to solve [2] for k:
5435
Tim Peters8bb5ad22003-01-24 02:44:45 +00005436 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005437
5438By #1, this is the same as
5439
Tim Peters8bb5ad22003-01-24 02:44:45 +00005440 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005441
5442By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5443Substituting that into [3],
5444
Tim Peters8bb5ad22003-01-24 02:44:45 +00005445 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5446 k - (y+k).s - (y+k).d = 0; rearranging,
5447 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5448 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005449
Tim Peters8bb5ad22003-01-24 02:44:45 +00005450On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5451approximate k by ignoring the (y+k).d term at first. Note that k can't be
5452very large, since all offset-returning methods return a duration of magnitude
5453less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5454be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005455
5456In any case, the new value is
5457
Tim Peters8bb5ad22003-01-24 02:44:45 +00005458 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005459
Tim Peters8bb5ad22003-01-24 02:44:45 +00005460It's helpful to step back at look at [4] from a higher level: it's simply
5461mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005462
5463At this point, if
5464
Tim Peters8bb5ad22003-01-24 02:44:45 +00005465 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005466
5467we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005468at the start of daylight time. Picture US Eastern for concreteness. The wall
5469time 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 +00005470sense then. The docs ask that an Eastern tzinfo class consider such a time to
5471be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5472on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005473the only spelling that makes sense on the local wall clock.
5474
Tim Petersc5dc4da2003-01-02 17:55:03 +00005475In fact, if [5] holds at this point, we do have the standard-time spelling,
5476but that takes a bit of proof. We first prove a stronger result. What's the
5477difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005478
Tim Peters8bb5ad22003-01-24 02:44:45 +00005479 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005480
Tim Petersc5dc4da2003-01-02 17:55:03 +00005481Now
5482 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005483 (y + y.s).n = by #5
5484 y.n + y.s = since y.n = x.n
5485 x.n + y.s = since z and y are have the same tzinfo member,
5486 y.s = z.s by #2
5487 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005488
Tim Petersc5dc4da2003-01-02 17:55:03 +00005489Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005490
Tim Petersc5dc4da2003-01-02 17:55:03 +00005491 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005492 x.n - ((x.n + z.s) - z.o) = expanding
5493 x.n - x.n - z.s + z.o = cancelling
5494 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005495 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005496
Tim Petersc5dc4da2003-01-02 17:55:03 +00005497So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005498
Tim Petersc5dc4da2003-01-02 17:55:03 +00005499If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005500spelling we wanted in the endcase described above. We're done. Contrarily,
5501if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005502
Tim Petersc5dc4da2003-01-02 17:55:03 +00005503If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5504add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005505local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005506
Tim Petersc5dc4da2003-01-02 17:55:03 +00005507Let
Tim Petersf3615152003-01-01 21:51:37 +00005508
Tim Peters4fede1a2003-01-04 00:26:59 +00005509 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005510
Tim Peters4fede1a2003-01-04 00:26:59 +00005511and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005512
Tim Peters8bb5ad22003-01-24 02:44:45 +00005513 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005514
Tim Peters8bb5ad22003-01-24 02:44:45 +00005515If so, we're done. If not, the tzinfo class is insane, according to the
5516assumptions we've made. This also requires a bit of proof. As before, let's
5517compute the difference between the LHS and RHS of [8] (and skipping some of
5518the justifications for the kinds of substitutions we've done several times
5519already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005520
Tim Peters8bb5ad22003-01-24 02:44:45 +00005521 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5523 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5524 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5525 - z.n + z.n - z.o + z'.o = cancel z.n
5526 - z.o + z'.o = #1 twice
5527 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5528 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005529
5530So 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 +00005531we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5532return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005533
Tim Peters8bb5ad22003-01-24 02:44:45 +00005534How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5535a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5536would have to change the result dst() returns: we start in DST, and moving
5537a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005538
Tim Peters8bb5ad22003-01-24 02:44:45 +00005539There isn't a sane case where this can happen. The closest it gets is at
5540the end of DST, where there's an hour in UTC with no spelling in a hybrid
5541tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5542that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5543UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5544time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5545clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5546standard time. Since that's what the local clock *does*, we want to map both
5547UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005548in local time, but so it goes -- it's the way the local clock works.
5549
Tim Peters8bb5ad22003-01-24 02:44:45 +00005550When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5551so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5552z' = 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 +00005553(correctly) concludes that z' is not UTC-equivalent to x.
5554
5555Because we know z.d said z was in daylight time (else [5] would have held and
5556we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005557and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005558return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5559but the reasoning doesn't depend on the example -- it depends on there being
5560two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005561z' must be in standard time, and is the spelling we want in this case.
5562
5563Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5564concerned (because it takes z' as being in standard time rather than the
5565daylight time we intend here), but returning it gives the real-life "local
5566clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5567tz.
5568
5569When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5570the 1:MM standard time spelling we want.
5571
5572So how can this break? One of the assumptions must be violated. Two
5573possibilities:
5574
55751) [2] effectively says that y.s is invariant across all y belong to a given
5576 time zone. This isn't true if, for political reasons or continental drift,
5577 a region decides to change its base offset from UTC.
5578
55792) There may be versions of "double daylight" time where the tail end of
5580 the analysis gives up a step too early. I haven't thought about that
5581 enough to say.
5582
5583In any case, it's clear that the default fromutc() is strong enough to handle
5584"almost all" time zones: so long as the standard offset is invariant, it
5585doesn't matter if daylight time transition points change from year to year, or
5586if daylight time is skipped in some years; it doesn't matter how large or
5587small dst() may get within its bounds; and it doesn't even matter if some
5588perverse time zone returns a negative dst()). So a breaking case must be
5589pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005590--------------------------------------------------------------------------- */