blob: d791cdeca897b1f6fb3aa492500e9c16b635cd4e [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"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +000011#include "_time.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
Alexander Belopolskycf86e362010-07-23 19:25:47 +000028# error "_datetime.c requires that C int have at least 32 bits"
Tim Peters2a799bf2002-12-16 20:18:38 +000029#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
Alexander Belopolskyf03a6162010-05-27 21:42:58 +000033#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
Tim Peters2a799bf2002-12-16 20:18:38 +000034
35/* Nine decimal digits is easy to communicate, and leaves enough room
36 * so that two delta days can be added w/o fear of overflowing a signed
37 * 32-bit int, and with plenty of room left over to absorb any possible
38 * carries from adding seconds.
39 */
40#define MAX_DELTA_DAYS 999999999
41
42/* Rename the long macros in datetime.h to more reasonable short names. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043#define GET_YEAR PyDateTime_GET_YEAR
44#define GET_MONTH PyDateTime_GET_MONTH
45#define GET_DAY PyDateTime_GET_DAY
46#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
47#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
48#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
49#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
Tim Peters2a799bf2002-12-16 20:18:38 +000050
51/* Date accessors for date and datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
53 ((o)->data[1] = ((v) & 0x00ff)))
54#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
55#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000056
57/* Date/Time accessors for datetime. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
59#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
60#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
61#define DATE_SET_MICROSECOND(o, v) \
62 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
63 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
64 ((o)->data[9] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000065
66/* Time accessors for time. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
68#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
69#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
70#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
71#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
72#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
73#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
74#define TIME_SET_MICROSECOND(o, v) \
75 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
76 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
77 ((o)->data[5] = ((v) & 0x0000ff)))
Tim Peters2a799bf2002-12-16 20:18:38 +000078
79/* Delta accessors for timedelta. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000080#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
81#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
82#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
Tim Peters2a799bf2002-12-16 20:18:38 +000083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084#define SET_TD_DAYS(o, v) ((o)->days = (v))
85#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
Tim Peters2a799bf2002-12-16 20:18:38 +000086#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
87
Tim Petersa032d2e2003-01-11 00:15:54 +000088/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
89 * p->hastzinfo.
90 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +000091#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
92#define GET_TIME_TZINFO(p) (HASTZINFO(p) ? \
93 ((PyDateTime_Time *)(p))->tzinfo : Py_None)
94#define GET_DT_TZINFO(p) (HASTZINFO(p) ? \
95 ((PyDateTime_DateTime *)(p))->tzinfo : Py_None)
Tim Peters3f606292004-03-21 23:38:41 +000096/* M is a char or int claiming to be a valid month. The macro is equivalent
97 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +000099 */
100#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
101
Tim Peters2a799bf2002-12-16 20:18:38 +0000102/* Forward declarations. */
103static PyTypeObject PyDateTime_DateType;
104static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000105static PyTypeObject PyDateTime_DeltaType;
106static PyTypeObject PyDateTime_TimeType;
107static PyTypeObject PyDateTime_TZInfoType;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000108static PyTypeObject PyDateTime_TimeZoneType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000109
110/* ---------------------------------------------------------------------------
111 * Math utilities.
112 */
113
114/* k = i+j overflows iff k differs in sign from both inputs,
115 * iff k^i has sign bit set and k^j has sign bit set,
116 * iff (k^i)&(k^j) has sign bit set.
117 */
118#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000120
121/* Compute Python divmod(x, y), returning the quotient and storing the
122 * remainder into *r. The quotient is the floor of x/y, and that's
123 * the real point of this. C will probably truncate instead (C99
124 * requires truncation; C89 left it implementation-defined).
125 * Simplification: we *require* that y > 0 here. That's appropriate
126 * for all the uses made of it. This simplifies the code and makes
127 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
128 * overflow case).
129 */
130static int
131divmod(int x, int y, int *r)
132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 assert(y > 0);
136 quo = x / y;
137 *r = x - quo * y;
138 if (*r < 0) {
139 --quo;
140 *r += y;
141 }
142 assert(0 <= *r && *r < y);
143 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000144}
145
Tim Peters5d644dd2003-01-02 16:32:54 +0000146/* Round a double to the nearest long. |x| must be small enough to fit
147 * in a C long; this is not checked.
148 */
149static long
150round_to_long(double x)
151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 if (x >= 0.0)
153 x = floor(x + 0.5);
154 else
155 x = ceil(x - 0.5);
156 return (long)x;
Tim Peters5d644dd2003-01-02 16:32:54 +0000157}
158
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000159/* Nearest integer to m / n for integers m and n. Half-integer results
160 * are rounded to even.
161 */
162static PyObject *
163divide_nearest(PyObject *m, PyObject *n)
164{
165 PyObject *result;
166 PyObject *temp;
167
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000168 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000169 if (temp == NULL)
170 return NULL;
171 result = PyTuple_GET_ITEM(temp, 0);
172 Py_INCREF(result);
173 Py_DECREF(temp);
174
175 return result;
176}
177
Tim Peters2a799bf2002-12-16 20:18:38 +0000178/* ---------------------------------------------------------------------------
179 * General calendrical helper functions
180 */
181
182/* For each month ordinal in 1..12, the number of days in that month,
183 * and the number of days before that month in the same year. These
184 * are correct for non-leap years only.
185 */
186static int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 0, /* unused; this vector uses 1-based indexing */
188 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000189};
190
191static int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 0, /* unused; this vector uses 1-based indexing */
193 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000194};
195
196/* year -> 1 if leap year, else 0. */
197static int
198is_leap(int year)
199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 /* Cast year to unsigned. The result is the same either way, but
201 * C can generate faster code for unsigned mod than for signed
202 * mod (especially for % 4 -- a good compiler should just grab
203 * the last 2 bits when the LHS is unsigned).
204 */
205 const unsigned int ayear = (unsigned int)year;
206 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000207}
208
209/* year, month -> number of days in that month in that year */
210static int
211days_in_month(int year, int month)
212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 assert(month >= 1);
214 assert(month <= 12);
215 if (month == 2 && is_leap(year))
216 return 29;
217 else
218 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000219}
220
221/* year, month -> number of days in year preceeding first day of month */
222static int
223days_before_month(int year, int month)
224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 assert(month >= 1);
228 assert(month <= 12);
229 days = _days_before_month[month];
230 if (month > 2 && is_leap(year))
231 ++days;
232 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000233}
234
235/* year -> number of days before January 1st of year. Remember that we
236 * start with year 1, so days_before_year(1) == 0.
237 */
238static int
239days_before_year(int year)
240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 int y = year - 1;
242 /* This is incorrect if year <= 0; we really want the floor
243 * here. But so long as MINYEAR is 1, the smallest year this
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000244 * can see is 1.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000246 assert (year >= 1);
247 return y*365 + y/4 - y/100 + y/400;
Tim Peters2a799bf2002-12-16 20:18:38 +0000248}
249
250/* Number of days in 4, 100, and 400 year cycles. That these have
251 * the correct values is asserted in the module init function.
252 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253#define DI4Y 1461 /* days_before_year(5); days in 4 years */
254#define DI100Y 36524 /* days_before_year(101); days in 100 years */
255#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000256
257/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
258static void
259ord_to_ymd(int ordinal, int *year, int *month, int *day)
260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
264 * leap years repeats exactly every 400 years. The basic strategy is
265 * to find the closest 400-year boundary at or before ordinal, then
266 * work with the offset from that boundary to ordinal. Life is much
267 * clearer if we subtract 1 from ordinal first -- then the values
268 * of ordinal at 400-year boundaries are exactly those divisible
269 * by DI400Y:
270 *
271 * D M Y n n-1
272 * -- --- ---- ---------- ----------------
273 * 31 Dec -400 -DI400Y -DI400Y -1
274 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
275 * ...
276 * 30 Dec 000 -1 -2
277 * 31 Dec 000 0 -1
278 * 1 Jan 001 1 0 400-year boundary
279 * 2 Jan 001 2 1
280 * 3 Jan 001 3 2
281 * ...
282 * 31 Dec 400 DI400Y DI400Y -1
283 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
284 */
285 assert(ordinal >= 1);
286 --ordinal;
287 n400 = ordinal / DI400Y;
288 n = ordinal % DI400Y;
289 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 /* Now n is the (non-negative) offset, in days, from January 1 of
292 * year, to the desired date. Now compute how many 100-year cycles
293 * precede n.
294 * Note that it's possible for n100 to equal 4! In that case 4 full
295 * 100-year cycles precede the desired day, which implies the
296 * desired day is December 31 at the end of a 400-year cycle.
297 */
298 n100 = n / DI100Y;
299 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 /* Now compute how many 4-year cycles precede it. */
302 n4 = n / DI4Y;
303 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 /* And now how many single years. Again n1 can be 4, and again
306 * meaning that the desired day is December 31 at the end of the
307 * 4-year cycle.
308 */
309 n1 = n / 365;
310 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 *year += n100 * 100 + n4 * 4 + n1;
313 if (n1 == 4 || n100 == 4) {
314 assert(n == 0);
315 *year -= 1;
316 *month = 12;
317 *day = 31;
318 return;
319 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 /* Now the year is correct, and n is the offset from January 1. We
322 * find the month via an estimate that's either exact or one too
323 * large.
324 */
325 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
326 assert(leapyear == is_leap(*year));
327 *month = (n + 50) >> 5;
328 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
329 if (preceding > n) {
330 /* estimate is too large */
331 *month -= 1;
332 preceding -= days_in_month(*year, *month);
333 }
334 n -= preceding;
335 assert(0 <= n);
336 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000339}
340
341/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
342static int
343ymd_to_ord(int year, int month, int day)
344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000346}
347
348/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
349static int
350weekday(int year, int month, int day)
351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000353}
354
355/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
356 * first calendar week containing a Thursday.
357 */
358static int
359iso_week1_monday(int year)
360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
362 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
363 int first_weekday = (first_day + 6) % 7;
364 /* ordinal of closest Monday at or before 1/1 */
365 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
368 week1_monday += 7;
369 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000370}
371
372/* ---------------------------------------------------------------------------
373 * Range checkers.
374 */
375
376/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
377 * If not, raise OverflowError and return -1.
378 */
379static int
380check_delta_day_range(int days)
381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
383 return 0;
384 PyErr_Format(PyExc_OverflowError,
385 "days=%d; must have magnitude <= %d",
386 days, MAX_DELTA_DAYS);
387 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000388}
389
390/* Check that date arguments are in range. Return 0 if they are. If they
391 * aren't, raise ValueError and return -1.
392 */
393static int
394check_date_args(int year, int month, int day)
395{
396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (year < MINYEAR || year > MAXYEAR) {
398 PyErr_SetString(PyExc_ValueError,
399 "year is out of range");
400 return -1;
401 }
402 if (month < 1 || month > 12) {
403 PyErr_SetString(PyExc_ValueError,
404 "month must be in 1..12");
405 return -1;
406 }
407 if (day < 1 || day > days_in_month(year, month)) {
408 PyErr_SetString(PyExc_ValueError,
409 "day is out of range for month");
410 return -1;
411 }
412 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000413}
414
415/* Check that time arguments are in range. Return 0 if they are. If they
416 * aren't, raise ValueError and return -1.
417 */
418static int
419check_time_args(int h, int m, int s, int us)
420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (h < 0 || h > 23) {
422 PyErr_SetString(PyExc_ValueError,
423 "hour must be in 0..23");
424 return -1;
425 }
426 if (m < 0 || m > 59) {
427 PyErr_SetString(PyExc_ValueError,
428 "minute must be in 0..59");
429 return -1;
430 }
431 if (s < 0 || s > 59) {
432 PyErr_SetString(PyExc_ValueError,
433 "second must be in 0..59");
434 return -1;
435 }
436 if (us < 0 || us > 999999) {
437 PyErr_SetString(PyExc_ValueError,
438 "microsecond must be in 0..999999");
439 return -1;
440 }
441 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000442}
443
444/* ---------------------------------------------------------------------------
445 * Normalization utilities.
446 */
447
448/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
449 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
450 * at least factor, enough of *lo is converted into "hi" units so that
451 * 0 <= *lo < factor. The input values must be such that int overflow
452 * is impossible.
453 */
454static void
455normalize_pair(int *hi, int *lo, int factor)
456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 assert(factor > 0);
458 assert(lo != hi);
459 if (*lo < 0 || *lo >= factor) {
460 const int num_hi = divmod(*lo, factor, lo);
461 const int new_hi = *hi + num_hi;
462 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
463 *hi = new_hi;
464 }
465 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000466}
467
468/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 * 0 <= *s < 24*3600
470 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000471 * The input values must be such that the internals don't overflow.
472 * The way this routine is used, we don't get close.
473 */
474static void
475normalize_d_s_us(int *d, int *s, int *us)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (*us < 0 || *us >= 1000000) {
478 normalize_pair(s, us, 1000000);
479 /* |s| can't be bigger than about
480 * |original s| + |original us|/1000000 now.
481 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 }
484 if (*s < 0 || *s >= 24*3600) {
485 normalize_pair(d, s, 24*3600);
486 /* |d| can't be bigger than about
487 * |original d| +
488 * (|original s| + |original us|/1000000) / (24*3600) now.
489 */
490 }
491 assert(0 <= *s && *s < 24*3600);
492 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000493}
494
495/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 * 1 <= *m <= 12
497 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000498 * The input values must be such that the internals don't overflow.
499 * The way this routine is used, we don't get close.
500 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000501static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000502normalize_y_m_d(int *y, int *m, int *d)
503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000505
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000506 /* In actual use, m is always the month component extracted from a
507 * date/datetime object. Therefore it is always in [1, 12] range.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 */
Alexander Belopolsky59a289d2010-10-13 22:54:34 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* Now only day can be out of bounds (year may also be out of bounds
513 * for a datetime object, but we don't care about that here).
514 * If day is out of bounds, what to do is arguable, but at least the
515 * method here is principled and explainable.
516 */
517 dim = days_in_month(*y, *m);
518 if (*d < 1 || *d > dim) {
519 /* Move day-1 days from the first of the month. First try to
520 * get off cheap if we're only one day out of range
521 * (adjustments for timezone alone can't be worse than that).
522 */
523 if (*d == 0) {
524 --*m;
525 if (*m > 0)
526 *d = days_in_month(*y, *m);
527 else {
528 --*y;
529 *m = 12;
530 *d = 31;
531 }
532 }
533 else if (*d == dim + 1) {
534 /* move forward a day */
535 ++*m;
536 *d = 1;
537 if (*m > 12) {
538 *m = 1;
539 ++*y;
540 }
541 }
542 else {
543 int ordinal = ymd_to_ord(*y, *m, 1) +
544 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000545 if (ordinal < 1 || ordinal > MAXORDINAL) {
546 goto error;
547 } else {
548 ord_to_ymd(ordinal, y, m, d);
549 return 0;
550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
552 }
553 assert(*m > 0);
554 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000555 if (MINYEAR <= *y && *y <= MAXYEAR)
556 return 0;
557 error:
558 PyErr_SetString(PyExc_OverflowError,
559 "date value out of range");
560 return -1;
561
Tim Peters2a799bf2002-12-16 20:18:38 +0000562}
563
564/* Fiddle out-of-bounds months and days so that the result makes some kind
565 * of sense. The parameters are both inputs and outputs. Returns < 0 on
566 * failure, where failure means the adjusted year is out of bounds.
567 */
568static int
569normalize_date(int *year, int *month, int *day)
570{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000571 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000572}
573
574/* Force all the datetime fields into range. The parameters are both
575 * inputs and outputs. Returns < 0 on error.
576 */
577static int
578normalize_datetime(int *year, int *month, int *day,
579 int *hour, int *minute, int *second,
580 int *microsecond)
581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 normalize_pair(second, microsecond, 1000000);
583 normalize_pair(minute, second, 60);
584 normalize_pair(hour, minute, 60);
585 normalize_pair(day, hour, 24);
586 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000587}
588
589/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000590 * Basic object allocation: tp_alloc implementations. These allocate
591 * Python objects of the right size and type, and do the Python object-
592 * initialization bit. If there's not enough memory, they return NULL after
593 * setting MemoryError. All data members remain uninitialized trash.
594 *
595 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000596 * member is needed. This is ugly, imprecise, and possibly insecure.
597 * tp_basicsize for the time and datetime types is set to the size of the
598 * struct that has room for the tzinfo member, so subclasses in Python will
599 * allocate enough space for a tzinfo member whether or not one is actually
600 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
601 * part is that PyType_GenericAlloc() (which subclasses in Python end up
602 * using) just happens today to effectively ignore the nitems argument
603 * when tp_itemsize is 0, which it is for these type objects. If that
604 * changes, perhaps the callers of tp_alloc slots in this file should
605 * be changed to force a 0 nitems argument unless the type being allocated
606 * is a base type implemented in this file (so that tp_alloc is time_alloc
607 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000608 */
609
610static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000611time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 self = (PyObject *)
616 PyObject_MALLOC(aware ?
617 sizeof(PyDateTime_Time) :
618 sizeof(_PyDateTime_BaseTime));
619 if (self == NULL)
620 return (PyObject *)PyErr_NoMemory();
621 PyObject_INIT(self, type);
622 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000623}
624
625static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000626datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 self = (PyObject *)
631 PyObject_MALLOC(aware ?
632 sizeof(PyDateTime_DateTime) :
633 sizeof(_PyDateTime_BaseDateTime));
634 if (self == NULL)
635 return (PyObject *)PyErr_NoMemory();
636 PyObject_INIT(self, type);
637 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000638}
639
640/* ---------------------------------------------------------------------------
641 * Helpers for setting object fields. These work on pointers to the
642 * appropriate base class.
643 */
644
645/* For date and datetime. */
646static void
647set_date_fields(PyDateTime_Date *self, int y, int m, int d)
648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 self->hashcode = -1;
650 SET_YEAR(self, y);
651 SET_MONTH(self, m);
652 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000653}
654
655/* ---------------------------------------------------------------------------
656 * Create various objects, mostly without range checking.
657 */
658
659/* Create a date instance with no range checking. */
660static PyObject *
661new_date_ex(int year, int month, int day, PyTypeObject *type)
662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
666 if (self != NULL)
667 set_date_fields(self, year, month, day);
668 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000669}
670
671#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000673
674/* Create a datetime instance with no range checking. */
675static PyObject *
676new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyDateTime_DateTime *self;
680 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
683 if (self != NULL) {
684 self->hastzinfo = aware;
685 set_date_fields((PyDateTime_Date *)self, year, month, day);
686 DATE_SET_HOUR(self, hour);
687 DATE_SET_MINUTE(self, minute);
688 DATE_SET_SECOND(self, second);
689 DATE_SET_MICROSECOND(self, usecond);
690 if (aware) {
691 Py_INCREF(tzinfo);
692 self->tzinfo = tzinfo;
693 }
694 }
695 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000696}
697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
699 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
700 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000701
702/* Create a time instance with no range checking. */
703static PyObject *
704new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 PyDateTime_Time *self;
708 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
711 if (self != NULL) {
712 self->hastzinfo = aware;
713 self->hashcode = -1;
714 TIME_SET_HOUR(self, hour);
715 TIME_SET_MINUTE(self, minute);
716 TIME_SET_SECOND(self, second);
717 TIME_SET_MICROSECOND(self, usecond);
718 if (aware) {
719 Py_INCREF(tzinfo);
720 self->tzinfo = tzinfo;
721 }
722 }
723 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000724}
725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726#define new_time(hh, mm, ss, us, tzinfo) \
727 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000728
729/* Create a timedelta instance. Normalize the members iff normalize is
730 * true. Passing false is a speed optimization, if you know for sure
731 * that seconds and microseconds are already in their proper ranges. In any
732 * case, raises OverflowError and returns NULL if the normalized days is out
733 * of range).
734 */
735static PyObject *
736new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (normalize)
742 normalize_d_s_us(&days, &seconds, &microseconds);
743 assert(0 <= seconds && seconds < 24*3600);
744 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (check_delta_day_range(days) < 0)
747 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
750 if (self != NULL) {
751 self->hashcode = -1;
752 SET_TD_DAYS(self, days);
753 SET_TD_SECONDS(self, seconds);
754 SET_TD_MICROSECONDS(self, microseconds);
755 }
756 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000757}
758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759#define new_delta(d, s, us, normalize) \
760 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000761
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000762
763typedef struct
764{
765 PyObject_HEAD
766 PyObject *offset;
767 PyObject *name;
768} PyDateTime_TimeZone;
769
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000770/* The interned UTC timezone instance */
771static PyObject *PyDateTime_TimeZone_UTC;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +0000772
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000773/* Create new timezone instance checking offset range. This
774 function does not check the name argument. Caller must assure
775 that offset is a timedelta instance and name is either NULL
776 or a unicode object. */
777static PyObject *
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000778create_timezone(PyObject *offset, PyObject *name)
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000779{
780 PyDateTime_TimeZone *self;
781 PyTypeObject *type = &PyDateTime_TimeZoneType;
782
783 assert(offset != NULL);
784 assert(PyDelta_Check(offset));
785 assert(name == NULL || PyUnicode_Check(name));
786
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000787 self = (PyDateTime_TimeZone *)(type->tp_alloc(type, 0));
788 if (self == NULL) {
789 return NULL;
790 }
791 Py_INCREF(offset);
792 self->offset = offset;
793 Py_XINCREF(name);
794 self->name = name;
795 return (PyObject *)self;
796}
797
798static int delta_bool(PyDateTime_Delta *self);
799
800static PyObject *
801new_timezone(PyObject *offset, PyObject *name)
802{
803 assert(offset != NULL);
804 assert(PyDelta_Check(offset));
805 assert(name == NULL || PyUnicode_Check(name));
806
807 if (name == NULL && delta_bool((PyDateTime_Delta *)offset) == 0) {
808 Py_INCREF(PyDateTime_TimeZone_UTC);
809 return PyDateTime_TimeZone_UTC;
810 }
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000811 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
812 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
813 " representing a whole number of minutes");
814 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"
820 " timedelta(hours=24).");
821 return NULL;
822 }
823
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +0000824 return create_timezone(offset, name);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +0000825}
826
Tim Petersb0c854d2003-05-17 15:57:00 +0000827/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 * tzinfo helpers.
829 */
830
Tim Peters855fe882002-12-22 03:43:39 +0000831/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
832 * raise TypeError and return -1.
833 */
834static int
835check_tzinfo_subclass(PyObject *p)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (p == Py_None || PyTZInfo_Check(p))
838 return 0;
839 PyErr_Format(PyExc_TypeError,
840 "tzinfo argument must be None or of a tzinfo subclass, "
841 "not type '%s'",
842 Py_TYPE(p)->tp_name);
843 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000844}
845
Tim Peters2a799bf2002-12-16 20:18:38 +0000846/* If self has a tzinfo member, return a BORROWED reference to it. Else
847 * return NULL, which is NOT AN ERROR. There are no error returns here,
848 * and the caller must not decref the result.
849 */
850static PyObject *
851get_tzinfo_member(PyObject *self)
852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (PyDateTime_Check(self) && HASTZINFO(self))
856 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
857 else if (PyTime_Check(self) && HASTZINFO(self))
858 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000861}
862
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000863/* Call getattr(tzinfo, name)(tzinfoarg), and check the result. tzinfo must
864 * be an instance of the tzinfo class. If the method returns None, this
865 * returns None. If the method doesn't return None or timedelta, TypeError is
866 * raised and this returns NULL. If it returns a timedelta and the value is
867 * out of range or isn't a whole number of minutes, ValueError is raised and
868 * this returns NULL. Else result is returned.
Tim Peters2a799bf2002-12-16 20:18:38 +0000869 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000870static PyObject *
871call_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000872{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000873 PyObject *offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 assert(tzinfo != NULL);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000876 assert(PyTZInfo_Check(tzinfo) || tzinfo == Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000878
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000879 if (tzinfo == Py_None)
880 Py_RETURN_NONE;
881 offset = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
882 if (offset == Py_None || offset == NULL)
883 return offset;
884 if (PyDelta_Check(offset)) {
885 if (GET_TD_MICROSECONDS(offset) != 0 || GET_TD_SECONDS(offset) % 60 != 0) {
886 Py_DECREF(offset);
887 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
888 " representing a whole number of minutes");
889 return NULL;
890 }
891 if ((GET_TD_DAYS(offset) == -1 && GET_TD_SECONDS(offset) == 0) ||
892 GET_TD_DAYS(offset) < -1 || GET_TD_DAYS(offset) >= 1) {
893 Py_DECREF(offset);
894 PyErr_Format(PyExc_ValueError, "offset must be a timedelta"
895 " strictly between -timedelta(hours=24) and"
896 " timedelta(hours=24).");
897 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 }
899 }
900 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000901 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyErr_Format(PyExc_TypeError,
903 "tzinfo.%s() must return None or "
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000904 "timedelta, not '%.200s'",
905 name, Py_TYPE(offset)->tp_name);
906 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000908
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000909 return offset;
Tim Peters2a799bf2002-12-16 20:18:38 +0000910}
911
912/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
913 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
914 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000915 * doesn't return None or timedelta, TypeError is raised and this returns -1.
916 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
917 * # of minutes), ValueError is raised and this returns -1. Else *none is
918 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000919 */
Tim Peters855fe882002-12-22 03:43:39 +0000920static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000921call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg)
922{
923 return call_tzinfo_method(tzinfo, "utcoffset", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000924}
925
Tim Peters2a799bf2002-12-16 20:18:38 +0000926/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
927 * result. tzinfo must be an instance of the tzinfo class. If dst()
928 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000929 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000930 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000931 * ValueError is raised and this returns -1. Else *none is set to 0 and
932 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000933 */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000934static PyObject *
935call_dst(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000936{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000937 return call_tzinfo_method(tzinfo, "dst", tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000938}
939
Tim Petersbad8ff02002-12-30 20:52:32 +0000940/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000941 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000942 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000943 * returns NULL. If the result is a string, we ensure it is a Unicode
944 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000945 */
946static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000947call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 assert(tzinfo != NULL);
952 assert(check_tzinfo_subclass(tzinfo) >= 0);
953 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (tzinfo == Py_None)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000956 Py_RETURN_NONE;
Tim Peters2a799bf2002-12-16 20:18:38 +0000957
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000958 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
959
960 if (result == NULL || result == Py_None)
961 return result;
962
963 if (!PyUnicode_Check(result)) {
964 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
965 "return None or a string, not '%s'",
966 Py_TYPE(result)->tp_name);
967 Py_DECREF(result);
968 result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +0000970
971 return result;
Tim Peters00237032002-12-27 02:21:51 +0000972}
973
Tim Peters2a799bf2002-12-16 20:18:38 +0000974/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
975 * stuff
976 * ", tzinfo=" + repr(tzinfo)
977 * before the closing ")".
978 */
979static PyObject *
980append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 assert(PyUnicode_Check(repr));
985 assert(tzinfo);
986 if (tzinfo == Py_None)
987 return repr;
988 /* Get rid of the trailing ')'. */
989 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
990 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
991 PyUnicode_GET_SIZE(repr) - 1);
992 Py_DECREF(repr);
993 if (temp == NULL)
994 return NULL;
995 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
996 Py_DECREF(temp);
997 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +0000998}
999
1000/* ---------------------------------------------------------------------------
1001 * String format helpers.
1002 */
1003
1004static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001005format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 static const char *DayNames[] = {
1008 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1009 };
1010 static const char *MonthNames[] = {
1011 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1012 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1013 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1018 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1019 GET_DAY(date), hours, minutes, seconds,
1020 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001021}
1022
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001023static PyObject *delta_negative(PyDateTime_Delta *self);
1024
Tim Peters2a799bf2002-12-16 20:18:38 +00001025/* Add an hours & minutes UTC offset string to buf. buf has no more than
1026 * buflen bytes remaining. The UTC offset is gotten by calling
1027 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1028 * *buf, and that's all. Else the returned value is checked for sanity (an
1029 * integer in range), and if that's OK it's converted to an hours & minutes
1030 * string of the form
1031 * sign HH sep MM
1032 * Returns 0 if everything is OK. If the return value from utcoffset() is
1033 * bogus, an appropriate exception is set and -1 is returned.
1034 */
1035static int
Tim Peters328fff72002-12-20 01:31:27 +00001036format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001038{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001039 PyObject *offset;
1040 int hours, minutes, seconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 char sign;
Tim Peters2a799bf2002-12-16 20:18:38 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001044
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001045 offset = call_utcoffset(tzinfo, tzinfoarg);
1046 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001048 if (offset == Py_None) {
1049 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 *buf = '\0';
1051 return 0;
1052 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001053 /* Offset is normalized, so it is negative if days < 0 */
1054 if (GET_TD_DAYS(offset) < 0) {
1055 PyObject *temp = offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 sign = '-';
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001057 offset = delta_negative((PyDateTime_Delta *)offset);
1058 Py_DECREF(temp);
1059 if (offset == NULL)
1060 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001062 else {
1063 sign = '+';
1064 }
1065 /* Offset is not negative here. */
1066 seconds = GET_TD_SECONDS(offset);
1067 Py_DECREF(offset);
1068 minutes = divmod(seconds, 60, &seconds);
1069 hours = divmod(minutes, 60, &minutes);
1070 assert(seconds == 0);
1071 /* XXX ignore sub-minute data, curently not allowed. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001075}
1076
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001077static PyObject *
1078make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyObject *temp;
1081 PyObject *tzinfo = get_tzinfo_member(object);
1082 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
1083 if (Zreplacement == NULL)
1084 return NULL;
1085 if (tzinfo == Py_None || tzinfo == NULL)
1086 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 assert(tzinfoarg != NULL);
1089 temp = call_tzname(tzinfo, tzinfoarg);
1090 if (temp == NULL)
1091 goto Error;
1092 if (temp == Py_None) {
1093 Py_DECREF(temp);
1094 return Zreplacement;
1095 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 assert(PyUnicode_Check(temp));
1098 /* Since the tzname is getting stuffed into the
1099 * format, we have to double any % signs so that
1100 * strftime doesn't treat them as format codes.
1101 */
1102 Py_DECREF(Zreplacement);
1103 Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1104 Py_DECREF(temp);
1105 if (Zreplacement == NULL)
1106 return NULL;
1107 if (!PyUnicode_Check(Zreplacement)) {
1108 PyErr_SetString(PyExc_TypeError,
1109 "tzname.replace() did not return a string");
1110 goto Error;
1111 }
1112 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001113
1114 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 Py_DECREF(Zreplacement);
1116 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001117}
1118
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001119static PyObject *
1120make_freplacement(PyObject *object)
1121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 char freplacement[64];
1123 if (PyTime_Check(object))
1124 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1125 else if (PyDateTime_Check(object))
1126 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1127 else
1128 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001131}
1132
Tim Peters2a799bf2002-12-16 20:18:38 +00001133/* I sure don't want to reproduce the strftime code from the time module,
1134 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001135 * giving special meanings to the %z, %Z and %f format codes via a
1136 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001137 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1138 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001139 */
1140static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001141wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1147 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1148 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 const char *pin; /* pointer to next char in input format */
1151 Py_ssize_t flen; /* length of input format */
1152 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyObject *newfmt = NULL; /* py string, the output format */
1155 char *pnew; /* pointer to available byte in output format */
1156 size_t totalnew; /* number bytes total in output format buffer,
1157 exclusive of trailing \0 */
1158 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 const char *ptoappend; /* ptr to string to append to output buffer */
1161 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 assert(object && format && timetuple);
1164 assert(PyUnicode_Check(format));
1165 /* Convert the input format to a C string and size */
1166 pin = _PyUnicode_AsStringAndSize(format, &flen);
1167 if (!pin)
1168 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 /* Give up if the year is before 1900.
1171 * Python strftime() plays games with the year, and different
1172 * games depending on whether envar PYTHON2K is set. This makes
1173 * years before 1900 a nightmare, even if the platform strftime
1174 * supports them (and not all do).
1175 * We could get a lot farther here by avoiding Python's strftime
1176 * wrapper and calling the C strftime() directly, but that isn't
1177 * an option in the Python implementation of this module.
1178 */
1179 {
1180 long year;
1181 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1182 if (pyyear == NULL) return NULL;
1183 assert(PyLong_Check(pyyear));
1184 year = PyLong_AsLong(pyyear);
1185 Py_DECREF(pyyear);
1186 if (year < 1900) {
1187 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1188 "1900; the datetime strftime() "
1189 "methods require year >= 1900",
1190 year);
1191 return NULL;
1192 }
1193 }
Tim Petersd6844152002-12-22 20:58:42 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 /* Scan the input format, looking for %z/%Z/%f escapes, building
1196 * a new format. Since computing the replacements for those codes
1197 * is expensive, don't unless they're actually used.
1198 */
1199 if (flen > INT_MAX - 1) {
1200 PyErr_NoMemory();
1201 goto Done;
1202 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 totalnew = flen + 1; /* realistic if no %z/%Z */
1205 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1206 if (newfmt == NULL) goto Done;
1207 pnew = PyBytes_AsString(newfmt);
1208 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 while ((ch = *pin++) != '\0') {
1211 if (ch != '%') {
1212 ptoappend = pin - 1;
1213 ntoappend = 1;
1214 }
1215 else if ((ch = *pin++) == '\0') {
1216 /* There's a lone trailing %; doesn't make sense. */
1217 PyErr_SetString(PyExc_ValueError, "strftime format "
1218 "ends with raw %");
1219 goto Done;
1220 }
1221 /* A % has been seen and ch is the character after it. */
1222 else if (ch == 'z') {
1223 if (zreplacement == NULL) {
1224 /* format utcoffset */
1225 char buf[100];
1226 PyObject *tzinfo = get_tzinfo_member(object);
1227 zreplacement = PyBytes_FromStringAndSize("", 0);
1228 if (zreplacement == NULL) goto Done;
1229 if (tzinfo != Py_None && tzinfo != NULL) {
1230 assert(tzinfoarg != NULL);
1231 if (format_utcoffset(buf,
1232 sizeof(buf),
1233 "",
1234 tzinfo,
1235 tzinfoarg) < 0)
1236 goto Done;
1237 Py_DECREF(zreplacement);
1238 zreplacement =
1239 PyBytes_FromStringAndSize(buf,
1240 strlen(buf));
1241 if (zreplacement == NULL)
1242 goto Done;
1243 }
1244 }
1245 assert(zreplacement != NULL);
1246 ptoappend = PyBytes_AS_STRING(zreplacement);
1247 ntoappend = PyBytes_GET_SIZE(zreplacement);
1248 }
1249 else if (ch == 'Z') {
1250 /* format tzname */
1251 if (Zreplacement == NULL) {
1252 Zreplacement = make_Zreplacement(object,
1253 tzinfoarg);
1254 if (Zreplacement == NULL)
1255 goto Done;
1256 }
1257 assert(Zreplacement != NULL);
1258 assert(PyUnicode_Check(Zreplacement));
1259 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1260 &ntoappend);
1261 ntoappend = Py_SIZE(Zreplacement);
1262 }
1263 else if (ch == 'f') {
1264 /* format microseconds */
1265 if (freplacement == NULL) {
1266 freplacement = make_freplacement(object);
1267 if (freplacement == NULL)
1268 goto Done;
1269 }
1270 assert(freplacement != NULL);
1271 assert(PyBytes_Check(freplacement));
1272 ptoappend = PyBytes_AS_STRING(freplacement);
1273 ntoappend = PyBytes_GET_SIZE(freplacement);
1274 }
1275 else {
1276 /* percent followed by neither z nor Z */
1277 ptoappend = pin - 2;
1278 ntoappend = 2;
1279 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 /* Append the ntoappend chars starting at ptoappend to
1282 * the new format.
1283 */
1284 if (ntoappend == 0)
1285 continue;
1286 assert(ptoappend != NULL);
1287 assert(ntoappend > 0);
1288 while (usednew + ntoappend > totalnew) {
1289 size_t bigger = totalnew << 1;
1290 if ((bigger >> 1) != totalnew) { /* overflow */
1291 PyErr_NoMemory();
1292 goto Done;
1293 }
1294 if (_PyBytes_Resize(&newfmt, bigger) < 0)
1295 goto Done;
1296 totalnew = bigger;
1297 pnew = PyBytes_AsString(newfmt) + usednew;
1298 }
1299 memcpy(pnew, ptoappend, ntoappend);
1300 pnew += ntoappend;
1301 usednew += ntoappend;
1302 assert(usednew <= totalnew);
1303 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1306 goto Done;
1307 {
1308 PyObject *format;
1309 PyObject *time = PyImport_ImportModuleNoBlock("time");
1310 if (time == NULL)
1311 goto Done;
1312 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1313 if (format != NULL) {
1314 result = PyObject_CallMethod(time, "strftime", "OO",
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001315 format, timetuple, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 Py_DECREF(format);
1317 }
1318 Py_DECREF(time);
1319 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001320 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_XDECREF(freplacement);
1322 Py_XDECREF(zreplacement);
1323 Py_XDECREF(Zreplacement);
1324 Py_XDECREF(newfmt);
1325 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001326}
1327
Tim Peters2a799bf2002-12-16 20:18:38 +00001328/* ---------------------------------------------------------------------------
1329 * Wrap functions from the time module. These aren't directly available
1330 * from C. Perhaps they should be.
1331 */
1332
1333/* Call time.time() and return its result (a Python float). */
1334static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001335time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyObject *result = NULL;
1338 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (time != NULL) {
1341 result = PyObject_CallMethod(time, "time", "()");
1342 Py_DECREF(time);
1343 }
1344 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001345}
1346
1347/* Build a time.struct_time. The weekday and day number are automatically
1348 * computed from the y,m,d args.
1349 */
1350static PyObject *
1351build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 PyObject *time;
1354 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 time = PyImport_ImportModuleNoBlock("time");
1357 if (time != NULL) {
1358 result = PyObject_CallMethod(time, "struct_time",
1359 "((iiiiiiiii))",
1360 y, m, d,
1361 hh, mm, ss,
1362 weekday(y, m, d),
1363 days_before_month(y, m) + d,
1364 dstflag);
1365 Py_DECREF(time);
1366 }
1367 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001368}
1369
1370/* ---------------------------------------------------------------------------
1371 * Miscellaneous helpers.
1372 */
1373
Mark Dickinsone94c6792009-02-02 20:36:42 +00001374/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001375 * The comparisons here all most naturally compute a cmp()-like result.
1376 * This little helper turns that into a bool result for rich comparisons.
1377 */
1378static PyObject *
1379diff_to_bool(int diff, int op)
1380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 PyObject *result;
1382 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 switch (op) {
1385 case Py_EQ: istrue = diff == 0; break;
1386 case Py_NE: istrue = diff != 0; break;
1387 case Py_LE: istrue = diff <= 0; break;
1388 case Py_GE: istrue = diff >= 0; break;
1389 case Py_LT: istrue = diff < 0; break;
1390 case Py_GT: istrue = diff > 0; break;
1391 default:
1392 assert(! "op unknown");
1393 istrue = 0; /* To shut up compiler */
1394 }
1395 result = istrue ? Py_True : Py_False;
1396 Py_INCREF(result);
1397 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001398}
1399
Tim Peters07534a62003-02-07 22:50:28 +00001400/* Raises a "can't compare" TypeError and returns NULL. */
1401static PyObject *
1402cmperror(PyObject *a, PyObject *b)
1403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 PyErr_Format(PyExc_TypeError,
1405 "can't compare %s to %s",
1406 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1407 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001408}
1409
Tim Peters2a799bf2002-12-16 20:18:38 +00001410/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001411 * Cached Python objects; these are set by the module init function.
1412 */
1413
1414/* Conversion factors. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415static PyObject *us_per_us = NULL; /* 1 */
1416static PyObject *us_per_ms = NULL; /* 1000 */
1417static PyObject *us_per_second = NULL; /* 1000000 */
1418static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1419static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1420static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1421static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
Tim Peters2a799bf2002-12-16 20:18:38 +00001422static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1423
Tim Peters2a799bf2002-12-16 20:18:38 +00001424/* ---------------------------------------------------------------------------
1425 * Class implementations.
1426 */
1427
1428/*
1429 * PyDateTime_Delta implementation.
1430 */
1431
1432/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Tim Peters2a799bf2002-12-16 20:18:38 +00001434 * as a Python int or long.
1435 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1436 * due to ubiquitous overflow possibilities.
1437 */
1438static PyObject *
1439delta_to_microseconds(PyDateTime_Delta *self)
1440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyObject *x1 = NULL;
1442 PyObject *x2 = NULL;
1443 PyObject *x3 = NULL;
1444 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1447 if (x1 == NULL)
1448 goto Done;
1449 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1450 if (x2 == NULL)
1451 goto Done;
1452 Py_DECREF(x1);
1453 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 /* x2 has days in seconds */
1456 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1457 if (x1 == NULL)
1458 goto Done;
1459 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1460 if (x3 == NULL)
1461 goto Done;
1462 Py_DECREF(x1);
1463 Py_DECREF(x2);
1464 x1 = x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 /* x3 has days+seconds in seconds */
1467 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1468 if (x1 == NULL)
1469 goto Done;
1470 Py_DECREF(x3);
1471 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 /* x1 has days+seconds in us */
1474 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1475 if (x2 == NULL)
1476 goto Done;
1477 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001478
1479Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 Py_XDECREF(x1);
1481 Py_XDECREF(x2);
1482 Py_XDECREF(x3);
1483 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001484}
1485
1486/* Convert a number of us (as a Python int or long) to a timedelta.
1487 */
1488static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001489microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 int us;
1492 int s;
1493 int d;
1494 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 PyObject *tuple = NULL;
1497 PyObject *num = NULL;
1498 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 tuple = PyNumber_Divmod(pyus, us_per_second);
1501 if (tuple == NULL)
1502 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 num = PyTuple_GetItem(tuple, 1); /* us */
1505 if (num == NULL)
1506 goto Done;
1507 temp = PyLong_AsLong(num);
1508 num = NULL;
1509 if (temp == -1 && PyErr_Occurred())
1510 goto Done;
1511 assert(0 <= temp && temp < 1000000);
1512 us = (int)temp;
1513 if (us < 0) {
1514 /* The divisor was positive, so this must be an error. */
1515 assert(PyErr_Occurred());
1516 goto Done;
1517 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1520 if (num == NULL)
1521 goto Done;
1522 Py_INCREF(num);
1523 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 tuple = PyNumber_Divmod(num, seconds_per_day);
1526 if (tuple == NULL)
1527 goto Done;
1528 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 num = PyTuple_GetItem(tuple, 1); /* seconds */
1531 if (num == NULL)
1532 goto Done;
1533 temp = PyLong_AsLong(num);
1534 num = NULL;
1535 if (temp == -1 && PyErr_Occurred())
1536 goto Done;
1537 assert(0 <= temp && temp < 24*3600);
1538 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 if (s < 0) {
1541 /* The divisor was positive, so this must be an error. */
1542 assert(PyErr_Occurred());
1543 goto Done;
1544 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1547 if (num == NULL)
1548 goto Done;
1549 Py_INCREF(num);
1550 temp = PyLong_AsLong(num);
1551 if (temp == -1 && PyErr_Occurred())
1552 goto Done;
1553 d = (int)temp;
1554 if ((long)d != temp) {
1555 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1556 "large to fit in a C int");
1557 goto Done;
1558 }
1559 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001560
1561Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 Py_XDECREF(tuple);
1563 Py_XDECREF(num);
1564 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001565}
1566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567#define microseconds_to_delta(pymicros) \
1568 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001569
Tim Peters2a799bf2002-12-16 20:18:38 +00001570static PyObject *
1571multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 PyObject *pyus_in;
1574 PyObject *pyus_out;
1575 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 pyus_in = delta_to_microseconds(delta);
1578 if (pyus_in == NULL)
1579 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1582 Py_DECREF(pyus_in);
1583 if (pyus_out == NULL)
1584 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 result = microseconds_to_delta(pyus_out);
1587 Py_DECREF(pyus_out);
1588 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001589}
1590
1591static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001592multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1593{
1594 PyObject *result = NULL;
1595 PyObject *pyus_in = NULL, *temp, *pyus_out;
1596 PyObject *ratio = NULL;
1597
1598 pyus_in = delta_to_microseconds(delta);
1599 if (pyus_in == NULL)
1600 return NULL;
1601 ratio = PyObject_CallMethod(floatobj, "as_integer_ratio", NULL);
1602 if (ratio == NULL)
1603 goto error;
1604 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1605 Py_DECREF(pyus_in);
1606 pyus_in = NULL;
1607 if (temp == NULL)
1608 goto error;
1609 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1610 Py_DECREF(temp);
1611 if (pyus_out == NULL)
1612 goto error;
1613 result = microseconds_to_delta(pyus_out);
1614 Py_DECREF(pyus_out);
1615 error:
1616 Py_XDECREF(pyus_in);
1617 Py_XDECREF(ratio);
1618
1619 return result;
1620}
1621
1622static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001623divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 PyObject *pyus_in;
1626 PyObject *pyus_out;
1627 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 pyus_in = delta_to_microseconds(delta);
1630 if (pyus_in == NULL)
1631 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1634 Py_DECREF(pyus_in);
1635 if (pyus_out == NULL)
1636 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 result = microseconds_to_delta(pyus_out);
1639 Py_DECREF(pyus_out);
1640 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001641}
1642
1643static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001644divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 PyObject *pyus_left;
1647 PyObject *pyus_right;
1648 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 pyus_left = delta_to_microseconds(left);
1651 if (pyus_left == NULL)
1652 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 pyus_right = delta_to_microseconds(right);
1655 if (pyus_right == NULL) {
1656 Py_DECREF(pyus_left);
1657 return NULL;
1658 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1661 Py_DECREF(pyus_left);
1662 Py_DECREF(pyus_right);
1663 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001664}
1665
1666static PyObject *
1667truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 PyObject *pyus_left;
1670 PyObject *pyus_right;
1671 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 pyus_left = delta_to_microseconds(left);
1674 if (pyus_left == NULL)
1675 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 pyus_right = delta_to_microseconds(right);
1678 if (pyus_right == NULL) {
1679 Py_DECREF(pyus_left);
1680 return NULL;
1681 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1684 Py_DECREF(pyus_left);
1685 Py_DECREF(pyus_right);
1686 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001687}
1688
1689static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001690truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1691{
1692 PyObject *result = NULL;
1693 PyObject *pyus_in = NULL, *temp, *pyus_out;
1694 PyObject *ratio = NULL;
1695
1696 pyus_in = delta_to_microseconds(delta);
1697 if (pyus_in == NULL)
1698 return NULL;
1699 ratio = PyObject_CallMethod(f, "as_integer_ratio", NULL);
1700 if (ratio == NULL)
1701 goto error;
1702 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1703 Py_DECREF(pyus_in);
1704 pyus_in = NULL;
1705 if (temp == NULL)
1706 goto error;
1707 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1708 Py_DECREF(temp);
1709 if (pyus_out == NULL)
1710 goto error;
1711 result = microseconds_to_delta(pyus_out);
1712 Py_DECREF(pyus_out);
1713 error:
1714 Py_XDECREF(pyus_in);
1715 Py_XDECREF(ratio);
1716
1717 return result;
1718}
1719
1720static PyObject *
1721truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1722{
1723 PyObject *result;
1724 PyObject *pyus_in, *pyus_out;
1725 pyus_in = delta_to_microseconds(delta);
1726 if (pyus_in == NULL)
1727 return NULL;
1728 pyus_out = divide_nearest(pyus_in, i);
1729 Py_DECREF(pyus_in);
1730 if (pyus_out == NULL)
1731 return NULL;
1732 result = microseconds_to_delta(pyus_out);
1733 Py_DECREF(pyus_out);
1734
1735 return result;
1736}
1737
1738static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001739delta_add(PyObject *left, PyObject *right)
1740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1744 /* delta + delta */
1745 /* The C-level additions can't overflow because of the
1746 * invariant bounds.
1747 */
1748 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1749 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1750 int microseconds = GET_TD_MICROSECONDS(left) +
1751 GET_TD_MICROSECONDS(right);
1752 result = new_delta(days, seconds, microseconds, 1);
1753 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 if (result == Py_NotImplemented)
1756 Py_INCREF(result);
1757 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001758}
1759
1760static PyObject *
1761delta_negative(PyDateTime_Delta *self)
1762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 return new_delta(-GET_TD_DAYS(self),
1764 -GET_TD_SECONDS(self),
1765 -GET_TD_MICROSECONDS(self),
1766 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001767}
1768
1769static PyObject *
1770delta_positive(PyDateTime_Delta *self)
1771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 /* Could optimize this (by returning self) if this isn't a
1773 * subclass -- but who uses unary + ? Approximately nobody.
1774 */
1775 return new_delta(GET_TD_DAYS(self),
1776 GET_TD_SECONDS(self),
1777 GET_TD_MICROSECONDS(self),
1778 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001779}
1780
1781static PyObject *
1782delta_abs(PyDateTime_Delta *self)
1783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 assert(GET_TD_MICROSECONDS(self) >= 0);
1787 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (GET_TD_DAYS(self) < 0)
1790 result = delta_negative(self);
1791 else
1792 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001795}
1796
1797static PyObject *
1798delta_subtract(PyObject *left, PyObject *right)
1799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1803 /* delta - delta */
1804 PyObject *minus_right = PyNumber_Negative(right);
1805 if (minus_right) {
1806 result = delta_add(left, minus_right);
1807 Py_DECREF(minus_right);
1808 }
1809 else
1810 result = NULL;
1811 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 if (result == Py_NotImplemented)
1814 Py_INCREF(result);
1815 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001816}
1817
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001818static int
1819delta_cmp(PyObject *self, PyObject *other)
1820{
1821 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1822 if (diff == 0) {
1823 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1824 if (diff == 0)
1825 diff = GET_TD_MICROSECONDS(self) -
1826 GET_TD_MICROSECONDS(other);
1827 }
1828 return diff;
1829}
1830
Tim Peters2a799bf2002-12-16 20:18:38 +00001831static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001832delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (PyDelta_Check(other)) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00001835 int diff = delta_cmp(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 return diff_to_bool(diff, op);
1837 }
1838 else {
1839 Py_INCREF(Py_NotImplemented);
1840 return Py_NotImplemented;
1841 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001842}
1843
1844static PyObject *delta_getstate(PyDateTime_Delta *self);
1845
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001846static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00001847delta_hash(PyDateTime_Delta *self)
1848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 if (self->hashcode == -1) {
1850 PyObject *temp = delta_getstate(self);
1851 if (temp != NULL) {
1852 self->hashcode = PyObject_Hash(temp);
1853 Py_DECREF(temp);
1854 }
1855 }
1856 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001857}
1858
1859static PyObject *
1860delta_multiply(PyObject *left, PyObject *right)
1861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 if (PyDelta_Check(left)) {
1865 /* delta * ??? */
1866 if (PyLong_Check(right))
1867 result = multiply_int_timedelta(right,
1868 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001869 else if (PyFloat_Check(right))
1870 result = multiply_float_timedelta(right,
1871 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 }
1873 else if (PyLong_Check(left))
1874 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001875 (PyDateTime_Delta *) right);
1876 else if (PyFloat_Check(left))
1877 result = multiply_float_timedelta(left,
1878 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (result == Py_NotImplemented)
1881 Py_INCREF(result);
1882 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001883}
1884
1885static PyObject *
1886delta_divide(PyObject *left, PyObject *right)
1887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 if (PyDelta_Check(left)) {
1891 /* delta * ??? */
1892 if (PyLong_Check(right))
1893 result = divide_timedelta_int(
1894 (PyDateTime_Delta *)left,
1895 right);
1896 else if (PyDelta_Check(right))
1897 result = divide_timedelta_timedelta(
1898 (PyDateTime_Delta *)left,
1899 (PyDateTime_Delta *)right);
1900 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 if (result == Py_NotImplemented)
1903 Py_INCREF(result);
1904 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001905}
1906
Mark Dickinson7c186e22010-04-20 22:32:49 +00001907static PyObject *
1908delta_truedivide(PyObject *left, PyObject *right)
1909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 if (PyDelta_Check(left)) {
1913 if (PyDelta_Check(right))
1914 result = truedivide_timedelta_timedelta(
1915 (PyDateTime_Delta *)left,
1916 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001917 else if (PyFloat_Check(right))
1918 result = truedivide_timedelta_float(
1919 (PyDateTime_Delta *)left, right);
1920 else if (PyLong_Check(right))
1921 result = truedivide_timedelta_int(
1922 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 if (result == Py_NotImplemented)
1926 Py_INCREF(result);
1927 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001928}
1929
1930static PyObject *
1931delta_remainder(PyObject *left, PyObject *right)
1932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 PyObject *pyus_left;
1934 PyObject *pyus_right;
1935 PyObject *pyus_remainder;
1936 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
1939 Py_INCREF(Py_NotImplemented);
1940 return Py_NotImplemented;
1941 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1944 if (pyus_left == NULL)
1945 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1948 if (pyus_right == NULL) {
1949 Py_DECREF(pyus_left);
1950 return NULL;
1951 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
1954 Py_DECREF(pyus_left);
1955 Py_DECREF(pyus_right);
1956 if (pyus_remainder == NULL)
1957 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 remainder = microseconds_to_delta(pyus_remainder);
1960 Py_DECREF(pyus_remainder);
1961 if (remainder == NULL)
1962 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001965}
1966
1967static PyObject *
1968delta_divmod(PyObject *left, PyObject *right)
1969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 PyObject *pyus_left;
1971 PyObject *pyus_right;
1972 PyObject *divmod;
1973 PyObject *delta;
1974 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
1977 Py_INCREF(Py_NotImplemented);
1978 return Py_NotImplemented;
1979 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1982 if (pyus_left == NULL)
1983 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1986 if (pyus_right == NULL) {
1987 Py_DECREF(pyus_left);
1988 return NULL;
1989 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 divmod = PyNumber_Divmod(pyus_left, pyus_right);
1992 Py_DECREF(pyus_left);
1993 Py_DECREF(pyus_right);
1994 if (divmod == NULL)
1995 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 assert(PyTuple_Size(divmod) == 2);
1998 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
1999 if (delta == NULL) {
2000 Py_DECREF(divmod);
2001 return NULL;
2002 }
2003 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
2004 Py_DECREF(delta);
2005 Py_DECREF(divmod);
2006 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002007}
2008
Tim Peters2a799bf2002-12-16 20:18:38 +00002009/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2010 * timedelta constructor. sofar is the # of microseconds accounted for
2011 * so far, and there are factor microseconds per current unit, the number
2012 * of which is given by num. num * factor is added to sofar in a
2013 * numerically careful way, and that's the result. Any fractional
2014 * microseconds left over (this can happen if num is a float type) are
2015 * added into *leftover.
2016 * Note that there are many ways this can give an error (NULL) return.
2017 */
2018static PyObject *
2019accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2020 double *leftover)
2021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 PyObject *prod;
2023 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 if (PyLong_Check(num)) {
2028 prod = PyNumber_Multiply(num, factor);
2029 if (prod == NULL)
2030 return NULL;
2031 sum = PyNumber_Add(sofar, prod);
2032 Py_DECREF(prod);
2033 return sum;
2034 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 if (PyFloat_Check(num)) {
2037 double dnum;
2038 double fracpart;
2039 double intpart;
2040 PyObject *x;
2041 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 /* The Plan: decompose num into an integer part and a
2044 * fractional part, num = intpart + fracpart.
2045 * Then num * factor ==
2046 * intpart * factor + fracpart * factor
2047 * and the LHS can be computed exactly in long arithmetic.
2048 * The RHS is again broken into an int part and frac part.
2049 * and the frac part is added into *leftover.
2050 */
2051 dnum = PyFloat_AsDouble(num);
2052 if (dnum == -1.0 && PyErr_Occurred())
2053 return NULL;
2054 fracpart = modf(dnum, &intpart);
2055 x = PyLong_FromDouble(intpart);
2056 if (x == NULL)
2057 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 prod = PyNumber_Multiply(x, factor);
2060 Py_DECREF(x);
2061 if (prod == NULL)
2062 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 sum = PyNumber_Add(sofar, prod);
2065 Py_DECREF(prod);
2066 if (sum == NULL)
2067 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (fracpart == 0.0)
2070 return sum;
2071 /* So far we've lost no information. Dealing with the
2072 * fractional part requires float arithmetic, and may
2073 * lose a little info.
2074 */
2075 assert(PyLong_Check(factor));
2076 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 dnum *= fracpart;
2079 fracpart = modf(dnum, &intpart);
2080 x = PyLong_FromDouble(intpart);
2081 if (x == NULL) {
2082 Py_DECREF(sum);
2083 return NULL;
2084 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 y = PyNumber_Add(sum, x);
2087 Py_DECREF(sum);
2088 Py_DECREF(x);
2089 *leftover += fracpart;
2090 return y;
2091 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 PyErr_Format(PyExc_TypeError,
2094 "unsupported type for timedelta %s component: %s",
2095 tag, Py_TYPE(num)->tp_name);
2096 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002097}
2098
2099static PyObject *
2100delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 /* Argument objects. */
2105 PyObject *day = NULL;
2106 PyObject *second = NULL;
2107 PyObject *us = NULL;
2108 PyObject *ms = NULL;
2109 PyObject *minute = NULL;
2110 PyObject *hour = NULL;
2111 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 PyObject *x = NULL; /* running sum of microseconds */
2114 PyObject *y = NULL; /* temp sum of microseconds */
2115 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 static char *keywords[] = {
2118 "days", "seconds", "microseconds", "milliseconds",
2119 "minutes", "hours", "weeks", NULL
2120 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2123 keywords,
2124 &day, &second, &us,
2125 &ms, &minute, &hour, &week) == 0)
2126 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 x = PyLong_FromLong(0);
2129 if (x == NULL)
2130 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132#define CLEANUP \
2133 Py_DECREF(x); \
2134 x = y; \
2135 if (x == NULL) \
2136 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (us) {
2139 y = accum("microseconds", x, us, us_per_us, &leftover_us);
2140 CLEANUP;
2141 }
2142 if (ms) {
2143 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2144 CLEANUP;
2145 }
2146 if (second) {
2147 y = accum("seconds", x, second, us_per_second, &leftover_us);
2148 CLEANUP;
2149 }
2150 if (minute) {
2151 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2152 CLEANUP;
2153 }
2154 if (hour) {
2155 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2156 CLEANUP;
2157 }
2158 if (day) {
2159 y = accum("days", x, day, us_per_day, &leftover_us);
2160 CLEANUP;
2161 }
2162 if (week) {
2163 y = accum("weeks", x, week, us_per_week, &leftover_us);
2164 CLEANUP;
2165 }
2166 if (leftover_us) {
2167 /* Round to nearest whole # of us, and add into x. */
2168 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
2169 if (temp == NULL) {
2170 Py_DECREF(x);
2171 goto Done;
2172 }
2173 y = PyNumber_Add(x, temp);
2174 Py_DECREF(temp);
2175 CLEANUP;
2176 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 self = microseconds_to_delta_ex(x, type);
2179 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002180Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002182
2183#undef CLEANUP
2184}
2185
2186static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002187delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 return (GET_TD_DAYS(self) != 0
2190 || GET_TD_SECONDS(self) != 0
2191 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002192}
2193
2194static PyObject *
2195delta_repr(PyDateTime_Delta *self)
2196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 if (GET_TD_MICROSECONDS(self) != 0)
2198 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2199 Py_TYPE(self)->tp_name,
2200 GET_TD_DAYS(self),
2201 GET_TD_SECONDS(self),
2202 GET_TD_MICROSECONDS(self));
2203 if (GET_TD_SECONDS(self) != 0)
2204 return PyUnicode_FromFormat("%s(%d, %d)",
2205 Py_TYPE(self)->tp_name,
2206 GET_TD_DAYS(self),
2207 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 return PyUnicode_FromFormat("%s(%d)",
2210 Py_TYPE(self)->tp_name,
2211 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002212}
2213
2214static PyObject *
2215delta_str(PyDateTime_Delta *self)
2216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 int us = GET_TD_MICROSECONDS(self);
2218 int seconds = GET_TD_SECONDS(self);
2219 int minutes = divmod(seconds, 60, &seconds);
2220 int hours = divmod(minutes, 60, &minutes);
2221 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 if (days) {
2224 if (us)
2225 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2226 days, (days == 1 || days == -1) ? "" : "s",
2227 hours, minutes, seconds, us);
2228 else
2229 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2230 days, (days == 1 || days == -1) ? "" : "s",
2231 hours, minutes, seconds);
2232 } else {
2233 if (us)
2234 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2235 hours, minutes, seconds, us);
2236 else
2237 return PyUnicode_FromFormat("%d:%02d:%02d",
2238 hours, minutes, seconds);
2239 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002240
Tim Peters2a799bf2002-12-16 20:18:38 +00002241}
2242
Tim Peters371935f2003-02-01 01:52:50 +00002243/* Pickle support, a simple use of __reduce__. */
2244
Tim Petersb57f8f02003-02-01 02:54:15 +00002245/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002246static PyObject *
2247delta_getstate(PyDateTime_Delta *self)
2248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 return Py_BuildValue("iii", GET_TD_DAYS(self),
2250 GET_TD_SECONDS(self),
2251 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002252}
2253
Tim Peters2a799bf2002-12-16 20:18:38 +00002254static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002255delta_total_seconds(PyObject *self)
2256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 PyObject *total_seconds;
2258 PyObject *total_microseconds;
2259 PyObject *one_million;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2262 if (total_microseconds == NULL)
2263 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 one_million = PyLong_FromLong(1000000L);
2266 if (one_million == NULL) {
2267 Py_DECREF(total_microseconds);
2268 return NULL;
2269 }
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 Py_DECREF(total_microseconds);
2274 Py_DECREF(one_million);
2275 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002276}
2277
2278static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002279delta_reduce(PyDateTime_Delta* self)
2280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002282}
2283
2284#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2285
2286static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 {"days", T_INT, OFFSET(days), READONLY,
2289 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 {"seconds", T_INT, OFFSET(seconds), READONLY,
2292 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2295 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2296 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002297};
2298
2299static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2301 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2304 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002307};
2308
2309static char delta_doc[] =
2310PyDoc_STR("Difference between two datetime values.");
2311
2312static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 delta_add, /* nb_add */
2314 delta_subtract, /* nb_subtract */
2315 delta_multiply, /* nb_multiply */
2316 delta_remainder, /* nb_remainder */
2317 delta_divmod, /* nb_divmod */
2318 0, /* nb_power */
2319 (unaryfunc)delta_negative, /* nb_negative */
2320 (unaryfunc)delta_positive, /* nb_positive */
2321 (unaryfunc)delta_abs, /* nb_absolute */
2322 (inquiry)delta_bool, /* nb_bool */
2323 0, /*nb_invert*/
2324 0, /*nb_lshift*/
2325 0, /*nb_rshift*/
2326 0, /*nb_and*/
2327 0, /*nb_xor*/
2328 0, /*nb_or*/
2329 0, /*nb_int*/
2330 0, /*nb_reserved*/
2331 0, /*nb_float*/
2332 0, /*nb_inplace_add*/
2333 0, /*nb_inplace_subtract*/
2334 0, /*nb_inplace_multiply*/
2335 0, /*nb_inplace_remainder*/
2336 0, /*nb_inplace_power*/
2337 0, /*nb_inplace_lshift*/
2338 0, /*nb_inplace_rshift*/
2339 0, /*nb_inplace_and*/
2340 0, /*nb_inplace_xor*/
2341 0, /*nb_inplace_or*/
2342 delta_divide, /* nb_floor_divide */
2343 delta_truedivide, /* nb_true_divide */
2344 0, /* nb_inplace_floor_divide */
2345 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002346};
2347
2348static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 PyVarObject_HEAD_INIT(NULL, 0)
2350 "datetime.timedelta", /* tp_name */
2351 sizeof(PyDateTime_Delta), /* tp_basicsize */
2352 0, /* tp_itemsize */
2353 0, /* tp_dealloc */
2354 0, /* tp_print */
2355 0, /* tp_getattr */
2356 0, /* tp_setattr */
2357 0, /* tp_reserved */
2358 (reprfunc)delta_repr, /* tp_repr */
2359 &delta_as_number, /* tp_as_number */
2360 0, /* tp_as_sequence */
2361 0, /* tp_as_mapping */
2362 (hashfunc)delta_hash, /* tp_hash */
2363 0, /* tp_call */
2364 (reprfunc)delta_str, /* tp_str */
2365 PyObject_GenericGetAttr, /* tp_getattro */
2366 0, /* tp_setattro */
2367 0, /* tp_as_buffer */
2368 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2369 delta_doc, /* tp_doc */
2370 0, /* tp_traverse */
2371 0, /* tp_clear */
2372 delta_richcompare, /* tp_richcompare */
2373 0, /* tp_weaklistoffset */
2374 0, /* tp_iter */
2375 0, /* tp_iternext */
2376 delta_methods, /* tp_methods */
2377 delta_members, /* tp_members */
2378 0, /* tp_getset */
2379 0, /* tp_base */
2380 0, /* tp_dict */
2381 0, /* tp_descr_get */
2382 0, /* tp_descr_set */
2383 0, /* tp_dictoffset */
2384 0, /* tp_init */
2385 0, /* tp_alloc */
2386 delta_new, /* tp_new */
2387 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002388};
2389
2390/*
2391 * PyDateTime_Date implementation.
2392 */
2393
2394/* Accessor properties. */
2395
2396static PyObject *
2397date_year(PyDateTime_Date *self, void *unused)
2398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002400}
2401
2402static PyObject *
2403date_month(PyDateTime_Date *self, void *unused)
2404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002406}
2407
2408static PyObject *
2409date_day(PyDateTime_Date *self, void *unused)
2410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002412}
2413
2414static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 {"year", (getter)date_year},
2416 {"month", (getter)date_month},
2417 {"day", (getter)date_day},
2418 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002419};
2420
2421/* Constructors. */
2422
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002423static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002424
Tim Peters2a799bf2002-12-16 20:18:38 +00002425static PyObject *
2426date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 PyObject *self = NULL;
2429 PyObject *state;
2430 int year;
2431 int month;
2432 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 /* Check for invocation from pickle with __getstate__ state */
2435 if (PyTuple_GET_SIZE(args) == 1 &&
2436 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2437 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2438 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2439 {
2440 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2443 if (me != NULL) {
2444 char *pdata = PyBytes_AS_STRING(state);
2445 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2446 me->hashcode = -1;
2447 }
2448 return (PyObject *)me;
2449 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2452 &year, &month, &day)) {
2453 if (check_date_args(year, month, day) < 0)
2454 return NULL;
2455 self = new_date_ex(year, month, day, type);
2456 }
2457 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002458}
2459
2460/* Return new date from localtime(t). */
2461static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002462date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 struct tm *tm;
2465 time_t t;
2466 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 t = _PyTime_DoubleToTimet(ts);
2469 if (t == (time_t)-1 && PyErr_Occurred())
2470 return NULL;
2471 tm = localtime(&t);
2472 if (tm)
2473 result = PyObject_CallFunction(cls, "iii",
2474 tm->tm_year + 1900,
2475 tm->tm_mon + 1,
2476 tm->tm_mday);
2477 else
2478 PyErr_SetString(PyExc_ValueError,
2479 "timestamp out of range for "
2480 "platform localtime() function");
2481 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002482}
2483
2484/* Return new date from current time.
2485 * We say this is equivalent to fromtimestamp(time.time()), and the
2486 * only way to be sure of that is to *call* time.time(). That's not
2487 * generally the same as calling C's time.
2488 */
2489static PyObject *
2490date_today(PyObject *cls, PyObject *dummy)
2491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 PyObject *time;
2493 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 time = time_time();
2496 if (time == NULL)
2497 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 /* Note well: today() is a class method, so this may not call
2500 * date.fromtimestamp. For example, it may call
2501 * datetime.fromtimestamp. That's why we need all the accuracy
2502 * time.time() delivers; if someone were gonzo about optimization,
2503 * date.today() could get away with plain C time().
2504 */
2505 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2506 Py_DECREF(time);
2507 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002508}
2509
2510/* Return new date from given timestamp (Python timestamp -- a double). */
2511static PyObject *
2512date_fromtimestamp(PyObject *cls, PyObject *args)
2513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 double timestamp;
2515 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2518 result = date_local_from_time_t(cls, timestamp);
2519 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002520}
2521
2522/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2523 * the ordinal is out of range.
2524 */
2525static PyObject *
2526date_fromordinal(PyObject *cls, PyObject *args)
2527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 PyObject *result = NULL;
2529 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2532 int year;
2533 int month;
2534 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (ordinal < 1)
2537 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2538 ">= 1");
2539 else {
2540 ord_to_ymd(ordinal, &year, &month, &day);
2541 result = PyObject_CallFunction(cls, "iii",
2542 year, month, day);
2543 }
2544 }
2545 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002546}
2547
2548/*
2549 * Date arithmetic.
2550 */
2551
2552/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2553 * instead.
2554 */
2555static PyObject *
2556add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 PyObject *result = NULL;
2559 int year = GET_YEAR(date);
2560 int month = GET_MONTH(date);
2561 int deltadays = GET_TD_DAYS(delta);
2562 /* C-level overflow is impossible because |deltadays| < 1e9. */
2563 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (normalize_date(&year, &month, &day) >= 0)
2566 result = new_date(year, month, day);
2567 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002568}
2569
2570static PyObject *
2571date_add(PyObject *left, PyObject *right)
2572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2574 Py_INCREF(Py_NotImplemented);
2575 return Py_NotImplemented;
2576 }
2577 if (PyDate_Check(left)) {
2578 /* date + ??? */
2579 if (PyDelta_Check(right))
2580 /* date + delta */
2581 return add_date_timedelta((PyDateTime_Date *) left,
2582 (PyDateTime_Delta *) right,
2583 0);
2584 }
2585 else {
2586 /* ??? + date
2587 * 'right' must be one of us, or we wouldn't have been called
2588 */
2589 if (PyDelta_Check(left))
2590 /* delta + date */
2591 return add_date_timedelta((PyDateTime_Date *) right,
2592 (PyDateTime_Delta *) left,
2593 0);
2594 }
2595 Py_INCREF(Py_NotImplemented);
2596 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002597}
2598
2599static PyObject *
2600date_subtract(PyObject *left, PyObject *right)
2601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2603 Py_INCREF(Py_NotImplemented);
2604 return Py_NotImplemented;
2605 }
2606 if (PyDate_Check(left)) {
2607 if (PyDate_Check(right)) {
2608 /* date - date */
2609 int left_ord = ymd_to_ord(GET_YEAR(left),
2610 GET_MONTH(left),
2611 GET_DAY(left));
2612 int right_ord = ymd_to_ord(GET_YEAR(right),
2613 GET_MONTH(right),
2614 GET_DAY(right));
2615 return new_delta(left_ord - right_ord, 0, 0, 0);
2616 }
2617 if (PyDelta_Check(right)) {
2618 /* date - delta */
2619 return add_date_timedelta((PyDateTime_Date *) left,
2620 (PyDateTime_Delta *) right,
2621 1);
2622 }
2623 }
2624 Py_INCREF(Py_NotImplemented);
2625 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002626}
2627
2628
2629/* Various ways to turn a date into a string. */
2630
2631static PyObject *
2632date_repr(PyDateTime_Date *self)
2633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2635 Py_TYPE(self)->tp_name,
2636 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002637}
2638
2639static PyObject *
2640date_isoformat(PyDateTime_Date *self)
2641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 return PyUnicode_FromFormat("%04d-%02d-%02d",
2643 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002644}
2645
Tim Peterse2df5ff2003-05-02 18:39:55 +00002646/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002647static PyObject *
2648date_str(PyDateTime_Date *self)
2649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002651}
2652
2653
2654static PyObject *
2655date_ctime(PyDateTime_Date *self)
2656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002658}
2659
2660static PyObject *
2661date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 /* This method can be inherited, and needs to call the
2664 * timetuple() method appropriate to self's class.
2665 */
2666 PyObject *result;
2667 PyObject *tuple;
2668 PyObject *format;
2669 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2672 &format))
2673 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2676 if (tuple == NULL)
2677 return NULL;
2678 result = wrap_strftime((PyObject *)self, format, tuple,
2679 (PyObject *)self);
2680 Py_DECREF(tuple);
2681 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002682}
2683
Eric Smith1ba31142007-09-11 18:06:02 +00002684static PyObject *
2685date_format(PyDateTime_Date *self, PyObject *args)
2686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2690 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 /* if the format is zero length, return str(self) */
2693 if (PyUnicode_GetSize(format) == 0)
2694 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002697}
2698
Tim Peters2a799bf2002-12-16 20:18:38 +00002699/* ISO methods. */
2700
2701static PyObject *
2702date_isoweekday(PyDateTime_Date *self)
2703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002707}
2708
2709static PyObject *
2710date_isocalendar(PyDateTime_Date *self)
2711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 int year = GET_YEAR(self);
2713 int week1_monday = iso_week1_monday(year);
2714 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2715 int week;
2716 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 week = divmod(today - week1_monday, 7, &day);
2719 if (week < 0) {
2720 --year;
2721 week1_monday = iso_week1_monday(year);
2722 week = divmod(today - week1_monday, 7, &day);
2723 }
2724 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2725 ++year;
2726 week = 0;
2727 }
2728 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002729}
2730
2731/* Miscellaneous methods. */
2732
Tim Peters2a799bf2002-12-16 20:18:38 +00002733static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002734date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 if (PyDate_Check(other)) {
2737 int diff = memcmp(((PyDateTime_Date *)self)->data,
2738 ((PyDateTime_Date *)other)->data,
2739 _PyDateTime_DATE_DATASIZE);
2740 return diff_to_bool(diff, op);
2741 }
2742 else {
2743 Py_INCREF(Py_NotImplemented);
2744 return Py_NotImplemented;
2745 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002746}
2747
2748static PyObject *
2749date_timetuple(PyDateTime_Date *self)
2750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 return build_struct_time(GET_YEAR(self),
2752 GET_MONTH(self),
2753 GET_DAY(self),
2754 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002755}
2756
Tim Peters12bf3392002-12-24 05:41:27 +00002757static PyObject *
2758date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 PyObject *clone;
2761 PyObject *tuple;
2762 int year = GET_YEAR(self);
2763 int month = GET_MONTH(self);
2764 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2767 &year, &month, &day))
2768 return NULL;
2769 tuple = Py_BuildValue("iii", year, month, day);
2770 if (tuple == NULL)
2771 return NULL;
2772 clone = date_new(Py_TYPE(self), tuple, NULL);
2773 Py_DECREF(tuple);
2774 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002775}
2776
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002777/*
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 Borrowed from stringobject.c, originally it was string_hash()
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002779*/
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002780static Py_hash_t
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002781generic_hash(unsigned char *data, int len)
2782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 register unsigned char *p;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002784 register Py_hash_t x;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 p = (unsigned char *) data;
2787 x = *p << 7;
2788 while (--len >= 0)
2789 x = (1000003*x) ^ *p++;
2790 x ^= len;
2791 if (x == -1)
2792 x = -2;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 return x;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002795}
2796
2797
2798static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002799
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002800static Py_hash_t
Tim Peters2a799bf2002-12-16 20:18:38 +00002801date_hash(PyDateTime_Date *self)
2802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 if (self->hashcode == -1)
2804 self->hashcode = generic_hash(
2805 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002808}
2809
2810static PyObject *
2811date_toordinal(PyDateTime_Date *self)
2812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2814 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002815}
2816
2817static PyObject *
2818date_weekday(PyDateTime_Date *self)
2819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002823}
2824
Tim Peters371935f2003-02-01 01:52:50 +00002825/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002826
Tim Petersb57f8f02003-02-01 02:54:15 +00002827/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002828static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002829date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 PyObject* field;
2832 field = PyBytes_FromStringAndSize((char*)self->data,
2833 _PyDateTime_DATE_DATASIZE);
2834 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002835}
2836
2837static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002838date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002841}
2842
2843static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2848 METH_CLASS,
2849 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2850 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2853 METH_CLASS,
2854 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2855 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2858 PyDoc_STR("Current date or datetime: same as "
2859 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2864 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2867 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2870 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2873 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2876 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2877 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2880 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2883 PyDoc_STR("Return the day of the week represented by the date.\n"
2884 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2887 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2888 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2891 PyDoc_STR("Return the day of the week represented by the date.\n"
2892 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2895 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2898 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002901};
2902
2903static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002904PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002905
2906static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 date_add, /* nb_add */
2908 date_subtract, /* nb_subtract */
2909 0, /* nb_multiply */
2910 0, /* nb_remainder */
2911 0, /* nb_divmod */
2912 0, /* nb_power */
2913 0, /* nb_negative */
2914 0, /* nb_positive */
2915 0, /* nb_absolute */
2916 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002917};
2918
2919static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 PyVarObject_HEAD_INIT(NULL, 0)
2921 "datetime.date", /* tp_name */
2922 sizeof(PyDateTime_Date), /* tp_basicsize */
2923 0, /* tp_itemsize */
2924 0, /* tp_dealloc */
2925 0, /* tp_print */
2926 0, /* tp_getattr */
2927 0, /* tp_setattr */
2928 0, /* tp_reserved */
2929 (reprfunc)date_repr, /* tp_repr */
2930 &date_as_number, /* tp_as_number */
2931 0, /* tp_as_sequence */
2932 0, /* tp_as_mapping */
2933 (hashfunc)date_hash, /* tp_hash */
2934 0, /* tp_call */
2935 (reprfunc)date_str, /* tp_str */
2936 PyObject_GenericGetAttr, /* tp_getattro */
2937 0, /* tp_setattro */
2938 0, /* tp_as_buffer */
2939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2940 date_doc, /* tp_doc */
2941 0, /* tp_traverse */
2942 0, /* tp_clear */
2943 date_richcompare, /* tp_richcompare */
2944 0, /* tp_weaklistoffset */
2945 0, /* tp_iter */
2946 0, /* tp_iternext */
2947 date_methods, /* tp_methods */
2948 0, /* tp_members */
2949 date_getset, /* tp_getset */
2950 0, /* tp_base */
2951 0, /* tp_dict */
2952 0, /* tp_descr_get */
2953 0, /* tp_descr_set */
2954 0, /* tp_dictoffset */
2955 0, /* tp_init */
2956 0, /* tp_alloc */
2957 date_new, /* tp_new */
2958 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002959};
2960
2961/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002962 * PyDateTime_TZInfo implementation.
2963 */
2964
2965/* This is a pure abstract base class, so doesn't do anything beyond
2966 * raising NotImplemented exceptions. Real tzinfo classes need
2967 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002968 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002969 * be subclasses of this tzinfo class, which is easy and quick to check).
2970 *
2971 * Note: For reasons having to do with pickling of subclasses, we have
2972 * to allow tzinfo objects to be instantiated. This wasn't an issue
2973 * in the Python implementation (__init__() could raise NotImplementedError
2974 * there without ill effect), but doing so in the C implementation hit a
2975 * brick wall.
2976 */
2977
2978static PyObject *
2979tzinfo_nogo(const char* methodname)
2980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 PyErr_Format(PyExc_NotImplementedError,
2982 "a tzinfo subclass must implement %s()",
2983 methodname);
2984 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002985}
2986
2987/* Methods. A subclass must implement these. */
2988
Tim Peters52dcce22003-01-23 16:36:11 +00002989static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002990tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00002993}
2994
Tim Peters52dcce22003-01-23 16:36:11 +00002995static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002996tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00002999}
3000
Tim Peters52dcce22003-01-23 16:36:11 +00003001static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003002tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003005}
3006
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003007
3008static PyObject *add_datetime_timedelta(PyDateTime_DateTime *date,
3009 PyDateTime_Delta *delta,
3010 int factor);
3011static PyObject *datetime_utcoffset(PyObject *self, PyObject *);
3012static PyObject *datetime_dst(PyObject *self, PyObject *);
3013
Tim Peters52dcce22003-01-23 16:36:11 +00003014static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003015tzinfo_fromutc(PyDateTime_TZInfo *self, PyObject *dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003016{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003017 PyObject *result = NULL;
3018 PyObject *off = NULL, *dst = NULL;
3019 PyDateTime_Delta *delta = NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003020
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003021 if (!PyDateTime_Check(dt)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 PyErr_SetString(PyExc_TypeError,
3023 "fromutc: argument must be a datetime");
3024 return NULL;
3025 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003026 if (GET_DT_TZINFO(dt) != (PyObject *)self) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3028 "is not self");
3029 return NULL;
3030 }
Tim Peters52dcce22003-01-23 16:36:11 +00003031
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003032 off = datetime_utcoffset(dt, NULL);
3033 if (off == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003035 if (off == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3037 "utcoffset() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003038 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 }
Tim Peters52dcce22003-01-23 16:36:11 +00003040
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003041 dst = datetime_dst(dt, NULL);
3042 if (dst == NULL)
3043 goto Fail;
3044 if (dst == Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3046 "dst() result required");
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003047 goto Fail;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 }
Tim Peters52dcce22003-01-23 16:36:11 +00003049
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003050 delta = (PyDateTime_Delta *)delta_subtract(off, dst);
3051 if (delta == NULL)
3052 goto Fail;
3053 result = add_datetime_timedelta((PyDateTime_DateTime *)dt, delta, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 goto Fail;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003056
3057 Py_DECREF(dst);
3058 dst = call_dst(GET_DT_TZINFO(dt), result);
3059 if (dst == NULL)
3060 goto Fail;
3061 if (dst == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 goto Inconsistent;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003063 if (delta_bool(delta) != 0) {
3064 PyObject *temp = result;
3065 result = add_datetime_timedelta((PyDateTime_DateTime *)result,
3066 (PyDateTime_Delta *)dst, 1);
3067 Py_DECREF(temp);
3068 if (result == NULL)
3069 goto Fail;
3070 }
3071 Py_DECREF(delta);
3072 Py_DECREF(dst);
3073 Py_DECREF(off);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003075
3076Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3078 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003081Fail:
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003082 Py_XDECREF(off);
3083 Py_XDECREF(dst);
3084 Py_XDECREF(delta);
3085 Py_XDECREF(result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003087}
3088
Tim Peters2a799bf2002-12-16 20:18:38 +00003089/*
3090 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003091 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003092 */
3093
Guido van Rossum177e41a2003-01-30 22:06:23 +00003094static PyObject *
3095tzinfo_reduce(PyObject *self)
3096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 PyObject *args, *state, *tmp;
3098 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 tmp = PyTuple_New(0);
3101 if (tmp == NULL)
3102 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
3105 if (getinitargs != NULL) {
3106 args = PyObject_CallObject(getinitargs, tmp);
3107 Py_DECREF(getinitargs);
3108 if (args == NULL) {
3109 Py_DECREF(tmp);
3110 return NULL;
3111 }
3112 }
3113 else {
3114 PyErr_Clear();
3115 args = tmp;
3116 Py_INCREF(args);
3117 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 getstate = PyObject_GetAttrString(self, "__getstate__");
3120 if (getstate != NULL) {
3121 state = PyObject_CallObject(getstate, tmp);
3122 Py_DECREF(getstate);
3123 if (state == NULL) {
3124 Py_DECREF(args);
3125 Py_DECREF(tmp);
3126 return NULL;
3127 }
3128 }
3129 else {
3130 PyObject **dictptr;
3131 PyErr_Clear();
3132 state = Py_None;
3133 dictptr = _PyObject_GetDictPtr(self);
3134 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3135 state = *dictptr;
3136 Py_INCREF(state);
3137 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 if (state == Py_None) {
3142 Py_DECREF(state);
3143 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3144 }
3145 else
3146 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003147}
Tim Peters2a799bf2002-12-16 20:18:38 +00003148
3149static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3152 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003155 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3156 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3159 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
Alexander Belopolsky2f194b92010-07-03 03:35:27 +00003162 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3165 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003168};
3169
3170static char tzinfo_doc[] =
3171PyDoc_STR("Abstract base class for time zone info objects.");
3172
Neal Norwitz227b5332006-03-22 09:28:35 +00003173static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 PyVarObject_HEAD_INIT(NULL, 0)
3175 "datetime.tzinfo", /* tp_name */
3176 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3177 0, /* tp_itemsize */
3178 0, /* tp_dealloc */
3179 0, /* tp_print */
3180 0, /* tp_getattr */
3181 0, /* tp_setattr */
3182 0, /* tp_reserved */
3183 0, /* tp_repr */
3184 0, /* tp_as_number */
3185 0, /* tp_as_sequence */
3186 0, /* tp_as_mapping */
3187 0, /* tp_hash */
3188 0, /* tp_call */
3189 0, /* tp_str */
3190 PyObject_GenericGetAttr, /* tp_getattro */
3191 0, /* tp_setattro */
3192 0, /* tp_as_buffer */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003193 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 tzinfo_doc, /* tp_doc */
3195 0, /* tp_traverse */
3196 0, /* tp_clear */
3197 0, /* tp_richcompare */
3198 0, /* tp_weaklistoffset */
3199 0, /* tp_iter */
3200 0, /* tp_iternext */
3201 tzinfo_methods, /* tp_methods */
3202 0, /* tp_members */
3203 0, /* tp_getset */
3204 0, /* tp_base */
3205 0, /* tp_dict */
3206 0, /* tp_descr_get */
3207 0, /* tp_descr_set */
3208 0, /* tp_dictoffset */
3209 0, /* tp_init */
3210 0, /* tp_alloc */
3211 PyType_GenericNew, /* tp_new */
3212 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003213};
3214
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003215static char *timezone_kws[] = {"offset", "name", NULL};
3216
3217static PyObject *
3218timezone_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3219{
3220 PyObject *offset;
3221 PyObject *name = NULL;
3222 if (PyArg_ParseTupleAndKeywords(args, kw, "O!|O!:timezone", timezone_kws,
3223 &PyDateTime_DeltaType, &offset,
3224 &PyUnicode_Type, &name))
3225 return new_timezone(offset, name);
3226
3227 return NULL;
3228}
3229
3230static void
3231timezone_dealloc(PyDateTime_TimeZone *self)
3232{
3233 Py_CLEAR(self->offset);
3234 Py_CLEAR(self->name);
3235 Py_TYPE(self)->tp_free((PyObject *)self);
3236}
3237
3238static PyObject *
3239timezone_richcompare(PyDateTime_TimeZone *self,
3240 PyDateTime_TimeZone *other, int op)
3241{
3242 if (op != Py_EQ && op != Py_NE) {
3243 Py_INCREF(Py_NotImplemented);
3244 return Py_NotImplemented;
3245 }
3246 return delta_richcompare(self->offset, other->offset, op);
3247}
3248
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003249static Py_hash_t
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003250timezone_hash(PyDateTime_TimeZone *self)
3251{
3252 return delta_hash((PyDateTime_Delta *)self->offset);
3253}
3254
3255/* Check argument type passed to tzname, utcoffset, or dst methods.
3256 Returns 0 for good argument. Returns -1 and sets exception info
3257 otherwise.
3258 */
3259static int
3260_timezone_check_argument(PyObject *dt, const char *meth)
3261{
3262 if (dt == Py_None || PyDateTime_Check(dt))
3263 return 0;
3264 PyErr_Format(PyExc_TypeError, "%s(dt) argument must be a datetime instance"
3265 " or None, not %.200s", meth, Py_TYPE(dt)->tp_name);
3266 return -1;
3267}
3268
3269static PyObject *
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003270timezone_repr(PyDateTime_TimeZone *self)
3271{
3272 /* Note that although timezone is not subclassable, it is convenient
3273 to use Py_TYPE(self)->tp_name here. */
3274 const char *type_name = Py_TYPE(self)->tp_name;
3275
3276 if (((PyObject *)self) == PyDateTime_TimeZone_UTC)
3277 return PyUnicode_FromFormat("%s.utc", type_name);
3278
3279 if (self->name == NULL)
3280 return PyUnicode_FromFormat("%s(%R)", type_name, self->offset);
3281
3282 return PyUnicode_FromFormat("%s(%R, %R)", type_name, self->offset,
3283 self->name);
3284}
3285
3286
3287static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003288timezone_str(PyDateTime_TimeZone *self)
3289{
3290 char buf[10];
3291 int hours, minutes, seconds;
3292 PyObject *offset;
3293 char sign;
3294
3295 if (self->name != NULL) {
3296 Py_INCREF(self->name);
3297 return self->name;
3298 }
3299 /* Offset is normalized, so it is negative if days < 0 */
3300 if (GET_TD_DAYS(self->offset) < 0) {
3301 sign = '-';
3302 offset = delta_negative((PyDateTime_Delta *)self->offset);
3303 if (offset == NULL)
3304 return NULL;
3305 }
3306 else {
3307 sign = '+';
3308 offset = self->offset;
3309 Py_INCREF(offset);
3310 }
3311 /* Offset is not negative here. */
3312 seconds = GET_TD_SECONDS(offset);
3313 Py_DECREF(offset);
3314 minutes = divmod(seconds, 60, &seconds);
3315 hours = divmod(minutes, 60, &minutes);
3316 assert(seconds == 0);
3317 /* XXX ignore sub-minute data, curently not allowed. */
3318 PyOS_snprintf(buf, sizeof(buf), "UTC%c%02d:%02d", sign, hours, minutes);
3319
3320 return PyUnicode_FromString(buf);
3321}
3322
3323static PyObject *
3324timezone_tzname(PyDateTime_TimeZone *self, PyObject *dt)
3325{
3326 if (_timezone_check_argument(dt, "tzname") == -1)
3327 return NULL;
3328
3329 return timezone_str(self);
3330}
3331
3332static PyObject *
3333timezone_utcoffset(PyDateTime_TimeZone *self, PyObject *dt)
3334{
3335 if (_timezone_check_argument(dt, "utcoffset") == -1)
3336 return NULL;
3337
3338 Py_INCREF(self->offset);
3339 return self->offset;
3340}
3341
3342static PyObject *
3343timezone_dst(PyObject *self, PyObject *dt)
3344{
3345 if (_timezone_check_argument(dt, "dst") == -1)
3346 return NULL;
3347
3348 Py_RETURN_NONE;
3349}
3350
3351static PyObject *
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003352timezone_fromutc(PyDateTime_TimeZone *self, PyDateTime_DateTime *dt)
3353{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003354 if (!PyDateTime_Check(dt)) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003355 PyErr_SetString(PyExc_TypeError,
3356 "fromutc: argument must be a datetime");
3357 return NULL;
3358 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003359 if (!HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003360 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3361 "is not self");
3362 return NULL;
3363 }
3364
3365 return add_datetime_timedelta(dt, (PyDateTime_Delta *)self->offset, 1);
3366}
3367
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003368static PyObject *
3369timezone_getinitargs(PyDateTime_TimeZone *self)
3370{
3371 if (self->name == NULL)
3372 return Py_BuildValue("(O)", self->offset);
3373 return Py_BuildValue("(OO)", self->offset, self->name);
3374}
3375
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003376static PyMethodDef timezone_methods[] = {
3377 {"tzname", (PyCFunction)timezone_tzname, METH_O,
3378 PyDoc_STR("If name is specified when timezone is created, returns the name."
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003379 " Otherwise returns offset as 'UTC(+|-)HH:MM'.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003380
3381 {"utcoffset", (PyCFunction)timezone_utcoffset, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003382 PyDoc_STR("Return fixed offset.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003383
3384 {"dst", (PyCFunction)timezone_dst, METH_O,
Alexander Belopolskyb39a0c22010-06-15 19:24:52 +00003385 PyDoc_STR("Return None.")},
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003386
3387 {"fromutc", (PyCFunction)timezone_fromutc, METH_O,
3388 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3389
Alexander Belopolsky1b7046b2010-06-23 21:40:15 +00003390 {"__getinitargs__", (PyCFunction)timezone_getinitargs, METH_NOARGS,
3391 PyDoc_STR("pickle support")},
3392
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003393 {NULL, NULL}
3394};
3395
3396static char timezone_doc[] =
3397PyDoc_STR("Fixed offset from UTC implementation of tzinfo.");
3398
3399static PyTypeObject PyDateTime_TimeZoneType = {
3400 PyVarObject_HEAD_INIT(NULL, 0)
3401 "datetime.timezone", /* tp_name */
3402 sizeof(PyDateTime_TimeZone), /* tp_basicsize */
3403 0, /* tp_itemsize */
3404 (destructor)timezone_dealloc, /* tp_dealloc */
3405 0, /* tp_print */
3406 0, /* tp_getattr */
3407 0, /* tp_setattr */
3408 0, /* tp_reserved */
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00003409 (reprfunc)timezone_repr, /* tp_repr */
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00003410 0, /* tp_as_number */
3411 0, /* tp_as_sequence */
3412 0, /* tp_as_mapping */
3413 (hashfunc)timezone_hash, /* tp_hash */
3414 0, /* tp_call */
3415 (reprfunc)timezone_str, /* tp_str */
3416 0, /* tp_getattro */
3417 0, /* tp_setattro */
3418 0, /* tp_as_buffer */
3419 Py_TPFLAGS_DEFAULT, /* tp_flags */
3420 timezone_doc, /* tp_doc */
3421 0, /* tp_traverse */
3422 0, /* tp_clear */
3423 (richcmpfunc)timezone_richcompare,/* tp_richcompare */
3424 0, /* tp_weaklistoffset */
3425 0, /* tp_iter */
3426 0, /* tp_iternext */
3427 timezone_methods, /* tp_methods */
3428 0, /* tp_members */
3429 0, /* tp_getset */
3430 &PyDateTime_TZInfoType, /* tp_base */
3431 0, /* tp_dict */
3432 0, /* tp_descr_get */
3433 0, /* tp_descr_set */
3434 0, /* tp_dictoffset */
3435 0, /* tp_init */
3436 0, /* tp_alloc */
3437 timezone_new, /* tp_new */
3438};
3439
Tim Peters2a799bf2002-12-16 20:18:38 +00003440/*
Tim Peters37f39822003-01-10 03:49:02 +00003441 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003442 */
3443
Tim Peters37f39822003-01-10 03:49:02 +00003444/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003445 */
3446
3447static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003448time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003451}
3452
Tim Peters37f39822003-01-10 03:49:02 +00003453static PyObject *
3454time_minute(PyDateTime_Time *self, void *unused)
3455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003457}
3458
3459/* The name time_second conflicted with some platform header file. */
3460static PyObject *
3461py_time_second(PyDateTime_Time *self, void *unused)
3462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003464}
3465
3466static PyObject *
3467time_microsecond(PyDateTime_Time *self, void *unused)
3468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003470}
3471
3472static PyObject *
3473time_tzinfo(PyDateTime_Time *self, void *unused)
3474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3476 Py_INCREF(result);
3477 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003478}
3479
3480static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 {"hour", (getter)time_hour},
3482 {"minute", (getter)time_minute},
3483 {"second", (getter)py_time_second},
3484 {"microsecond", (getter)time_microsecond},
3485 {"tzinfo", (getter)time_tzinfo},
3486 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003487};
3488
3489/*
3490 * Constructors.
3491 */
3492
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003493static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003495
Tim Peters2a799bf2002-12-16 20:18:38 +00003496static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003497time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 PyObject *self = NULL;
3500 PyObject *state;
3501 int hour = 0;
3502 int minute = 0;
3503 int second = 0;
3504 int usecond = 0;
3505 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 /* Check for invocation from pickle with __getstate__ state */
3508 if (PyTuple_GET_SIZE(args) >= 1 &&
3509 PyTuple_GET_SIZE(args) <= 2 &&
3510 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3511 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3512 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
3513 {
3514 PyDateTime_Time *me;
3515 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 if (PyTuple_GET_SIZE(args) == 2) {
3518 tzinfo = PyTuple_GET_ITEM(args, 1);
3519 if (check_tzinfo_subclass(tzinfo) < 0) {
3520 PyErr_SetString(PyExc_TypeError, "bad "
3521 "tzinfo state arg");
3522 return NULL;
3523 }
3524 }
3525 aware = (char)(tzinfo != Py_None);
3526 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3527 if (me != NULL) {
3528 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3531 me->hashcode = -1;
3532 me->hastzinfo = aware;
3533 if (aware) {
3534 Py_INCREF(tzinfo);
3535 me->tzinfo = tzinfo;
3536 }
3537 }
3538 return (PyObject *)me;
3539 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3542 &hour, &minute, &second, &usecond,
3543 &tzinfo)) {
3544 if (check_time_args(hour, minute, second, usecond) < 0)
3545 return NULL;
3546 if (check_tzinfo_subclass(tzinfo) < 0)
3547 return NULL;
3548 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3549 type);
3550 }
3551 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003552}
3553
3554/*
3555 * Destructor.
3556 */
3557
3558static void
Tim Peters37f39822003-01-10 03:49:02 +00003559time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 if (HASTZINFO(self)) {
3562 Py_XDECREF(self->tzinfo);
3563 }
3564 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003565}
3566
3567/*
Tim Peters855fe882002-12-22 03:43:39 +00003568 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003569 */
3570
Tim Peters2a799bf2002-12-16 20:18:38 +00003571/* These are all METH_NOARGS, so don't need to check the arglist. */
3572static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003573time_utcoffset(PyObject *self, PyObject *unused) {
3574 return call_utcoffset(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003575}
3576
3577static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003578time_dst(PyObject *self, PyObject *unused) {
3579 return call_dst(GET_TIME_TZINFO(self), Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003580}
3581
3582static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003583time_tzname(PyDateTime_Time *self, PyObject *unused) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003584 return call_tzname(GET_TIME_TZINFO(self), Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003585}
3586
3587/*
Tim Peters37f39822003-01-10 03:49:02 +00003588 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003589 */
3590
3591static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003592time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 const char *type_name = Py_TYPE(self)->tp_name;
3595 int h = TIME_GET_HOUR(self);
3596 int m = TIME_GET_MINUTE(self);
3597 int s = TIME_GET_SECOND(self);
3598 int us = TIME_GET_MICROSECOND(self);
3599 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 if (us)
3602 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3603 type_name, h, m, s, us);
3604 else if (s)
3605 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3606 type_name, h, m, s);
3607 else
3608 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3609 if (result != NULL && HASTZINFO(self))
3610 result = append_keyword_tzinfo(result, self->tzinfo);
3611 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003612}
3613
Tim Peters37f39822003-01-10 03:49:02 +00003614static PyObject *
3615time_str(PyDateTime_Time *self)
3616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters37f39822003-01-10 03:49:02 +00003618}
Tim Peters2a799bf2002-12-16 20:18:38 +00003619
3620static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003621time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 char buf[100];
3624 PyObject *result;
3625 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 if (us)
3628 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3629 TIME_GET_HOUR(self),
3630 TIME_GET_MINUTE(self),
3631 TIME_GET_SECOND(self),
3632 us);
3633 else
3634 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3635 TIME_GET_HOUR(self),
3636 TIME_GET_MINUTE(self),
3637 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003638
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003639 if (result == NULL || !HASTZINFO(self) || self->tzinfo == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 /* We need to append the UTC offset. */
3643 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3644 Py_None) < 0) {
3645 Py_DECREF(result);
3646 return NULL;
3647 }
3648 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3649 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003650}
3651
Tim Peters37f39822003-01-10 03:49:02 +00003652static PyObject *
3653time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 PyObject *result;
3656 PyObject *tuple;
3657 PyObject *format;
3658 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3661 &format))
3662 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 /* Python's strftime does insane things with the year part of the
3665 * timetuple. The year is forced to (the otherwise nonsensical)
3666 * 1900 to worm around that.
3667 */
3668 tuple = Py_BuildValue("iiiiiiiii",
3669 1900, 1, 1, /* year, month, day */
3670 TIME_GET_HOUR(self),
3671 TIME_GET_MINUTE(self),
3672 TIME_GET_SECOND(self),
3673 0, 1, -1); /* weekday, daynum, dst */
3674 if (tuple == NULL)
3675 return NULL;
3676 assert(PyTuple_Size(tuple) == 9);
3677 result = wrap_strftime((PyObject *)self, format, tuple,
3678 Py_None);
3679 Py_DECREF(tuple);
3680 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003681}
Tim Peters2a799bf2002-12-16 20:18:38 +00003682
3683/*
3684 * Miscellaneous methods.
3685 */
3686
Tim Peters37f39822003-01-10 03:49:02 +00003687static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003688time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003689{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003690 PyObject *result = NULL;
3691 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 int diff;
Tim Peters37f39822003-01-10 03:49:02 +00003693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 if (! PyTime_Check(other)) {
3695 Py_INCREF(Py_NotImplemented);
3696 return Py_NotImplemented;
3697 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003698
3699 if (GET_TIME_TZINFO(self) == GET_TIME_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 diff = memcmp(((PyDateTime_Time *)self)->data,
3701 ((PyDateTime_Time *)other)->data,
3702 _PyDateTime_TIME_DATASIZE);
3703 return diff_to_bool(diff, op);
3704 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003705 offset1 = time_utcoffset(self, NULL);
3706 if (offset1 == NULL)
3707 return NULL;
3708 offset2 = time_utcoffset(other, NULL);
3709 if (offset2 == NULL)
3710 goto done;
3711 /* If they're both naive, or both aware and have the same offsets,
3712 * we get off cheap. Note that if they're both naive, offset1 ==
3713 * offset2 == Py_None at this point.
3714 */
3715 if ((offset1 == offset2) ||
3716 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
3717 delta_cmp(offset1, offset2) == 0)) {
3718 diff = memcmp(((PyDateTime_Time *)self)->data,
3719 ((PyDateTime_Time *)other)->data,
3720 _PyDateTime_TIME_DATASIZE);
3721 result = diff_to_bool(diff, op);
3722 }
3723 /* The hard case: both aware with different UTC offsets */
3724 else if (offset1 != Py_None && offset2 != Py_None) {
3725 int offsecs1, offsecs2;
3726 assert(offset1 != offset2); /* else last "if" handled it */
3727 offsecs1 = TIME_GET_HOUR(self) * 3600 +
3728 TIME_GET_MINUTE(self) * 60 +
3729 TIME_GET_SECOND(self) -
3730 GET_TD_DAYS(offset1) * 86400 -
3731 GET_TD_SECONDS(offset1);
3732 offsecs2 = TIME_GET_HOUR(other) * 3600 +
3733 TIME_GET_MINUTE(other) * 60 +
3734 TIME_GET_SECOND(other) -
3735 GET_TD_DAYS(offset2) * 86400 -
3736 GET_TD_SECONDS(offset2);
3737 diff = offsecs1 - offsecs2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 if (diff == 0)
3739 diff = TIME_GET_MICROSECOND(self) -
3740 TIME_GET_MICROSECOND(other);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003741 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003743 else {
3744 PyErr_SetString(PyExc_TypeError,
3745 "can't compare offset-naive and "
3746 "offset-aware times");
3747 }
3748 done:
3749 Py_DECREF(offset1);
3750 Py_XDECREF(offset2);
3751 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003752}
3753
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003754static Py_hash_t
Tim Peters37f39822003-01-10 03:49:02 +00003755time_hash(PyDateTime_Time *self)
3756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003758 PyObject *offset;
Tim Peters37f39822003-01-10 03:49:02 +00003759
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003760 offset = time_utcoffset((PyObject *)self, NULL);
3761
3762 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003766 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 self->hashcode = generic_hash(
3768 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003770 PyObject *temp1, *temp2;
3771 int seconds, microseconds;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 assert(HASTZINFO(self));
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003773 seconds = TIME_GET_HOUR(self) * 3600 +
3774 TIME_GET_MINUTE(self) * 60 +
3775 TIME_GET_SECOND(self);
3776 microseconds = TIME_GET_MICROSECOND(self);
3777 temp1 = new_delta(0, seconds, microseconds, 1);
3778 if (temp1 == NULL) {
3779 Py_DECREF(offset);
3780 return -1;
3781 }
3782 temp2 = delta_subtract(temp1, offset);
3783 Py_DECREF(temp1);
3784 if (temp2 == NULL) {
3785 Py_DECREF(offset);
3786 return -1;
3787 }
3788 self->hashcode = PyObject_Hash(temp2);
3789 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003791 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 }
3793 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003794}
Tim Peters2a799bf2002-12-16 20:18:38 +00003795
Tim Peters12bf3392002-12-24 05:41:27 +00003796static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003797time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 PyObject *clone;
3800 PyObject *tuple;
3801 int hh = TIME_GET_HOUR(self);
3802 int mm = TIME_GET_MINUTE(self);
3803 int ss = TIME_GET_SECOND(self);
3804 int us = TIME_GET_MICROSECOND(self);
3805 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3808 time_kws,
3809 &hh, &mm, &ss, &us, &tzinfo))
3810 return NULL;
3811 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3812 if (tuple == NULL)
3813 return NULL;
3814 clone = time_new(Py_TYPE(self), tuple, NULL);
3815 Py_DECREF(tuple);
3816 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003817}
3818
Tim Peters2a799bf2002-12-16 20:18:38 +00003819static int
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003820time_bool(PyObject *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003821{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003822 PyObject *offset, *tzinfo;
3823 int offsecs = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3826 /* Since utcoffset is in whole minutes, nothing can
3827 * alter the conclusion that this is nonzero.
3828 */
3829 return 1;
3830 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003831 tzinfo = GET_TIME_TZINFO(self);
3832 if (tzinfo != Py_None) {
3833 offset = call_utcoffset(tzinfo, Py_None);
3834 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 return -1;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003836 offsecs = GET_TD_DAYS(offset)*86400 + GET_TD_SECONDS(offset);
3837 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00003839 return (TIME_GET_MINUTE(self)*60 - offsecs + TIME_GET_HOUR(self)*3600) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003840}
3841
Tim Peters371935f2003-02-01 01:52:50 +00003842/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003843
Tim Peters33e0f382003-01-10 02:05:14 +00003844/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003845 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3846 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003847 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003848 */
3849static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003850time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 PyObject *basestate;
3853 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 basestate = PyBytes_FromStringAndSize((char *)self->data,
3856 _PyDateTime_TIME_DATASIZE);
3857 if (basestate != NULL) {
3858 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3859 result = PyTuple_Pack(1, basestate);
3860 else
3861 result = PyTuple_Pack(2, basestate, self->tzinfo);
3862 Py_DECREF(basestate);
3863 }
3864 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003865}
3866
3867static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003868time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003871}
3872
Tim Peters37f39822003-01-10 03:49:02 +00003873static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3876 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3877 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3880 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3883 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3886 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3889 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3892 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3895 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3898 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003901};
3902
Tim Peters37f39822003-01-10 03:49:02 +00003903static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003904PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3905\n\
3906All arguments are optional. tzinfo may be None, or an instance of\n\
3907a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003908
Tim Peters37f39822003-01-10 03:49:02 +00003909static PyNumberMethods time_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 0, /* nb_add */
3911 0, /* nb_subtract */
3912 0, /* nb_multiply */
3913 0, /* nb_remainder */
3914 0, /* nb_divmod */
3915 0, /* nb_power */
3916 0, /* nb_negative */
3917 0, /* nb_positive */
3918 0, /* nb_absolute */
3919 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003920};
3921
Neal Norwitz227b5332006-03-22 09:28:35 +00003922static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 PyVarObject_HEAD_INIT(NULL, 0)
3924 "datetime.time", /* tp_name */
3925 sizeof(PyDateTime_Time), /* tp_basicsize */
3926 0, /* tp_itemsize */
3927 (destructor)time_dealloc, /* tp_dealloc */
3928 0, /* tp_print */
3929 0, /* tp_getattr */
3930 0, /* tp_setattr */
3931 0, /* tp_reserved */
3932 (reprfunc)time_repr, /* tp_repr */
3933 &time_as_number, /* tp_as_number */
3934 0, /* tp_as_sequence */
3935 0, /* tp_as_mapping */
3936 (hashfunc)time_hash, /* tp_hash */
3937 0, /* tp_call */
3938 (reprfunc)time_str, /* tp_str */
3939 PyObject_GenericGetAttr, /* tp_getattro */
3940 0, /* tp_setattro */
3941 0, /* tp_as_buffer */
3942 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3943 time_doc, /* tp_doc */
3944 0, /* tp_traverse */
3945 0, /* tp_clear */
3946 time_richcompare, /* tp_richcompare */
3947 0, /* tp_weaklistoffset */
3948 0, /* tp_iter */
3949 0, /* tp_iternext */
3950 time_methods, /* tp_methods */
3951 0, /* tp_members */
3952 time_getset, /* tp_getset */
3953 0, /* tp_base */
3954 0, /* tp_dict */
3955 0, /* tp_descr_get */
3956 0, /* tp_descr_set */
3957 0, /* tp_dictoffset */
3958 0, /* tp_init */
3959 time_alloc, /* tp_alloc */
3960 time_new, /* tp_new */
3961 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003962};
3963
3964/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003965 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003966 */
3967
Tim Petersa9bc1682003-01-11 03:39:11 +00003968/* Accessor properties. Properties for day, month, and year are inherited
3969 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003970 */
3971
3972static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003973datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003976}
3977
Tim Petersa9bc1682003-01-11 03:39:11 +00003978static PyObject *
3979datetime_minute(PyDateTime_DateTime *self, void *unused)
3980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003982}
3983
3984static PyObject *
3985datetime_second(PyDateTime_DateTime *self, void *unused)
3986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003988}
3989
3990static PyObject *
3991datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003994}
3995
3996static PyObject *
3997datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
4000 Py_INCREF(result);
4001 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004002}
4003
4004static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 {"hour", (getter)datetime_hour},
4006 {"minute", (getter)datetime_minute},
4007 {"second", (getter)datetime_second},
4008 {"microsecond", (getter)datetime_microsecond},
4009 {"tzinfo", (getter)datetime_tzinfo},
4010 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004011};
4012
4013/*
4014 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00004015 */
4016
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004017static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 "year", "month", "day", "hour", "minute", "second",
4019 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00004020};
4021
Tim Peters2a799bf2002-12-16 20:18:38 +00004022static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004023datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 PyObject *self = NULL;
4026 PyObject *state;
4027 int year;
4028 int month;
4029 int day;
4030 int hour = 0;
4031 int minute = 0;
4032 int second = 0;
4033 int usecond = 0;
4034 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00004035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 /* Check for invocation from pickle with __getstate__ state */
4037 if (PyTuple_GET_SIZE(args) >= 1 &&
4038 PyTuple_GET_SIZE(args) <= 2 &&
4039 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
4040 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
4041 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
4042 {
4043 PyDateTime_DateTime *me;
4044 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 if (PyTuple_GET_SIZE(args) == 2) {
4047 tzinfo = PyTuple_GET_ITEM(args, 1);
4048 if (check_tzinfo_subclass(tzinfo) < 0) {
4049 PyErr_SetString(PyExc_TypeError, "bad "
4050 "tzinfo state arg");
4051 return NULL;
4052 }
4053 }
4054 aware = (char)(tzinfo != Py_None);
4055 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
4056 if (me != NULL) {
4057 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00004058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
4060 me->hashcode = -1;
4061 me->hastzinfo = aware;
4062 if (aware) {
4063 Py_INCREF(tzinfo);
4064 me->tzinfo = tzinfo;
4065 }
4066 }
4067 return (PyObject *)me;
4068 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00004069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004070 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
4071 &year, &month, &day, &hour, &minute,
4072 &second, &usecond, &tzinfo)) {
4073 if (check_date_args(year, month, day) < 0)
4074 return NULL;
4075 if (check_time_args(hour, minute, second, usecond) < 0)
4076 return NULL;
4077 if (check_tzinfo_subclass(tzinfo) < 0)
4078 return NULL;
4079 self = new_datetime_ex(year, month, day,
4080 hour, minute, second, usecond,
4081 tzinfo, type);
4082 }
4083 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004084}
4085
Tim Petersa9bc1682003-01-11 03:39:11 +00004086/* TM_FUNC is the shared type of localtime() and gmtime(). */
4087typedef struct tm *(*TM_FUNC)(const time_t *timer);
4088
4089/* Internal helper.
4090 * Build datetime from a time_t and a distinct count of microseconds.
4091 * Pass localtime or gmtime for f, to control the interpretation of timet.
4092 */
4093static PyObject *
4094datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004095 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 struct tm *tm;
4098 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 tm = f(&timet);
4101 if (tm) {
4102 /* The platform localtime/gmtime may insert leap seconds,
4103 * indicated by tm->tm_sec > 59. We don't care about them,
4104 * except to the extent that passing them on to the datetime
4105 * constructor would raise ValueError for a reason that
4106 * made no sense to the user.
4107 */
4108 if (tm->tm_sec > 59)
4109 tm->tm_sec = 59;
4110 result = PyObject_CallFunction(cls, "iiiiiiiO",
4111 tm->tm_year + 1900,
4112 tm->tm_mon + 1,
4113 tm->tm_mday,
4114 tm->tm_hour,
4115 tm->tm_min,
4116 tm->tm_sec,
4117 us,
4118 tzinfo);
4119 }
4120 else
4121 PyErr_SetString(PyExc_ValueError,
4122 "timestamp out of range for "
4123 "platform localtime()/gmtime() function");
4124 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004125}
4126
4127/* Internal helper.
4128 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
4129 * to control the interpretation of the timestamp. Since a double doesn't
4130 * have enough bits to cover a datetime's full range of precision, it's
4131 * better to call datetime_from_timet_and_us provided you have a way
4132 * to get that much precision (e.g., C time() isn't good enough).
4133 */
4134static PyObject *
4135datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00004137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 time_t timet;
4139 double fraction;
4140 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00004141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 timet = _PyTime_DoubleToTimet(timestamp);
4143 if (timet == (time_t)-1 && PyErr_Occurred())
4144 return NULL;
4145 fraction = timestamp - (double)timet;
4146 us = (int)round_to_long(fraction * 1e6);
4147 if (us < 0) {
4148 /* Truncation towards zero is not what we wanted
4149 for negative numbers (Python's mod semantics) */
4150 timet -= 1;
4151 us += 1000000;
4152 }
4153 /* If timestamp is less than one microsecond smaller than a
4154 * full second, round up. Otherwise, ValueErrors are raised
4155 * for some floats. */
4156 if (us == 1000000) {
4157 timet += 1;
4158 us = 0;
4159 }
4160 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004161}
4162
4163/* Internal helper.
4164 * Build most accurate possible datetime for current time. Pass localtime or
4165 * gmtime for f as appropriate.
4166 */
4167static PyObject *
4168datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4169{
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +00004170 _PyTime_timeval t;
4171 _PyTime_gettimeofday(&t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
4173 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004174}
4175
Tim Peters2a799bf2002-12-16 20:18:38 +00004176/* Return best possible local time -- this isn't constrained by the
4177 * precision of a timestamp.
4178 */
4179static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004180datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 PyObject *self;
4183 PyObject *tzinfo = Py_None;
4184 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
4187 &tzinfo))
4188 return NULL;
4189 if (check_tzinfo_subclass(tzinfo) < 0)
4190 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 self = datetime_best_possible(cls,
4193 tzinfo == Py_None ? localtime : gmtime,
4194 tzinfo);
4195 if (self != NULL && tzinfo != Py_None) {
4196 /* Convert UTC to tzinfo's zone. */
4197 PyObject *temp = self;
4198 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
4199 Py_DECREF(temp);
4200 }
4201 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004202}
4203
Tim Petersa9bc1682003-01-11 03:39:11 +00004204/* Return best possible UTC time -- this isn't constrained by the
4205 * precision of a timestamp.
4206 */
4207static PyObject *
4208datetime_utcnow(PyObject *cls, PyObject *dummy)
4209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004211}
4212
Tim Peters2a799bf2002-12-16 20:18:38 +00004213/* Return new local datetime from timestamp (Python timestamp -- a double). */
4214static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004215datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 PyObject *self;
4218 double timestamp;
4219 PyObject *tzinfo = Py_None;
4220 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
4223 keywords, &timestamp, &tzinfo))
4224 return NULL;
4225 if (check_tzinfo_subclass(tzinfo) < 0)
4226 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 self = datetime_from_timestamp(cls,
4229 tzinfo == Py_None ? localtime : gmtime,
4230 timestamp,
4231 tzinfo);
4232 if (self != NULL && tzinfo != Py_None) {
4233 /* Convert UTC to tzinfo's zone. */
4234 PyObject *temp = self;
4235 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
4236 Py_DECREF(temp);
4237 }
4238 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004239}
4240
Tim Petersa9bc1682003-01-11 03:39:11 +00004241/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4242static PyObject *
4243datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 double timestamp;
4246 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004248 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
4249 result = datetime_from_timestamp(cls, gmtime, timestamp,
4250 Py_None);
4251 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004252}
4253
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004254/* Return new datetime from _strptime.strptime_datetime(). */
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004255static PyObject *
4256datetime_strptime(PyObject *cls, PyObject *args)
4257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 static PyObject *module = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
4262 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004263
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004264 if (module == NULL) {
4265 module = PyImport_ImportModuleNoBlock("_strptime");
Alexander Belopolsky311d2a92010-06-28 14:36:55 +00004266 if (module == NULL)
Alexander Belopolskyca94f552010-06-17 18:30:34 +00004267 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004268 }
Alexander Belopolskyf5682182010-06-18 18:44:37 +00004269 return PyObject_CallMethod(module, "_strptime_datetime", "Ouu",
4270 cls, string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004271}
4272
Tim Petersa9bc1682003-01-11 03:39:11 +00004273/* Return new datetime from date/datetime and time arguments. */
4274static PyObject *
4275datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 static char *keywords[] = {"date", "time", NULL};
4278 PyObject *date;
4279 PyObject *time;
4280 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4283 &PyDateTime_DateType, &date,
4284 &PyDateTime_TimeType, &time)) {
4285 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 if (HASTZINFO(time))
4288 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4289 result = PyObject_CallFunction(cls, "iiiiiiiO",
4290 GET_YEAR(date),
4291 GET_MONTH(date),
4292 GET_DAY(date),
4293 TIME_GET_HOUR(time),
4294 TIME_GET_MINUTE(time),
4295 TIME_GET_SECOND(time),
4296 TIME_GET_MICROSECOND(time),
4297 tzinfo);
4298 }
4299 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004300}
Tim Peters2a799bf2002-12-16 20:18:38 +00004301
4302/*
4303 * Destructor.
4304 */
4305
4306static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004307datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 if (HASTZINFO(self)) {
4310 Py_XDECREF(self->tzinfo);
4311 }
4312 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004313}
4314
4315/*
4316 * Indirect access to tzinfo methods.
4317 */
4318
Tim Peters2a799bf2002-12-16 20:18:38 +00004319/* These are all METH_NOARGS, so don't need to check the arglist. */
4320static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004321datetime_utcoffset(PyObject *self, PyObject *unused) {
4322 return call_utcoffset(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004323}
4324
4325static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004326datetime_dst(PyObject *self, PyObject *unused) {
4327 return call_dst(GET_DT_TZINFO(self), self);
Tim Peters855fe882002-12-22 03:43:39 +00004328}
4329
4330static PyObject *
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004331datetime_tzname(PyObject *self, PyObject *unused) {
4332 return call_tzname(GET_DT_TZINFO(self), self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004333}
4334
4335/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004336 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004337 */
4338
Tim Petersa9bc1682003-01-11 03:39:11 +00004339/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4340 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004341 */
4342static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004343add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 /* Note that the C-level additions can't overflow, because of
4347 * invariant bounds on the member values.
4348 */
4349 int year = GET_YEAR(date);
4350 int month = GET_MONTH(date);
4351 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4352 int hour = DATE_GET_HOUR(date);
4353 int minute = DATE_GET_MINUTE(date);
4354 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4355 int microsecond = DATE_GET_MICROSECOND(date) +
4356 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 assert(factor == 1 || factor == -1);
4359 if (normalize_datetime(&year, &month, &day,
4360 &hour, &minute, &second, &microsecond) < 0)
4361 return NULL;
4362 else
4363 return new_datetime(year, month, day,
4364 hour, minute, second, microsecond,
4365 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004366}
4367
4368static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004369datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 if (PyDateTime_Check(left)) {
4372 /* datetime + ??? */
4373 if (PyDelta_Check(right))
4374 /* datetime + delta */
4375 return add_datetime_timedelta(
4376 (PyDateTime_DateTime *)left,
4377 (PyDateTime_Delta *)right,
4378 1);
4379 }
4380 else if (PyDelta_Check(left)) {
4381 /* delta + datetime */
4382 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4383 (PyDateTime_Delta *) left,
4384 1);
4385 }
4386 Py_INCREF(Py_NotImplemented);
4387 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004388}
4389
4390static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004391datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004393 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 if (PyDateTime_Check(left)) {
4396 /* datetime - ??? */
4397 if (PyDateTime_Check(right)) {
4398 /* datetime - datetime */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004399 PyObject *offset1, *offset2, *offdiff = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004401
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004402 if (GET_DT_TZINFO(left) == GET_DT_TZINFO(right)) {
4403 offset2 = offset1 = Py_None;
4404 Py_INCREF(offset1);
4405 Py_INCREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004407 else {
4408 offset1 = datetime_utcoffset(left, NULL);
4409 if (offset1 == NULL)
4410 return NULL;
4411 offset2 = datetime_utcoffset(right, NULL);
4412 if (offset2 == NULL) {
4413 Py_DECREF(offset1);
4414 return NULL;
4415 }
4416 if ((offset1 != Py_None) != (offset2 != Py_None)) {
4417 PyErr_SetString(PyExc_TypeError,
4418 "can't subtract offset-naive and "
4419 "offset-aware datetimes");
4420 Py_DECREF(offset1);
4421 Py_DECREF(offset2);
4422 return NULL;
4423 }
4424 }
4425 if ((offset1 != offset2) &&
4426 delta_cmp(offset1, offset2) != 0) {
4427 offdiff = delta_subtract(offset1, offset2);
4428 if (offdiff == NULL) {
4429 Py_DECREF(offset1);
4430 Py_DECREF(offset2);
4431 return NULL;
4432 }
4433 }
4434 Py_DECREF(offset1);
4435 Py_DECREF(offset2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 delta_d = ymd_to_ord(GET_YEAR(left),
4437 GET_MONTH(left),
4438 GET_DAY(left)) -
4439 ymd_to_ord(GET_YEAR(right),
4440 GET_MONTH(right),
4441 GET_DAY(right));
4442 /* These can't overflow, since the values are
4443 * normalized. At most this gives the number of
4444 * seconds in one day.
4445 */
4446 delta_s = (DATE_GET_HOUR(left) -
4447 DATE_GET_HOUR(right)) * 3600 +
4448 (DATE_GET_MINUTE(left) -
4449 DATE_GET_MINUTE(right)) * 60 +
4450 (DATE_GET_SECOND(left) -
4451 DATE_GET_SECOND(right));
4452 delta_us = DATE_GET_MICROSECOND(left) -
4453 DATE_GET_MICROSECOND(right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 result = new_delta(delta_d, delta_s, delta_us, 1);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004455 if (offdiff != NULL) {
4456 PyObject *temp = result;
4457 result = delta_subtract(result, offdiff);
4458 Py_DECREF(temp);
4459 Py_DECREF(offdiff);
4460 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 }
4462 else if (PyDelta_Check(right)) {
4463 /* datetime - delta */
4464 result = add_datetime_timedelta(
4465 (PyDateTime_DateTime *)left,
4466 (PyDateTime_Delta *)right,
4467 -1);
4468 }
4469 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 if (result == Py_NotImplemented)
4472 Py_INCREF(result);
4473 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004474}
4475
4476/* Various ways to turn a datetime into a string. */
4477
4478static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004479datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 const char *type_name = Py_TYPE(self)->tp_name;
4482 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 if (DATE_GET_MICROSECOND(self)) {
4485 baserepr = PyUnicode_FromFormat(
4486 "%s(%d, %d, %d, %d, %d, %d, %d)",
4487 type_name,
4488 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4489 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4490 DATE_GET_SECOND(self),
4491 DATE_GET_MICROSECOND(self));
4492 }
4493 else if (DATE_GET_SECOND(self)) {
4494 baserepr = PyUnicode_FromFormat(
4495 "%s(%d, %d, %d, %d, %d, %d)",
4496 type_name,
4497 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4498 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4499 DATE_GET_SECOND(self));
4500 }
4501 else {
4502 baserepr = PyUnicode_FromFormat(
4503 "%s(%d, %d, %d, %d, %d)",
4504 type_name,
4505 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4506 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4507 }
4508 if (baserepr == NULL || ! HASTZINFO(self))
4509 return baserepr;
4510 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004511}
4512
Tim Petersa9bc1682003-01-11 03:39:11 +00004513static PyObject *
4514datetime_str(PyDateTime_DateTime *self)
4515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004517}
Tim Peters2a799bf2002-12-16 20:18:38 +00004518
4519static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004520datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 int sep = 'T';
4523 static char *keywords[] = {"sep", NULL};
4524 char buffer[100];
4525 PyObject *result;
4526 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4529 return NULL;
4530 if (us)
4531 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4532 GET_YEAR(self), GET_MONTH(self),
4533 GET_DAY(self), (int)sep,
4534 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4535 DATE_GET_SECOND(self), us);
4536 else
4537 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4538 GET_YEAR(self), GET_MONTH(self),
4539 GET_DAY(self), (int)sep,
4540 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4541 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 if (!result || !HASTZINFO(self))
4544 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 /* We need to append the UTC offset. */
4547 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4548 (PyObject *)self) < 0) {
4549 Py_DECREF(result);
4550 return NULL;
4551 }
4552 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4553 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004554}
4555
Tim Petersa9bc1682003-01-11 03:39:11 +00004556static PyObject *
4557datetime_ctime(PyDateTime_DateTime *self)
4558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 return format_ctime((PyDateTime_Date *)self,
4560 DATE_GET_HOUR(self),
4561 DATE_GET_MINUTE(self),
4562 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004563}
4564
Tim Peters2a799bf2002-12-16 20:18:38 +00004565/* Miscellaneous methods. */
4566
Tim Petersa9bc1682003-01-11 03:39:11 +00004567static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004568datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004569{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004570 PyObject *result = NULL;
4571 PyObject *offset1, *offset2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 int diff;
Tim Petersa9bc1682003-01-11 03:39:11 +00004573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 if (! PyDateTime_Check(other)) {
4575 if (PyDate_Check(other)) {
4576 /* Prevent invocation of date_richcompare. We want to
4577 return NotImplemented here to give the other object
4578 a chance. But since DateTime is a subclass of
4579 Date, if the other object is a Date, it would
4580 compute an ordering based on the date part alone,
4581 and we don't want that. So force unequal or
4582 uncomparable here in that case. */
4583 if (op == Py_EQ)
4584 Py_RETURN_FALSE;
4585 if (op == Py_NE)
4586 Py_RETURN_TRUE;
4587 return cmperror(self, other);
4588 }
4589 Py_INCREF(Py_NotImplemented);
4590 return Py_NotImplemented;
4591 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004592
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004593 if (GET_DT_TZINFO(self) == GET_DT_TZINFO(other)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4595 ((PyDateTime_DateTime *)other)->data,
4596 _PyDateTime_DATETIME_DATASIZE);
4597 return diff_to_bool(diff, op);
4598 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004599 offset1 = datetime_utcoffset(self, NULL);
4600 if (offset1 == NULL)
4601 return NULL;
4602 offset2 = datetime_utcoffset(other, NULL);
4603 if (offset2 == NULL)
4604 goto done;
4605 /* If they're both naive, or both aware and have the same offsets,
4606 * we get off cheap. Note that if they're both naive, offset1 ==
4607 * offset2 == Py_None at this point.
4608 */
4609 if ((offset1 == offset2) ||
4610 (PyDelta_Check(offset1) && PyDelta_Check(offset2) &&
4611 delta_cmp(offset1, offset2) == 0)) {
4612 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4613 ((PyDateTime_DateTime *)other)->data,
4614 _PyDateTime_DATETIME_DATASIZE);
4615 result = diff_to_bool(diff, op);
4616 }
4617 else if (offset1 != Py_None && offset2 != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004619
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004620 assert(offset1 != offset2); /* else last "if" handled it */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4622 other);
4623 if (delta == NULL)
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004624 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 diff = GET_TD_DAYS(delta);
4626 if (diff == 0)
4627 diff = GET_TD_SECONDS(delta) |
4628 GET_TD_MICROSECONDS(delta);
4629 Py_DECREF(delta);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004630 result = diff_to_bool(diff, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004632 else {
4633 PyErr_SetString(PyExc_TypeError,
4634 "can't compare offset-naive and "
4635 "offset-aware datetimes");
4636 }
4637 done:
4638 Py_DECREF(offset1);
4639 Py_XDECREF(offset2);
4640 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004641}
4642
Benjamin Peterson8f67d082010-10-17 20:54:53 +00004643static Py_hash_t
Tim Petersa9bc1682003-01-11 03:39:11 +00004644datetime_hash(PyDateTime_DateTime *self)
4645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 if (self->hashcode == -1) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004647 PyObject *offset;
Tim Petersa9bc1682003-01-11 03:39:11 +00004648
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004649 offset = datetime_utcoffset((PyObject *)self, NULL);
4650
4651 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 /* Reduce this to a hash of another object. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004655 if (offset == Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 self->hashcode = generic_hash(
4657 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 else {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004659 PyObject *temp1, *temp2;
4660 int days, seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 assert(HASTZINFO(self));
4663 days = ymd_to_ord(GET_YEAR(self),
4664 GET_MONTH(self),
4665 GET_DAY(self));
4666 seconds = DATE_GET_HOUR(self) * 3600 +
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004667 DATE_GET_MINUTE(self) * 60 +
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 DATE_GET_SECOND(self);
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004669 temp1 = new_delta(days, seconds,
4670 DATE_GET_MICROSECOND(self),
4671 1);
4672 if (temp1 == NULL) {
4673 Py_DECREF(offset);
4674 return -1;
4675 }
4676 temp2 = delta_subtract(temp1, offset);
4677 Py_DECREF(temp1);
4678 if (temp2 == NULL) {
4679 Py_DECREF(offset);
4680 return -1;
4681 }
4682 self->hashcode = PyObject_Hash(temp2);
4683 Py_DECREF(temp2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004685 Py_DECREF(offset);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 }
4687 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004688}
Tim Peters2a799bf2002-12-16 20:18:38 +00004689
4690static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004691datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 PyObject *clone;
4694 PyObject *tuple;
4695 int y = GET_YEAR(self);
4696 int m = GET_MONTH(self);
4697 int d = GET_DAY(self);
4698 int hh = DATE_GET_HOUR(self);
4699 int mm = DATE_GET_MINUTE(self);
4700 int ss = DATE_GET_SECOND(self);
4701 int us = DATE_GET_MICROSECOND(self);
4702 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4705 datetime_kws,
4706 &y, &m, &d, &hh, &mm, &ss, &us,
4707 &tzinfo))
4708 return NULL;
4709 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4710 if (tuple == NULL)
4711 return NULL;
4712 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4713 Py_DECREF(tuple);
4714 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004715}
4716
4717static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004718datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 PyObject *result;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004721 PyObject *offset;
4722 PyObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 PyObject *tzinfo;
4724 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4727 &PyDateTime_TZInfoType, &tzinfo))
4728 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4731 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 /* Conversion to self's own time zone is a NOP. */
4734 if (self->tzinfo == tzinfo) {
4735 Py_INCREF(self);
4736 return (PyObject *)self;
4737 }
Tim Peters521fc152002-12-31 17:36:56 +00004738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 /* Convert self to UTC. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004740 offset = datetime_utcoffset((PyObject *)self, NULL);
4741 if (offset == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004743 if (offset == Py_None) {
4744 Py_DECREF(offset);
4745 NeedAware:
4746 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4747 "a naive datetime");
4748 return NULL;
4749 }
Tim Petersf3615152003-01-01 21:51:37 +00004750
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004751 /* result = self - offset */
4752 result = add_datetime_timedelta(self,
4753 (PyDateTime_Delta *)offset, -1);
4754 Py_DECREF(offset);
4755 if (result == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 /* Attach new tzinfo and let fromutc() do the rest. */
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004759 temp = ((PyDateTime_DateTime *)result)->tzinfo;
4760 ((PyDateTime_DateTime *)result)->tzinfo = tzinfo;
4761 Py_INCREF(tzinfo);
4762 Py_DECREF(temp);
Tim Peters52dcce22003-01-23 16:36:11 +00004763
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004764 temp = result;
4765 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4766 Py_DECREF(temp);
4767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 return result;
Tim Peters80475bb2002-12-25 07:40:55 +00004769}
4770
4771static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004772datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004774 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004777 PyObject * dst;
Tim Peters2a799bf2002-12-16 20:18:38 +00004778
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004779 dst = call_dst(self->tzinfo, (PyObject *)self);
4780 if (dst == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004782
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004783 if (dst != Py_None)
4784 dstflag = delta_bool((PyDateTime_Delta *)dst);
4785 Py_DECREF(dst);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 }
4787 return build_struct_time(GET_YEAR(self),
4788 GET_MONTH(self),
4789 GET_DAY(self),
4790 DATE_GET_HOUR(self),
4791 DATE_GET_MINUTE(self),
4792 DATE_GET_SECOND(self),
4793 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004794}
4795
4796static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004797datetime_getdate(PyDateTime_DateTime *self)
4798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 return new_date(GET_YEAR(self),
4800 GET_MONTH(self),
4801 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004802}
4803
4804static PyObject *
4805datetime_gettime(PyDateTime_DateTime *self)
4806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 return new_time(DATE_GET_HOUR(self),
4808 DATE_GET_MINUTE(self),
4809 DATE_GET_SECOND(self),
4810 DATE_GET_MICROSECOND(self),
4811 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004812}
4813
4814static PyObject *
4815datetime_gettimetz(PyDateTime_DateTime *self)
4816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 return new_time(DATE_GET_HOUR(self),
4818 DATE_GET_MINUTE(self),
4819 DATE_GET_SECOND(self),
4820 DATE_GET_MICROSECOND(self),
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004821 GET_DT_TZINFO(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004822}
4823
4824static PyObject *
4825datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004826{
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004827 int y, m, d, hh, mm, ss;
4828 PyObject *tzinfo;
4829 PyDateTime_DateTime *utcself;
Tim Peters2a799bf2002-12-16 20:18:38 +00004830
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004831 tzinfo = GET_DT_TZINFO(self);
4832 if (tzinfo == Py_None) {
4833 utcself = self;
4834 Py_INCREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004836 else {
4837 PyObject *offset;
4838 offset = call_utcoffset(tzinfo, (PyObject *)self);
4839 if (offset == NULL)
Alexander Belopolsky75f94c22010-06-21 15:21:14 +00004840 return NULL;
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004841 if (offset == Py_None) {
4842 Py_DECREF(offset);
4843 utcself = self;
4844 Py_INCREF(utcself);
4845 }
4846 else {
4847 utcself = (PyDateTime_DateTime *)add_datetime_timedelta(self,
4848 (PyDateTime_Delta *)offset, -1);
4849 Py_DECREF(offset);
4850 if (utcself == NULL)
4851 return NULL;
4852 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 }
Alexander Belopolsky73ca4402010-07-07 23:56:38 +00004854 y = GET_YEAR(utcself);
4855 m = GET_MONTH(utcself);
4856 d = GET_DAY(utcself);
4857 hh = DATE_GET_HOUR(utcself);
4858 mm = DATE_GET_MINUTE(utcself);
4859 ss = DATE_GET_SECOND(utcself);
4860
4861 Py_DECREF(utcself);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004863}
4864
Tim Peters371935f2003-02-01 01:52:50 +00004865/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004866
Tim Petersa9bc1682003-01-11 03:39:11 +00004867/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004868 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4869 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004870 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004871 */
4872static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004873datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 PyObject *basestate;
4876 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 basestate = PyBytes_FromStringAndSize((char *)self->data,
4879 _PyDateTime_DATETIME_DATASIZE);
4880 if (basestate != NULL) {
4881 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4882 result = PyTuple_Pack(1, basestate);
4883 else
4884 result = PyTuple_Pack(2, basestate, self->tzinfo);
4885 Py_DECREF(basestate);
4886 }
4887 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004888}
4889
4890static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004891datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004894}
4895
Tim Petersa9bc1682003-01-11 03:39:11 +00004896static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900 {"now", (PyCFunction)datetime_now,
4901 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4902 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004904 {"utcnow", (PyCFunction)datetime_utcnow,
4905 METH_NOARGS | METH_CLASS,
4906 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004908 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4909 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4910 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004912 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4913 METH_VARARGS | METH_CLASS,
4914 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4915 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 {"strptime", (PyCFunction)datetime_strptime,
4918 METH_VARARGS | METH_CLASS,
4919 PyDoc_STR("string, format -> new datetime parsed from a string "
4920 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004922 {"combine", (PyCFunction)datetime_combine,
4923 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4924 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004926 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004928 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4929 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4932 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4935 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004937 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4938 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004940 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
4941 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004943 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4944 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004946 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
4947 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4948 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4949 "sep is used to separate the year from the time, and "
4950 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004952 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
4953 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
4956 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
4959 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004961 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
4962 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
4965 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00004966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004967 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4968 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004971};
4972
Tim Petersa9bc1682003-01-11 03:39:11 +00004973static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004974PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4975\n\
4976The year, month and day arguments are required. tzinfo may be None, or an\n\
4977instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004978
Tim Petersa9bc1682003-01-11 03:39:11 +00004979static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004980 datetime_add, /* nb_add */
4981 datetime_subtract, /* nb_subtract */
4982 0, /* nb_multiply */
4983 0, /* nb_remainder */
4984 0, /* nb_divmod */
4985 0, /* nb_power */
4986 0, /* nb_negative */
4987 0, /* nb_positive */
4988 0, /* nb_absolute */
4989 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004990};
4991
Neal Norwitz227b5332006-03-22 09:28:35 +00004992static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 PyVarObject_HEAD_INIT(NULL, 0)
4994 "datetime.datetime", /* tp_name */
4995 sizeof(PyDateTime_DateTime), /* tp_basicsize */
4996 0, /* tp_itemsize */
4997 (destructor)datetime_dealloc, /* tp_dealloc */
4998 0, /* tp_print */
4999 0, /* tp_getattr */
5000 0, /* tp_setattr */
5001 0, /* tp_reserved */
5002 (reprfunc)datetime_repr, /* tp_repr */
5003 &datetime_as_number, /* tp_as_number */
5004 0, /* tp_as_sequence */
5005 0, /* tp_as_mapping */
5006 (hashfunc)datetime_hash, /* tp_hash */
5007 0, /* tp_call */
5008 (reprfunc)datetime_str, /* tp_str */
5009 PyObject_GenericGetAttr, /* tp_getattro */
5010 0, /* tp_setattro */
5011 0, /* tp_as_buffer */
5012 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
5013 datetime_doc, /* tp_doc */
5014 0, /* tp_traverse */
5015 0, /* tp_clear */
5016 datetime_richcompare, /* tp_richcompare */
5017 0, /* tp_weaklistoffset */
5018 0, /* tp_iter */
5019 0, /* tp_iternext */
5020 datetime_methods, /* tp_methods */
5021 0, /* tp_members */
5022 datetime_getset, /* tp_getset */
5023 &PyDateTime_DateType, /* tp_base */
5024 0, /* tp_dict */
5025 0, /* tp_descr_get */
5026 0, /* tp_descr_set */
5027 0, /* tp_dictoffset */
5028 0, /* tp_init */
5029 datetime_alloc, /* tp_alloc */
5030 datetime_new, /* tp_new */
5031 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00005032};
5033
5034/* ---------------------------------------------------------------------------
5035 * Module methods and initialization.
5036 */
5037
5038static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00005040};
5041
Tim Peters9ddf40b2004-06-20 22:41:32 +00005042/* C API. Clients get at this via PyDateTime_IMPORT, defined in
5043 * datetime.h.
5044 */
5045static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 &PyDateTime_DateType,
5047 &PyDateTime_DateTimeType,
5048 &PyDateTime_TimeType,
5049 &PyDateTime_DeltaType,
5050 &PyDateTime_TZInfoType,
5051 new_date_ex,
5052 new_datetime_ex,
5053 new_time_ex,
5054 new_delta_ex,
5055 datetime_fromtimestamp,
5056 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00005057};
5058
5059
Martin v. Löwis1a214512008-06-11 05:26:20 +00005060
5061static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 PyModuleDef_HEAD_INIT,
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005063 "_datetime",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 "Fast implementation of the datetime type.",
5065 -1,
5066 module_methods,
5067 NULL,
5068 NULL,
5069 NULL,
5070 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005071};
5072
Tim Peters2a799bf2002-12-16 20:18:38 +00005073PyMODINIT_FUNC
Alexander Belopolskycf86e362010-07-23 19:25:47 +00005074PyInit__datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00005075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 PyObject *m; /* a module object */
5077 PyObject *d; /* its dict */
5078 PyObject *x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005079 PyObject *delta;
Tim Peters2a799bf2002-12-16 20:18:38 +00005080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005081 m = PyModule_Create(&datetimemodule);
5082 if (m == NULL)
5083 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 if (PyType_Ready(&PyDateTime_DateType) < 0)
5086 return NULL;
5087 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5088 return NULL;
5089 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5090 return NULL;
5091 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5092 return NULL;
5093 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5094 return NULL;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005095 if (PyType_Ready(&PyDateTime_TimeZoneType) < 0)
5096 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 /* timedelta values */
5099 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 x = new_delta(0, 0, 1, 0);
5102 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5103 return NULL;
5104 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5107 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5108 return NULL;
5109 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5112 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5113 return NULL;
5114 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 /* date values */
5117 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 x = new_date(1, 1, 1);
5120 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5121 return NULL;
5122 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 x = new_date(MAXYEAR, 12, 31);
5125 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5126 return NULL;
5127 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 x = new_delta(1, 0, 0, 0);
5130 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5131 return NULL;
5132 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 /* time values */
5135 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005137 x = new_time(0, 0, 0, 0, Py_None);
5138 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5139 return NULL;
5140 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 x = new_time(23, 59, 59, 999999, Py_None);
5143 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5144 return NULL;
5145 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005147 x = new_delta(0, 0, 1, 0);
5148 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5149 return NULL;
5150 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 /* datetime values */
5153 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005155 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
5156 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5157 return NULL;
5158 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5161 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5162 return NULL;
5163 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 x = new_delta(0, 0, 1, 0);
5166 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5167 return NULL;
5168 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005169
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005170 /* timezone values */
5171 d = PyDateTime_TimeZoneType.tp_dict;
5172
5173 delta = new_delta(0, 0, 0, 0);
5174 if (delta == NULL)
5175 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005176 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005177 Py_DECREF(delta);
5178 if (x == NULL || PyDict_SetItemString(d, "utc", x) < 0)
5179 return NULL;
Alexander Belopolskya11d8c02010-07-06 23:19:45 +00005180 PyDateTime_TimeZone_UTC = x;
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005181
5182 delta = new_delta(-1, 60, 0, 1); /* -23:59 */
5183 if (delta == NULL)
5184 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005185 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005186 Py_DECREF(delta);
5187 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5188 return NULL;
5189 Py_DECREF(x);
5190
5191 delta = new_delta(0, (23 * 60 + 59) * 60, 0, 0); /* +23:59 */
5192 if (delta == NULL)
5193 return NULL;
Alexander Belopolsky1bcbaab2010-10-14 17:03:51 +00005194 x = create_timezone(delta, NULL);
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005195 Py_DECREF(delta);
5196 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5197 return NULL;
5198 Py_DECREF(x);
5199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 /* module initialization */
5201 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
5202 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 Py_INCREF(&PyDateTime_DateType);
5205 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005207 Py_INCREF(&PyDateTime_DateTimeType);
5208 PyModule_AddObject(m, "datetime",
5209 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 Py_INCREF(&PyDateTime_TimeType);
5212 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 Py_INCREF(&PyDateTime_DeltaType);
5215 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 Py_INCREF(&PyDateTime_TZInfoType);
5218 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005219
Alexander Belopolsky4e749a12010-06-14 14:15:50 +00005220 Py_INCREF(&PyDateTime_TimeZoneType);
5221 PyModule_AddObject(m, "timezone", (PyObject *) &PyDateTime_TimeZoneType);
5222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005223 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5224 if (x == NULL)
5225 return NULL;
5226 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005228 /* A 4-year cycle has an extra leap day over what we'd get from
5229 * pasting together 4 single years.
5230 */
5231 assert(DI4Y == 4 * 365 + 1);
5232 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005234 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5235 * get from pasting together 4 100-year cycles.
5236 */
5237 assert(DI400Y == 4 * DI100Y + 1);
5238 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005240 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5241 * pasting together 25 4-year cycles.
5242 */
5243 assert(DI100Y == 25 * DI4Y - 1);
5244 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 us_per_us = PyLong_FromLong(1);
5247 us_per_ms = PyLong_FromLong(1000);
5248 us_per_second = PyLong_FromLong(1000000);
5249 us_per_minute = PyLong_FromLong(60000000);
5250 seconds_per_day = PyLong_FromLong(24 * 3600);
5251 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5252 us_per_minute == NULL || seconds_per_day == NULL)
5253 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005255 /* The rest are too big for 32-bit ints, but even
5256 * us_per_week fits in 40 bits, so doubles should be exact.
5257 */
5258 us_per_hour = PyLong_FromDouble(3600000000.0);
5259 us_per_day = PyLong_FromDouble(86400000000.0);
5260 us_per_week = PyLong_FromDouble(604800000000.0);
5261 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5262 return NULL;
5263 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005264}
Tim Petersf3615152003-01-01 21:51:37 +00005265
5266/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005267Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005268 x.n = x stripped of its timezone -- its naive time.
5269 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005270 return None
Tim Petersf3615152003-01-01 21:51:37 +00005271 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 return None
Tim Petersf3615152003-01-01 21:51:37 +00005273 x.s = x's standard offset, x.o - x.d
5274
5275Now some derived rules, where k is a duration (timedelta).
5276
52771. x.o = x.s + x.d
5278 This follows from the definition of x.s.
5279
Tim Petersc5dc4da2003-01-02 17:55:03 +000052802. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005281 This is actually a requirement, an assumption we need to make about
5282 sane tzinfo classes.
5283
52843. The naive UTC time corresponding to x is x.n - x.o.
5285 This is again a requirement for a sane tzinfo class.
5286
52874. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005288 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005289
Tim Petersc5dc4da2003-01-02 17:55:03 +000052905. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005291 Again follows from how arithmetic is defined.
5292
Tim Peters8bb5ad22003-01-24 02:44:45 +00005293Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005294(meaning that the various tzinfo methods exist, and don't blow up or return
5295None when called).
5296
Tim Petersa9bc1682003-01-11 03:39:11 +00005297The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005298x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005299
5300By #3, we want
5301
Tim Peters8bb5ad22003-01-24 02:44:45 +00005302 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005303
5304The algorithm starts by attaching tz to x.n, and calling that y. So
5305x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5306becomes true; in effect, we want to solve [2] for k:
5307
Tim Peters8bb5ad22003-01-24 02:44:45 +00005308 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005309
5310By #1, this is the same as
5311
Tim Peters8bb5ad22003-01-24 02:44:45 +00005312 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005313
5314By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5315Substituting that into [3],
5316
Tim Peters8bb5ad22003-01-24 02:44:45 +00005317 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5318 k - (y+k).s - (y+k).d = 0; rearranging,
5319 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5320 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005321
Tim Peters8bb5ad22003-01-24 02:44:45 +00005322On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5323approximate k by ignoring the (y+k).d term at first. Note that k can't be
5324very large, since all offset-returning methods return a duration of magnitude
5325less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5326be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005327
5328In any case, the new value is
5329
Tim Peters8bb5ad22003-01-24 02:44:45 +00005330 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005331
Tim Peters8bb5ad22003-01-24 02:44:45 +00005332It's helpful to step back at look at [4] from a higher level: it's simply
5333mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005334
5335At this point, if
5336
Tim Peters8bb5ad22003-01-24 02:44:45 +00005337 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005338
5339we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005340at the start of daylight time. Picture US Eastern for concreteness. The wall
5341time 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 +00005342sense then. The docs ask that an Eastern tzinfo class consider such a time to
5343be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5344on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005345the only spelling that makes sense on the local wall clock.
5346
Tim Petersc5dc4da2003-01-02 17:55:03 +00005347In fact, if [5] holds at this point, we do have the standard-time spelling,
5348but that takes a bit of proof. We first prove a stronger result. What's the
5349difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005350
Tim Peters8bb5ad22003-01-24 02:44:45 +00005351 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005352
Tim Petersc5dc4da2003-01-02 17:55:03 +00005353Now
5354 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005355 (y + y.s).n = by #5
5356 y.n + y.s = since y.n = x.n
5357 x.n + y.s = since z and y are have the same tzinfo member,
5358 y.s = z.s by #2
5359 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005360
Tim Petersc5dc4da2003-01-02 17:55:03 +00005361Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005362
Tim Petersc5dc4da2003-01-02 17:55:03 +00005363 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005364 x.n - ((x.n + z.s) - z.o) = expanding
5365 x.n - x.n - z.s + z.o = cancelling
5366 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005367 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005368
Tim Petersc5dc4da2003-01-02 17:55:03 +00005369So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005370
Tim Petersc5dc4da2003-01-02 17:55:03 +00005371If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005372spelling we wanted in the endcase described above. We're done. Contrarily,
5373if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005374
Tim Petersc5dc4da2003-01-02 17:55:03 +00005375If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5376add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005377local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005378
Tim Petersc5dc4da2003-01-02 17:55:03 +00005379Let
Tim Petersf3615152003-01-01 21:51:37 +00005380
Tim Peters4fede1a2003-01-04 00:26:59 +00005381 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005382
Tim Peters4fede1a2003-01-04 00:26:59 +00005383and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005384
Tim Peters8bb5ad22003-01-24 02:44:45 +00005385 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005386
Tim Peters8bb5ad22003-01-24 02:44:45 +00005387If so, we're done. If not, the tzinfo class is insane, according to the
5388assumptions we've made. This also requires a bit of proof. As before, let's
5389compute the difference between the LHS and RHS of [8] (and skipping some of
5390the justifications for the kinds of substitutions we've done several times
5391already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005392
Tim Peters8bb5ad22003-01-24 02:44:45 +00005393 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5395 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5396 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5397 - z.n + z.n - z.o + z'.o = cancel z.n
5398 - z.o + z'.o = #1 twice
5399 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5400 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005401
5402So 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 +00005403we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5404return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005405
Tim Peters8bb5ad22003-01-24 02:44:45 +00005406How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5407a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5408would have to change the result dst() returns: we start in DST, and moving
5409a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005410
Tim Peters8bb5ad22003-01-24 02:44:45 +00005411There isn't a sane case where this can happen. The closest it gets is at
5412the end of DST, where there's an hour in UTC with no spelling in a hybrid
5413tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5414that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5415UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5416time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5417clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5418standard time. Since that's what the local clock *does*, we want to map both
5419UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005420in local time, but so it goes -- it's the way the local clock works.
5421
Tim Peters8bb5ad22003-01-24 02:44:45 +00005422When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5423so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5424z' = 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 +00005425(correctly) concludes that z' is not UTC-equivalent to x.
5426
5427Because we know z.d said z was in daylight time (else [5] would have held and
5428we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005429and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005430return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5431but the reasoning doesn't depend on the example -- it depends on there being
5432two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005433z' must be in standard time, and is the spelling we want in this case.
5434
5435Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5436concerned (because it takes z' as being in standard time rather than the
5437daylight time we intend here), but returning it gives the real-life "local
5438clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5439tz.
5440
5441When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5442the 1:MM standard time spelling we want.
5443
5444So how can this break? One of the assumptions must be violated. Two
5445possibilities:
5446
54471) [2] effectively says that y.s is invariant across all y belong to a given
5448 time zone. This isn't true if, for political reasons or continental drift,
5449 a region decides to change its base offset from UTC.
5450
54512) There may be versions of "double daylight" time where the tail end of
5452 the analysis gives up a step too early. I haven't thought about that
5453 enough to say.
5454
5455In any case, it's clear that the default fromutc() is strong enough to handle
5456"almost all" time zones: so long as the standard offset is invariant, it
5457doesn't matter if daylight time transition points change from year to year, or
5458if daylight time is skipped in some years; it doesn't matter how large or
5459small dst() may get within its bounds; and it doesn't even matter if some
5460perverse time zone returns a negative dst()). So a breaking case must be
5461pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005462--------------------------------------------------------------------------- */