blob: 01c85d1cd32e3d80a0cea943e5dd28e04d6cf2ba [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
Tim Peters9ddf40b2004-06-20 22:41:32 +000010/* Differentiate between building the core module and building extension
11 * modules.
12 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000013#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000014#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000015#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000016#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000018
19/* We require that C int be at least 32 bits, and use int virtually
20 * everywhere. In just a few cases we use a temp long, where a Python
21 * API returns a C long. In such cases, we have to ensure that the
22 * final result fits in a C int (this can be an issue on 64-bit boxes).
23 */
24#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000025# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000026#endif
27
28#define MINYEAR 1
29#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000030#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000031
32/* Nine decimal digits is easy to communicate, and leaves enough room
33 * so that two delta days can be added w/o fear of overflowing a signed
34 * 32-bit int, and with plenty of room left over to absorb any possible
35 * carries from adding seconds.
36 */
37#define MAX_DELTA_DAYS 999999999
38
39/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040#define GET_YEAR PyDateTime_GET_YEAR
41#define GET_MONTH PyDateTime_GET_MONTH
42#define GET_DAY PyDateTime_GET_DAY
43#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
44#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
45#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
46#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000047
48/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
50 ((o)->data[1] = ((v) & 0x00ff)))
51#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
52#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000053
54/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
56#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
57#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
58#define DATE_SET_MICROSECOND(o, v) \
59 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
60 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
61 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000062
63/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
65#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
66#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
67#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
68#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
69#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
70#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
71#define TIME_SET_MICROSECOND(o, v) \
72 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
73 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
74 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000075
76/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
78#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
79#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081#define SET_TD_DAYS(o, v) ((o)->days = (v))
82#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000083#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
84
Tim Petersa032d2e2003-01-11 00:15:54 +000085/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
86 * p->hastzinfo.
87 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +000088#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
89#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
90 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
91#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
92 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +000093/* M is a char or int claiming to be a valid month. The macro is equivalent
94 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +000096 */
97#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
98
Tim Peters2a799bf2002-12-16 20:18:38 +000099/* Forward declarations. */
100static PyTypeObject PyDateTime_DateType;
101static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000102static PyTypeObject PyDateTime_DeltaType;
103static PyTypeObject PyDateTime_TimeType;
104static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000105static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000106
107/* ---------------------------------------------------------------------------
108 * Math utilities.
109 */
110
111/* k = i+j overflows iff k differs in sign from both inputs,
112 * iff k^i has sign bit set and k^j has sign bit set,
113 * iff (k^i)&(k^j) has sign bit set.
114 */
115#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000117
118/* Compute Python divmod(x, y), returning the quotient and storing the
119 * remainder into *r. The quotient is the floor of x/y, and that's
120 * the real point of this. C will probably truncate instead (C99
121 * requires truncation; C89 left it implementation-defined).
122 * Simplification: we *require* that y > 0 here. That's appropriate
123 * for all the uses made of it. This simplifies the code and makes
124 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
125 * overflow case).
126 */
127static int
128divmod(int x, int y, int *r)
129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 assert(y > 0);
133 quo = x / y;
134 *r = x - quo * y;
135 if (*r < 0) {
136 --quo;
137 *r += y;
138 }
139 assert(0 <= *r && *r < y);
140 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000141}
142
Tim Peters5d644dd2003-01-02 16:32:54 +0000143/* Round a double to the nearest long. |x| must be small enough to fit
144 * in a C long; this is not checked.
145 */
146static long
147round_to_long(double x)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (x >= 0.0)
150 x = floor(x + 0.5);
151 else
152 x = ceil(x - 0.5);
153 return (long)x;
Tim Peters5d644dd2003-01-02 16:32:54 +0000154}
155
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000156/* Nearest integer to m / n for integers m and n. Half-integer results
157 * are rounded to even.
158 */
159static PyObject *
160divide_nearest(PyObject *m, PyObject *n)
161{
162 PyObject *result;
163 PyObject *temp;
164
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000165 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000166 if (temp == NULL)
167 return NULL;
168 result = PyTuple_GET_ITEM(temp, 0);
169 Py_INCREF(result);
170 Py_DECREF(temp);
171
172 return result;
173}
174
Tim Peters2a799bf2002-12-16 20:18:38 +0000175/* ---------------------------------------------------------------------------
176 * General calendrical helper functions
177 */
178
179/* For each month ordinal in 1..12, the number of days in that month,
180 * and the number of days before that month in the same year. These
181 * are correct for non-leap years only.
182 */
183static int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 0, /* unused; this vector uses 1-based indexing */
185 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000186};
187
188static int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 0, /* unused; this vector uses 1-based indexing */
190 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000191};
192
193/* year -> 1 if leap year, else 0. */
194static int
195is_leap(int year)
196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 /* Cast year to unsigned. The result is the same either way, but
198 * C can generate faster code for unsigned mod than for signed
199 * mod (especially for % 4 -- a good compiler should just grab
200 * the last 2 bits when the LHS is unsigned).
201 */
202 const unsigned int ayear = (unsigned int)year;
203 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000204}
205
206/* year, month -> number of days in that month in that year */
207static int
208days_in_month(int year, int month)
209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 assert(month >= 1);
211 assert(month <= 12);
212 if (month == 2 && is_leap(year))
213 return 29;
214 else
215 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000216}
217
218/* year, month -> number of days in year preceeding first day of month */
219static int
220days_before_month(int year, int month)
221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 assert(month >= 1);
225 assert(month <= 12);
226 days = _days_before_month[month];
227 if (month > 2 && is_leap(year))
228 ++days;
229 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000230}
231
232/* year -> number of days before January 1st of year. Remember that we
233 * start with year 1, so days_before_year(1) == 0.
234 */
235static int
236days_before_year(int year)
237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 int y = year - 1;
239 /* This is incorrect if year <= 0; we really want the floor
240 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000241 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000243 assert (year >= 1);
244 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000245}
246
247/* Number of days in 4, 100, and 400 year cycles. That these have
248 * the correct values is asserted in the module init function.
249 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250#define DI4Y 1461 /* days_before_year(5); days in 4 years */
251#define DI100Y 36524 /* days_before_year(101); days in 100 years */
252#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000253
254/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
255static void
256ord_to_ymd(int ordinal, int *year, int *month, int *day)
257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
261 * leap years repeats exactly every 400 years. The basic strategy is
262 * to find the closest 400-year boundary at or before ordinal, then
263 * work with the offset from that boundary to ordinal. Life is much
264 * clearer if we subtract 1 from ordinal first -- then the values
265 * of ordinal at 400-year boundaries are exactly those divisible
266 * by DI400Y:
267 *
268 * D M Y n n-1
269 * -- --- ---- ---------- ----------------
270 * 31 Dec -400 -DI400Y -DI400Y -1
271 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
272 * ...
273 * 30 Dec 000 -1 -2
274 * 31 Dec 000 0 -1
275 * 1 Jan 001 1 0 400-year boundary
276 * 2 Jan 001 2 1
277 * 3 Jan 001 3 2
278 * ...
279 * 31 Dec 400 DI400Y DI400Y -1
280 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
281 */
282 assert(ordinal >= 1);
283 --ordinal;
284 n400 = ordinal / DI400Y;
285 n = ordinal % DI400Y;
286 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 /* Now n is the (non-negative) offset, in days, from January 1 of
289 * year, to the desired date. Now compute how many 100-year cycles
290 * precede n.
291 * Note that it's possible for n100 to equal 4! In that case 4 full
292 * 100-year cycles precede the desired day, which implies the
293 * desired day is December 31 at the end of a 400-year cycle.
294 */
295 n100 = n / DI100Y;
296 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* Now compute how many 4-year cycles precede it. */
299 n4 = n / DI4Y;
300 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 /* And now how many single years. Again n1 can be 4, and again
303 * meaning that the desired day is December 31 at the end of the
304 * 4-year cycle.
305 */
306 n1 = n / 365;
307 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 *year += n100 * 100 + n4 * 4 + n1;
310 if (n1 == 4 || n100 == 4) {
311 assert(n == 0);
312 *year -= 1;
313 *month = 12;
314 *day = 31;
315 return;
316 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 /* Now the year is correct, and n is the offset from January 1. We
319 * find the month via an estimate that's either exact or one too
320 * large.
321 */
322 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
323 assert(leapyear == is_leap(*year));
324 *month = (n + 50) >> 5;
325 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
326 if (preceding > n) {
327 /* estimate is too large */
328 *month -= 1;
329 preceding -= days_in_month(*year, *month);
330 }
331 n -= preceding;
332 assert(0 <= n);
333 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000336}
337
338/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
339static int
340ymd_to_ord(int year, int month, int day)
341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000343}
344
345/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
346static int
347weekday(int year, int month, int day)
348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000350}
351
352/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
353 * first calendar week containing a Thursday.
354 */
355static int
356iso_week1_monday(int year)
357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
359 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
360 int first_weekday = (first_day + 6) % 7;
361 /* ordinal of closest Monday at or before 1/1 */
362 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
365 week1_monday += 7;
366 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000367}
368
369/* ---------------------------------------------------------------------------
370 * Range checkers.
371 */
372
373/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
374 * If not, raise OverflowError and return -1.
375 */
376static int
377check_delta_day_range(int days)
378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
380 return 0;
381 PyErr_Format(PyExc_OverflowError,
382 "days=%d; must have magnitude <= %d",
383 days, MAX_DELTA_DAYS);
384 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000385}
386
387/* Check that date arguments are in range. Return 0 if they are. If they
388 * aren't, raise ValueError and return -1.
389 */
390static int
391check_date_args(int year, int month, int day)
392{
393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (year < MINYEAR || year > MAXYEAR) {
395 PyErr_SetString(PyExc_ValueError,
396 "year is out of range");
397 return -1;
398 }
399 if (month < 1 || month > 12) {
400 PyErr_SetString(PyExc_ValueError,
401 "month must be in 1..12");
402 return -1;
403 }
404 if (day < 1 || day > days_in_month(year, month)) {
405 PyErr_SetString(PyExc_ValueError,
406 "day is out of range for month");
407 return -1;
408 }
409 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000410}
411
412/* Check that time arguments are in range. Return 0 if they are. If they
413 * aren't, raise ValueError and return -1.
414 */
415static int
416check_time_args(int h, int m, int s, int us)
417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (h < 0 || h > 23) {
419 PyErr_SetString(PyExc_ValueError,
420 "hour must be in 0..23");
421 return -1;
422 }
423 if (m < 0 || m > 59) {
424 PyErr_SetString(PyExc_ValueError,
425 "minute must be in 0..59");
426 return -1;
427 }
428 if (s < 0 || s > 59) {
429 PyErr_SetString(PyExc_ValueError,
430 "second must be in 0..59");
431 return -1;
432 }
433 if (us < 0 || us > 999999) {
434 PyErr_SetString(PyExc_ValueError,
435 "microsecond must be in 0..999999");
436 return -1;
437 }
438 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000439}
440
441/* ---------------------------------------------------------------------------
442 * Normalization utilities.
443 */
444
445/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
446 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
447 * at least factor, enough of *lo is converted into "hi" units so that
448 * 0 <= *lo < factor. The input values must be such that int overflow
449 * is impossible.
450 */
451static void
452normalize_pair(int *hi, int *lo, int factor)
453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 assert(factor > 0);
455 assert(lo != hi);
456 if (*lo < 0 || *lo >= factor) {
457 const int num_hi = divmod(*lo, factor, lo);
458 const int new_hi = *hi + num_hi;
459 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
460 *hi = new_hi;
461 }
462 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000463}
464
465/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 * 0 <= *s < 24*3600
467 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000468 * The input values must be such that the internals don't overflow.
469 * The way this routine is used, we don't get close.
470 */
471static void
472normalize_d_s_us(int *d, int *s, int *us)
473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (*us < 0 || *us >= 1000000) {
475 normalize_pair(s, us, 1000000);
476 /* |s| can't be bigger than about
477 * |original s| + |original us|/1000000 now.
478 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 }
481 if (*s < 0 || *s >= 24*3600) {
482 normalize_pair(d, s, 24*3600);
483 /* |d| can't be bigger than about
484 * |original d| +
485 * (|original s| + |original us|/1000000) / (24*3600) now.
486 */
487 }
488 assert(0 <= *s && *s < 24*3600);
489 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000490}
491
492/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 * 1 <= *m <= 12
494 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000495 * The input values must be such that the internals don't overflow.
496 * The way this routine is used, we don't get close.
497 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000498static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000499normalize_y_m_d(int *y, int *m, int *d)
500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000502
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000503 /* In actual use, m is always the month component extracted from a
504 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Now only day can be out of bounds (year may also be out of bounds
510 * for a datetime object, but we don't care about that here).
511 * If day is out of bounds, what to do is arguable, but at least the
512 * method here is principled and explainable.
513 */
514 dim = days_in_month(*y, *m);
515 if (*d < 1 || *d > dim) {
516 /* Move day-1 days from the first of the month. First try to
517 * get off cheap if we're only one day out of range
518 * (adjustments for timezone alone can't be worse than that).
519 */
520 if (*d == 0) {
521 --*m;
522 if (*m > 0)
523 *d = days_in_month(*y, *m);
524 else {
525 --*y;
526 *m = 12;
527 *d = 31;
528 }
529 }
530 else if (*d == dim + 1) {
531 /* move forward a day */
532 ++*m;
533 *d = 1;
534 if (*m > 12) {
535 *m = 1;
536 ++*y;
537 }
538 }
539 else {
540 int ordinal = ymd_to_ord(*y, *m, 1) +
541 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000542 if (ordinal < 1 || ordinal > MAXORDINAL) {
543 goto error;
544 } else {
545 ord_to_ymd(ordinal, y, m, d);
546 return 0;
547 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 }
549 }
550 assert(*m > 0);
551 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000552 if (MINYEAR <= *y && *y <= MAXYEAR)
553 return 0;
554 error:
555 PyErr_SetString(PyExc_OverflowError,
556 "date value out of range");
557 return -1;
558
Tim Peters2a799bf2002-12-16 20:18:38 +0000559}
560
561/* Fiddle out-of-bounds months and days so that the result makes some kind
562 * of sense. The parameters are both inputs and outputs. Returns < 0 on
563 * failure, where failure means the adjusted year is out of bounds.
564 */
565static int
566normalize_date(int *year, int *month, int *day)
567{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000568 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000569}
570
571/* Force all the datetime fields into range. The parameters are both
572 * inputs and outputs. Returns < 0 on error.
573 */
574static int
575normalize_datetime(int *year, int *month, int *day,
576 int *hour, int *minute, int *second,
577 int *microsecond)
578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 normalize_pair(second, microsecond, 1000000);
580 normalize_pair(minute, second, 60);
581 normalize_pair(hour, minute, 60);
582 normalize_pair(day, hour, 24);
583 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000584}
585
586/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000587 * Basic object allocation: tp_alloc implementations. These allocate
588 * Python objects of the right size and type, and do the Python object-
589 * initialization bit. If there's not enough memory, they return NULL after
590 * setting MemoryError. All data members remain uninitialized trash.
591 *
592 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000593 * member is needed. This is ugly, imprecise, and possibly insecure.
594 * tp_basicsize for the time and datetime types is set to the size of the
595 * struct that has room for the tzinfo member, so subclasses in Python will
596 * allocate enough space for a tzinfo member whether or not one is actually
597 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
598 * part is that PyType_GenericAlloc() (which subclasses in Python end up
599 * using) just happens today to effectively ignore the nitems argument
600 * when tp_itemsize is 0, which it is for these type objects. If that
601 * changes, perhaps the callers of tp_alloc slots in this file should
602 * be changed to force a 0 nitems argument unless the type being allocated
603 * is a base type implemented in this file (so that tp_alloc is time_alloc
604 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000605 */
606
607static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000608time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 self = (PyObject *)
613 PyObject_MALLOC(aware ?
614 sizeof(PyDateTime_Time) :
615 sizeof(_PyDateTime_BaseTime));
616 if (self == NULL)
617 return (PyObject *)PyErr_NoMemory();
618 PyObject_INIT(self, type);
619 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000620}
621
622static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000623datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 self = (PyObject *)
628 PyObject_MALLOC(aware ?
629 sizeof(PyDateTime_DateTime) :
630 sizeof(_PyDateTime_BaseDateTime));
631 if (self == NULL)
632 return (PyObject *)PyErr_NoMemory();
633 PyObject_INIT(self, type);
634 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000635}
636
637/* ---------------------------------------------------------------------------
638 * Helpers for setting object fields. These work on pointers to the
639 * appropriate base class.
640 */
641
642/* For date and datetime. */
643static void
644set_date_fields(PyDateTime_Date *self, int y, int m, int d)
645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 self->hashcode = -1;
647 SET_YEAR(self, y);
648 SET_MONTH(self, m);
649 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000650}
651
652/* ---------------------------------------------------------------------------
653 * Create various objects, mostly without range checking.
654 */
655
656/* Create a date instance with no range checking. */
657static PyObject *
658new_date_ex(int year, int month, int day, PyTypeObject *type)
659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
663 if (self != NULL)
664 set_date_fields(self, year, month, day);
665 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000666}
667
668#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000670
671/* Create a datetime instance with no range checking. */
672static PyObject *
673new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyDateTime_DateTime *self;
677 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
680 if (self != NULL) {
681 self->hastzinfo = aware;
682 set_date_fields((PyDateTime_Date *)self, year, month, day);
683 DATE_SET_HOUR(self, hour);
684 DATE_SET_MINUTE(self, minute);
685 DATE_SET_SECOND(self, second);
686 DATE_SET_MICROSECOND(self, usecond);
687 if (aware) {
688 Py_INCREF(tzinfo);
689 self->tzinfo = tzinfo;
690 }
691 }
692 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000693}
694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
696 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
697 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000698
699/* Create a time instance with no range checking. */
700static PyObject *
701new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyDateTime_Time *self;
705 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
708 if (self != NULL) {
709 self->hastzinfo = aware;
710 self->hashcode = -1;
711 TIME_SET_HOUR(self, hour);
712 TIME_SET_MINUTE(self, minute);
713 TIME_SET_SECOND(self, second);
714 TIME_SET_MICROSECOND(self, usecond);
715 if (aware) {
716 Py_INCREF(tzinfo);
717 self->tzinfo = tzinfo;
718 }
719 }
720 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000721}
722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723#define new_time(hh, mm, ss, us, tzinfo) \
724 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000725
726/* Create a timedelta instance. Normalize the members iff normalize is
727 * true. Passing false is a speed optimization, if you know for sure
728 * that seconds and microseconds are already in their proper ranges. In any
729 * case, raises OverflowError and returns NULL if the normalized days is out
730 * of range).
731 */
732static PyObject *
733new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (normalize)
739 normalize_d_s_us(&days, &seconds, &microseconds);
740 assert(0 <= seconds && seconds < 24*3600);
741 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (check_delta_day_range(days) < 0)
744 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
747 if (self != NULL) {
748 self->hashcode = -1;
749 SET_TD_DAYS(self, days);
750 SET_TD_SECONDS(self, seconds);
751 SET_TD_MICROSECONDS(self, microseconds);
752 }
753 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000754}
755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756#define new_delta(d, s, us, normalize) \
757 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000758
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000759
760typedef struct
761{
762 PyObject_HEAD
763 PyObject *offset;
764 PyObject *name;
765} PyDateTime_TimeZone;
766
Victor Stinner6ced7c42011-03-21 18:15:42 +0100767/* The interned UTC timezone instance */
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000768static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya4415142012-06-08 12:33:09 -0400769/* The interned Epoch datetime instance */
770static PyObject *PyDateTime_Epoch;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +0000771
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000772/* Create new timezone instance checking offset range. This
773 function does not check the name argument. Caller must assure
774 that offset is a timedelta instance and name is either NULL
775 or a unicode object. */
776static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000777create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000778{
779 PyDateTime_TimeZone *self;
780 PyTypeObject *type = &PyDateTime_TimeZoneType;
781
782 assert(offset != NULL);
783 assert(PyDelta_Check(offset));
784 assert(name == NULL || PyUnicode_Check(name));
785
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000786 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
787 if (self == NULL) {
788 return NULL;
789 }
790 Py_INCREF(offset);
791 self->offset = offset;
792 Py_XINCREF(name);
793 self->name = name;
794 return (PyObject *)self;
795}
796
797static int delta_bool(PyDateTime_Delta *self);
798
799static PyObject *
800new_timezone(PyObject *offset, PyObject *name)
801{
802 assert(offset != NULL);
803 assert(PyDelta_Check(offset));
804 assert(name == NULL || PyUnicode_Check(name));
805
806 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
807 Py_INCREF(PyDateTime_TimeZone_UTC);
808 return PyDateTime_TimeZone_UTC;
809 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000810 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
811 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400812 " representing a whole number of minutes,"
813 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000814 return NULL;
815 }
816 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
817 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
818 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
819 " strictly between -timedelta(hours=24) and"
Alexander Belopolsky31227ca2012-06-22 13:23:21 -0400820 " timedelta(hours=24),"
821 " not %R.", offset);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000822 return NULL;
823 }
824
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000825 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000826}
827
Tim Petersb0c854d2003-05-17 15:57:00 +0000828/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000829 * tzinfo helpers.
830 */
831
Tim Peters855fe882002-12-22 03:43:39 +0000832/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
833 * raise TypeError and return -1.
834 */
835static int
836check_tzinfo_subclass(PyObject *p)
837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (p == Py_None || PyTZInfo_Check(p))
839 return 0;
840 PyErr_Format(PyExc_TypeError,
841 "tzinfo argument must be None or of a tzinfo subclass, "
842 "not type '%s'",
843 Py_TYPE(p)->tp_name);
844 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000845}
846
Tim Peters2a799bf2002-12-16 20:18:38 +0000847/* If self has a tzinfo member, return a BORROWED reference to it. Else
848 * return NULL, which is NOT AN ERROR. There are no error returns here,
849 * and the caller must not decref the result.
850 */
851static PyObject *
852get_tzinfo_member(PyObject *self)
853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (PyDateTime_Check(self) && HASTZINFO(self))
857 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
858 else if (PyTime_Check(self) && HASTZINFO(self))
859 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000862}
863
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000864/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
865 * be an instance of the tzinfo class. If the method returns None, this
866 * returns None. If the method doesn't return None or timedelta, TypeError is
867 * raised and this returns NULL. If it returns a timedelta and the value is
868 * out of range or isn't a whole number of minutes, ValueError is raised and
869 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000870 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000871static PyObject *
872call_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000873{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000874 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000877 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000879
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000880 if (tzinfo == Py_None)
881 Py_RETURN_NONE;
882 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
883 if (offset == Py_None || offset == NULL)
884 return offset;
885 if (PyDelta_Check(offset)) {
886 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
887 Py_DECREF(offset);
888 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
889 " representing a whole number of minutes");
890 return NULL;
891 }
892 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
893 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
894 Py_DECREF(offset);
895 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
896 " strictly between -timedelta(hours=24) and"
897 " timedelta(hours=24).");
898 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 }
900 }
901 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000902 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 PyErr_Format(PyExc_TypeError,
904 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000905 "timedelta, not '%.200s'",
906 name, Py_TYPE(offset)->tp_name);
907 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000909
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000910 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000911}
912
913/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
915 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000916 * doesn't return None or timedelta, TypeError is raised and this returns -1.
917 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
918 * # of minutes), ValueError is raised and this returns -1. Else *none is
919 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000920 */
Tim Peters855fe882002-12-22 03:43:39 +0000921static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000922call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
923{
924 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000925}
926
Tim Peters2a799bf2002-12-16 20:18:38 +0000927/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
928 * result. tzinfo must be an instance of the tzinfo class. If dst()
929 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000930 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000931 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000932 * ValueError is raised and this returns -1. Else *none is set to 0 and
933 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000934 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000935static PyObject *
936call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000937{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000938 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000939}
940
Tim Petersbad8ff02002-12-30 20:52:32 +0000941/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000942 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000943 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000944 * returns NULL. If the result is a string, we ensure it is a Unicode
945 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000946 */
947static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000948call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200951 _Py_IDENTIFIER(tzname);
Tim Peters2a799bf2002-12-16 20:18:38 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 assert(tzinfo != NULL);
954 assert(check_tzinfo_subclass(tzinfo) >= 0);
955 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000958 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +0000959
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200960 result = _PyObject_CallMethodId(tzinfo, &PyId_tzname, "O", tzinfoarg);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000961
962 if (result == NULL || result == Py_None)
963 return result;
964
965 if (!PyUnicode_Check(result)) {
966 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
967 "return None or a string, not '%s'",
968 Py_TYPE(result)->tp_name);
969 Py_DECREF(result);
970 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000972
973 return result;
Tim Peters00237032002-12-27 02:21:51 +0000974}
975
Tim Peters2a799bf2002-12-16 20:18:38 +0000976/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
977 * stuff
978 * ", tzinfo=" + repr(tzinfo)
979 * before the closing ")".
980 */
981static PyObject *
982append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 assert(PyUnicode_Check(repr));
987 assert(tzinfo);
988 if (tzinfo == Py_None)
989 return repr;
990 /* Get rid of the trailing ')'. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200991 assert(PyUnicode_READ_CHAR(repr, PyUnicode_GET_LENGTH(repr)-1) == ')');
992 temp = PyUnicode_Substring(repr, 0, PyUnicode_GET_LENGTH(repr) - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 Py_DECREF(repr);
994 if (temp == NULL)
995 return NULL;
996 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
997 Py_DECREF(temp);
998 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +0000999}
1000
1001/* ---------------------------------------------------------------------------
1002 * String format helpers.
1003 */
1004
1005static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001006format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 static const char *DayNames[] = {
1009 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1010 };
1011 static const char *MonthNames[] = {
1012 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1013 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1014 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1019 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1020 GET_DAY(date), hours, minutes, seconds,
1021 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001022}
1023
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001024static PyObject *delta_negative(PyDateTime_Delta *self);
1025
Tim Peters2a799bf2002-12-16 20:18:38 +00001026/* Add an hours & minutes UTC offset string to buf. buf has no more than
1027 * buflen bytes remaining. The UTC offset is gotten by calling
1028 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1029 * *buf, and that's all. Else the returned value is checked for sanity (an
1030 * integer in range), and if that's OK it's converted to an hours & minutes
1031 * string of the form
1032 * sign HH sep MM
1033 * Returns 0 if everything is OK. If the return value from utcoffset() is
1034 * bogus, an appropriate exception is set and -1 is returned.
1035 */
1036static int
Tim Peters328fff72002-12-20 01:31:27 +00001037format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001039{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001040 PyObject *offset;
1041 int hours, minutes, seconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001045
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001046 offset = call_utcoffset(tzinfo, tzinfoarg);
1047 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001049 if (offset == Py_None) {
1050 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 *buf = '\0';
1052 return 0;
1053 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001054 /* Offset is normalized, so it is negative if days < 0 */
1055 if (GET_TD_DAYS(offset) < 0) {
1056 PyObject *temp = offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 sign = '-';
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001058 offset = delta_negative((PyDateTime_Delta *)offset);
1059 Py_DECREF(temp);
1060 if (offset == NULL)
1061 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001063 else {
1064 sign = '+';
1065 }
1066 /* Offset is not negative here. */
1067 seconds = GET_TD_SECONDS(offset);
1068 Py_DECREF(offset);
1069 minutes = divmod(seconds, 60, &seconds);
1070 hours = divmod(minutes, 60, &minutes);
1071 assert(seconds == 0);
1072 /* XXX ignore sub-minute data, curently not allowed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001076}
1077
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001078static PyObject *
1079make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 PyObject *temp;
1082 PyObject *tzinfo = get_tzinfo_member(object);
1083 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001084 _Py_IDENTIFIER(replace);
Victor Stinner9e30aa52011-11-21 02:49:52 +01001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 if (Zreplacement == NULL)
1087 return NULL;
1088 if (tzinfo == Py_None || tzinfo == NULL)
1089 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 assert(tzinfoarg != NULL);
1092 temp = call_tzname(tzinfo, tzinfoarg);
1093 if (temp == NULL)
1094 goto Error;
1095 if (temp == Py_None) {
1096 Py_DECREF(temp);
1097 return Zreplacement;
1098 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 assert(PyUnicode_Check(temp));
1101 /* Since the tzname is getting stuffed into the
1102 * format, we have to double any % signs so that
1103 * strftime doesn't treat them as format codes.
1104 */
1105 Py_DECREF(Zreplacement);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001106 Zreplacement = _PyObject_CallMethodId(temp, &PyId_replace, "ss", "%", "%%");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 Py_DECREF(temp);
1108 if (Zreplacement == NULL)
1109 return NULL;
1110 if (!PyUnicode_Check(Zreplacement)) {
1111 PyErr_SetString(PyExc_TypeError,
1112 "tzname.replace() did not return a string");
1113 goto Error;
1114 }
1115 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001116
1117 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 Py_DECREF(Zreplacement);
1119 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001120}
1121
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001122static PyObject *
1123make_freplacement(PyObject *object)
1124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 char freplacement[64];
1126 if (PyTime_Check(object))
1127 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1128 else if (PyDateTime_Check(object))
1129 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1130 else
1131 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001134}
1135
Tim Peters2a799bf2002-12-16 20:18:38 +00001136/* I sure don't want to reproduce the strftime code from the time module,
1137 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001138 * giving special meanings to the %z, %Z and %f format codes via a
1139 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001140 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1141 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001142 */
1143static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001144wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1150 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1151 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 const char *pin; /* pointer to next char in input format */
1154 Py_ssize_t flen; /* length of input format */
1155 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 PyObject *newfmt = NULL; /* py string, the output format */
1158 char *pnew; /* pointer to available byte in output format */
1159 size_t totalnew; /* number bytes total in output format buffer,
1160 exclusive of trailing \0 */
1161 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 const char *ptoappend; /* ptr to string to append to output buffer */
1164 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 assert(object && format && timetuple);
1167 assert(PyUnicode_Check(format));
1168 /* Convert the input format to a C string and size */
1169 pin = _PyUnicode_AsStringAndSize(format, &flen);
1170 if (!pin)
1171 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 /* Scan the input format, looking for %z/%Z/%f escapes, building
1174 * a new format. Since computing the replacements for those codes
1175 * is expensive, don't unless they're actually used.
1176 */
1177 if (flen > INT_MAX - 1) {
1178 PyErr_NoMemory();
1179 goto Done;
1180 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 totalnew = flen + 1; /* realistic if no %z/%Z */
1183 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1184 if (newfmt == NULL) goto Done;
1185 pnew = PyBytes_AsString(newfmt);
1186 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 while ((ch = *pin++) != '\0') {
1189 if (ch != '%') {
1190 ptoappend = pin - 1;
1191 ntoappend = 1;
1192 }
1193 else if ((ch = *pin++) == '\0') {
1194 /* There's a lone trailing %; doesn't make sense. */
1195 PyErr_SetString(PyExc_ValueError, "strftime format "
1196 "ends with raw %");
1197 goto Done;
1198 }
1199 /* A % has been seen and ch is the character after it. */
1200 else if (ch == 'z') {
1201 if (zreplacement == NULL) {
1202 /* format utcoffset */
1203 char buf[100];
1204 PyObject *tzinfo = get_tzinfo_member(object);
1205 zreplacement = PyBytes_FromStringAndSize("", 0);
1206 if (zreplacement == NULL) goto Done;
1207 if (tzinfo != Py_None && tzinfo != NULL) {
1208 assert(tzinfoarg != NULL);
1209 if (format_utcoffset(buf,
1210 sizeof(buf),
1211 "",
1212 tzinfo,
1213 tzinfoarg) < 0)
1214 goto Done;
1215 Py_DECREF(zreplacement);
1216 zreplacement =
1217 PyBytes_FromStringAndSize(buf,
1218 strlen(buf));
1219 if (zreplacement == NULL)
1220 goto Done;
1221 }
1222 }
1223 assert(zreplacement != NULL);
1224 ptoappend = PyBytes_AS_STRING(zreplacement);
1225 ntoappend = PyBytes_GET_SIZE(zreplacement);
1226 }
1227 else if (ch == 'Z') {
1228 /* format tzname */
1229 if (Zreplacement == NULL) {
1230 Zreplacement = make_Zreplacement(object,
1231 tzinfoarg);
1232 if (Zreplacement == NULL)
1233 goto Done;
1234 }
1235 assert(Zreplacement != NULL);
1236 assert(PyUnicode_Check(Zreplacement));
1237 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1238 &ntoappend);
Alexander Belopolskye239d232010-12-08 23:31:48 +00001239 if (ptoappend == NULL)
1240 goto Done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 }
1242 else if (ch == 'f') {
1243 /* format microseconds */
1244 if (freplacement == NULL) {
1245 freplacement = make_freplacement(object);
1246 if (freplacement == NULL)
1247 goto Done;
1248 }
1249 assert(freplacement != NULL);
1250 assert(PyBytes_Check(freplacement));
1251 ptoappend = PyBytes_AS_STRING(freplacement);
1252 ntoappend = PyBytes_GET_SIZE(freplacement);
1253 }
1254 else {
1255 /* percent followed by neither z nor Z */
1256 ptoappend = pin - 2;
1257 ntoappend = 2;
1258 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 /* Append the ntoappend chars starting at ptoappend to
1261 * the new format.
1262 */
1263 if (ntoappend == 0)
1264 continue;
1265 assert(ptoappend != NULL);
1266 assert(ntoappend > 0);
1267 while (usednew + ntoappend > totalnew) {
1268 size_t bigger = totalnew << 1;
1269 if ((bigger >> 1) != totalnew) { /* overflow */
1270 PyErr_NoMemory();
1271 goto Done;
1272 }
1273 if (_PyBytes_Resize(&newfmt, bigger) < 0)
1274 goto Done;
1275 totalnew = bigger;
1276 pnew = PyBytes_AsString(newfmt) + usednew;
1277 }
1278 memcpy(pnew, ptoappend, ntoappend);
1279 pnew += ntoappend;
1280 usednew += ntoappend;
1281 assert(usednew <= totalnew);
1282 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1285 goto Done;
1286 {
1287 PyObject *format;
1288 PyObject *time = PyImport_ImportModuleNoBlock("time");
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (time == NULL)
1291 goto Done;
1292 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1293 if (format != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001294 _Py_IDENTIFIER(strftime);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001295
1296 result = _PyObject_CallMethodId(time, &PyId_strftime, "OO",
1297 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 Py_DECREF(format);
1299 }
1300 Py_DECREF(time);
1301 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001302 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 Py_XDECREF(freplacement);
1304 Py_XDECREF(zreplacement);
1305 Py_XDECREF(Zreplacement);
1306 Py_XDECREF(newfmt);
1307 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001308}
1309
Tim Peters2a799bf2002-12-16 20:18:38 +00001310/* ---------------------------------------------------------------------------
1311 * Wrap functions from the time module. These aren't directly available
1312 * from C. Perhaps they should be.
1313 */
1314
1315/* Call time.time() and return its result (a Python float). */
1316static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001317time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 PyObject *result = NULL;
1320 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001323 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001324
1325 result = _PyObject_CallMethodId(time, &PyId_time, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 Py_DECREF(time);
1327 }
1328 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001329}
1330
1331/* Build a time.struct_time. The weekday and day number are automatically
1332 * computed from the y,m,d args.
1333 */
1334static PyObject *
1335build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyObject *time;
1338 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 time = PyImport_ImportModuleNoBlock("time");
1341 if (time != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001342 _Py_IDENTIFIER(struct_time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001343
1344 result = _PyObject_CallMethodId(time, &PyId_struct_time,
1345 "((iiiiiiiii))",
1346 y, m, d,
1347 hh, mm, ss,
1348 weekday(y, m, d),
1349 days_before_month(y, m) + d,
1350 dstflag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 Py_DECREF(time);
1352 }
1353 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001354}
1355
1356/* ---------------------------------------------------------------------------
1357 * Miscellaneous helpers.
1358 */
1359
Mark Dickinsone94c6792009-02-02 20:36:42 +00001360/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001361 * The comparisons here all most naturally compute a cmp()-like result.
1362 * This little helper turns that into a bool result for rich comparisons.
1363 */
1364static PyObject *
1365diff_to_bool(int diff, int op)
1366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 PyObject *result;
1368 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 switch (op) {
1371 case Py_EQ: istrue = diff == 0; break;
1372 case Py_NE: istrue = diff != 0; break;
1373 case Py_LE: istrue = diff <= 0; break;
1374 case Py_GE: istrue = diff >= 0; break;
1375 case Py_LT: istrue = diff < 0; break;
1376 case Py_GT: istrue = diff > 0; break;
1377 default:
1378 assert(! "op unknown");
1379 istrue = 0; /* To shut up compiler */
1380 }
1381 result = istrue ? Py_True : Py_False;
1382 Py_INCREF(result);
1383 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001384}
1385
Tim Peters07534a62003-02-07 22:50:28 +00001386/* Raises a "can't compare" TypeError and returns NULL. */
1387static PyObject *
1388cmperror(PyObject *a, PyObject *b)
1389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 PyErr_Format(PyExc_TypeError,
1391 "can't compare %s to %s",
1392 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1393 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001394}
1395
Tim Peters2a799bf2002-12-16 20:18:38 +00001396/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001397 * Cached Python objects; these are set by the module init function.
1398 */
1399
1400/* Conversion factors. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401static PyObject *us_per_us = NULL; /* 1 */
1402static PyObject *us_per_ms = NULL; /* 1000 */
1403static PyObject *us_per_second = NULL; /* 1000000 */
1404static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1405static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1406static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1407static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
Tim Peters2a799bf2002-12-16 20:18:38 +00001408static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1409
Tim Peters2a799bf2002-12-16 20:18:38 +00001410/* ---------------------------------------------------------------------------
1411 * Class implementations.
1412 */
1413
1414/*
1415 * PyDateTime_Delta implementation.
1416 */
1417
1418/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Tim Peters2a799bf2002-12-16 20:18:38 +00001420 * as a Python int or long.
1421 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1422 * due to ubiquitous overflow possibilities.
1423 */
1424static PyObject *
1425delta_to_microseconds(PyDateTime_Delta *self)
1426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 PyObject *x1 = NULL;
1428 PyObject *x2 = NULL;
1429 PyObject *x3 = NULL;
1430 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1433 if (x1 == NULL)
1434 goto Done;
1435 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1436 if (x2 == NULL)
1437 goto Done;
1438 Py_DECREF(x1);
1439 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 /* x2 has days in seconds */
1442 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1443 if (x1 == NULL)
1444 goto Done;
1445 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1446 if (x3 == NULL)
1447 goto Done;
1448 Py_DECREF(x1);
1449 Py_DECREF(x2);
Brett Cannonb94767f2011-02-22 20:15:44 +00001450 /* x1 = */ x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 /* x3 has days+seconds in seconds */
1453 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1454 if (x1 == NULL)
1455 goto Done;
1456 Py_DECREF(x3);
1457 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 /* x1 has days+seconds in us */
1460 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1461 if (x2 == NULL)
1462 goto Done;
1463 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001464
1465Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 Py_XDECREF(x1);
1467 Py_XDECREF(x2);
1468 Py_XDECREF(x3);
1469 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001470}
1471
1472/* Convert a number of us (as a Python int or long) to a timedelta.
1473 */
1474static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001475microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 int us;
1478 int s;
1479 int d;
1480 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 PyObject *tuple = NULL;
1483 PyObject *num = NULL;
1484 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 tuple = PyNumber_Divmod(pyus, us_per_second);
1487 if (tuple == NULL)
1488 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 num = PyTuple_GetItem(tuple, 1); /* us */
1491 if (num == NULL)
1492 goto Done;
1493 temp = PyLong_AsLong(num);
1494 num = NULL;
1495 if (temp == -1 && PyErr_Occurred())
1496 goto Done;
1497 assert(0 <= temp && temp < 1000000);
1498 us = (int)temp;
1499 if (us < 0) {
1500 /* The divisor was positive, so this must be an error. */
1501 assert(PyErr_Occurred());
1502 goto Done;
1503 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1506 if (num == NULL)
1507 goto Done;
1508 Py_INCREF(num);
1509 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 tuple = PyNumber_Divmod(num, seconds_per_day);
1512 if (tuple == NULL)
1513 goto Done;
1514 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 num = PyTuple_GetItem(tuple, 1); /* seconds */
1517 if (num == NULL)
1518 goto Done;
1519 temp = PyLong_AsLong(num);
1520 num = NULL;
1521 if (temp == -1 && PyErr_Occurred())
1522 goto Done;
1523 assert(0 <= temp && temp < 24*3600);
1524 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (s < 0) {
1527 /* The divisor was positive, so this must be an error. */
1528 assert(PyErr_Occurred());
1529 goto Done;
1530 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1533 if (num == NULL)
1534 goto Done;
1535 Py_INCREF(num);
1536 temp = PyLong_AsLong(num);
1537 if (temp == -1 && PyErr_Occurred())
1538 goto Done;
1539 d = (int)temp;
1540 if ((long)d != temp) {
1541 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1542 "large to fit in a C int");
1543 goto Done;
1544 }
1545 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001546
1547Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 Py_XDECREF(tuple);
1549 Py_XDECREF(num);
1550 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001551}
1552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553#define microseconds_to_delta(pymicros) \
1554 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001555
Tim Peters2a799bf2002-12-16 20:18:38 +00001556static PyObject *
1557multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyObject *pyus_in;
1560 PyObject *pyus_out;
1561 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 pyus_in = delta_to_microseconds(delta);
1564 if (pyus_in == NULL)
1565 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1568 Py_DECREF(pyus_in);
1569 if (pyus_out == NULL)
1570 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 result = microseconds_to_delta(pyus_out);
1573 Py_DECREF(pyus_out);
1574 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001575}
1576
1577static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001578multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1579{
1580 PyObject *result = NULL;
1581 PyObject *pyus_in = NULL, *temp, *pyus_out;
1582 PyObject *ratio = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001583 _Py_IDENTIFIER(as_integer_ratio);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001584
1585 pyus_in = delta_to_microseconds(delta);
1586 if (pyus_in == NULL)
1587 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001588 ratio = _PyObject_CallMethodId(floatobj, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001589 if (ratio == NULL)
1590 goto error;
1591 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1592 Py_DECREF(pyus_in);
1593 pyus_in = NULL;
1594 if (temp == NULL)
1595 goto error;
1596 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1597 Py_DECREF(temp);
1598 if (pyus_out == NULL)
1599 goto error;
1600 result = microseconds_to_delta(pyus_out);
1601 Py_DECREF(pyus_out);
1602 error:
1603 Py_XDECREF(pyus_in);
1604 Py_XDECREF(ratio);
1605
1606 return result;
1607}
1608
1609static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001610divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyObject *pyus_in;
1613 PyObject *pyus_out;
1614 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 pyus_in = delta_to_microseconds(delta);
1617 if (pyus_in == NULL)
1618 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1621 Py_DECREF(pyus_in);
1622 if (pyus_out == NULL)
1623 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 result = microseconds_to_delta(pyus_out);
1626 Py_DECREF(pyus_out);
1627 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001628}
1629
1630static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001631divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 PyObject *pyus_left;
1634 PyObject *pyus_right;
1635 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 pyus_left = delta_to_microseconds(left);
1638 if (pyus_left == NULL)
1639 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 pyus_right = delta_to_microseconds(right);
1642 if (pyus_right == NULL) {
1643 Py_DECREF(pyus_left);
1644 return NULL;
1645 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1648 Py_DECREF(pyus_left);
1649 Py_DECREF(pyus_right);
1650 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001651}
1652
1653static PyObject *
1654truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 PyObject *pyus_left;
1657 PyObject *pyus_right;
1658 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 pyus_left = delta_to_microseconds(left);
1661 if (pyus_left == NULL)
1662 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 pyus_right = delta_to_microseconds(right);
1665 if (pyus_right == NULL) {
1666 Py_DECREF(pyus_left);
1667 return NULL;
1668 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1671 Py_DECREF(pyus_left);
1672 Py_DECREF(pyus_right);
1673 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001674}
1675
1676static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001677truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1678{
1679 PyObject *result = NULL;
1680 PyObject *pyus_in = NULL, *temp, *pyus_out;
1681 PyObject *ratio = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001682 _Py_IDENTIFIER(as_integer_ratio);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001683
1684 pyus_in = delta_to_microseconds(delta);
1685 if (pyus_in == NULL)
1686 return NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001687 ratio = _PyObject_CallMethodId(f, &PyId_as_integer_ratio, NULL);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001688 if (ratio == NULL)
1689 goto error;
1690 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1691 Py_DECREF(pyus_in);
1692 pyus_in = NULL;
1693 if (temp == NULL)
1694 goto error;
1695 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1696 Py_DECREF(temp);
1697 if (pyus_out == NULL)
1698 goto error;
1699 result = microseconds_to_delta(pyus_out);
1700 Py_DECREF(pyus_out);
1701 error:
1702 Py_XDECREF(pyus_in);
1703 Py_XDECREF(ratio);
1704
1705 return result;
1706}
1707
1708static PyObject *
1709truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1710{
1711 PyObject *result;
1712 PyObject *pyus_in, *pyus_out;
1713 pyus_in = delta_to_microseconds(delta);
1714 if (pyus_in == NULL)
1715 return NULL;
1716 pyus_out = divide_nearest(pyus_in, i);
1717 Py_DECREF(pyus_in);
1718 if (pyus_out == NULL)
1719 return NULL;
1720 result = microseconds_to_delta(pyus_out);
1721 Py_DECREF(pyus_out);
1722
1723 return result;
1724}
1725
1726static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001727delta_add(PyObject *left, PyObject *right)
1728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1732 /* delta + delta */
1733 /* The C-level additions can't overflow because of the
1734 * invariant bounds.
1735 */
1736 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1737 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1738 int microseconds = GET_TD_MICROSECONDS(left) +
1739 GET_TD_MICROSECONDS(right);
1740 result = new_delta(days, seconds, microseconds, 1);
1741 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (result == Py_NotImplemented)
1744 Py_INCREF(result);
1745 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001746}
1747
1748static PyObject *
1749delta_negative(PyDateTime_Delta *self)
1750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 return new_delta(-GET_TD_DAYS(self),
1752 -GET_TD_SECONDS(self),
1753 -GET_TD_MICROSECONDS(self),
1754 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001755}
1756
1757static PyObject *
1758delta_positive(PyDateTime_Delta *self)
1759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 /* Could optimize this (by returning self) if this isn't a
1761 * subclass -- but who uses unary + ? Approximately nobody.
1762 */
1763 return new_delta(GET_TD_DAYS(self),
1764 GET_TD_SECONDS(self),
1765 GET_TD_MICROSECONDS(self),
1766 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001767}
1768
1769static PyObject *
1770delta_abs(PyDateTime_Delta *self)
1771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 assert(GET_TD_MICROSECONDS(self) >= 0);
1775 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 if (GET_TD_DAYS(self) < 0)
1778 result = delta_negative(self);
1779 else
1780 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001783}
1784
1785static PyObject *
1786delta_subtract(PyObject *left, PyObject *right)
1787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1791 /* delta - delta */
Alexander Belopolskyb6f5ec72011-04-05 20:07:38 -04001792 /* The C-level additions can't overflow because of the
1793 * invariant bounds.
1794 */
1795 int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1796 int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1797 int microseconds = GET_TD_MICROSECONDS(left) -
1798 GET_TD_MICROSECONDS(right);
1799 result = new_delta(days, seconds, microseconds, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (result == Py_NotImplemented)
1803 Py_INCREF(result);
1804 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001805}
1806
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001807static int
1808delta_cmp(PyObject *self, PyObject *other)
1809{
1810 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1811 if (diff == 0) {
1812 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1813 if (diff == 0)
1814 diff = GET_TD_MICROSECONDS(self) -
1815 GET_TD_MICROSECONDS(other);
1816 }
1817 return diff;
1818}
1819
Tim Peters2a799bf2002-12-16 20:18:38 +00001820static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001821delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001824 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 return diff_to_bool(diff, op);
1826 }
1827 else {
Brian Curtindfc80e32011-08-10 20:28:54 -05001828 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001830}
1831
1832static PyObject *delta_getstate(PyDateTime_Delta *self);
1833
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001834static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001835delta_hash(PyDateTime_Delta *self)
1836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 if (self->hashcode == -1) {
1838 PyObject *temp = delta_getstate(self);
1839 if (temp != NULL) {
1840 self->hashcode = PyObject_Hash(temp);
1841 Py_DECREF(temp);
1842 }
1843 }
1844 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001845}
1846
1847static PyObject *
1848delta_multiply(PyObject *left, PyObject *right)
1849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 if (PyDelta_Check(left)) {
1853 /* delta * ??? */
1854 if (PyLong_Check(right))
1855 result = multiply_int_timedelta(right,
1856 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001857 else if (PyFloat_Check(right))
1858 result = multiply_float_timedelta(right,
1859 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 }
1861 else if (PyLong_Check(left))
1862 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001863 (PyDateTime_Delta *) right);
1864 else if (PyFloat_Check(left))
1865 result = multiply_float_timedelta(left,
1866 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (result == Py_NotImplemented)
1869 Py_INCREF(result);
1870 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001871}
1872
1873static PyObject *
1874delta_divide(PyObject *left, PyObject *right)
1875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (PyDelta_Check(left)) {
1879 /* delta * ??? */
1880 if (PyLong_Check(right))
1881 result = divide_timedelta_int(
1882 (PyDateTime_Delta *)left,
1883 right);
1884 else if (PyDelta_Check(right))
1885 result = divide_timedelta_timedelta(
1886 (PyDateTime_Delta *)left,
1887 (PyDateTime_Delta *)right);
1888 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 if (result == Py_NotImplemented)
1891 Py_INCREF(result);
1892 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001893}
1894
Mark Dickinson7c186e22010-04-20 22:32:49 +00001895static PyObject *
1896delta_truedivide(PyObject *left, PyObject *right)
1897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 if (PyDelta_Check(left)) {
1901 if (PyDelta_Check(right))
1902 result = truedivide_timedelta_timedelta(
1903 (PyDateTime_Delta *)left,
1904 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001905 else if (PyFloat_Check(right))
1906 result = truedivide_timedelta_float(
1907 (PyDateTime_Delta *)left, right);
1908 else if (PyLong_Check(right))
1909 result = truedivide_timedelta_int(
1910 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (result == Py_NotImplemented)
1914 Py_INCREF(result);
1915 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001916}
1917
1918static PyObject *
1919delta_remainder(PyObject *left, PyObject *right)
1920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 PyObject *pyus_left;
1922 PyObject *pyus_right;
1923 PyObject *pyus_remainder;
1924 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001925
Brian Curtindfc80e32011-08-10 20:28:54 -05001926 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1927 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1930 if (pyus_left == NULL)
1931 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1934 if (pyus_right == NULL) {
1935 Py_DECREF(pyus_left);
1936 return NULL;
1937 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
1940 Py_DECREF(pyus_left);
1941 Py_DECREF(pyus_right);
1942 if (pyus_remainder == NULL)
1943 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 remainder = microseconds_to_delta(pyus_remainder);
1946 Py_DECREF(pyus_remainder);
1947 if (remainder == NULL)
1948 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001951}
1952
1953static PyObject *
1954delta_divmod(PyObject *left, PyObject *right)
1955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 PyObject *pyus_left;
1957 PyObject *pyus_right;
1958 PyObject *divmod;
1959 PyObject *delta;
1960 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001961
Brian Curtindfc80e32011-08-10 20:28:54 -05001962 if (!PyDelta_Check(left) || !PyDelta_Check(right))
1963 Py_RETURN_NOTIMPLEMENTED;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1966 if (pyus_left == NULL)
1967 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1970 if (pyus_right == NULL) {
1971 Py_DECREF(pyus_left);
1972 return NULL;
1973 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 divmod = PyNumber_Divmod(pyus_left, pyus_right);
1976 Py_DECREF(pyus_left);
1977 Py_DECREF(pyus_right);
1978 if (divmod == NULL)
1979 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 assert(PyTuple_Size(divmod) == 2);
1982 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
1983 if (delta == NULL) {
1984 Py_DECREF(divmod);
1985 return NULL;
1986 }
1987 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
1988 Py_DECREF(delta);
1989 Py_DECREF(divmod);
1990 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001991}
1992
Tim Peters2a799bf2002-12-16 20:18:38 +00001993/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1994 * timedelta constructor. sofar is the # of microseconds accounted for
1995 * so far, and there are factor microseconds per current unit, the number
1996 * of which is given by num. num * factor is added to sofar in a
1997 * numerically careful way, and that's the result. Any fractional
1998 * microseconds left over (this can happen if num is a float type) are
1999 * added into *leftover.
2000 * Note that there are many ways this can give an error (NULL) return.
2001 */
2002static PyObject *
2003accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2004 double *leftover)
2005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 PyObject *prod;
2007 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (PyLong_Check(num)) {
2012 prod = PyNumber_Multiply(num, factor);
2013 if (prod == NULL)
2014 return NULL;
2015 sum = PyNumber_Add(sofar, prod);
2016 Py_DECREF(prod);
2017 return sum;
2018 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (PyFloat_Check(num)) {
2021 double dnum;
2022 double fracpart;
2023 double intpart;
2024 PyObject *x;
2025 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* The Plan: decompose num into an integer part and a
2028 * fractional part, num = intpart + fracpart.
2029 * Then num * factor ==
2030 * intpart * factor + fracpart * factor
2031 * and the LHS can be computed exactly in long arithmetic.
2032 * The RHS is again broken into an int part and frac part.
2033 * and the frac part is added into *leftover.
2034 */
2035 dnum = PyFloat_AsDouble(num);
2036 if (dnum == -1.0 && PyErr_Occurred())
2037 return NULL;
2038 fracpart = modf(dnum, &intpart);
2039 x = PyLong_FromDouble(intpart);
2040 if (x == NULL)
2041 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 prod = PyNumber_Multiply(x, factor);
2044 Py_DECREF(x);
2045 if (prod == NULL)
2046 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 sum = PyNumber_Add(sofar, prod);
2049 Py_DECREF(prod);
2050 if (sum == NULL)
2051 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (fracpart == 0.0)
2054 return sum;
2055 /* So far we've lost no information. Dealing with the
2056 * fractional part requires float arithmetic, and may
2057 * lose a little info.
2058 */
2059 assert(PyLong_Check(factor));
2060 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 dnum *= fracpart;
2063 fracpart = modf(dnum, &intpart);
2064 x = PyLong_FromDouble(intpart);
2065 if (x == NULL) {
2066 Py_DECREF(sum);
2067 return NULL;
2068 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 y = PyNumber_Add(sum, x);
2071 Py_DECREF(sum);
2072 Py_DECREF(x);
2073 *leftover += fracpart;
2074 return y;
2075 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 PyErr_Format(PyExc_TypeError,
2078 "unsupported type for timedelta %s component: %s",
2079 tag, Py_TYPE(num)->tp_name);
2080 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002081}
2082
2083static PyObject *
2084delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 /* Argument objects. */
2089 PyObject *day = NULL;
2090 PyObject *second = NULL;
2091 PyObject *us = NULL;
2092 PyObject *ms = NULL;
2093 PyObject *minute = NULL;
2094 PyObject *hour = NULL;
2095 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 PyObject *x = NULL; /* running sum of microseconds */
2098 PyObject *y = NULL; /* temp sum of microseconds */
2099 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 static char *keywords[] = {
2102 "days", "seconds", "microseconds", "milliseconds",
2103 "minutes", "hours", "weeks", NULL
2104 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2107 keywords,
2108 &day, &second, &us,
2109 &ms, &minute, &hour, &week) == 0)
2110 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 x = PyLong_FromLong(0);
2113 if (x == NULL)
2114 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116#define CLEANUP \
2117 Py_DECREF(x); \
2118 x = y; \
2119 if (x == NULL) \
2120 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 if (us) {
2123 y = accum("microseconds", x, us, us_per_us, &leftover_us);
2124 CLEANUP;
2125 }
2126 if (ms) {
2127 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2128 CLEANUP;
2129 }
2130 if (second) {
2131 y = accum("seconds", x, second, us_per_second, &leftover_us);
2132 CLEANUP;
2133 }
2134 if (minute) {
2135 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2136 CLEANUP;
2137 }
2138 if (hour) {
2139 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2140 CLEANUP;
2141 }
2142 if (day) {
2143 y = accum("days", x, day, us_per_day, &leftover_us);
2144 CLEANUP;
2145 }
2146 if (week) {
2147 y = accum("weeks", x, week, us_per_week, &leftover_us);
2148 CLEANUP;
2149 }
2150 if (leftover_us) {
2151 /* Round to nearest whole # of us, and add into x. */
2152 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
2153 if (temp == NULL) {
2154 Py_DECREF(x);
2155 goto Done;
2156 }
2157 y = PyNumber_Add(x, temp);
2158 Py_DECREF(temp);
2159 CLEANUP;
2160 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 self = microseconds_to_delta_ex(x, type);
2163 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002164Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002166
2167#undef CLEANUP
2168}
2169
2170static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002171delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 return (GET_TD_DAYS(self) != 0
2174 || GET_TD_SECONDS(self) != 0
2175 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002176}
2177
2178static PyObject *
2179delta_repr(PyDateTime_Delta *self)
2180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 if (GET_TD_MICROSECONDS(self) != 0)
2182 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2183 Py_TYPE(self)->tp_name,
2184 GET_TD_DAYS(self),
2185 GET_TD_SECONDS(self),
2186 GET_TD_MICROSECONDS(self));
2187 if (GET_TD_SECONDS(self) != 0)
2188 return PyUnicode_FromFormat("%s(%d, %d)",
2189 Py_TYPE(self)->tp_name,
2190 GET_TD_DAYS(self),
2191 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 return PyUnicode_FromFormat("%s(%d)",
2194 Py_TYPE(self)->tp_name,
2195 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002196}
2197
2198static PyObject *
2199delta_str(PyDateTime_Delta *self)
2200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 int us = GET_TD_MICROSECONDS(self);
2202 int seconds = GET_TD_SECONDS(self);
2203 int minutes = divmod(seconds, 60, &seconds);
2204 int hours = divmod(minutes, 60, &minutes);
2205 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 if (days) {
2208 if (us)
2209 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2210 days, (days == 1 || days == -1) ? "" : "s",
2211 hours, minutes, seconds, us);
2212 else
2213 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2214 days, (days == 1 || days == -1) ? "" : "s",
2215 hours, minutes, seconds);
2216 } else {
2217 if (us)
2218 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2219 hours, minutes, seconds, us);
2220 else
2221 return PyUnicode_FromFormat("%d:%02d:%02d",
2222 hours, minutes, seconds);
2223 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002224
Tim Peters2a799bf2002-12-16 20:18:38 +00002225}
2226
Tim Peters371935f2003-02-01 01:52:50 +00002227/* Pickle support, a simple use of __reduce__. */
2228
Tim Petersb57f8f02003-02-01 02:54:15 +00002229/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002230static PyObject *
2231delta_getstate(PyDateTime_Delta *self)
2232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 return Py_BuildValue("iii", GET_TD_DAYS(self),
2234 GET_TD_SECONDS(self),
2235 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002236}
2237
Tim Peters2a799bf2002-12-16 20:18:38 +00002238static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002239delta_total_seconds(PyObject *self)
2240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 PyObject *total_seconds;
2242 PyObject *total_microseconds;
2243 PyObject *one_million;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2246 if (total_microseconds == NULL)
2247 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 one_million = PyLong_FromLong(1000000L);
2250 if (one_million == NULL) {
2251 Py_DECREF(total_microseconds);
2252 return NULL;
2253 }
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 Py_DECREF(total_microseconds);
2258 Py_DECREF(one_million);
2259 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002260}
2261
2262static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002263delta_reduce(PyDateTime_Delta* self)
2264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002266}
2267
2268#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2269
2270static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 {"days", T_INT, OFFSET(days), READONLY,
2273 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 {"seconds", T_INT, OFFSET(seconds), READONLY,
2276 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2279 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2280 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002281};
2282
2283static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2285 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2288 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002291};
2292
2293static char delta_doc[] =
2294PyDoc_STR("Difference between two datetime values.");
2295
2296static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 delta_add, /* nb_add */
2298 delta_subtract, /* nb_subtract */
2299 delta_multiply, /* nb_multiply */
2300 delta_remainder, /* nb_remainder */
2301 delta_divmod, /* nb_divmod */
2302 0, /* nb_power */
2303 (unaryfunc)delta_negative, /* nb_negative */
2304 (unaryfunc)delta_positive, /* nb_positive */
2305 (unaryfunc)delta_abs, /* nb_absolute */
2306 (inquiry)delta_bool, /* nb_bool */
2307 0, /*nb_invert*/
2308 0, /*nb_lshift*/
2309 0, /*nb_rshift*/
2310 0, /*nb_and*/
2311 0, /*nb_xor*/
2312 0, /*nb_or*/
2313 0, /*nb_int*/
2314 0, /*nb_reserved*/
2315 0, /*nb_float*/
2316 0, /*nb_inplace_add*/
2317 0, /*nb_inplace_subtract*/
2318 0, /*nb_inplace_multiply*/
2319 0, /*nb_inplace_remainder*/
2320 0, /*nb_inplace_power*/
2321 0, /*nb_inplace_lshift*/
2322 0, /*nb_inplace_rshift*/
2323 0, /*nb_inplace_and*/
2324 0, /*nb_inplace_xor*/
2325 0, /*nb_inplace_or*/
2326 delta_divide, /* nb_floor_divide */
2327 delta_truedivide, /* nb_true_divide */
2328 0, /* nb_inplace_floor_divide */
2329 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002330};
2331
2332static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 PyVarObject_HEAD_INIT(NULL, 0)
2334 "datetime.timedelta", /* tp_name */
2335 sizeof(PyDateTime_Delta), /* tp_basicsize */
2336 0, /* tp_itemsize */
2337 0, /* tp_dealloc */
2338 0, /* tp_print */
2339 0, /* tp_getattr */
2340 0, /* tp_setattr */
2341 0, /* tp_reserved */
2342 (reprfunc)delta_repr, /* tp_repr */
2343 &delta_as_number, /* tp_as_number */
2344 0, /* tp_as_sequence */
2345 0, /* tp_as_mapping */
2346 (hashfunc)delta_hash, /* tp_hash */
2347 0, /* tp_call */
2348 (reprfunc)delta_str, /* tp_str */
2349 PyObject_GenericGetAttr, /* tp_getattro */
2350 0, /* tp_setattro */
2351 0, /* tp_as_buffer */
2352 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2353 delta_doc, /* tp_doc */
2354 0, /* tp_traverse */
2355 0, /* tp_clear */
2356 delta_richcompare, /* tp_richcompare */
2357 0, /* tp_weaklistoffset */
2358 0, /* tp_iter */
2359 0, /* tp_iternext */
2360 delta_methods, /* tp_methods */
2361 delta_members, /* tp_members */
2362 0, /* tp_getset */
2363 0, /* tp_base */
2364 0, /* tp_dict */
2365 0, /* tp_descr_get */
2366 0, /* tp_descr_set */
2367 0, /* tp_dictoffset */
2368 0, /* tp_init */
2369 0, /* tp_alloc */
2370 delta_new, /* tp_new */
2371 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002372};
2373
2374/*
2375 * PyDateTime_Date implementation.
2376 */
2377
2378/* Accessor properties. */
2379
2380static PyObject *
2381date_year(PyDateTime_Date *self, void *unused)
2382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002384}
2385
2386static PyObject *
2387date_month(PyDateTime_Date *self, void *unused)
2388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002390}
2391
2392static PyObject *
2393date_day(PyDateTime_Date *self, void *unused)
2394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002396}
2397
2398static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 {"year", (getter)date_year},
2400 {"month", (getter)date_month},
2401 {"day", (getter)date_day},
2402 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002403};
2404
2405/* Constructors. */
2406
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002407static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002408
Tim Peters2a799bf2002-12-16 20:18:38 +00002409static PyObject *
2410date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 PyObject *self = NULL;
2413 PyObject *state;
2414 int year;
2415 int month;
2416 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* Check for invocation from pickle with __getstate__ state */
2419 if (PyTuple_GET_SIZE(args) == 1 &&
2420 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2421 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2422 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2423 {
2424 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2427 if (me != NULL) {
2428 char *pdata = PyBytes_AS_STRING(state);
2429 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2430 me->hashcode = -1;
2431 }
2432 return (PyObject *)me;
2433 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2436 &year, &month, &day)) {
2437 if (check_date_args(year, month, day) < 0)
2438 return NULL;
2439 self = new_date_ex(year, month, day, type);
2440 }
2441 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002442}
2443
2444/* Return new date from localtime(t). */
2445static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01002446date_local_from_object(PyObject *cls, PyObject *obj)
Tim Peters2a799bf2002-12-16 20:18:38 +00002447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 struct tm *tm;
2449 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002450
Victor Stinner5d272cc2012-03-13 13:35:55 +01002451 if (_PyTime_ObjectToTime_t(obj, &t) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 return NULL;
Victor Stinner5d272cc2012-03-13 13:35:55 +01002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 tm = localtime(&t);
Victor Stinner21f58932012-03-14 00:15:40 +01002455 if (tm == NULL) {
2456 /* unconvertible time */
2457#ifdef EINVAL
2458 if (errno == 0)
2459 errno = EINVAL;
2460#endif
2461 PyErr_SetFromErrno(PyExc_OSError);
2462 return NULL;
2463 }
2464
2465 return PyObject_CallFunction(cls, "iii",
2466 tm->tm_year + 1900,
2467 tm->tm_mon + 1,
2468 tm->tm_mday);
Tim Peters2a799bf2002-12-16 20:18:38 +00002469}
2470
2471/* Return new date from current time.
2472 * We say this is equivalent to fromtimestamp(time.time()), and the
2473 * only way to be sure of that is to *call* time.time(). That's not
2474 * generally the same as calling C's time.
2475 */
2476static PyObject *
2477date_today(PyObject *cls, PyObject *dummy)
2478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 PyObject *time;
2480 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002481 _Py_IDENTIFIER(fromtimestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 time = time_time();
2484 if (time == NULL)
2485 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 /* Note well: today() is a class method, so this may not call
2488 * date.fromtimestamp. For example, it may call
2489 * datetime.fromtimestamp. That's why we need all the accuracy
2490 * time.time() delivers; if someone were gonzo about optimization,
2491 * date.today() could get away with plain C time().
2492 */
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002493 result = _PyObject_CallMethodId(cls, &PyId_fromtimestamp, "O", time);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 Py_DECREF(time);
2495 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002496}
2497
2498/* Return new date from given timestamp (Python timestamp -- a double). */
2499static PyObject *
2500date_fromtimestamp(PyObject *cls, PyObject *args)
2501{
Victor Stinner5d272cc2012-03-13 13:35:55 +01002502 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002504
Victor Stinner5d272cc2012-03-13 13:35:55 +01002505 if (PyArg_ParseTuple(args, "O:fromtimestamp", &timestamp))
2506 result = date_local_from_object(cls, timestamp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002508}
2509
2510/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2511 * the ordinal is out of range.
2512 */
2513static PyObject *
2514date_fromordinal(PyObject *cls, PyObject *args)
2515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 PyObject *result = NULL;
2517 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2520 int year;
2521 int month;
2522 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 if (ordinal < 1)
2525 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2526 ">= 1");
2527 else {
2528 ord_to_ymd(ordinal, &year, &month, &day);
2529 result = PyObject_CallFunction(cls, "iii",
2530 year, month, day);
2531 }
2532 }
2533 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002534}
2535
2536/*
2537 * Date arithmetic.
2538 */
2539
2540/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2541 * instead.
2542 */
2543static PyObject *
2544add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 PyObject *result = NULL;
2547 int year = GET_YEAR(date);
2548 int month = GET_MONTH(date);
2549 int deltadays = GET_TD_DAYS(delta);
2550 /* C-level overflow is impossible because |deltadays| < 1e9. */
2551 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 if (normalize_date(&year, &month, &day) >= 0)
2554 result = new_date(year, month, day);
2555 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002556}
2557
2558static PyObject *
2559date_add(PyObject *left, PyObject *right)
2560{
Brian Curtindfc80e32011-08-10 20:28:54 -05002561 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2562 Py_RETURN_NOTIMPLEMENTED;
2563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 if (PyDate_Check(left)) {
2565 /* date + ??? */
2566 if (PyDelta_Check(right))
2567 /* date + delta */
2568 return add_date_timedelta((PyDateTime_Date *) left,
2569 (PyDateTime_Delta *) right,
2570 0);
2571 }
2572 else {
2573 /* ??? + date
2574 * 'right' must be one of us, or we wouldn't have been called
2575 */
2576 if (PyDelta_Check(left))
2577 /* delta + date */
2578 return add_date_timedelta((PyDateTime_Date *) right,
2579 (PyDateTime_Delta *) left,
2580 0);
2581 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002582 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002583}
2584
2585static PyObject *
2586date_subtract(PyObject *left, PyObject *right)
2587{
Brian Curtindfc80e32011-08-10 20:28:54 -05002588 if (PyDateTime_Check(left) || PyDateTime_Check(right))
2589 Py_RETURN_NOTIMPLEMENTED;
2590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (PyDate_Check(left)) {
2592 if (PyDate_Check(right)) {
2593 /* date - date */
2594 int left_ord = ymd_to_ord(GET_YEAR(left),
2595 GET_MONTH(left),
2596 GET_DAY(left));
2597 int right_ord = ymd_to_ord(GET_YEAR(right),
2598 GET_MONTH(right),
2599 GET_DAY(right));
2600 return new_delta(left_ord - right_ord, 0, 0, 0);
2601 }
2602 if (PyDelta_Check(right)) {
2603 /* date - delta */
2604 return add_date_timedelta((PyDateTime_Date *) left,
2605 (PyDateTime_Delta *) right,
2606 1);
2607 }
2608 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002609 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002610}
2611
2612
2613/* Various ways to turn a date into a string. */
2614
2615static PyObject *
2616date_repr(PyDateTime_Date *self)
2617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2619 Py_TYPE(self)->tp_name,
2620 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002621}
2622
2623static PyObject *
2624date_isoformat(PyDateTime_Date *self)
2625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 return PyUnicode_FromFormat("%04d-%02d-%02d",
2627 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002628}
2629
Tim Peterse2df5ff2003-05-02 18:39:55 +00002630/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002631static PyObject *
2632date_str(PyDateTime_Date *self)
2633{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002634 _Py_IDENTIFIER(isoformat);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002635
2636 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002637}
2638
2639
2640static PyObject *
2641date_ctime(PyDateTime_Date *self)
2642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002644}
2645
2646static PyObject *
2647date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 /* This method can be inherited, and needs to call the
2650 * timetuple() method appropriate to self's class.
2651 */
2652 PyObject *result;
2653 PyObject *tuple;
2654 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002655 _Py_IDENTIFIER(timetuple);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2659 &format))
2660 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002661
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002662 tuple = _PyObject_CallMethodId((PyObject *)self, &PyId_timetuple, "()");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 if (tuple == NULL)
2664 return NULL;
2665 result = wrap_strftime((PyObject *)self, format, tuple,
2666 (PyObject *)self);
2667 Py_DECREF(tuple);
2668 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002669}
2670
Eric Smith1ba31142007-09-11 18:06:02 +00002671static PyObject *
2672date_format(PyDateTime_Date *self, PyObject *args)
2673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 PyObject *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002675 _Py_IDENTIFIER(strftime);
Eric Smith1ba31142007-09-11 18:06:02 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2678 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 /* if the format is zero length, return str(self) */
Victor Stinner9e30aa52011-11-21 02:49:52 +01002681 if (PyUnicode_GetLength(format) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002683
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002684 return _PyObject_CallMethodId((PyObject *)self, &PyId_strftime, "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002685}
2686
Tim Peters2a799bf2002-12-16 20:18:38 +00002687/* ISO methods. */
2688
2689static PyObject *
2690date_isoweekday(PyDateTime_Date *self)
2691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002695}
2696
2697static PyObject *
2698date_isocalendar(PyDateTime_Date *self)
2699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 int year = GET_YEAR(self);
2701 int week1_monday = iso_week1_monday(year);
2702 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2703 int week;
2704 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 week = divmod(today - week1_monday, 7, &day);
2707 if (week < 0) {
2708 --year;
2709 week1_monday = iso_week1_monday(year);
2710 week = divmod(today - week1_monday, 7, &day);
2711 }
2712 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2713 ++year;
2714 week = 0;
2715 }
2716 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002717}
2718
2719/* Miscellaneous methods. */
2720
Tim Peters2a799bf2002-12-16 20:18:38 +00002721static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002722date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 if (PyDate_Check(other)) {
2725 int diff = memcmp(((PyDateTime_Date *)self)->data,
2726 ((PyDateTime_Date *)other)->data,
2727 _PyDateTime_DATE_DATASIZE);
2728 return diff_to_bool(diff, op);
2729 }
Brian Curtindfc80e32011-08-10 20:28:54 -05002730 else
2731 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00002732}
2733
2734static PyObject *
2735date_timetuple(PyDateTime_Date *self)
2736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 return build_struct_time(GET_YEAR(self),
2738 GET_MONTH(self),
2739 GET_DAY(self),
2740 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002741}
2742
Tim Peters12bf3392002-12-24 05:41:27 +00002743static PyObject *
2744date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 PyObject *clone;
2747 PyObject *tuple;
2748 int year = GET_YEAR(self);
2749 int month = GET_MONTH(self);
2750 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2753 &year, &month, &day))
2754 return NULL;
2755 tuple = Py_BuildValue("iii", year, month, day);
2756 if (tuple == NULL)
2757 return NULL;
2758 clone = date_new(Py_TYPE(self), tuple, NULL);
2759 Py_DECREF(tuple);
2760 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002761}
2762
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002763static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002764generic_hash(unsigned char *data, int len)
2765{
Gregory P. Smith5831bd22012-01-14 14:31:13 -08002766 return _Py_HashBytes(data, len);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002767}
2768
2769
2770static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002771
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002772static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002773date_hash(PyDateTime_Date *self)
2774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 if (self->hashcode == -1)
2776 self->hashcode = generic_hash(
2777 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002780}
2781
2782static PyObject *
2783date_toordinal(PyDateTime_Date *self)
2784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2786 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002787}
2788
2789static PyObject *
2790date_weekday(PyDateTime_Date *self)
2791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002795}
2796
Tim Peters371935f2003-02-01 01:52:50 +00002797/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002798
Tim Petersb57f8f02003-02-01 02:54:15 +00002799/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002800static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002801date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 PyObject* field;
2804 field = PyBytes_FromStringAndSize((char*)self->data,
2805 _PyDateTime_DATE_DATASIZE);
2806 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002807}
2808
2809static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002810date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002813}
2814
2815static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2820 METH_CLASS,
2821 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2822 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2825 METH_CLASS,
2826 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2827 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2830 PyDoc_STR("Current date or datetime: same as "
2831 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2836 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2839 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2842 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2845 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2848 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2849 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2852 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2855 PyDoc_STR("Return the day of the week represented by the date.\n"
2856 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2859 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2860 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2863 PyDoc_STR("Return the day of the week represented by the date.\n"
2864 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2867 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2870 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002873};
2874
2875static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002876PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002877
2878static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 date_add, /* nb_add */
2880 date_subtract, /* nb_subtract */
2881 0, /* nb_multiply */
2882 0, /* nb_remainder */
2883 0, /* nb_divmod */
2884 0, /* nb_power */
2885 0, /* nb_negative */
2886 0, /* nb_positive */
2887 0, /* nb_absolute */
2888 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002889};
2890
2891static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 PyVarObject_HEAD_INIT(NULL, 0)
2893 "datetime.date", /* tp_name */
2894 sizeof(PyDateTime_Date), /* tp_basicsize */
2895 0, /* tp_itemsize */
2896 0, /* tp_dealloc */
2897 0, /* tp_print */
2898 0, /* tp_getattr */
2899 0, /* tp_setattr */
2900 0, /* tp_reserved */
2901 (reprfunc)date_repr, /* tp_repr */
2902 &date_as_number, /* tp_as_number */
2903 0, /* tp_as_sequence */
2904 0, /* tp_as_mapping */
2905 (hashfunc)date_hash, /* tp_hash */
2906 0, /* tp_call */
2907 (reprfunc)date_str, /* tp_str */
2908 PyObject_GenericGetAttr, /* tp_getattro */
2909 0, /* tp_setattro */
2910 0, /* tp_as_buffer */
2911 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2912 date_doc, /* tp_doc */
2913 0, /* tp_traverse */
2914 0, /* tp_clear */
2915 date_richcompare, /* tp_richcompare */
2916 0, /* tp_weaklistoffset */
2917 0, /* tp_iter */
2918 0, /* tp_iternext */
2919 date_methods, /* tp_methods */
2920 0, /* tp_members */
2921 date_getset, /* tp_getset */
2922 0, /* tp_base */
2923 0, /* tp_dict */
2924 0, /* tp_descr_get */
2925 0, /* tp_descr_set */
2926 0, /* tp_dictoffset */
2927 0, /* tp_init */
2928 0, /* tp_alloc */
2929 date_new, /* tp_new */
2930 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002931};
2932
2933/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002934 * PyDateTime_TZInfo implementation.
2935 */
2936
2937/* This is a pure abstract base class, so doesn't do anything beyond
2938 * raising NotImplemented exceptions. Real tzinfo classes need
2939 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002940 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002941 * be subclasses of this tzinfo class, which is easy and quick to check).
2942 *
2943 * Note: For reasons having to do with pickling of subclasses, we have
2944 * to allow tzinfo objects to be instantiated. This wasn't an issue
2945 * in the Python implementation (__init__() could raise NotImplementedError
2946 * there without ill effect), but doing so in the C implementation hit a
2947 * brick wall.
2948 */
2949
2950static PyObject *
2951tzinfo_nogo(const char* methodname)
2952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 PyErr_Format(PyExc_NotImplementedError,
2954 "a tzinfo subclass must implement %s()",
2955 methodname);
2956 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002957}
2958
2959/* Methods. A subclass must implement these. */
2960
Tim Peters52dcce22003-01-23 16:36:11 +00002961static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002962tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002965}
2966
Tim Peters52dcce22003-01-23 16:36:11 +00002967static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002968tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002971}
2972
Tim Peters52dcce22003-01-23 16:36:11 +00002973static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002974tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00002977}
2978
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002979
2980static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
2981 PyDateTime_Delta *delta,
2982 int factor);
2983static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
2984static PyObject *datetime_dst(PyObject *self, PyObject *);
2985
Tim Peters52dcce22003-01-23 16:36:11 +00002986static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002987tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00002988{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002989 PyObject *result = NULL;
2990 PyObject *off = NULL, *dst = NULL;
2991 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002992
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002993 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 PyErr_SetString(PyExc_TypeError,
2995 "fromutc: argument must be a datetime");
2996 return NULL;
2997 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00002998 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3000 "is not self");
3001 return NULL;
3002 }
Tim Peters52dcce22003-01-23 16:36:11 +00003003
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003004 off = datetime_utcoffset(dt, NULL);
3005 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003007 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3009 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003010 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 }
Tim Peters52dcce22003-01-23 16:36:11 +00003012
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003013 dst = datetime_dst(dt, NULL);
3014 if (dst == NULL)
3015 goto Fail;
3016 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3018 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003019 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 }
Tim Peters52dcce22003-01-23 16:36:11 +00003021
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003022 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3023 if (delta == NULL)
3024 goto Fail;
3025 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003028
3029 Py_DECREF(dst);
3030 dst = call_dst(GET_DT_TZINFO(dt), result);
3031 if (dst == NULL)
3032 goto Fail;
3033 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 goto Inconsistent;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003035 if (delta_bool(delta) != 0) {
3036 PyObject *temp = result;
3037 result = add_datetime_timedelta((PyDateTime_DateTime *)result,
3038 (PyDateTime_Delta *)dst, 1);
3039 Py_DECREF(temp);
3040 if (result == NULL)
3041 goto Fail;
3042 }
3043 Py_DECREF(delta);
3044 Py_DECREF(dst);
3045 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003047
3048Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3050 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003053Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003054 Py_XDECREF(off);
3055 Py_XDECREF(dst);
3056 Py_XDECREF(delta);
3057 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003059}
3060
Tim Peters2a799bf2002-12-16 20:18:38 +00003061/*
3062 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003063 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003064 */
3065
Guido van Rossum177e41a2003-01-30 22:06:23 +00003066static PyObject *
3067tzinfo_reduce(PyObject *self)
3068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 PyObject *args, *state, *tmp;
3070 PyObject *getinitargs, *getstate;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003071 _Py_IDENTIFIER(__getinitargs__);
3072 _Py_IDENTIFIER(__getstate__);
Tim Peters2a799bf2002-12-16 20:18:38 +00003073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 tmp = PyTuple_New(0);
3075 if (tmp == NULL)
3076 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003077
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003078 getinitargs = _PyObject_GetAttrId(self, &PyId___getinitargs__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 if (getinitargs != NULL) {
3080 args = PyObject_CallObject(getinitargs, tmp);
3081 Py_DECREF(getinitargs);
3082 if (args == NULL) {
3083 Py_DECREF(tmp);
3084 return NULL;
3085 }
3086 }
3087 else {
3088 PyErr_Clear();
3089 args = tmp;
3090 Py_INCREF(args);
3091 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003092
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003093 getstate = _PyObject_GetAttrId(self, &PyId___getstate__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 if (getstate != NULL) {
3095 state = PyObject_CallObject(getstate, tmp);
3096 Py_DECREF(getstate);
3097 if (state == NULL) {
3098 Py_DECREF(args);
3099 Py_DECREF(tmp);
3100 return NULL;
3101 }
3102 }
3103 else {
3104 PyObject **dictptr;
3105 PyErr_Clear();
3106 state = Py_None;
3107 dictptr = _PyObject_GetDictPtr(self);
3108 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3109 state = *dictptr;
3110 Py_INCREF(state);
3111 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 if (state == Py_None) {
3116 Py_DECREF(state);
3117 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3118 }
3119 else
3120 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003121}
Tim Peters2a799bf2002-12-16 20:18:38 +00003122
3123static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3126 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003129 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3130 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3133 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003136 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3139 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003142};
3143
3144static char tzinfo_doc[] =
3145PyDoc_STR("Abstract base class for time zone info objects.");
3146
Neal Norwitz227b5332006-03-22 09:28:35 +00003147static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 PyVarObject_HEAD_INIT(NULL, 0)
3149 "datetime.tzinfo", /* tp_name */
3150 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3151 0, /* tp_itemsize */
3152 0, /* tp_dealloc */
3153 0, /* tp_print */
3154 0, /* tp_getattr */
3155 0, /* tp_setattr */
3156 0, /* tp_reserved */
3157 0, /* tp_repr */
3158 0, /* tp_as_number */
3159 0, /* tp_as_sequence */
3160 0, /* tp_as_mapping */
3161 0, /* tp_hash */
3162 0, /* tp_call */
3163 0, /* tp_str */
3164 PyObject_GenericGetAttr, /* tp_getattro */
3165 0, /* tp_setattro */
3166 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003167 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 tzinfo_doc, /* tp_doc */
3169 0, /* tp_traverse */
3170 0, /* tp_clear */
3171 0, /* tp_richcompare */
3172 0, /* tp_weaklistoffset */
3173 0, /* tp_iter */
3174 0, /* tp_iternext */
3175 tzinfo_methods, /* tp_methods */
3176 0, /* tp_members */
3177 0, /* tp_getset */
3178 0, /* tp_base */
3179 0, /* tp_dict */
3180 0, /* tp_descr_get */
3181 0, /* tp_descr_set */
3182 0, /* tp_dictoffset */
3183 0, /* tp_init */
3184 0, /* tp_alloc */
3185 PyType_GenericNew, /* tp_new */
3186 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003187};
3188
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003189static char *timezone_kws[] = {"offset", "name", NULL};
3190
3191static PyObject *
3192timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3193{
3194 PyObject *offset;
3195 PyObject *name = NULL;
3196 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
3197 &PyDateTime_DeltaType, &offset,
3198 &PyUnicode_Type, &name))
3199 return new_timezone(offset, name);
3200
3201 return NULL;
3202}
3203
3204static void
3205timezone_dealloc(PyDateTime_TimeZone *self)
3206{
3207 Py_CLEAR(self->offset);
3208 Py_CLEAR(self->name);
3209 Py_TYPE(self)->tp_free((PyObject *)self);
3210}
3211
3212static PyObject *
3213timezone_richcompare(PyDateTime_TimeZone *self,
3214 PyDateTime_TimeZone *other, int op)
3215{
Brian Curtindfc80e32011-08-10 20:28:54 -05003216 if (op != Py_EQ && op != Py_NE)
3217 Py_RETURN_NOTIMPLEMENTED;
Georg Brandl0085a242012-09-22 09:23:12 +02003218 if (Py_TYPE(other) != &PyDateTime_TimeZoneType) {
3219 if (op == Py_EQ)
3220 Py_RETURN_FALSE;
3221 else
3222 Py_RETURN_TRUE;
3223 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003224 return delta_richcompare(self->offset, other->offset, op);
3225}
3226
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003227static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003228timezone_hash(PyDateTime_TimeZone *self)
3229{
3230 return delta_hash((PyDateTime_Delta *)self->offset);
3231}
3232
3233/* Check argument type passed to tzname, utcoffset, or dst methods.
3234 Returns 0 for good argument. Returns -1 and sets exception info
3235 otherwise.
3236 */
3237static int
3238_timezone_check_argument(PyObject *dt, const char *meth)
3239{
3240 if (dt == Py_None || PyDateTime_Check(dt))
3241 return 0;
3242 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3243 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3244 return -1;
3245}
3246
3247static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003248timezone_repr(PyDateTime_TimeZone *self)
3249{
3250 /* Note that although timezone is not subclassable, it is convenient
3251 to use Py_TYPE(self)->tp_name here. */
3252 const char *type_name = Py_TYPE(self)->tp_name;
3253
3254 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3255 return PyUnicode_FromFormat("%s.utc", type_name);
3256
3257 if (self->name == NULL)
3258 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3259
3260 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3261 self->name);
3262}
3263
3264
3265static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003266timezone_str(PyDateTime_TimeZone *self)
3267{
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003268 int hours, minutes, seconds;
3269 PyObject *offset;
3270 char sign;
3271
3272 if (self->name != NULL) {
3273 Py_INCREF(self->name);
3274 return self->name;
3275 }
3276 /* Offset is normalized, so it is negative if days < 0 */
3277 if (GET_TD_DAYS(self->offset) < 0) {
3278 sign = '-';
3279 offset = delta_negative((PyDateTime_Delta *)self->offset);
3280 if (offset == NULL)
3281 return NULL;
3282 }
3283 else {
3284 sign = '+';
3285 offset = self->offset;
3286 Py_INCREF(offset);
3287 }
3288 /* Offset is not negative here. */
3289 seconds = GET_TD_SECONDS(offset);
3290 Py_DECREF(offset);
3291 minutes = divmod(seconds, 60, &seconds);
3292 hours = divmod(minutes, 60, &minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003293 /* XXX ignore sub-minute data, curently not allowed. */
Victor Stinner6ced7c42011-03-21 18:15:42 +01003294 assert(seconds == 0);
3295 return PyUnicode_FromFormat("UTC%c%02d:%02d", sign, hours, minutes);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003296}
3297
3298static PyObject *
3299timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3300{
3301 if (_timezone_check_argument(dt, "tzname") == -1)
3302 return NULL;
3303
3304 return timezone_str(self);
3305}
3306
3307static PyObject *
3308timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3309{
3310 if (_timezone_check_argument(dt, "utcoffset") == -1)
3311 return NULL;
3312
3313 Py_INCREF(self->offset);
3314 return self->offset;
3315}
3316
3317static PyObject *
3318timezone_dst(PyObject *self, PyObject *dt)
3319{
3320 if (_timezone_check_argument(dt, "dst") == -1)
3321 return NULL;
3322
3323 Py_RETURN_NONE;
3324}
3325
3326static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003327timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3328{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003329 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003330 PyErr_SetString(PyExc_TypeError,
3331 "fromutc: argument must be a datetime");
3332 return NULL;
3333 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003334 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003335 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3336 "is not self");
3337 return NULL;
3338 }
3339
3340 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3341}
3342
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003343static PyObject *
3344timezone_getinitargs(PyDateTime_TimeZone *self)
3345{
3346 if (self->name == NULL)
3347 return Py_BuildValue("(O)", self->offset);
3348 return Py_BuildValue("(OO)", self->offset, self->name);
3349}
3350
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003351static PyMethodDef timezone_methods[] = {
3352 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3353 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003354 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003355
3356 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003357 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003358
3359 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003360 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003361
3362 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3363 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3364
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003365 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3366 PyDoc_STR("pickle support")},
3367
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003368 {NULL, NULL}
3369};
3370
3371static char timezone_doc[] =
3372PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3373
3374static PyTypeObject PyDateTime_TimeZoneType = {
3375 PyVarObject_HEAD_INIT(NULL, 0)
3376 "datetime.timezone", /* tp_name */
3377 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3378 0, /* tp_itemsize */
3379 (destructor)timezone_dealloc, /* tp_dealloc */
3380 0, /* tp_print */
3381 0, /* tp_getattr */
3382 0, /* tp_setattr */
3383 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003384 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003385 0, /* tp_as_number */
3386 0, /* tp_as_sequence */
3387 0, /* tp_as_mapping */
3388 (hashfunc)timezone_hash, /* tp_hash */
3389 0, /* tp_call */
3390 (reprfunc)timezone_str, /* tp_str */
3391 0, /* tp_getattro */
3392 0, /* tp_setattro */
3393 0, /* tp_as_buffer */
3394 Py_TPFLAGS_DEFAULT, /* tp_flags */
3395 timezone_doc, /* tp_doc */
3396 0, /* tp_traverse */
3397 0, /* tp_clear */
3398 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3399 0, /* tp_weaklistoffset */
3400 0, /* tp_iter */
3401 0, /* tp_iternext */
3402 timezone_methods, /* tp_methods */
3403 0, /* tp_members */
3404 0, /* tp_getset */
3405 &PyDateTime_TZInfoType, /* tp_base */
3406 0, /* tp_dict */
3407 0, /* tp_descr_get */
3408 0, /* tp_descr_set */
3409 0, /* tp_dictoffset */
3410 0, /* tp_init */
3411 0, /* tp_alloc */
3412 timezone_new, /* tp_new */
3413};
3414
Tim Peters2a799bf2002-12-16 20:18:38 +00003415/*
Tim Peters37f39822003-01-10 03:49:02 +00003416 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003417 */
3418
Tim Peters37f39822003-01-10 03:49:02 +00003419/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003420 */
3421
3422static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003423time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003426}
3427
Tim Peters37f39822003-01-10 03:49:02 +00003428static PyObject *
3429time_minute(PyDateTime_Time *self, void *unused)
3430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003432}
3433
3434/* The name time_second conflicted with some platform header file. */
3435static PyObject *
3436py_time_second(PyDateTime_Time *self, void *unused)
3437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003439}
3440
3441static PyObject *
3442time_microsecond(PyDateTime_Time *self, void *unused)
3443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003445}
3446
3447static PyObject *
3448time_tzinfo(PyDateTime_Time *self, void *unused)
3449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3451 Py_INCREF(result);
3452 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003453}
3454
3455static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 {"hour", (getter)time_hour},
3457 {"minute", (getter)time_minute},
3458 {"second", (getter)py_time_second},
3459 {"microsecond", (getter)time_microsecond},
3460 {"tzinfo", (getter)time_tzinfo},
3461 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003462};
3463
3464/*
3465 * Constructors.
3466 */
3467
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003468static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003470
Tim Peters2a799bf2002-12-16 20:18:38 +00003471static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003472time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 PyObject *self = NULL;
3475 PyObject *state;
3476 int hour = 0;
3477 int minute = 0;
3478 int second = 0;
3479 int usecond = 0;
3480 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 /* Check for invocation from pickle with __getstate__ state */
3483 if (PyTuple_GET_SIZE(args) >= 1 &&
3484 PyTuple_GET_SIZE(args) <= 2 &&
3485 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3486 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3487 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
3488 {
3489 PyDateTime_Time *me;
3490 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 if (PyTuple_GET_SIZE(args) == 2) {
3493 tzinfo = PyTuple_GET_ITEM(args, 1);
3494 if (check_tzinfo_subclass(tzinfo) < 0) {
3495 PyErr_SetString(PyExc_TypeError, "bad "
3496 "tzinfo state arg");
3497 return NULL;
3498 }
3499 }
3500 aware = (char)(tzinfo != Py_None);
3501 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3502 if (me != NULL) {
3503 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3506 me->hashcode = -1;
3507 me->hastzinfo = aware;
3508 if (aware) {
3509 Py_INCREF(tzinfo);
3510 me->tzinfo = tzinfo;
3511 }
3512 }
3513 return (PyObject *)me;
3514 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3517 &hour, &minute, &second, &usecond,
3518 &tzinfo)) {
3519 if (check_time_args(hour, minute, second, usecond) < 0)
3520 return NULL;
3521 if (check_tzinfo_subclass(tzinfo) < 0)
3522 return NULL;
3523 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3524 type);
3525 }
3526 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003527}
3528
3529/*
3530 * Destructor.
3531 */
3532
3533static void
Tim Peters37f39822003-01-10 03:49:02 +00003534time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 if (HASTZINFO(self)) {
3537 Py_XDECREF(self->tzinfo);
3538 }
3539 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003540}
3541
3542/*
Tim Peters855fe882002-12-22 03:43:39 +00003543 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003544 */
3545
Tim Peters2a799bf2002-12-16 20:18:38 +00003546/* These are all METH_NOARGS, so don't need to check the arglist. */
3547static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003548time_utcoffset(PyObject *self, PyObject *unused) {
3549 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003550}
3551
3552static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003553time_dst(PyObject *self, PyObject *unused) {
3554 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003555}
3556
3557static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003558time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003559 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003560}
3561
3562/*
Tim Peters37f39822003-01-10 03:49:02 +00003563 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003564 */
3565
3566static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003567time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 const char *type_name = Py_TYPE(self)->tp_name;
3570 int h = TIME_GET_HOUR(self);
3571 int m = TIME_GET_MINUTE(self);
3572 int s = TIME_GET_SECOND(self);
3573 int us = TIME_GET_MICROSECOND(self);
3574 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 if (us)
3577 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3578 type_name, h, m, s, us);
3579 else if (s)
3580 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3581 type_name, h, m, s);
3582 else
3583 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3584 if (result != NULL && HASTZINFO(self))
3585 result = append_keyword_tzinfo(result, self->tzinfo);
3586 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003587}
3588
Tim Peters37f39822003-01-10 03:49:02 +00003589static PyObject *
3590time_str(PyDateTime_Time *self)
3591{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02003592 _Py_IDENTIFIER(isoformat);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02003593
3594 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "()");
Tim Peters37f39822003-01-10 03:49:02 +00003595}
Tim Peters2a799bf2002-12-16 20:18:38 +00003596
3597static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003598time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 char buf[100];
3601 PyObject *result;
3602 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 if (us)
3605 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3606 TIME_GET_HOUR(self),
3607 TIME_GET_MINUTE(self),
3608 TIME_GET_SECOND(self),
3609 us);
3610 else
3611 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3612 TIME_GET_HOUR(self),
3613 TIME_GET_MINUTE(self),
3614 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003615
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003616 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 /* We need to append the UTC offset. */
3620 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3621 Py_None) < 0) {
3622 Py_DECREF(result);
3623 return NULL;
3624 }
3625 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3626 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003627}
3628
Tim Peters37f39822003-01-10 03:49:02 +00003629static PyObject *
3630time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 PyObject *result;
3633 PyObject *tuple;
3634 PyObject *format;
3635 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3638 &format))
3639 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 /* Python's strftime does insane things with the year part of the
3642 * timetuple. The year is forced to (the otherwise nonsensical)
Alexander Belopolskyb8bb4662011-01-08 00:13:34 +00003643 * 1900 to work around that.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 */
3645 tuple = Py_BuildValue("iiiiiiiii",
3646 1900, 1, 1, /* year, month, day */
3647 TIME_GET_HOUR(self),
3648 TIME_GET_MINUTE(self),
3649 TIME_GET_SECOND(self),
3650 0, 1, -1); /* weekday, daynum, dst */
3651 if (tuple == NULL)
3652 return NULL;
3653 assert(PyTuple_Size(tuple) == 9);
3654 result = wrap_strftime((PyObject *)self, format, tuple,
3655 Py_None);
3656 Py_DECREF(tuple);
3657 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003658}
Tim Peters2a799bf2002-12-16 20:18:38 +00003659
3660/*
3661 * Miscellaneous methods.
3662 */
3663
Tim Peters37f39822003-01-10 03:49:02 +00003664static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003665time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003666{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003667 PyObject *result = NULL;
3668 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003670
Brian Curtindfc80e32011-08-10 20:28:54 -05003671 if (! PyTime_Check(other))
3672 Py_RETURN_NOTIMPLEMENTED;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003673
3674 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 diff = memcmp(((PyDateTime_Time *)self)->data,
3676 ((PyDateTime_Time *)other)->data,
3677 _PyDateTime_TIME_DATASIZE);
3678 return diff_to_bool(diff, op);
3679 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003680 offset1 = time_utcoffset(self, NULL);
3681 if (offset1 == NULL)
3682 return NULL;
3683 offset2 = time_utcoffset(other, NULL);
3684 if (offset2 == NULL)
3685 goto done;
3686 /* If they're both naive, or both aware and have the same offsets,
3687 * we get off cheap. Note that if they're both naive, offset1 ==
3688 * offset2 == Py_None at this point.
3689 */
3690 if ((offset1 == offset2) ||
3691 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3692 delta_cmp(offset1, offset2) == 0)) {
3693 diff = memcmp(((PyDateTime_Time *)self)->data,
3694 ((PyDateTime_Time *)other)->data,
3695 _PyDateTime_TIME_DATASIZE);
3696 result = diff_to_bool(diff, op);
3697 }
3698 /* The hard case: both aware with different UTC offsets */
3699 else if (offset1 != Py_None && offset2 != Py_None) {
3700 int offsecs1, offsecs2;
3701 assert(offset1 != offset2); /* else last "if" handled it */
3702 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3703 TIME_GET_MINUTE(self) * 60 +
3704 TIME_GET_SECOND(self) -
3705 GET_TD_DAYS(offset1) * 86400 -
3706 GET_TD_SECONDS(offset1);
3707 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3708 TIME_GET_MINUTE(other) * 60 +
3709 TIME_GET_SECOND(other) -
3710 GET_TD_DAYS(offset2) * 86400 -
3711 GET_TD_SECONDS(offset2);
3712 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 if (diff == 0)
3714 diff = TIME_GET_MICROSECOND(self) -
3715 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003716 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04003718 else if (op == Py_EQ) {
3719 result = Py_False;
3720 Py_INCREF(result);
3721 }
3722 else if (op == Py_NE) {
3723 result = Py_True;
3724 Py_INCREF(result);
3725 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003726 else {
3727 PyErr_SetString(PyExc_TypeError,
3728 "can't compare offset-naive and "
3729 "offset-aware times");
3730 }
3731 done:
3732 Py_DECREF(offset1);
3733 Py_XDECREF(offset2);
3734 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003735}
3736
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003737static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003738time_hash(PyDateTime_Time *self)
3739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003741 PyObject *offset;
Tim Peters37f39822003-01-10 03:49:02 +00003742
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003743 offset = time_utcoffset((PyObject *)self, NULL);
3744
3745 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003749 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 self->hashcode = generic_hash(
3751 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003753 PyObject *temp1, *temp2;
3754 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003756 seconds = TIME_GET_HOUR(self) * 3600 +
3757 TIME_GET_MINUTE(self) * 60 +
3758 TIME_GET_SECOND(self);
3759 microseconds = TIME_GET_MICROSECOND(self);
3760 temp1 = new_delta(0, seconds, microseconds, 1);
3761 if (temp1 == NULL) {
3762 Py_DECREF(offset);
3763 return -1;
3764 }
3765 temp2 = delta_subtract(temp1, offset);
3766 Py_DECREF(temp1);
3767 if (temp2 == NULL) {
3768 Py_DECREF(offset);
3769 return -1;
3770 }
3771 self->hashcode = PyObject_Hash(temp2);
3772 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003774 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 }
3776 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003777}
Tim Peters2a799bf2002-12-16 20:18:38 +00003778
Tim Peters12bf3392002-12-24 05:41:27 +00003779static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003780time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 PyObject *clone;
3783 PyObject *tuple;
3784 int hh = TIME_GET_HOUR(self);
3785 int mm = TIME_GET_MINUTE(self);
3786 int ss = TIME_GET_SECOND(self);
3787 int us = TIME_GET_MICROSECOND(self);
3788 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3791 time_kws,
3792 &hh, &mm, &ss, &us, &tzinfo))
3793 return NULL;
3794 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3795 if (tuple == NULL)
3796 return NULL;
3797 clone = time_new(Py_TYPE(self), tuple, NULL);
3798 Py_DECREF(tuple);
3799 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003800}
3801
Tim Peters2a799bf2002-12-16 20:18:38 +00003802static int
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003803time_bool(PyObject *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003804{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003805 PyObject *offset, *tzinfo;
3806 int offsecs = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3809 /* Since utcoffset is in whole minutes, nothing can
3810 * alter the conclusion that this is nonzero.
3811 */
3812 return 1;
3813 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003814 tzinfo = GET_TIME_TZINFO(self);
3815 if (tzinfo != Py_None) {
3816 offset = call_utcoffset(tzinfo, Py_None);
3817 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003819 offsecs = GET_TD_DAYS(offset)*86400 + GET_TD_SECONDS(offset);
3820 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003822 return (TIME_GET_MINUTE(self)*60 - offsecs + TIME_GET_HOUR(self)*3600) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003823}
3824
Tim Peters371935f2003-02-01 01:52:50 +00003825/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003826
Tim Peters33e0f382003-01-10 02:05:14 +00003827/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003828 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3829 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003830 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003831 */
3832static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003833time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 PyObject *basestate;
3836 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 basestate = PyBytes_FromStringAndSize((char *)self->data,
3839 _PyDateTime_TIME_DATASIZE);
3840 if (basestate != NULL) {
3841 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3842 result = PyTuple_Pack(1, basestate);
3843 else
3844 result = PyTuple_Pack(2, basestate, self->tzinfo);
3845 Py_DECREF(basestate);
3846 }
3847 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003848}
3849
3850static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003851time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003854}
3855
Tim Peters37f39822003-01-10 03:49:02 +00003856static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3859 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3860 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3863 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3866 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3869 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3872 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3875 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3878 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3881 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003884};
3885
Tim Peters37f39822003-01-10 03:49:02 +00003886static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003887PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3888\n\
3889All arguments are optional. tzinfo may be None, or an instance of\n\
3890a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003891
Tim Peters37f39822003-01-10 03:49:02 +00003892static PyNumberMethods time_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 0, /* nb_add */
3894 0, /* nb_subtract */
3895 0, /* nb_multiply */
3896 0, /* nb_remainder */
3897 0, /* nb_divmod */
3898 0, /* nb_power */
3899 0, /* nb_negative */
3900 0, /* nb_positive */
3901 0, /* nb_absolute */
3902 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003903};
3904
Neal Norwitz227b5332006-03-22 09:28:35 +00003905static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 PyVarObject_HEAD_INIT(NULL, 0)
3907 "datetime.time", /* tp_name */
3908 sizeof(PyDateTime_Time), /* tp_basicsize */
3909 0, /* tp_itemsize */
3910 (destructor)time_dealloc, /* tp_dealloc */
3911 0, /* tp_print */
3912 0, /* tp_getattr */
3913 0, /* tp_setattr */
3914 0, /* tp_reserved */
3915 (reprfunc)time_repr, /* tp_repr */
3916 &time_as_number, /* tp_as_number */
3917 0, /* tp_as_sequence */
3918 0, /* tp_as_mapping */
3919 (hashfunc)time_hash, /* tp_hash */
3920 0, /* tp_call */
3921 (reprfunc)time_str, /* tp_str */
3922 PyObject_GenericGetAttr, /* tp_getattro */
3923 0, /* tp_setattro */
3924 0, /* tp_as_buffer */
3925 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3926 time_doc, /* tp_doc */
3927 0, /* tp_traverse */
3928 0, /* tp_clear */
3929 time_richcompare, /* tp_richcompare */
3930 0, /* tp_weaklistoffset */
3931 0, /* tp_iter */
3932 0, /* tp_iternext */
3933 time_methods, /* tp_methods */
3934 0, /* tp_members */
3935 time_getset, /* tp_getset */
3936 0, /* tp_base */
3937 0, /* tp_dict */
3938 0, /* tp_descr_get */
3939 0, /* tp_descr_set */
3940 0, /* tp_dictoffset */
3941 0, /* tp_init */
3942 time_alloc, /* tp_alloc */
3943 time_new, /* tp_new */
3944 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003945};
3946
3947/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003948 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003949 */
3950
Tim Petersa9bc1682003-01-11 03:39:11 +00003951/* Accessor properties. Properties for day, month, and year are inherited
3952 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003953 */
3954
3955static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003956datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003959}
3960
Tim Petersa9bc1682003-01-11 03:39:11 +00003961static PyObject *
3962datetime_minute(PyDateTime_DateTime *self, void *unused)
3963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003965}
3966
3967static PyObject *
3968datetime_second(PyDateTime_DateTime *self, void *unused)
3969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003971}
3972
3973static PyObject *
3974datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003977}
3978
3979static PyObject *
3980datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3983 Py_INCREF(result);
3984 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003985}
3986
3987static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 {"hour", (getter)datetime_hour},
3989 {"minute", (getter)datetime_minute},
3990 {"second", (getter)datetime_second},
3991 {"microsecond", (getter)datetime_microsecond},
3992 {"tzinfo", (getter)datetime_tzinfo},
3993 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003994};
3995
3996/*
3997 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003998 */
3999
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004000static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 "year", "month", "day", "hour", "minute", "second",
4002 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004003};
4004
Tim Peters2a799bf2002-12-16 20:18:38 +00004005static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004006datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 PyObject *self = NULL;
4009 PyObject *state;
4010 int year;
4011 int month;
4012 int day;
4013 int hour = 0;
4014 int minute = 0;
4015 int second = 0;
4016 int usecond = 0;
4017 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 /* Check for invocation from pickle with __getstate__ state */
4020 if (PyTuple_GET_SIZE(args) >= 1 &&
4021 PyTuple_GET_SIZE(args) <= 2 &&
4022 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4023 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
4024 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
4025 {
4026 PyDateTime_DateTime *me;
4027 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 if (PyTuple_GET_SIZE(args) == 2) {
4030 tzinfo = PyTuple_GET_ITEM(args, 1);
4031 if (check_tzinfo_subclass(tzinfo) < 0) {
4032 PyErr_SetString(PyExc_TypeError, "bad "
4033 "tzinfo state arg");
4034 return NULL;
4035 }
4036 }
4037 aware = (char)(tzinfo != Py_None);
4038 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4039 if (me != NULL) {
4040 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4043 me->hashcode = -1;
4044 me->hastzinfo = aware;
4045 if (aware) {
4046 Py_INCREF(tzinfo);
4047 me->tzinfo = tzinfo;
4048 }
4049 }
4050 return (PyObject *)me;
4051 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
4054 &year, &month, &day, &hour, &minute,
4055 &second, &usecond, &tzinfo)) {
4056 if (check_date_args(year, month, day) < 0)
4057 return NULL;
4058 if (check_time_args(hour, minute, second, usecond) < 0)
4059 return NULL;
4060 if (check_tzinfo_subclass(tzinfo) < 0)
4061 return NULL;
4062 self = new_datetime_ex(year, month, day,
4063 hour, minute, second, usecond,
4064 tzinfo, type);
4065 }
4066 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004067}
4068
Tim Petersa9bc1682003-01-11 03:39:11 +00004069/* TM_FUNC is the shared type of localtime() and gmtime(). */
4070typedef struct tm *(*TM_FUNC)(const time_t *timer);
4071
4072/* Internal helper.
4073 * Build datetime from a time_t and a distinct count of microseconds.
4074 * Pass localtime or gmtime for f, to control the interpretation of timet.
4075 */
4076static PyObject *
4077datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 struct tm *tm;
Tim Petersa9bc1682003-01-11 03:39:11 +00004081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 tm = f(&timet);
Victor Stinner21f58932012-03-14 00:15:40 +01004083 if (tm == NULL) {
4084#ifdef EINVAL
4085 if (errno == 0)
4086 errno = EINVAL;
4087#endif
4088 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 }
Victor Stinner21f58932012-03-14 00:15:40 +01004090
4091 /* The platform localtime/gmtime may insert leap seconds,
4092 * indicated by tm->tm_sec > 59. We don't care about them,
4093 * except to the extent that passing them on to the datetime
4094 * constructor would raise ValueError for a reason that
4095 * made no sense to the user.
4096 */
4097 if (tm->tm_sec > 59)
4098 tm->tm_sec = 59;
4099 return PyObject_CallFunction(cls, "iiiiiiiO",
4100 tm->tm_year + 1900,
4101 tm->tm_mon + 1,
4102 tm->tm_mday,
4103 tm->tm_hour,
4104 tm->tm_min,
4105 tm->tm_sec,
4106 us,
4107 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004108}
4109
4110/* Internal helper.
4111 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4112 * to control the interpretation of the timestamp. Since a double doesn't
4113 * have enough bits to cover a datetime's full range of precision, it's
4114 * better to call datetime_from_timet_and_us provided you have a way
4115 * to get that much precision (e.g., C time() isn't good enough).
4116 */
4117static PyObject *
Victor Stinner5d272cc2012-03-13 13:35:55 +01004118datetime_from_timestamp(PyObject *cls, TM_FUNC f, PyObject *timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004121 time_t timet;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004122 long us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004123
Victor Stinner5d272cc2012-03-13 13:35:55 +01004124 if (_PyTime_ObjectToTimeval(timestamp, &timet, &us) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 return NULL;
Victor Stinner21f58932012-03-14 00:15:40 +01004126 return datetime_from_timet_and_us(cls, f, timet, (int)us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004127}
4128
4129/* Internal helper.
4130 * Build most accurate possible datetime for current time. Pass localtime or
4131 * gmtime for f as appropriate.
4132 */
4133static PyObject *
4134datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4135{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00004136 _PyTime_timeval t;
4137 _PyTime_gettimeofday(&t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
4139 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004140}
4141
Tim Peters2a799bf2002-12-16 20:18:38 +00004142/* Return best possible local time -- this isn't constrained by the
4143 * precision of a timestamp.
4144 */
4145static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004146datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 PyObject *self;
4149 PyObject *tzinfo = Py_None;
4150 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
4153 &tzinfo))
4154 return NULL;
4155 if (check_tzinfo_subclass(tzinfo) < 0)
4156 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 self = datetime_best_possible(cls,
4159 tzinfo == Py_None ? localtime : gmtime,
4160 tzinfo);
4161 if (self != NULL && tzinfo != Py_None) {
4162 /* Convert UTC to tzinfo's zone. */
4163 PyObject *temp = self;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004164 _Py_IDENTIFIER(fromutc);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004165
4166 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 Py_DECREF(temp);
4168 }
4169 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004170}
4171
Tim Petersa9bc1682003-01-11 03:39:11 +00004172/* Return best possible UTC time -- this isn't constrained by the
4173 * precision of a timestamp.
4174 */
4175static PyObject *
4176datetime_utcnow(PyObject *cls, PyObject *dummy)
4177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004179}
4180
Tim Peters2a799bf2002-12-16 20:18:38 +00004181/* Return new local datetime from timestamp (Python timestamp -- a double). */
4182static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004183datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 PyObject *self;
Victor Stinner5d272cc2012-03-13 13:35:55 +01004186 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 PyObject *tzinfo = Py_None;
4188 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004189
Victor Stinner5d272cc2012-03-13 13:35:55 +01004190 if (! PyArg_ParseTupleAndKeywords(args, kw, "O|O:fromtimestamp",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 keywords, &timestamp, &tzinfo))
4192 return NULL;
4193 if (check_tzinfo_subclass(tzinfo) < 0)
4194 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004196 self = datetime_from_timestamp(cls,
4197 tzinfo == Py_None ? localtime : gmtime,
4198 timestamp,
4199 tzinfo);
4200 if (self != NULL && tzinfo != Py_None) {
4201 /* Convert UTC to tzinfo's zone. */
4202 PyObject *temp = self;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004203 _Py_IDENTIFIER(fromutc);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004204
4205 self = _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 Py_DECREF(temp);
4207 }
4208 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004209}
4210
Tim Petersa9bc1682003-01-11 03:39:11 +00004211/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4212static PyObject *
4213datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4214{
Victor Stinner5d272cc2012-03-13 13:35:55 +01004215 PyObject *timestamp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004217
Victor Stinner5d272cc2012-03-13 13:35:55 +01004218 if (PyArg_ParseTuple(args, "O:utcfromtimestamp", &timestamp))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 result = datetime_from_timestamp(cls, gmtime, timestamp,
4220 Py_None);
4221 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004222}
4223
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004224/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004225static PyObject *
4226datetime_strptime(PyObject *cls, PyObject *args)
4227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 static PyObject *module = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004229 PyObject *string, *format;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004230 _Py_IDENTIFIER(_strptime_datetime);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004232 if (!PyArg_ParseTuple(args, "UU:strptime", &string, &format))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004233 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004234
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004235 if (module == NULL) {
4236 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004237 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004238 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004240 return _PyObject_CallMethodId(module, &PyId__strptime_datetime, "OOO",
4241 cls, string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004242}
4243
Tim Petersa9bc1682003-01-11 03:39:11 +00004244/* Return new datetime from date/datetime and time arguments. */
4245static PyObject *
4246datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 static char *keywords[] = {"date", "time", NULL};
4249 PyObject *date;
4250 PyObject *time;
4251 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4254 &PyDateTime_DateType, &date,
4255 &PyDateTime_TimeType, &time)) {
4256 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 if (HASTZINFO(time))
4259 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4260 result = PyObject_CallFunction(cls, "iiiiiiiO",
4261 GET_YEAR(date),
4262 GET_MONTH(date),
4263 GET_DAY(date),
4264 TIME_GET_HOUR(time),
4265 TIME_GET_MINUTE(time),
4266 TIME_GET_SECOND(time),
4267 TIME_GET_MICROSECOND(time),
4268 tzinfo);
4269 }
4270 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004271}
Tim Peters2a799bf2002-12-16 20:18:38 +00004272
4273/*
4274 * Destructor.
4275 */
4276
4277static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004278datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 if (HASTZINFO(self)) {
4281 Py_XDECREF(self->tzinfo);
4282 }
4283 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004284}
4285
4286/*
4287 * Indirect access to tzinfo methods.
4288 */
4289
Tim Peters2a799bf2002-12-16 20:18:38 +00004290/* These are all METH_NOARGS, so don't need to check the arglist. */
4291static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004292datetime_utcoffset(PyObject *self, PyObject *unused) {
4293 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004294}
4295
4296static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004297datetime_dst(PyObject *self, PyObject *unused) {
4298 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004299}
4300
4301static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004302datetime_tzname(PyObject *self, PyObject *unused) {
4303 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004304}
4305
4306/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004307 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004308 */
4309
Tim Petersa9bc1682003-01-11 03:39:11 +00004310/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4311 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004312 */
4313static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004314add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 /* Note that the C-level additions can't overflow, because of
4318 * invariant bounds on the member values.
4319 */
4320 int year = GET_YEAR(date);
4321 int month = GET_MONTH(date);
4322 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4323 int hour = DATE_GET_HOUR(date);
4324 int minute = DATE_GET_MINUTE(date);
4325 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4326 int microsecond = DATE_GET_MICROSECOND(date) +
4327 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 assert(factor == 1 || factor == -1);
4330 if (normalize_datetime(&year, &month, &day,
4331 &hour, &minute, &second, &microsecond) < 0)
4332 return NULL;
4333 else
4334 return new_datetime(year, month, day,
4335 hour, minute, second, microsecond,
4336 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004337}
4338
4339static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004340datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 if (PyDateTime_Check(left)) {
4343 /* datetime + ??? */
4344 if (PyDelta_Check(right))
4345 /* datetime + delta */
4346 return add_datetime_timedelta(
4347 (PyDateTime_DateTime *)left,
4348 (PyDateTime_Delta *)right,
4349 1);
4350 }
4351 else if (PyDelta_Check(left)) {
4352 /* delta + datetime */
4353 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4354 (PyDateTime_Delta *) left,
4355 1);
4356 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004357 Py_RETURN_NOTIMPLEMENTED;
Tim Peters2a799bf2002-12-16 20:18:38 +00004358}
4359
4360static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004361datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 if (PyDateTime_Check(left)) {
4366 /* datetime - ??? */
4367 if (PyDateTime_Check(right)) {
4368 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004369 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004371
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004372 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4373 offset2 = offset1 = Py_None;
4374 Py_INCREF(offset1);
4375 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004377 else {
4378 offset1 = datetime_utcoffset(left, NULL);
4379 if (offset1 == NULL)
4380 return NULL;
4381 offset2 = datetime_utcoffset(right, NULL);
4382 if (offset2 == NULL) {
4383 Py_DECREF(offset1);
4384 return NULL;
4385 }
4386 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4387 PyErr_SetString(PyExc_TypeError,
4388 "can't subtract offset-naive and "
4389 "offset-aware datetimes");
4390 Py_DECREF(offset1);
4391 Py_DECREF(offset2);
4392 return NULL;
4393 }
4394 }
4395 if ((offset1 != offset2) &&
4396 delta_cmp(offset1, offset2) != 0) {
4397 offdiff = delta_subtract(offset1, offset2);
4398 if (offdiff == NULL) {
4399 Py_DECREF(offset1);
4400 Py_DECREF(offset2);
4401 return NULL;
4402 }
4403 }
4404 Py_DECREF(offset1);
4405 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 delta_d = ymd_to_ord(GET_YEAR(left),
4407 GET_MONTH(left),
4408 GET_DAY(left)) -
4409 ymd_to_ord(GET_YEAR(right),
4410 GET_MONTH(right),
4411 GET_DAY(right));
4412 /* These can't overflow, since the values are
4413 * normalized. At most this gives the number of
4414 * seconds in one day.
4415 */
4416 delta_s = (DATE_GET_HOUR(left) -
4417 DATE_GET_HOUR(right)) * 3600 +
4418 (DATE_GET_MINUTE(left) -
4419 DATE_GET_MINUTE(right)) * 60 +
4420 (DATE_GET_SECOND(left) -
4421 DATE_GET_SECOND(right));
4422 delta_us = DATE_GET_MICROSECOND(left) -
4423 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 result = new_delta(delta_d, delta_s, delta_us, 1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004425 if (offdiff != NULL) {
4426 PyObject *temp = result;
4427 result = delta_subtract(result, offdiff);
4428 Py_DECREF(temp);
4429 Py_DECREF(offdiff);
4430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 }
4432 else if (PyDelta_Check(right)) {
4433 /* datetime - delta */
4434 result = add_datetime_timedelta(
4435 (PyDateTime_DateTime *)left,
4436 (PyDateTime_Delta *)right,
4437 -1);
4438 }
4439 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 if (result == Py_NotImplemented)
4442 Py_INCREF(result);
4443 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004444}
4445
4446/* Various ways to turn a datetime into a string. */
4447
4448static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004449datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 const char *type_name = Py_TYPE(self)->tp_name;
4452 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 if (DATE_GET_MICROSECOND(self)) {
4455 baserepr = PyUnicode_FromFormat(
4456 "%s(%d, %d, %d, %d, %d, %d, %d)",
4457 type_name,
4458 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4459 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4460 DATE_GET_SECOND(self),
4461 DATE_GET_MICROSECOND(self));
4462 }
4463 else if (DATE_GET_SECOND(self)) {
4464 baserepr = PyUnicode_FromFormat(
4465 "%s(%d, %d, %d, %d, %d, %d)",
4466 type_name,
4467 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4468 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4469 DATE_GET_SECOND(self));
4470 }
4471 else {
4472 baserepr = PyUnicode_FromFormat(
4473 "%s(%d, %d, %d, %d, %d)",
4474 type_name,
4475 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4476 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4477 }
4478 if (baserepr == NULL || ! HASTZINFO(self))
4479 return baserepr;
4480 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004481}
4482
Tim Petersa9bc1682003-01-11 03:39:11 +00004483static PyObject *
4484datetime_str(PyDateTime_DateTime *self)
4485{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004486 _Py_IDENTIFIER(isoformat);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02004487
4488 return _PyObject_CallMethodId((PyObject *)self, &PyId_isoformat, "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004489}
Tim Peters2a799bf2002-12-16 20:18:38 +00004490
4491static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004492datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 int sep = 'T';
4495 static char *keywords[] = {"sep", NULL};
4496 char buffer[100];
4497 PyObject *result;
4498 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4501 return NULL;
4502 if (us)
4503 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4504 GET_YEAR(self), GET_MONTH(self),
4505 GET_DAY(self), (int)sep,
4506 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4507 DATE_GET_SECOND(self), us);
4508 else
4509 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4510 GET_YEAR(self), GET_MONTH(self),
4511 GET_DAY(self), (int)sep,
4512 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4513 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 if (!result || !HASTZINFO(self))
4516 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 /* We need to append the UTC offset. */
4519 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4520 (PyObject *)self) < 0) {
4521 Py_DECREF(result);
4522 return NULL;
4523 }
4524 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4525 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004526}
4527
Tim Petersa9bc1682003-01-11 03:39:11 +00004528static PyObject *
4529datetime_ctime(PyDateTime_DateTime *self)
4530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 return format_ctime((PyDateTime_Date *)self,
4532 DATE_GET_HOUR(self),
4533 DATE_GET_MINUTE(self),
4534 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004535}
4536
Tim Peters2a799bf2002-12-16 20:18:38 +00004537/* Miscellaneous methods. */
4538
Tim Petersa9bc1682003-01-11 03:39:11 +00004539static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004540datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004541{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004542 PyObject *result = NULL;
4543 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 if (! PyDateTime_Check(other)) {
4547 if (PyDate_Check(other)) {
4548 /* Prevent invocation of date_richcompare. We want to
4549 return NotImplemented here to give the other object
4550 a chance. But since DateTime is a subclass of
4551 Date, if the other object is a Date, it would
4552 compute an ordering based on the date part alone,
4553 and we don't want that. So force unequal or
4554 uncomparable here in that case. */
4555 if (op == Py_EQ)
4556 Py_RETURN_FALSE;
4557 if (op == Py_NE)
4558 Py_RETURN_TRUE;
4559 return cmperror(self, other);
4560 }
Brian Curtindfc80e32011-08-10 20:28:54 -05004561 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004563
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004564 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004565 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4566 ((PyDateTime_DateTime *)other)->data,
4567 _PyDateTime_DATETIME_DATASIZE);
4568 return diff_to_bool(diff, op);
4569 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004570 offset1 = datetime_utcoffset(self, NULL);
4571 if (offset1 == NULL)
4572 return NULL;
4573 offset2 = datetime_utcoffset(other, NULL);
4574 if (offset2 == NULL)
4575 goto done;
4576 /* If they're both naive, or both aware and have the same offsets,
4577 * we get off cheap. Note that if they're both naive, offset1 ==
4578 * offset2 == Py_None at this point.
4579 */
4580 if ((offset1 == offset2) ||
4581 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4582 delta_cmp(offset1, offset2) == 0)) {
4583 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4584 ((PyDateTime_DateTime *)other)->data,
4585 _PyDateTime_DATETIME_DATASIZE);
4586 result = diff_to_bool(diff, op);
4587 }
4588 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004590
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004591 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4593 other);
4594 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004595 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 diff = GET_TD_DAYS(delta);
4597 if (diff == 0)
4598 diff = GET_TD_SECONDS(delta) |
4599 GET_TD_MICROSECONDS(delta);
4600 Py_DECREF(delta);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004601 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 }
Alexander Belopolsky08313822012-06-15 20:19:47 -04004603 else if (op == Py_EQ) {
4604 result = Py_False;
4605 Py_INCREF(result);
4606 }
4607 else if (op == Py_NE) {
4608 result = Py_True;
4609 Py_INCREF(result);
4610 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004611 else {
4612 PyErr_SetString(PyExc_TypeError,
4613 "can't compare offset-naive and "
4614 "offset-aware datetimes");
4615 }
4616 done:
4617 Py_DECREF(offset1);
4618 Py_XDECREF(offset2);
4619 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004620}
4621
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004622static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004623datetime_hash(PyDateTime_DateTime *self)
4624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004626 PyObject *offset;
Tim Petersa9bc1682003-01-11 03:39:11 +00004627
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004628 offset = datetime_utcoffset((PyObject *)self, NULL);
4629
4630 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004634 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 self->hashcode = generic_hash(
4636 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004638 PyObject *temp1, *temp2;
4639 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 assert(HASTZINFO(self));
4642 days = ymd_to_ord(GET_YEAR(self),
4643 GET_MONTH(self),
4644 GET_DAY(self));
4645 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004646 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004648 temp1 = new_delta(days, seconds,
4649 DATE_GET_MICROSECOND(self),
4650 1);
4651 if (temp1 == NULL) {
4652 Py_DECREF(offset);
4653 return -1;
4654 }
4655 temp2 = delta_subtract(temp1, offset);
4656 Py_DECREF(temp1);
4657 if (temp2 == NULL) {
4658 Py_DECREF(offset);
4659 return -1;
4660 }
4661 self->hashcode = PyObject_Hash(temp2);
4662 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004664 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 }
4666 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004667}
Tim Peters2a799bf2002-12-16 20:18:38 +00004668
4669static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004670datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 PyObject *clone;
4673 PyObject *tuple;
4674 int y = GET_YEAR(self);
4675 int m = GET_MONTH(self);
4676 int d = GET_DAY(self);
4677 int hh = DATE_GET_HOUR(self);
4678 int mm = DATE_GET_MINUTE(self);
4679 int ss = DATE_GET_SECOND(self);
4680 int us = DATE_GET_MICROSECOND(self);
4681 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4684 datetime_kws,
4685 &y, &m, &d, &hh, &mm, &ss, &us,
4686 &tzinfo))
4687 return NULL;
4688 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4689 if (tuple == NULL)
4690 return NULL;
4691 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4692 Py_DECREF(tuple);
4693 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004694}
4695
4696static PyObject *
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004697local_timezone(PyDateTime_DateTime *utc_time)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004698{
4699 PyObject *result = NULL;
4700 struct tm *timep;
4701 time_t timestamp;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004702 PyObject *delta;
4703 PyObject *one_second;
4704 PyObject *seconds;
4705 PyObject *nameo = NULL;
4706 const char *zone = NULL;
4707
4708 delta = datetime_subtract((PyObject *)utc_time, PyDateTime_Epoch);
4709 if (delta == NULL)
4710 return NULL;
4711 one_second = new_delta(0, 1, 0, 0);
4712 if (one_second == NULL)
4713 goto error;
4714 seconds = divide_timedelta_timedelta((PyDateTime_Delta *)delta,
4715 (PyDateTime_Delta *)one_second);
4716 Py_DECREF(one_second);
4717 if (seconds == NULL)
4718 goto error;
4719 Py_DECREF(delta);
4720 timestamp = PyLong_AsLong(seconds);
4721 Py_DECREF(seconds);
4722 if (timestamp == -1 && PyErr_Occurred())
4723 return NULL;
4724 timep = localtime(&timestamp);
4725#ifdef HAVE_STRUCT_TM_TM_ZONE
Alexander Belopolsky93c9cd02012-06-22 16:04:19 -04004726 zone = timep->tm_zone;
4727 delta = new_delta(0, timep->tm_gmtoff, 0, 1);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004728#else /* HAVE_STRUCT_TM_TM_ZONE */
4729 {
4730 PyObject *local_time;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004731 local_time = new_datetime(timep->tm_year + 1900, timep->tm_mon + 1,
4732 timep->tm_mday, timep->tm_hour, timep->tm_min,
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004733 timep->tm_sec, DATE_GET_MICROSECOND(utc_time),
4734 utc_time->tzinfo);
4735 if (local_time == NULL)
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004736 goto error;
Alexander Belopolsky93c9cd02012-06-22 16:04:19 -04004737 delta = datetime_subtract(local_time, (PyObject*)utc_time);
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004738 /* XXX: before relying on tzname, we should compare delta
4739 to the offset implied by timezone/altzone */
4740 if (daylight && timep->tm_isdst >= 0)
4741 zone = tzname[timep->tm_isdst % 2];
4742 else
4743 zone = tzname[0];
4744 Py_DECREF(local_time);
4745 }
4746#endif /* HAVE_STRUCT_TM_TM_ZONE */
4747 if (zone != NULL) {
4748 nameo = PyUnicode_DecodeLocale(zone, "surrogateescape");
4749 if (nameo == NULL)
4750 goto error;
4751 }
4752 result = new_timezone(delta, nameo);
4753 Py_DECREF(nameo);
4754 error:
4755 Py_DECREF(delta);
4756 return result;
4757}
4758
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004759static PyDateTime_DateTime *
Tim Petersa9bc1682003-01-11 03:39:11 +00004760datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004761{
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004762 PyDateTime_DateTime *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004763 PyObject *offset;
4764 PyObject *temp;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004765 PyObject *tzinfo = Py_None;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02004766 _Py_IDENTIFIER(fromutc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004768
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004769 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:astimezone", keywords,
4770 &tzinfo))
4771 return NULL;
4772
4773 if (check_tzinfo_subclass(tzinfo) == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4777 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 /* Conversion to self's own time zone is a NOP. */
4780 if (self->tzinfo == tzinfo) {
4781 Py_INCREF(self);
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004782 return self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004783 }
Tim Peters521fc152002-12-31 17:36:56 +00004784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 /* Convert self to UTC. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004786 offset = datetime_utcoffset((PyObject *)self, NULL);
4787 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004789 if (offset == Py_None) {
4790 Py_DECREF(offset);
4791 NeedAware:
4792 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4793 "a naive datetime");
4794 return NULL;
4795 }
Tim Petersf3615152003-01-01 21:51:37 +00004796
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004797 /* result = self - offset */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004798 result = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4799 (PyDateTime_Delta *)offset, -1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004800 Py_DECREF(offset);
4801 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004805 temp = result->tzinfo;
Alexander Belopolskyfdc860f2012-06-22 12:23:23 -04004806 if (tzinfo == Py_None) {
4807 tzinfo = local_timezone(result);
4808 if (tzinfo == NULL) {
4809 Py_DECREF(result);
4810 return NULL;
4811 }
4812 }
4813 else
4814 Py_INCREF(tzinfo);
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004815 result->tzinfo = tzinfo;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004816 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00004817
Alexander Belopolsky31227ca2012-06-22 13:23:21 -04004818 temp = (PyObject *)result;
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004819 result = (PyDateTime_DateTime *)
4820 _PyObject_CallMethodId(tzinfo, &PyId_fromutc, "O", temp);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004821 Py_DECREF(temp);
4822
Alexander Belopolsky878054e2012-06-22 14:11:58 -04004823 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00004824}
4825
4826static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004827datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004832 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00004833
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004834 dst = call_dst(self->tzinfo, (PyObject *)self);
4835 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004837
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004838 if (dst != Py_None)
4839 dstflag = delta_bool((PyDateTime_Delta *)dst);
4840 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004841 }
4842 return build_struct_time(GET_YEAR(self),
4843 GET_MONTH(self),
4844 GET_DAY(self),
4845 DATE_GET_HOUR(self),
4846 DATE_GET_MINUTE(self),
4847 DATE_GET_SECOND(self),
4848 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004849}
4850
4851static PyObject *
Alexander Belopolskya4415142012-06-08 12:33:09 -04004852datetime_timestamp(PyDateTime_DateTime *self)
4853{
4854 PyObject *result;
4855
4856 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4857 PyObject *delta;
4858 delta = datetime_subtract((PyObject *)self, PyDateTime_Epoch);
4859 if (delta == NULL)
4860 return NULL;
4861 result = delta_total_seconds(delta);
4862 Py_DECREF(delta);
4863 }
4864 else {
4865 struct tm time;
4866 time_t timestamp;
4867 memset((void *) &time, '\0', sizeof(struct tm));
4868 time.tm_year = GET_YEAR(self) - 1900;
4869 time.tm_mon = GET_MONTH(self) - 1;
4870 time.tm_mday = GET_DAY(self);
4871 time.tm_hour = DATE_GET_HOUR(self);
4872 time.tm_min = DATE_GET_MINUTE(self);
4873 time.tm_sec = DATE_GET_SECOND(self);
4874 time.tm_wday = -1;
4875 time.tm_isdst = -1;
4876 timestamp = mktime(&time);
4877 /* Return value of -1 does not necessarily mean an error, but tm_wday
4878 * cannot remain set to -1 if mktime succeeded. */
4879 if (timestamp == (time_t)(-1) && time.tm_wday == -1) {
4880 PyErr_SetString(PyExc_OverflowError,
4881 "timestamp out of range");
4882 return NULL;
4883 }
4884 result = PyFloat_FromDouble(timestamp + DATE_GET_MICROSECOND(self) / 1e6);
4885 }
4886 return result;
4887}
4888
4889static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004890datetime_getdate(PyDateTime_DateTime *self)
4891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004892 return new_date(GET_YEAR(self),
4893 GET_MONTH(self),
4894 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004895}
4896
4897static PyObject *
4898datetime_gettime(PyDateTime_DateTime *self)
4899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900 return new_time(DATE_GET_HOUR(self),
4901 DATE_GET_MINUTE(self),
4902 DATE_GET_SECOND(self),
4903 DATE_GET_MICROSECOND(self),
4904 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004905}
4906
4907static PyObject *
4908datetime_gettimetz(PyDateTime_DateTime *self)
4909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004910 return new_time(DATE_GET_HOUR(self),
4911 DATE_GET_MINUTE(self),
4912 DATE_GET_SECOND(self),
4913 DATE_GET_MICROSECOND(self),
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004914 GET_DT_TZINFO(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004915}
4916
4917static PyObject *
4918datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004919{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004920 int y, m, d, hh, mm, ss;
4921 PyObject *tzinfo;
4922 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00004923
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004924 tzinfo = GET_DT_TZINFO(self);
4925 if (tzinfo == Py_None) {
4926 utcself = self;
4927 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004929 else {
4930 PyObject *offset;
4931 offset = call_utcoffset(tzinfo, (PyObject *)self);
4932 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00004933 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004934 if (offset == Py_None) {
4935 Py_DECREF(offset);
4936 utcself = self;
4937 Py_INCREF(utcself);
4938 }
4939 else {
4940 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4941 (PyDateTime_Delta *)offset, -1);
4942 Py_DECREF(offset);
4943 if (utcself == NULL)
4944 return NULL;
4945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004947 y = GET_YEAR(utcself);
4948 m = GET_MONTH(utcself);
4949 d = GET_DAY(utcself);
4950 hh = DATE_GET_HOUR(utcself);
4951 mm = DATE_GET_MINUTE(utcself);
4952 ss = DATE_GET_SECOND(utcself);
4953
4954 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004956}
4957
Tim Peters371935f2003-02-01 01:52:50 +00004958/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004959
Tim Petersa9bc1682003-01-11 03:39:11 +00004960/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004961 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4962 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004963 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004964 */
4965static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004966datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004968 PyObject *basestate;
4969 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 basestate = PyBytes_FromStringAndSize((char *)self->data,
4972 _PyDateTime_DATETIME_DATASIZE);
4973 if (basestate != NULL) {
4974 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4975 result = PyTuple_Pack(1, basestate);
4976 else
4977 result = PyTuple_Pack(2, basestate, self->tzinfo);
4978 Py_DECREF(basestate);
4979 }
4980 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004981}
4982
4983static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004984datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004986 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004987}
4988
Tim Petersa9bc1682003-01-11 03:39:11 +00004989static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 {"now", (PyCFunction)datetime_now,
4994 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4995 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 {"utcnow", (PyCFunction)datetime_utcnow,
4998 METH_NOARGS | METH_CLASS,
4999 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
5002 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5003 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005005 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
5006 METH_VARARGS | METH_CLASS,
5007 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
5008 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 {"strptime", (PyCFunction)datetime_strptime,
5011 METH_VARARGS | METH_CLASS,
5012 PyDoc_STR("string, format -> new datetime parsed from a string "
5013 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00005014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 {"combine", (PyCFunction)datetime_combine,
5016 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
5017 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005019 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00005020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
5022 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
5025 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005027 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
5028 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
5031 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00005032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
5034 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005035
Alexander Belopolskya4415142012-06-08 12:33:09 -04005036 {"timestamp", (PyCFunction)datetime_timestamp, METH_NOARGS,
5037 PyDoc_STR("Return POSIX timestamp as float.")},
5038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
5040 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
5043 PyDoc_STR("[sep] -> string in ISO 8601 format, "
5044 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
5045 "sep is used to separate the year from the time, and "
5046 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
5049 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005051 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
5052 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
5055 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00005056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
5058 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00005059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
5061 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00005062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
5064 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00005065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005067};
5068
Tim Petersa9bc1682003-01-11 03:39:11 +00005069static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00005070PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
5071\n\
5072The year, month and day arguments are required. tzinfo may be None, or an\n\
5073instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00005074
Tim Petersa9bc1682003-01-11 03:39:11 +00005075static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 datetime_add, /* nb_add */
5077 datetime_subtract, /* nb_subtract */
5078 0, /* nb_multiply */
5079 0, /* nb_remainder */
5080 0, /* nb_divmod */
5081 0, /* nb_power */
5082 0, /* nb_negative */
5083 0, /* nb_positive */
5084 0, /* nb_absolute */
5085 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00005086};
5087
Neal Norwitz227b5332006-03-22 09:28:35 +00005088static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 PyVarObject_HEAD_INIT(NULL, 0)
5090 "datetime.datetime", /* tp_name */
5091 sizeof(PyDateTime_DateTime), /* tp_basicsize */
5092 0, /* tp_itemsize */
5093 (destructor)datetime_dealloc, /* tp_dealloc */
5094 0, /* tp_print */
5095 0, /* tp_getattr */
5096 0, /* tp_setattr */
5097 0, /* tp_reserved */
5098 (reprfunc)datetime_repr, /* tp_repr */
5099 &datetime_as_number, /* tp_as_number */
5100 0, /* tp_as_sequence */
5101 0, /* tp_as_mapping */
5102 (hashfunc)datetime_hash, /* tp_hash */
5103 0, /* tp_call */
5104 (reprfunc)datetime_str, /* tp_str */
5105 PyObject_GenericGetAttr, /* tp_getattro */
5106 0, /* tp_setattro */
5107 0, /* tp_as_buffer */
5108 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5109 datetime_doc, /* tp_doc */
5110 0, /* tp_traverse */
5111 0, /* tp_clear */
5112 datetime_richcompare, /* tp_richcompare */
5113 0, /* tp_weaklistoffset */
5114 0, /* tp_iter */
5115 0, /* tp_iternext */
5116 datetime_methods, /* tp_methods */
5117 0, /* tp_members */
5118 datetime_getset, /* tp_getset */
5119 &PyDateTime_DateType, /* tp_base */
5120 0, /* tp_dict */
5121 0, /* tp_descr_get */
5122 0, /* tp_descr_set */
5123 0, /* tp_dictoffset */
5124 0, /* tp_init */
5125 datetime_alloc, /* tp_alloc */
5126 datetime_new, /* tp_new */
5127 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005128};
5129
5130/* ---------------------------------------------------------------------------
5131 * Module methods and initialization.
5132 */
5133
5134static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005136};
5137
Tim Peters9ddf40b2004-06-20 22:41:32 +00005138/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5139 * datetime.h.
5140 */
5141static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 &PyDateTime_DateType,
5143 &PyDateTime_DateTimeType,
5144 &PyDateTime_TimeType,
5145 &PyDateTime_DeltaType,
5146 &PyDateTime_TZInfoType,
5147 new_date_ex,
5148 new_datetime_ex,
5149 new_time_ex,
5150 new_delta_ex,
5151 datetime_fromtimestamp,
5152 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00005153};
5154
5155
Martin v. Löwis1a214512008-06-11 05:26:20 +00005156
5157static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005159 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 "Fast implementation of the datetime type.",
5161 -1,
5162 module_methods,
5163 NULL,
5164 NULL,
5165 NULL,
5166 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005167};
5168
Tim Peters2a799bf2002-12-16 20:18:38 +00005169PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005170PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005172 PyObject *m; /* a module object */
5173 PyObject *d; /* its dict */
5174 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005175 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005177 m = PyModule_Create(&datetimemodule);
5178 if (m == NULL)
5179 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005181 if (PyType_Ready(&PyDateTime_DateType) < 0)
5182 return NULL;
5183 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5184 return NULL;
5185 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5186 return NULL;
5187 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5188 return NULL;
5189 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5190 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005191 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5192 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 /* timedelta values */
5195 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005197 x = new_delta(0, 0, 1, 0);
5198 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5199 return NULL;
5200 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005202 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5203 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5204 return NULL;
5205 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5208 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5209 return NULL;
5210 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005212 /* date values */
5213 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005215 x = new_date(1, 1, 1);
5216 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5217 return NULL;
5218 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 x = new_date(MAXYEAR, 12, 31);
5221 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5222 return NULL;
5223 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005225 x = new_delta(1, 0, 0, 0);
5226 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5227 return NULL;
5228 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005230 /* time values */
5231 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005233 x = new_time(0, 0, 0, 0, Py_None);
5234 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5235 return NULL;
5236 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005238 x = new_time(23, 59, 59, 999999, Py_None);
5239 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5240 return NULL;
5241 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 x = new_delta(0, 0, 1, 0);
5244 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5245 return NULL;
5246 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005248 /* datetime values */
5249 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005251 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
5252 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5253 return NULL;
5254 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005256 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5257 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5258 return NULL;
5259 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005261 x = new_delta(0, 0, 1, 0);
5262 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5263 return NULL;
5264 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005265
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005266 /* timezone values */
5267 d = PyDateTime_TimeZoneType.tp_dict;
5268
5269 delta = new_delta(0, 0, 0, 0);
5270 if (delta == NULL)
5271 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005272 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005273 Py_DECREF(delta);
5274 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5275 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005276 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005277
5278 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5279 if (delta == NULL)
5280 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005281 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005282 Py_DECREF(delta);
5283 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5284 return NULL;
5285 Py_DECREF(x);
5286
5287 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5288 if (delta == NULL)
5289 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005290 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005291 Py_DECREF(delta);
5292 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5293 return NULL;
5294 Py_DECREF(x);
5295
Alexander Belopolskya4415142012-06-08 12:33:09 -04005296 /* Epoch */
5297 PyDateTime_Epoch = new_datetime(1970, 1, 1, 0, 0, 0, 0,
5298 PyDateTime_TimeZone_UTC);
5299 if (PyDateTime_Epoch == NULL)
5300 return NULL;
5301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005302 /* module initialization */
5303 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
5304 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005306 Py_INCREF(&PyDateTime_DateType);
5307 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005309 Py_INCREF(&PyDateTime_DateTimeType);
5310 PyModule_AddObject(m, "datetime",
5311 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005313 Py_INCREF(&PyDateTime_TimeType);
5314 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 Py_INCREF(&PyDateTime_DeltaType);
5317 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 Py_INCREF(&PyDateTime_TZInfoType);
5320 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005321
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005322 Py_INCREF(&PyDateTime_TimeZoneType);
5323 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5326 if (x == NULL)
5327 return NULL;
5328 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 /* A 4-year cycle has an extra leap day over what we'd get from
5331 * pasting together 4 single years.
5332 */
5333 assert(DI4Y == 4 * 365 + 1);
5334 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005336 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5337 * get from pasting together 4 100-year cycles.
5338 */
5339 assert(DI400Y == 4 * DI100Y + 1);
5340 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005342 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5343 * pasting together 25 4-year cycles.
5344 */
5345 assert(DI100Y == 25 * DI4Y - 1);
5346 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005348 us_per_us = PyLong_FromLong(1);
5349 us_per_ms = PyLong_FromLong(1000);
5350 us_per_second = PyLong_FromLong(1000000);
5351 us_per_minute = PyLong_FromLong(60000000);
5352 seconds_per_day = PyLong_FromLong(24 * 3600);
5353 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5354 us_per_minute == NULL || seconds_per_day == NULL)
5355 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 /* The rest are too big for 32-bit ints, but even
5358 * us_per_week fits in 40 bits, so doubles should be exact.
5359 */
5360 us_per_hour = PyLong_FromDouble(3600000000.0);
5361 us_per_day = PyLong_FromDouble(86400000000.0);
5362 us_per_week = PyLong_FromDouble(604800000000.0);
5363 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5364 return NULL;
5365 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005366}
Tim Petersf3615152003-01-01 21:51:37 +00005367
5368/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005369Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005370 x.n = x stripped of its timezone -- its naive time.
5371 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 return None
Tim Petersf3615152003-01-01 21:51:37 +00005373 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 return None
Tim Petersf3615152003-01-01 21:51:37 +00005375 x.s = x's standard offset, x.o - x.d
5376
5377Now some derived rules, where k is a duration (timedelta).
5378
53791. x.o = x.s + x.d
5380 This follows from the definition of x.s.
5381
Tim Petersc5dc4da2003-01-02 17:55:03 +000053822. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005383 This is actually a requirement, an assumption we need to make about
5384 sane tzinfo classes.
5385
53863. The naive UTC time corresponding to x is x.n - x.o.
5387 This is again a requirement for a sane tzinfo class.
5388
53894. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005390 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005391
Tim Petersc5dc4da2003-01-02 17:55:03 +000053925. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005393 Again follows from how arithmetic is defined.
5394
Tim Peters8bb5ad22003-01-24 02:44:45 +00005395Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005396(meaning that the various tzinfo methods exist, and don't blow up or return
5397None when called).
5398
Tim Petersa9bc1682003-01-11 03:39:11 +00005399The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005400x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005401
5402By #3, we want
5403
Tim Peters8bb5ad22003-01-24 02:44:45 +00005404 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005405
5406The algorithm starts by attaching tz to x.n, and calling that y. So
5407x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5408becomes true; in effect, we want to solve [2] for k:
5409
Tim Peters8bb5ad22003-01-24 02:44:45 +00005410 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005411
5412By #1, this is the same as
5413
Tim Peters8bb5ad22003-01-24 02:44:45 +00005414 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005415
5416By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5417Substituting that into [3],
5418
Tim Peters8bb5ad22003-01-24 02:44:45 +00005419 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5420 k - (y+k).s - (y+k).d = 0; rearranging,
5421 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5422 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005423
Tim Peters8bb5ad22003-01-24 02:44:45 +00005424On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5425approximate k by ignoring the (y+k).d term at first. Note that k can't be
5426very large, since all offset-returning methods return a duration of magnitude
5427less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5428be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005429
5430In any case, the new value is
5431
Tim Peters8bb5ad22003-01-24 02:44:45 +00005432 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005433
Tim Peters8bb5ad22003-01-24 02:44:45 +00005434It's helpful to step back at look at [4] from a higher level: it's simply
5435mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005436
5437At this point, if
5438
Tim Peters8bb5ad22003-01-24 02:44:45 +00005439 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005440
5441we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005442at the start of daylight time. Picture US Eastern for concreteness. The wall
5443time 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 +00005444sense then. The docs ask that an Eastern tzinfo class consider such a time to
5445be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5446on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005447the only spelling that makes sense on the local wall clock.
5448
Tim Petersc5dc4da2003-01-02 17:55:03 +00005449In fact, if [5] holds at this point, we do have the standard-time spelling,
5450but that takes a bit of proof. We first prove a stronger result. What's the
5451difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005452
Tim Peters8bb5ad22003-01-24 02:44:45 +00005453 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005454
Tim Petersc5dc4da2003-01-02 17:55:03 +00005455Now
5456 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005457 (y + y.s).n = by #5
5458 y.n + y.s = since y.n = x.n
5459 x.n + y.s = since z and y are have the same tzinfo member,
5460 y.s = z.s by #2
5461 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005462
Tim Petersc5dc4da2003-01-02 17:55:03 +00005463Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005464
Tim Petersc5dc4da2003-01-02 17:55:03 +00005465 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005466 x.n - ((x.n + z.s) - z.o) = expanding
5467 x.n - x.n - z.s + z.o = cancelling
5468 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005469 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005470
Tim Petersc5dc4da2003-01-02 17:55:03 +00005471So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005472
Tim Petersc5dc4da2003-01-02 17:55:03 +00005473If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005474spelling we wanted in the endcase described above. We're done. Contrarily,
5475if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005476
Tim Petersc5dc4da2003-01-02 17:55:03 +00005477If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5478add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005479local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005480
Tim Petersc5dc4da2003-01-02 17:55:03 +00005481Let
Tim Petersf3615152003-01-01 21:51:37 +00005482
Tim Peters4fede1a2003-01-04 00:26:59 +00005483 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005484
Tim Peters4fede1a2003-01-04 00:26:59 +00005485and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005486
Tim Peters8bb5ad22003-01-24 02:44:45 +00005487 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005488
Tim Peters8bb5ad22003-01-24 02:44:45 +00005489If so, we're done. If not, the tzinfo class is insane, according to the
5490assumptions we've made. This also requires a bit of proof. As before, let's
5491compute the difference between the LHS and RHS of [8] (and skipping some of
5492the justifications for the kinds of substitutions we've done several times
5493already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005494
Tim Peters8bb5ad22003-01-24 02:44:45 +00005495 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005496 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5497 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5498 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5499 - z.n + z.n - z.o + z'.o = cancel z.n
5500 - z.o + z'.o = #1 twice
5501 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5502 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005503
5504So 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 +00005505we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5506return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005507
Tim Peters8bb5ad22003-01-24 02:44:45 +00005508How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5509a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5510would have to change the result dst() returns: we start in DST, and moving
5511a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005512
Tim Peters8bb5ad22003-01-24 02:44:45 +00005513There isn't a sane case where this can happen. The closest it gets is at
5514the end of DST, where there's an hour in UTC with no spelling in a hybrid
5515tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5516that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5517UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5518time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5519clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5520standard time. Since that's what the local clock *does*, we want to map both
5521UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005522in local time, but so it goes -- it's the way the local clock works.
5523
Tim Peters8bb5ad22003-01-24 02:44:45 +00005524When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5525so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5526z' = 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 +00005527(correctly) concludes that z' is not UTC-equivalent to x.
5528
5529Because we know z.d said z was in daylight time (else [5] would have held and
5530we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005531and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005532return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5533but the reasoning doesn't depend on the example -- it depends on there being
5534two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005535z' must be in standard time, and is the spelling we want in this case.
5536
5537Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5538concerned (because it takes z' as being in standard time rather than the
5539daylight time we intend here), but returning it gives the real-life "local
5540clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5541tz.
5542
5543When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5544the 1:MM standard time spelling we want.
5545
5546So how can this break? One of the assumptions must be violated. Two
5547possibilities:
5548
55491) [2] effectively says that y.s is invariant across all y belong to a given
5550 time zone. This isn't true if, for political reasons or continental drift,
5551 a region decides to change its base offset from UTC.
5552
55532) There may be versions of "double daylight" time where the tail end of
5554 the analysis gives up a step too early. I haven't thought about that
5555 enough to say.
5556
5557In any case, it's clear that the default fromutc() is strong enough to handle
5558"almost all" time zones: so long as the standard offset is invariant, it
5559doesn't matter if daylight time transition points change from year to year, or
5560if daylight time is skipped in some years; it doesn't matter how large or
5561small dst() may get within its bounds; and it doesn't even matter if some
5562perverse time zone returns a negative dst()). So a breaking case must be
5563pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005564--------------------------------------------------------------------------- */