blob: c3e54f7af43530d198617d7df8630ae5c127853f [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 Stinner3c1b3792014-02-17 00:02:43 +01002466 if (_PyTime_ObjectToTime_t(obj, &t, _PyTime_ROUND_DOWN) == -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 Stinner3c1b3792014-02-17 00:02:43 +01004098 if (_PyTime_ObjectToTimeval(timestamp, &timet, &us, _PyTime_ROUND_DOWN) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 return NULL;
Victor Stinner09e5cf22015-03-30 00:09:18 +02004100 assert(0 <= us && us <= 999999);
4101
Victor Stinner21f58932012-03-14 00:15:40 +01004102 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004103}
4104
4105/* Internal helper.
4106 * Build most accurate possible datetime for current time. Pass localtime or
4107 * gmtime for f as appropriate.
4108 */
4109static PyObject *
4110datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4111{
Victor Stinner09e5cf22015-03-30 00:09:18 +02004112 _PyTime_t ts = _PyTime_GetSystemClock();
4113 struct timeval tv;
4114
4115 if (_PyTime_AsTimeval(ts, &tv, _PyTime_ROUND_FLOOR) < 0)
4116 return NULL;
4117 assert(0 <= tv.tv_usec && tv.tv_usec <= 999999);
4118
4119 return datetime_from_timet_and_us(cls, f, tv.tv_sec, tv.tv_usec, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004120}
4121
Larry Hastings61272b72014-01-07 12:41:53 -08004122/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07004123
4124@classmethod
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004125datetime.datetime.now
Larry Hastings31826802013-10-19 00:09:25 -07004126
4127 tz: object = None
4128 Timezone object.
4129
4130Returns new datetime object representing current time local to tz.
4131
4132If no tz is specified, uses local timezone.
Larry Hastings61272b72014-01-07 12:41:53 -08004133[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07004134
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004135PyDoc_STRVAR(datetime_datetime_now__doc__,
Larry Hastings2623c8c2014-02-08 22:15:29 -08004136"now($type, /, tz=None)\n"
4137"--\n"
4138"\n"
Larry Hastings31826802013-10-19 00:09:25 -07004139"Returns new datetime object representing current time local to tz.\n"
4140"\n"
Larry Hastings31826802013-10-19 00:09:25 -07004141" tz\n"
4142" Timezone object.\n"
4143"\n"
4144"If no tz is specified, uses local timezone.");
4145
Larry Hastingsed4a1c52013-11-18 09:32:13 -08004146#define DATETIME_DATETIME_NOW_METHODDEF \
4147 {"now", (PyCFunction)datetime_datetime_now, METH_VARARGS|METH_KEYWORDS|METH_CLASS, datetime_datetime_now__doc__},
Larry Hastings31826802013-10-19 00:09:25 -07004148
Tim Peters2a799bf2002-12-16 20:18:38 +00004149static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004150datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz);
Larry Hastings31826802013-10-19 00:09:25 -07004151
4152static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004153datetime_datetime_now(PyTypeObject *type, PyObject *args, PyObject *kwargs)
Larry Hastings31826802013-10-19 00:09:25 -07004154{
4155 PyObject *return_value = NULL;
4156 static char *_keywords[] = {"tz", NULL};
4157 PyObject *tz = Py_None;
4158
4159 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
4160 "|O:now", _keywords,
4161 &tz))
4162 goto exit;
Larry Hastings5c661892014-01-24 06:17:25 -08004163 return_value = datetime_datetime_now_impl(type, tz);
Larry Hastings31826802013-10-19 00:09:25 -07004164
4165exit:
4166 return return_value;
4167}
4168
4169static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -08004170datetime_datetime_now_impl(PyTypeObject *type, PyObject *tz)
Larry Hastings2623c8c2014-02-08 22:15:29 -08004171/*[clinic end generated code: output=583c5637e3c843fa input=80d09869c5267d00]*/
Tim Peters2a799bf2002-12-16 20:18:38 +00004172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004174
Larry Hastings31826802013-10-19 00:09:25 -07004175 /* Return best possible local time -- this isn't constrained by the
4176 * precision of a timestamp.
4177 */
4178 if (check_tzinfo_subclass(tz) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004180
Larry Hastings5c661892014-01-24 06:17:25 -08004181 self = datetime_best_possible((PyObject *)type,
Larry Hastings31826802013-10-19 00:09:25 -07004182 tz == Py_None ? localtime : gmtime,
4183 tz);
4184 if (self != NULL && tz != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 /* Convert UTC to tzinfo's zone. */
4186 PyObject *temp = self;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004187
Larry Hastings31826802013-10-19 00:09:25 -07004188 self = _PyObject_CallMethodId(tz, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 Py_DECREF(temp);
4190 }
4191 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004192}
4193
Tim Petersa9bc1682003-01-11 03:39:11 +00004194/* Return best possible UTC time -- this isn't constrained by the
4195 * precision of a timestamp.
4196 */
4197static PyObject *
4198datetime_utcnow(PyObject *cls, PyObject *dummy)
4199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004201}
4202
Tim Peters2a799bf2002-12-16 20:18:38 +00004203/* Return new local datetime from timestamp (Python timestamp -- a double). */
4204static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004205datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004208 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 PyObject *tzinfo = Py_None;
4210 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004211
Victor Stinner5d272cc2012-03-13 13:35:55 +01004212 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 keywords, &timestamp, &tzinfo))
4214 return NULL;
4215 if (check_tzinfo_subclass(tzinfo) < 0)
4216 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 self = datetime_from_timestamp(cls,
4219 tzinfo == Py_None ? localtime : gmtime,
4220 timestamp,
4221 tzinfo);
4222 if (self != NULL && tzinfo != Py_None) {
4223 /* Convert UTC to tzinfo's zone. */
4224 PyObject *temp = self;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004225
4226 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 Py_DECREF(temp);
4228 }
4229 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004230}
4231
Tim Petersa9bc1682003-01-11 03:39:11 +00004232/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4233static PyObject *
4234datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4235{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004236 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004238
Victor Stinner5d272cc2012-03-13 13:35:55 +01004239 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 result = datetime_from_timestamp(cls, gmtime, timestamp,
4241 Py_None);
4242 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004243}
4244
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004245/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004246static PyObject *
4247datetime_strptime(PyObject *cls, PyObject *args)
4248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004250 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004251 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004253 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004255
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004256 if (module == NULL) {
4257 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004258 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004259 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004260 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004261 return _PyObject_CallMethodId(module, &PyId__strptime_datetime, "OOO",
4262 cls, string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004263}
4264
Tim Petersa9bc1682003-01-11 03:39:11 +00004265/* Return new datetime from date/datetime and time arguments. */
4266static PyObject *
4267datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 static char *keywords[] = {"date", "time", NULL};
4270 PyObject *date;
4271 PyObject *time;
4272 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4275 &PyDateTime_DateType, &date,
4276 &PyDateTime_TimeType, &time)) {
4277 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 if (HASTZINFO(time))
4280 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4281 result = PyObject_CallFunction(cls, "iiiiiiiO",
4282 GET_YEAR(date),
4283 GET_MONTH(date),
4284 GET_DAY(date),
4285 TIME_GET_HOUR(time),
4286 TIME_GET_MINUTE(time),
4287 TIME_GET_SECOND(time),
4288 TIME_GET_MICROSECOND(time),
4289 tzinfo);
4290 }
4291 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004292}
Tim Peters2a799bf2002-12-16 20:18:38 +00004293
4294/*
4295 * Destructor.
4296 */
4297
4298static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004299datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 if (HASTZINFO(self)) {
4302 Py_XDECREF(self->tzinfo);
4303 }
4304 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004305}
4306
4307/*
4308 * Indirect access to tzinfo methods.
4309 */
4310
Tim Peters2a799bf2002-12-16 20:18:38 +00004311/* These are all METH_NOARGS, so don't need to check the arglist. */
4312static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004313datetime_utcoffset(PyObject *self, PyObject *unused) {
4314 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004315}
4316
4317static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004318datetime_dst(PyObject *self, PyObject *unused) {
4319 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004320}
4321
4322static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004323datetime_tzname(PyObject *self, PyObject *unused) {
4324 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004325}
4326
4327/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004328 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004329 */
4330
Tim Petersa9bc1682003-01-11 03:39:11 +00004331/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4332 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004333 */
4334static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004335add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 /* Note that the C-level additions can't overflow, because of
4339 * invariant bounds on the member values.
4340 */
4341 int year = GET_YEAR(date);
4342 int month = GET_MONTH(date);
4343 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4344 int hour = DATE_GET_HOUR(date);
4345 int minute = DATE_GET_MINUTE(date);
4346 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4347 int microsecond = DATE_GET_MICROSECOND(date) +
4348 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 assert(factor == 1 || factor == -1);
4351 if (normalize_datetime(&year, &month, &day,
4352 &hour, &minute, &second, &microsecond) < 0)
4353 return NULL;
4354 else
4355 return new_datetime(year, month, day,
4356 hour, minute, second, microsecond,
4357 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004358}
4359
4360static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004361datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 if (PyDateTime_Check(left)) {
4364 /* datetime + ??? */
4365 if (PyDelta_Check(right))
4366 /* datetime + delta */
4367 return add_datetime_timedelta(
4368 (PyDateTime_DateTime *)left,
4369 (PyDateTime_Delta *)right,
4370 1);
4371 }
4372 else if (PyDelta_Check(left)) {
4373 /* delta + datetime */
4374 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4375 (PyDateTime_Delta *) left,
4376 1);
4377 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004378 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004379}
4380
4381static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004382datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 if (PyDateTime_Check(left)) {
4387 /* datetime - ??? */
4388 if (PyDateTime_Check(right)) {
4389 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004390 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004392
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004393 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4394 offset2 = offset1 = Py_None;
4395 Py_INCREF(offset1);
4396 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004398 else {
4399 offset1 = datetime_utcoffset(left, NULL);
4400 if (offset1 == NULL)
4401 return NULL;
4402 offset2 = datetime_utcoffset(right, NULL);
4403 if (offset2 == NULL) {
4404 Py_DECREF(offset1);
4405 return NULL;
4406 }
4407 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4408 PyErr_SetString(PyExc_TypeError,
4409 "can't subtract offset-naive and "
4410 "offset-aware datetimes");
4411 Py_DECREF(offset1);
4412 Py_DECREF(offset2);
4413 return NULL;
4414 }
4415 }
4416 if ((offset1 != offset2) &&
4417 delta_cmp(offset1, offset2) != 0) {
4418 offdiff = delta_subtract(offset1, offset2);
4419 if (offdiff == NULL) {
4420 Py_DECREF(offset1);
4421 Py_DECREF(offset2);
4422 return NULL;
4423 }
4424 }
4425 Py_DECREF(offset1);
4426 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 delta_d = ymd_to_ord(GET_YEAR(left),
4428 GET_MONTH(left),
4429 GET_DAY(left)) -
4430 ymd_to_ord(GET_YEAR(right),
4431 GET_MONTH(right),
4432 GET_DAY(right));
4433 /* These can't overflow, since the values are
4434 * normalized. At most this gives the number of
4435 * seconds in one day.
4436 */
4437 delta_s = (DATE_GET_HOUR(left) -
4438 DATE_GET_HOUR(right)) * 3600 +
4439 (DATE_GET_MINUTE(left) -
4440 DATE_GET_MINUTE(right)) * 60 +
4441 (DATE_GET_SECOND(left) -
4442 DATE_GET_SECOND(right));
4443 delta_us = DATE_GET_MICROSECOND(left) -
4444 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 result = new_delta(delta_d, delta_s, delta_us, 1);
Victor Stinner70e11ac2013-11-08 00:50:58 +01004446 if (result == NULL)
4447 return NULL;
4448
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004449 if (offdiff != NULL) {
4450 PyObject *temp = result;
4451 result = delta_subtract(result, offdiff);
4452 Py_DECREF(temp);
4453 Py_DECREF(offdiff);
4454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 }
4456 else if (PyDelta_Check(right)) {
4457 /* datetime - delta */
4458 result = add_datetime_timedelta(
4459 (PyDateTime_DateTime *)left,
4460 (PyDateTime_Delta *)right,
4461 -1);
4462 }
4463 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 if (result == Py_NotImplemented)
4466 Py_INCREF(result);
4467 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004468}
4469
4470/* Various ways to turn a datetime into a string. */
4471
4472static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004473datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 const char *type_name = Py_TYPE(self)->tp_name;
4476 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 if (DATE_GET_MICROSECOND(self)) {
4479 baserepr = PyUnicode_FromFormat(
4480 "%s(%d, %d, %d, %d, %d, %d, %d)",
4481 type_name,
4482 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4483 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4484 DATE_GET_SECOND(self),
4485 DATE_GET_MICROSECOND(self));
4486 }
4487 else if (DATE_GET_SECOND(self)) {
4488 baserepr = PyUnicode_FromFormat(
4489 "%s(%d, %d, %d, %d, %d, %d)",
4490 type_name,
4491 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4492 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4493 DATE_GET_SECOND(self));
4494 }
4495 else {
4496 baserepr = PyUnicode_FromFormat(
4497 "%s(%d, %d, %d, %d, %d)",
4498 type_name,
4499 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4500 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4501 }
4502 if (baserepr == NULL || ! HASTZINFO(self))
4503 return baserepr;
4504 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004505}
4506
Tim Petersa9bc1682003-01-11 03:39:11 +00004507static PyObject *
4508datetime_str(PyDateTime_DateTime *self)
4509{
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004510 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004511}
Tim Peters2a799bf2002-12-16 20:18:38 +00004512
4513static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004514datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 int sep = 'T';
4517 static char *keywords[] = {"sep", NULL};
4518 char buffer[100];
4519 PyObject *result;
4520 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4523 return NULL;
4524 if (us)
4525 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4526 GET_YEAR(self), GET_MONTH(self),
4527 GET_DAY(self), (int)sep,
4528 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4529 DATE_GET_SECOND(self), us);
4530 else
4531 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4532 GET_YEAR(self), GET_MONTH(self),
4533 GET_DAY(self), (int)sep,
4534 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4535 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 if (!result || !HASTZINFO(self))
4538 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 /* We need to append the UTC offset. */
4541 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4542 (PyObject *)self) < 0) {
4543 Py_DECREF(result);
4544 return NULL;
4545 }
4546 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4547 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004548}
4549
Tim Petersa9bc1682003-01-11 03:39:11 +00004550static PyObject *
4551datetime_ctime(PyDateTime_DateTime *self)
4552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004553 return format_ctime((PyDateTime_Date *)self,
4554 DATE_GET_HOUR(self),
4555 DATE_GET_MINUTE(self),
4556 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004557}
4558
Tim Peters2a799bf2002-12-16 20:18:38 +00004559/* Miscellaneous methods. */
4560
Tim Petersa9bc1682003-01-11 03:39:11 +00004561static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004562datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004563{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004564 PyObject *result = NULL;
4565 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 if (! PyDateTime_Check(other)) {
4569 if (PyDate_Check(other)) {
4570 /* Prevent invocation of date_richcompare. We want to
4571 return NotImplemented here to give the other object
4572 a chance. But since DateTime is a subclass of
4573 Date, if the other object is a Date, it would
4574 compute an ordering based on the date part alone,
4575 and we don't want that. So force unequal or
4576 uncomparable here in that case. */
4577 if (op == Py_EQ)
4578 Py_RETURN_FALSE;
4579 if (op == Py_NE)
4580 Py_RETURN_TRUE;
4581 return cmperror(self, other);
4582 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004583 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004585
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004586 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4588 ((PyDateTime_DateTime *)other)->data,
4589 _PyDateTime_DATETIME_DATASIZE);
4590 return diff_to_bool(diff, op);
4591 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004592 offset1 = datetime_utcoffset(self, NULL);
4593 if (offset1 == NULL)
4594 return NULL;
4595 offset2 = datetime_utcoffset(other, NULL);
4596 if (offset2 == NULL)
4597 goto done;
4598 /* If they're both naive, or both aware and have the same offsets,
4599 * we get off cheap. Note that if they're both naive, offset1 ==
4600 * offset2 == Py_None at this point.
4601 */
4602 if ((offset1 == offset2) ||
4603 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4604 delta_cmp(offset1, offset2) == 0)) {
4605 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4606 ((PyDateTime_DateTime *)other)->data,
4607 _PyDateTime_DATETIME_DATASIZE);
4608 result = diff_to_bool(diff, op);
4609 }
4610 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004612
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004613 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4615 other);
4616 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004617 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 diff = GET_TD_DAYS(delta);
4619 if (diff == 0)
4620 diff = GET_TD_SECONDS(delta) |
4621 GET_TD_MICROSECONDS(delta);
4622 Py_DECREF(delta);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004623 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004625 else if (op == Py_EQ) {
4626 result = Py_False;
4627 Py_INCREF(result);
4628 }
4629 else if (op == Py_NE) {
4630 result = Py_True;
4631 Py_INCREF(result);
4632 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004633 else {
4634 PyErr_SetString(PyExc_TypeError,
4635 "can't compare offset-naive and "
4636 "offset-aware datetimes");
4637 }
4638 done:
4639 Py_DECREF(offset1);
4640 Py_XDECREF(offset2);
4641 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004642}
4643
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004644static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004645datetime_hash(PyDateTime_DateTime *self)
4646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004648 PyObject *offset;
Tim Petersa9bc1682003-01-11 03:39:11 +00004649
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004650 offset = datetime_utcoffset((PyObject *)self, NULL);
4651
4652 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004656 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 self->hashcode = generic_hash(
4658 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004660 PyObject *temp1, *temp2;
4661 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 assert(HASTZINFO(self));
4664 days = ymd_to_ord(GET_YEAR(self),
4665 GET_MONTH(self),
4666 GET_DAY(self));
4667 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004668 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004670 temp1 = new_delta(days, seconds,
4671 DATE_GET_MICROSECOND(self),
4672 1);
4673 if (temp1 == NULL) {
4674 Py_DECREF(offset);
4675 return -1;
4676 }
4677 temp2 = delta_subtract(temp1, offset);
4678 Py_DECREF(temp1);
4679 if (temp2 == NULL) {
4680 Py_DECREF(offset);
4681 return -1;
4682 }
4683 self->hashcode = PyObject_Hash(temp2);
4684 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004686 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 }
4688 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004689}
Tim Peters2a799bf2002-12-16 20:18:38 +00004690
4691static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004692datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 PyObject *clone;
4695 PyObject *tuple;
4696 int y = GET_YEAR(self);
4697 int m = GET_MONTH(self);
4698 int d = GET_DAY(self);
4699 int hh = DATE_GET_HOUR(self);
4700 int mm = DATE_GET_MINUTE(self);
4701 int ss = DATE_GET_SECOND(self);
4702 int us = DATE_GET_MICROSECOND(self);
4703 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4706 datetime_kws,
4707 &y, &m, &d, &hh, &mm, &ss, &us,
4708 &tzinfo))
4709 return NULL;
4710 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4711 if (tuple == NULL)
4712 return NULL;
4713 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4714 Py_DECREF(tuple);
4715 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004716}
4717
4718static PyObject *
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004719local_timezone(PyDateTime_DateTime *utc_time)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004720{
4721 PyObject *result = NULL;
4722 struct tm *timep;
4723 time_t timestamp;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004724 PyObject *delta;
4725 PyObject *one_second;
4726 PyObject *seconds;
4727 PyObject *nameo = NULL;
4728 const char *zone = NULL;
4729
4730 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
4731 if (delta == NULL)
4732 return NULL;
4733 one_second = new_delta(0, 1, 0, 0);
4734 if (one_second == NULL)
4735 goto error;
4736 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
4737 (PyDateTime_Delta *)one_second);
4738 Py_DECREF(one_second);
4739 if (seconds == NULL)
4740 goto error;
4741 Py_DECREF(delta);
4742 timestamp = PyLong_AsLong(seconds);
4743 Py_DECREF(seconds);
4744 if (timestamp == -1 && PyErr_Occurred())
4745 return NULL;
4746 timep = localtime(&timestamp);
4747#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky93c9cd02012-06-22 16:04:19 -04004748 zone = timep->tm_zone;
4749 delta = new_delta(0, timep->tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004750#else /* HAVE_STRUCT_TM_TM_ZONE */
4751 {
4752 PyObject *local_time;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004753 local_time = new_datetime(timep->tm_year + 1900, timep->tm_mon + 1,
4754 timep->tm_mday, timep->tm_hour, timep->tm_min,
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004755 timep->tm_sec, DATE_GET_MICROSECOND(utc_time),
4756 utc_time->tzinfo);
4757 if (local_time == NULL)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004758 goto error;
Alexander Belopolsky93c9cd02012-06-22 16:04:19 -04004759 delta = datetime_subtract(local_time, (PyObject*)utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004760 /* XXX: before relying on tzname, we should compare delta
4761 to the offset implied by timezone/altzone */
4762 if (daylight && timep->tm_isdst >= 0)
4763 zone = tzname[timep->tm_isdst % 2];
4764 else
4765 zone = tzname[0];
4766 Py_DECREF(local_time);
4767 }
4768#endif /* HAVE_STRUCT_TM_TM_ZONE */
4769 if (zone != NULL) {
4770 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
4771 if (nameo == NULL)
4772 goto error;
4773 }
4774 result = new_timezone(delta, nameo);
Christian Heimesb91ffaa2013-06-29 20:52:33 +02004775 Py_XDECREF(nameo);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004776 error:
4777 Py_DECREF(delta);
4778 return result;
4779}
4780
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004781static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00004782datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004783{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004784 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004785 PyObject *offset;
4786 PyObject *temp;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004787 PyObject *tzinfo = Py_None;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004789
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004790 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
Raymond Hettinger5a2146a2014-07-25 14:59:48 -07004791 &tzinfo))
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004792 return NULL;
4793
4794 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4798 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 /* Conversion to self's own time zone is a NOP. */
4801 if (self->tzinfo == tzinfo) {
4802 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004803 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 }
Tim Peters521fc152002-12-31 17:36:56 +00004805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 /* Convert self to UTC. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004807 offset = datetime_utcoffset((PyObject *)self, NULL);
4808 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004810 if (offset == Py_None) {
4811 Py_DECREF(offset);
4812 NeedAware:
4813 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4814 "a naive datetime");
4815 return NULL;
4816 }
Tim Petersf3615152003-01-01 21:51:37 +00004817
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004818 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004819 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4820 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004821 Py_DECREF(offset);
4822 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004826 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004827 if (tzinfo == Py_None) {
4828 tzinfo = local_timezone(result);
4829 if (tzinfo == NULL) {
4830 Py_DECREF(result);
4831 return NULL;
4832 }
4833 }
4834 else
4835 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004836 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004837 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00004838
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004839 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004840 result = (PyDateTime_DateTime *)
4841 _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", temp);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004842 Py_DECREF(temp);
4843
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004844 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00004845}
4846
4847static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004848datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004853 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00004854
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004855 dst = call_dst(self->tzinfo, (PyObject *)self);
4856 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004858
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004859 if (dst != Py_None)
4860 dstflag = delta_bool((PyDateTime_Delta *)dst);
4861 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 }
4863 return build_struct_time(GET_YEAR(self),
4864 GET_MONTH(self),
4865 GET_DAY(self),
4866 DATE_GET_HOUR(self),
4867 DATE_GET_MINUTE(self),
4868 DATE_GET_SECOND(self),
4869 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004870}
4871
4872static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04004873datetime_timestamp(PyDateTime_DateTime *self)
4874{
4875 PyObject *result;
4876
4877 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4878 PyObject *delta;
4879 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
4880 if (delta == NULL)
4881 return NULL;
4882 result = delta_total_seconds(delta);
4883 Py_DECREF(delta);
4884 }
4885 else {
4886 struct tm time;
4887 time_t timestamp;
4888 memset((void *) &time, '\0', sizeof(struct tm));
4889 time.tm_year = GET_YEAR(self) - 1900;
4890 time.tm_mon = GET_MONTH(self) - 1;
4891 time.tm_mday = GET_DAY(self);
4892 time.tm_hour = DATE_GET_HOUR(self);
4893 time.tm_min = DATE_GET_MINUTE(self);
4894 time.tm_sec = DATE_GET_SECOND(self);
4895 time.tm_wday = -1;
4896 time.tm_isdst = -1;
4897 timestamp = mktime(&time);
Victor Stinner93037492013-06-25 22:54:35 +02004898 if (timestamp == (time_t)(-1)
4899#ifndef _AIX
4900 /* Return value of -1 does not necessarily mean an error,
4901 * but tm_wday cannot remain set to -1 if mktime succeeded. */
4902 && time.tm_wday == -1
4903#else
4904 /* on AIX, tm_wday is always sets, even on error */
4905#endif
4906 )
4907 {
Alexander Belopolskya4415142012-06-08 12:33:09 -04004908 PyErr_SetString(PyExc_OverflowError,
4909 "timestamp out of range");
4910 return NULL;
4911 }
4912 result = PyFloat_FromDouble(timestamp + DATE_GET_MICROSECOND(self) / 1e6);
4913 }
4914 return result;
4915}
4916
4917static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004918datetime_getdate(PyDateTime_DateTime *self)
4919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004920 return new_date(GET_YEAR(self),
4921 GET_MONTH(self),
4922 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004923}
4924
4925static PyObject *
4926datetime_gettime(PyDateTime_DateTime *self)
4927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 return new_time(DATE_GET_HOUR(self),
4929 DATE_GET_MINUTE(self),
4930 DATE_GET_SECOND(self),
4931 DATE_GET_MICROSECOND(self),
4932 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004933}
4934
4935static PyObject *
4936datetime_gettimetz(PyDateTime_DateTime *self)
4937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004938 return new_time(DATE_GET_HOUR(self),
4939 DATE_GET_MINUTE(self),
4940 DATE_GET_SECOND(self),
4941 DATE_GET_MICROSECOND(self),
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004942 GET_DT_TZINFO(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004943}
4944
4945static PyObject *
4946datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004947{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004948 int y, m, d, hh, mm, ss;
4949 PyObject *tzinfo;
4950 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00004951
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004952 tzinfo = GET_DT_TZINFO(self);
4953 if (tzinfo == Py_None) {
4954 utcself = self;
4955 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004956 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004957 else {
4958 PyObject *offset;
4959 offset = call_utcoffset(tzinfo, (PyObject *)self);
4960 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00004961 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004962 if (offset == Py_None) {
4963 Py_DECREF(offset);
4964 utcself = self;
4965 Py_INCREF(utcself);
4966 }
4967 else {
4968 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4969 (PyDateTime_Delta *)offset, -1);
4970 Py_DECREF(offset);
4971 if (utcself == NULL)
4972 return NULL;
4973 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004974 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004975 y = GET_YEAR(utcself);
4976 m = GET_MONTH(utcself);
4977 d = GET_DAY(utcself);
4978 hh = DATE_GET_HOUR(utcself);
4979 mm = DATE_GET_MINUTE(utcself);
4980 ss = DATE_GET_SECOND(utcself);
4981
4982 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004984}
4985
Tim Peters371935f2003-02-01 01:52:50 +00004986/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004987
Tim Petersa9bc1682003-01-11 03:39:11 +00004988/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004989 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4990 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004991 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004992 */
4993static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004994datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 PyObject *basestate;
4997 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004999 basestate = PyBytes_FromStringAndSize((char *)self->data,
5000 _PyDateTime_DATETIME_DATASIZE);
5001 if (basestate != NULL) {
5002 if (! HASTZINFO(self) || self->tzinfo == Py_None)
5003 result = PyTuple_Pack(1, basestate);
5004 else
5005 result = PyTuple_Pack(2, basestate, self->tzinfo);
5006 Py_DECREF(basestate);
5007 }
5008 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00005009}
5010
5011static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00005012datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00005013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005014 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00005015}
5016
Tim Petersa9bc1682003-01-11 03:39:11 +00005017static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00005018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00005020
Larry Hastingsed4a1c52013-11-18 09:32:13 -08005021 DATETIME_DATETIME_NOW_METHODDEF
Tim Peters2a799bf2002-12-16 20:18:38 +00005022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 {"utcnow", (PyCFunction)datetime_utcnow,
5024 METH_NOARGS | METH_CLASS,
5025 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005027 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5028 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5029 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005031 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5032 METH_VARARGS | METH_CLASS,
Alexander Belopolskye2e178e2015-03-01 14:52:07 -05005033 PyDoc_STR("Construct a naive UTC datetime from a POSIX timestamp.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 {"strptime", (PyCFunction)datetime_strptime,
5036 METH_VARARGS | METH_CLASS,
5037 PyDoc_STR("string, format -> new datetime parsed from a string "
5038 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005040 {"combine", (PyCFunction)datetime_combine,
5041 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5042 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5047 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005049 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5050 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5053 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5056 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5059 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005060
Alexander Belopolskya4415142012-06-08 12:33:09 -04005061 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5062 PyDoc_STR("Return POSIX timestamp as float.")},
5063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5065 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5068 PyDoc_STR("[sep] -> string in ISO 8601 format, "
5069 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
5070 "sep is used to separate the year from the time, and "
5071 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5074 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5077 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5080 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5083 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5086 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
5089 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005092};
5093
Tim Petersa9bc1682003-01-11 03:39:11 +00005094static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005095PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5096\n\
5097The year, month and day arguments are required. tzinfo may be None, or an\n\
Serhiy Storchaka95949422013-08-27 19:40:23 +03005098instance of a tzinfo subclass. The remaining arguments may be ints.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005099
Tim Petersa9bc1682003-01-11 03:39:11 +00005100static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 datetime_add, /* nb_add */
5102 datetime_subtract, /* nb_subtract */
5103 0, /* nb_multiply */
5104 0, /* nb_remainder */
5105 0, /* nb_divmod */
5106 0, /* nb_power */
5107 0, /* nb_negative */
5108 0, /* nb_positive */
5109 0, /* nb_absolute */
5110 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005111};
5112
Neal Norwitz227b5332006-03-22 09:28:35 +00005113static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 PyVarObject_HEAD_INIT(NULL, 0)
5115 "datetime.datetime", /* tp_name */
5116 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5117 0, /* tp_itemsize */
5118 (destructor)datetime_dealloc, /* tp_dealloc */
5119 0, /* tp_print */
5120 0, /* tp_getattr */
5121 0, /* tp_setattr */
5122 0, /* tp_reserved */
5123 (reprfunc)datetime_repr, /* tp_repr */
5124 &datetime_as_number, /* tp_as_number */
5125 0, /* tp_as_sequence */
5126 0, /* tp_as_mapping */
5127 (hashfunc)datetime_hash, /* tp_hash */
5128 0, /* tp_call */
5129 (reprfunc)datetime_str, /* tp_str */
5130 PyObject_GenericGetAttr, /* tp_getattro */
5131 0, /* tp_setattro */
5132 0, /* tp_as_buffer */
5133 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5134 datetime_doc, /* tp_doc */
5135 0, /* tp_traverse */
5136 0, /* tp_clear */
5137 datetime_richcompare, /* tp_richcompare */
5138 0, /* tp_weaklistoffset */
5139 0, /* tp_iter */
5140 0, /* tp_iternext */
5141 datetime_methods, /* tp_methods */
5142 0, /* tp_members */
5143 datetime_getset, /* tp_getset */
5144 &PyDateTime_DateType, /* tp_base */
5145 0, /* tp_dict */
5146 0, /* tp_descr_get */
5147 0, /* tp_descr_set */
5148 0, /* tp_dictoffset */
5149 0, /* tp_init */
5150 datetime_alloc, /* tp_alloc */
5151 datetime_new, /* tp_new */
5152 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005153};
5154
5155/* ---------------------------------------------------------------------------
5156 * Module methods and initialization.
5157 */
5158
5159static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005161};
5162
Tim Peters9ddf40b2004-06-20 22:41:32 +00005163/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5164 * datetime.h.
5165 */
5166static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 &PyDateTime_DateType,
5168 &PyDateTime_DateTimeType,
5169 &PyDateTime_TimeType,
5170 &PyDateTime_DeltaType,
5171 &PyDateTime_TZInfoType,
5172 new_date_ex,
5173 new_datetime_ex,
5174 new_time_ex,
5175 new_delta_ex,
5176 datetime_fromtimestamp,
5177 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00005178};
5179
5180
Martin v. Löwis1a214512008-06-11 05:26:20 +00005181
5182static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005183 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005184 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005185 "Fast implementation of the datetime type.",
5186 -1,
5187 module_methods,
5188 NULL,
5189 NULL,
5190 NULL,
5191 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005192};
5193
Tim Peters2a799bf2002-12-16 20:18:38 +00005194PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005195PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 PyObject *m; /* a module object */
5198 PyObject *d; /* its dict */
5199 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005200 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 m = PyModule_Create(&datetimemodule);
5203 if (m == NULL)
5204 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005206 if (PyType_Ready(&PyDateTime_DateType) < 0)
5207 return NULL;
5208 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5209 return NULL;
5210 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5211 return NULL;
5212 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5213 return NULL;
5214 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5215 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005216 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5217 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005219 /* timedelta values */
5220 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 x = new_delta(0, 0, 1, 0);
5223 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5224 return NULL;
5225 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005227 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5228 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5229 return NULL;
5230 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005232 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5233 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5234 return NULL;
5235 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005237 /* date values */
5238 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 x = new_date(1, 1, 1);
5241 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5242 return NULL;
5243 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005245 x = new_date(MAXYEAR, 12, 31);
5246 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5247 return NULL;
5248 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005250 x = new_delta(1, 0, 0, 0);
5251 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5252 return NULL;
5253 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 /* time values */
5256 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 x = new_time(0, 0, 0, 0, Py_None);
5259 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5260 return NULL;
5261 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005263 x = new_time(23, 59, 59, 999999, Py_None);
5264 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5265 return NULL;
5266 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005268 x = new_delta(0, 0, 1, 0);
5269 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5270 return NULL;
5271 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005273 /* datetime values */
5274 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
5277 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5278 return NULL;
5279 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005281 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5282 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5283 return NULL;
5284 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 x = new_delta(0, 0, 1, 0);
5287 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5288 return NULL;
5289 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005290
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005291 /* timezone values */
5292 d = PyDateTime_TimeZoneType.tp_dict;
5293
5294 delta = new_delta(0, 0, 0, 0);
5295 if (delta == NULL)
5296 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005297 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005298 Py_DECREF(delta);
5299 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5300 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005301 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005302
5303 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5304 if (delta == NULL)
5305 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005306 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005307 Py_DECREF(delta);
5308 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5309 return NULL;
5310 Py_DECREF(x);
5311
5312 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5313 if (delta == NULL)
5314 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005315 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005316 Py_DECREF(delta);
5317 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5318 return NULL;
5319 Py_DECREF(x);
5320
Alexander Belopolskya4415142012-06-08 12:33:09 -04005321 /* Epoch */
5322 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
5323 PyDateTime_TimeZone_UTC);
5324 if (PyDateTime_Epoch == NULL)
5325 return NULL;
5326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 /* module initialization */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +02005328 PyModule_AddIntMacro(m, MINYEAR);
5329 PyModule_AddIntMacro(m, MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 Py_INCREF(&PyDateTime_DateType);
5332 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005334 Py_INCREF(&PyDateTime_DateTimeType);
5335 PyModule_AddObject(m, "datetime",
5336 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 Py_INCREF(&PyDateTime_TimeType);
5339 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 Py_INCREF(&PyDateTime_DeltaType);
5342 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 Py_INCREF(&PyDateTime_TZInfoType);
5345 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005346
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005347 Py_INCREF(&PyDateTime_TimeZoneType);
5348 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005350 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5351 if (x == NULL)
5352 return NULL;
5353 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 /* A 4-year cycle has an extra leap day over what we'd get from
5356 * pasting together 4 single years.
5357 */
5358 assert(DI4Y == 4 * 365 + 1);
5359 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5362 * get from pasting together 4 100-year cycles.
5363 */
5364 assert(DI400Y == 4 * DI100Y + 1);
5365 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005367 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5368 * pasting together 25 4-year cycles.
5369 */
5370 assert(DI100Y == 25 * DI4Y - 1);
5371 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005372
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005373 one = PyLong_FromLong(1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 us_per_ms = PyLong_FromLong(1000);
5375 us_per_second = PyLong_FromLong(1000000);
5376 us_per_minute = PyLong_FromLong(60000000);
5377 seconds_per_day = PyLong_FromLong(24 * 3600);
Alexander Belopolsky790d2692013-08-04 14:51:35 -04005378 if (one == NULL || us_per_ms == NULL || us_per_second == NULL ||
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 us_per_minute == NULL || seconds_per_day == NULL)
5380 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 /* The rest are too big for 32-bit ints, but even
5383 * us_per_week fits in 40 bits, so doubles should be exact.
5384 */
5385 us_per_hour = PyLong_FromDouble(3600000000.0);
5386 us_per_day = PyLong_FromDouble(86400000000.0);
5387 us_per_week = PyLong_FromDouble(604800000000.0);
5388 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5389 return NULL;
5390 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005391}
Tim Petersf3615152003-01-01 21:51:37 +00005392
5393/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005394Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005395 x.n = x stripped of its timezone -- its naive time.
5396 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005397 return None
Tim Petersf3615152003-01-01 21:51:37 +00005398 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005399 return None
Tim Petersf3615152003-01-01 21:51:37 +00005400 x.s = x's standard offset, x.o - x.d
5401
5402Now some derived rules, where k is a duration (timedelta).
5403
54041. x.o = x.s + x.d
5405 This follows from the definition of x.s.
5406
Tim Petersc5dc4da2003-01-02 17:55:03 +000054072. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005408 This is actually a requirement, an assumption we need to make about
5409 sane tzinfo classes.
5410
54113. The naive UTC time corresponding to x is x.n - x.o.
5412 This is again a requirement for a sane tzinfo class.
5413
54144. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005415 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005416
Tim Petersc5dc4da2003-01-02 17:55:03 +000054175. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005418 Again follows from how arithmetic is defined.
5419
Tim Peters8bb5ad22003-01-24 02:44:45 +00005420Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005421(meaning that the various tzinfo methods exist, and don't blow up or return
5422None when called).
5423
Tim Petersa9bc1682003-01-11 03:39:11 +00005424The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005425x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005426
5427By #3, we want
5428
Tim Peters8bb5ad22003-01-24 02:44:45 +00005429 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005430
5431The algorithm starts by attaching tz to x.n, and calling that y. So
5432x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5433becomes true; in effect, we want to solve [2] for k:
5434
Tim Peters8bb5ad22003-01-24 02:44:45 +00005435 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005436
5437By #1, this is the same as
5438
Tim Peters8bb5ad22003-01-24 02:44:45 +00005439 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005440
5441By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5442Substituting that into [3],
5443
Tim Peters8bb5ad22003-01-24 02:44:45 +00005444 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5445 k - (y+k).s - (y+k).d = 0; rearranging,
5446 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5447 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005448
Tim Peters8bb5ad22003-01-24 02:44:45 +00005449On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5450approximate k by ignoring the (y+k).d term at first. Note that k can't be
5451very large, since all offset-returning methods return a duration of magnitude
5452less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5453be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005454
5455In any case, the new value is
5456
Tim Peters8bb5ad22003-01-24 02:44:45 +00005457 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005458
Tim Peters8bb5ad22003-01-24 02:44:45 +00005459It's helpful to step back at look at [4] from a higher level: it's simply
5460mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005461
5462At this point, if
5463
Tim Peters8bb5ad22003-01-24 02:44:45 +00005464 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005465
5466we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005467at the start of daylight time. Picture US Eastern for concreteness. The wall
5468time 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 +00005469sense then. The docs ask that an Eastern tzinfo class consider such a time to
5470be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5471on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005472the only spelling that makes sense on the local wall clock.
5473
Tim Petersc5dc4da2003-01-02 17:55:03 +00005474In fact, if [5] holds at this point, we do have the standard-time spelling,
5475but that takes a bit of proof. We first prove a stronger result. What's the
5476difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005477
Tim Peters8bb5ad22003-01-24 02:44:45 +00005478 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005479
Tim Petersc5dc4da2003-01-02 17:55:03 +00005480Now
5481 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005482 (y + y.s).n = by #5
5483 y.n + y.s = since y.n = x.n
5484 x.n + y.s = since z and y are have the same tzinfo member,
5485 y.s = z.s by #2
5486 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005487
Tim Petersc5dc4da2003-01-02 17:55:03 +00005488Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005489
Tim Petersc5dc4da2003-01-02 17:55:03 +00005490 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005491 x.n - ((x.n + z.s) - z.o) = expanding
5492 x.n - x.n - z.s + z.o = cancelling
5493 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005494 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005495
Tim Petersc5dc4da2003-01-02 17:55:03 +00005496So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005497
Tim Petersc5dc4da2003-01-02 17:55:03 +00005498If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005499spelling we wanted in the endcase described above. We're done. Contrarily,
5500if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005501
Tim Petersc5dc4da2003-01-02 17:55:03 +00005502If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5503add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005504local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005505
Tim Petersc5dc4da2003-01-02 17:55:03 +00005506Let
Tim Petersf3615152003-01-01 21:51:37 +00005507
Tim Peters4fede1a2003-01-04 00:26:59 +00005508 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005509
Tim Peters4fede1a2003-01-04 00:26:59 +00005510and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005511
Tim Peters8bb5ad22003-01-24 02:44:45 +00005512 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005513
Tim Peters8bb5ad22003-01-24 02:44:45 +00005514If so, we're done. If not, the tzinfo class is insane, according to the
5515assumptions we've made. This also requires a bit of proof. As before, let's
5516compute the difference between the LHS and RHS of [8] (and skipping some of
5517the justifications for the kinds of substitutions we've done several times
5518already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005519
Tim Peters8bb5ad22003-01-24 02:44:45 +00005520 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5522 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5523 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5524 - z.n + z.n - z.o + z'.o = cancel z.n
5525 - z.o + z'.o = #1 twice
5526 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5527 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005528
5529So 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 +00005530we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5531return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005532
Tim Peters8bb5ad22003-01-24 02:44:45 +00005533How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5534a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5535would have to change the result dst() returns: we start in DST, and moving
5536a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005537
Tim Peters8bb5ad22003-01-24 02:44:45 +00005538There isn't a sane case where this can happen. The closest it gets is at
5539the end of DST, where there's an hour in UTC with no spelling in a hybrid
5540tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5541that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5542UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5543time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5544clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5545standard time. Since that's what the local clock *does*, we want to map both
5546UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005547in local time, but so it goes -- it's the way the local clock works.
5548
Tim Peters8bb5ad22003-01-24 02:44:45 +00005549When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5550so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5551z' = 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 +00005552(correctly) concludes that z' is not UTC-equivalent to x.
5553
5554Because we know z.d said z was in daylight time (else [5] would have held and
5555we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005556and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005557return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5558but the reasoning doesn't depend on the example -- it depends on there being
5559two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005560z' must be in standard time, and is the spelling we want in this case.
5561
5562Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5563concerned (because it takes z' as being in standard time rather than the
5564daylight time we intend here), but returning it gives the real-life "local
5565clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5566tz.
5567
5568When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5569the 1:MM standard time spelling we want.
5570
5571So how can this break? One of the assumptions must be violated. Two
5572possibilities:
5573
55741) [2] effectively says that y.s is invariant across all y belong to a given
5575 time zone. This isn't true if, for political reasons or continental drift,
5576 a region decides to change its base offset from UTC.
5577
55782) There may be versions of "double daylight" time where the tail end of
5579 the analysis gives up a step too early. I haven't thought about that
5580 enough to say.
5581
5582In any case, it's clear that the default fromutc() is strong enough to handle
5583"almost all" time zones: so long as the standard offset is invariant, it
5584doesn't matter if daylight time transition points change from year to year, or
5585if daylight time is skipped in some years; it doesn't matter how large or
5586small dst() may get within its bounds; and it doesn't even matter if some
5587perverse time zone returns a negative dst()). So a breaking case must be
5588pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005589--------------------------------------------------------------------------- */