blob: 30816ed418e24a6fc5a7bd8276d7c9e90e2326e6 [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
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
Tim Petersa032d2e2003-01-11 00:15:54 +000092
Tim Peters3f606292004-03-21 23:38:41 +000093/* M is a char or int claiming to be a valid month. The macro is equivalent
94 * to the two-sided Python test
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 * 1 <= M <= 12
Tim Peters3f606292004-03-21 23:38:41 +000096 */
97#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
98
Tim Peters2a799bf2002-12-16 20:18:38 +000099/* Forward declarations. */
100static PyTypeObject PyDateTime_DateType;
101static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000102static PyTypeObject PyDateTime_DeltaType;
103static PyTypeObject PyDateTime_TimeType;
104static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000105
106/* ---------------------------------------------------------------------------
107 * Math utilities.
108 */
109
110/* k = i+j overflows iff k differs in sign from both inputs,
111 * iff k^i has sign bit set and k^j has sign bit set,
112 * iff (k^i)&(k^j) has sign bit set.
113 */
114#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +0000116
117/* Compute Python divmod(x, y), returning the quotient and storing the
118 * remainder into *r. The quotient is the floor of x/y, and that's
119 * the real point of this. C will probably truncate instead (C99
120 * requires truncation; C89 left it implementation-defined).
121 * Simplification: we *require* that y > 0 here. That's appropriate
122 * for all the uses made of it. This simplifies the code and makes
123 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
124 * overflow case).
125 */
126static int
127divmod(int x, int y, int *r)
128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 assert(y > 0);
132 quo = x / y;
133 *r = x - quo * y;
134 if (*r < 0) {
135 --quo;
136 *r += y;
137 }
138 assert(0 <= *r && *r < y);
139 return quo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000140}
141
Tim Peters5d644dd2003-01-02 16:32:54 +0000142/* Round a double to the nearest long. |x| must be small enough to fit
143 * in a C long; this is not checked.
144 */
145static long
146round_to_long(double x)
147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (x >= 0.0)
149 x = floor(x + 0.5);
150 else
151 x = ceil(x - 0.5);
152 return (long)x;
Tim Peters5d644dd2003-01-02 16:32:54 +0000153}
154
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000155/* Nearest integer to m / n for integers m and n. Half-integer results
156 * are rounded to even.
157 */
158static PyObject *
159divide_nearest(PyObject *m, PyObject *n)
160{
161 PyObject *result;
162 PyObject *temp;
163
Mark Dickinsonfa68a612010-06-07 18:47:09 +0000164 temp = _PyLong_DivmodNear(m, n);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +0000165 if (temp == NULL)
166 return NULL;
167 result = PyTuple_GET_ITEM(temp, 0);
168 Py_INCREF(result);
169 Py_DECREF(temp);
170
171 return result;
172}
173
Tim Peters2a799bf2002-12-16 20:18:38 +0000174/* ---------------------------------------------------------------------------
175 * General calendrical helper functions
176 */
177
178/* For each month ordinal in 1..12, the number of days in that month,
179 * and the number of days before that month in the same year. These
180 * are correct for non-leap years only.
181 */
182static int _days_in_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 0, /* unused; this vector uses 1-based indexing */
184 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Tim Peters2a799bf2002-12-16 20:18:38 +0000185};
186
187static int _days_before_month[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 0, /* unused; this vector uses 1-based indexing */
189 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
Tim Peters2a799bf2002-12-16 20:18:38 +0000190};
191
192/* year -> 1 if leap year, else 0. */
193static int
194is_leap(int year)
195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Cast year to unsigned. The result is the same either way, but
197 * C can generate faster code for unsigned mod than for signed
198 * mod (especially for % 4 -- a good compiler should just grab
199 * the last 2 bits when the LHS is unsigned).
200 */
201 const unsigned int ayear = (unsigned int)year;
202 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000203}
204
205/* year, month -> number of days in that month in that year */
206static int
207days_in_month(int year, int month)
208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 assert(month >= 1);
210 assert(month <= 12);
211 if (month == 2 && is_leap(year))
212 return 29;
213 else
214 return _days_in_month[month];
Tim Peters2a799bf2002-12-16 20:18:38 +0000215}
216
217/* year, month -> number of days in year preceeding first day of month */
218static int
219days_before_month(int year, int month)
220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 int days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 assert(month >= 1);
224 assert(month <= 12);
225 days = _days_before_month[month];
226 if (month > 2 && is_leap(year))
227 ++days;
228 return days;
Tim Peters2a799bf2002-12-16 20:18:38 +0000229}
230
231/* year -> number of days before January 1st of year. Remember that we
232 * start with year 1, so days_before_year(1) == 0.
233 */
234static int
235days_before_year(int year)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 int y = year - 1;
238 /* This is incorrect if year <= 0; we really want the floor
239 * here. But so long as MINYEAR is 1, the smallest year this
240 * can see is 0 (this can happen in some normalization endcases),
241 * so we'll just special-case that.
242 */
243 assert (year >= 0);
244 if (y >= 0)
245 return y*365 + y/4 - y/100 + y/400;
246 else {
247 assert(y == -1);
248 return -366;
249 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000250}
251
252/* Number of days in 4, 100, and 400 year cycles. That these have
253 * the correct values is asserted in the module init function.
254 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255#define DI4Y 1461 /* days_before_year(5); days in 4 years */
256#define DI100Y 36524 /* days_before_year(101); days in 100 years */
257#define DI400Y 146097 /* days_before_year(401); days in 400 years */
Tim Peters2a799bf2002-12-16 20:18:38 +0000258
259/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
260static void
261ord_to_ymd(int ordinal, int *year, int *month, int *day)
262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 int n, n1, n4, n100, n400, leapyear, preceding;
Tim Peters2a799bf2002-12-16 20:18:38 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
266 * leap years repeats exactly every 400 years. The basic strategy is
267 * to find the closest 400-year boundary at or before ordinal, then
268 * work with the offset from that boundary to ordinal. Life is much
269 * clearer if we subtract 1 from ordinal first -- then the values
270 * of ordinal at 400-year boundaries are exactly those divisible
271 * by DI400Y:
272 *
273 * D M Y n n-1
274 * -- --- ---- ---------- ----------------
275 * 31 Dec -400 -DI400Y -DI400Y -1
276 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
277 * ...
278 * 30 Dec 000 -1 -2
279 * 31 Dec 000 0 -1
280 * 1 Jan 001 1 0 400-year boundary
281 * 2 Jan 001 2 1
282 * 3 Jan 001 3 2
283 * ...
284 * 31 Dec 400 DI400Y DI400Y -1
285 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
286 */
287 assert(ordinal >= 1);
288 --ordinal;
289 n400 = ordinal / DI400Y;
290 n = ordinal % DI400Y;
291 *year = n400 * 400 + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* Now n is the (non-negative) offset, in days, from January 1 of
294 * year, to the desired date. Now compute how many 100-year cycles
295 * precede n.
296 * Note that it's possible for n100 to equal 4! In that case 4 full
297 * 100-year cycles precede the desired day, which implies the
298 * desired day is December 31 at the end of a 400-year cycle.
299 */
300 n100 = n / DI100Y;
301 n = n % DI100Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 /* Now compute how many 4-year cycles precede it. */
304 n4 = n / DI4Y;
305 n = n % DI4Y;
Tim Peters2a799bf2002-12-16 20:18:38 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 /* And now how many single years. Again n1 can be 4, and again
308 * meaning that the desired day is December 31 at the end of the
309 * 4-year cycle.
310 */
311 n1 = n / 365;
312 n = n % 365;
Tim Peters2a799bf2002-12-16 20:18:38 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 *year += n100 * 100 + n4 * 4 + n1;
315 if (n1 == 4 || n100 == 4) {
316 assert(n == 0);
317 *year -= 1;
318 *month = 12;
319 *day = 31;
320 return;
321 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 /* Now the year is correct, and n is the offset from January 1. We
324 * find the month via an estimate that's either exact or one too
325 * large.
326 */
327 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
328 assert(leapyear == is_leap(*year));
329 *month = (n + 50) >> 5;
330 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
331 if (preceding > n) {
332 /* estimate is too large */
333 *month -= 1;
334 preceding -= days_in_month(*year, *month);
335 }
336 n -= preceding;
337 assert(0 <= n);
338 assert(n < days_in_month(*year, *month));
Tim Peters2a799bf2002-12-16 20:18:38 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 *day = n + 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000341}
342
343/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
344static int
345ymd_to_ord(int year, int month, int day)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return days_before_year(year) + days_before_month(year, month) + day;
Tim Peters2a799bf2002-12-16 20:18:38 +0000348}
349
350/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
351static int
352weekday(int year, int month, int day)
353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return (ymd_to_ord(year, month, day) + 6) % 7;
Tim Peters2a799bf2002-12-16 20:18:38 +0000355}
356
357/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
358 * first calendar week containing a Thursday.
359 */
360static int
361iso_week1_monday(int year)
362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
364 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
365 int first_weekday = (first_day + 6) % 7;
366 /* ordinal of closest Monday at or before 1/1 */
367 int week1_monday = first_day - first_weekday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
370 week1_monday += 7;
371 return week1_monday;
Tim Peters2a799bf2002-12-16 20:18:38 +0000372}
373
374/* ---------------------------------------------------------------------------
375 * Range checkers.
376 */
377
378/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
379 * If not, raise OverflowError and return -1.
380 */
381static int
382check_delta_day_range(int days)
383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
385 return 0;
386 PyErr_Format(PyExc_OverflowError,
387 "days=%d; must have magnitude <= %d",
388 days, MAX_DELTA_DAYS);
389 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000390}
391
392/* Check that date arguments are in range. Return 0 if they are. If they
393 * aren't, raise ValueError and return -1.
394 */
395static int
396check_date_args(int year, int month, int day)
397{
398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (year < MINYEAR || year > MAXYEAR) {
400 PyErr_SetString(PyExc_ValueError,
401 "year is out of range");
402 return -1;
403 }
404 if (month < 1 || month > 12) {
405 PyErr_SetString(PyExc_ValueError,
406 "month must be in 1..12");
407 return -1;
408 }
409 if (day < 1 || day > days_in_month(year, month)) {
410 PyErr_SetString(PyExc_ValueError,
411 "day is out of range for month");
412 return -1;
413 }
414 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000415}
416
417/* Check that time arguments are in range. Return 0 if they are. If they
418 * aren't, raise ValueError and return -1.
419 */
420static int
421check_time_args(int h, int m, int s, int us)
422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (h < 0 || h > 23) {
424 PyErr_SetString(PyExc_ValueError,
425 "hour must be in 0..23");
426 return -1;
427 }
428 if (m < 0 || m > 59) {
429 PyErr_SetString(PyExc_ValueError,
430 "minute must be in 0..59");
431 return -1;
432 }
433 if (s < 0 || s > 59) {
434 PyErr_SetString(PyExc_ValueError,
435 "second must be in 0..59");
436 return -1;
437 }
438 if (us < 0 || us > 999999) {
439 PyErr_SetString(PyExc_ValueError,
440 "microsecond must be in 0..999999");
441 return -1;
442 }
443 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +0000444}
445
446/* ---------------------------------------------------------------------------
447 * Normalization utilities.
448 */
449
450/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
451 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
452 * at least factor, enough of *lo is converted into "hi" units so that
453 * 0 <= *lo < factor. The input values must be such that int overflow
454 * is impossible.
455 */
456static void
457normalize_pair(int *hi, int *lo, int factor)
458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 assert(factor > 0);
460 assert(lo != hi);
461 if (*lo < 0 || *lo >= factor) {
462 const int num_hi = divmod(*lo, factor, lo);
463 const int new_hi = *hi + num_hi;
464 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
465 *hi = new_hi;
466 }
467 assert(0 <= *lo && *lo < factor);
Tim Peters2a799bf2002-12-16 20:18:38 +0000468}
469
470/* Fiddle days (d), seconds (s), and microseconds (us) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 * 0 <= *s < 24*3600
472 * 0 <= *us < 1000000
Tim Peters2a799bf2002-12-16 20:18:38 +0000473 * The input values must be such that the internals don't overflow.
474 * The way this routine is used, we don't get close.
475 */
476static void
477normalize_d_s_us(int *d, int *s, int *us)
478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (*us < 0 || *us >= 1000000) {
480 normalize_pair(s, us, 1000000);
481 /* |s| can't be bigger than about
482 * |original s| + |original us|/1000000 now.
483 */
Tim Peters2a799bf2002-12-16 20:18:38 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 }
486 if (*s < 0 || *s >= 24*3600) {
487 normalize_pair(d, s, 24*3600);
488 /* |d| can't be bigger than about
489 * |original d| +
490 * (|original s| + |original us|/1000000) / (24*3600) now.
491 */
492 }
493 assert(0 <= *s && *s < 24*3600);
494 assert(0 <= *us && *us < 1000000);
Tim Peters2a799bf2002-12-16 20:18:38 +0000495}
496
497/* Fiddle years (y), months (m), and days (d) so that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 * 1 <= *m <= 12
499 * 1 <= *d <= days_in_month(*y, *m)
Tim Peters2a799bf2002-12-16 20:18:38 +0000500 * The input values must be such that the internals don't overflow.
501 * The way this routine is used, we don't get close.
502 */
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000503static int
Tim Peters2a799bf2002-12-16 20:18:38 +0000504normalize_y_m_d(int *y, int *m, int *d)
505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 int dim; /* # of days in month */
Tim Peters2a799bf2002-12-16 20:18:38 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* This gets muddy: the proper range for day can't be determined
509 * without knowing the correct month and year, but if day is, e.g.,
510 * plus or minus a million, the current month and year values make
511 * no sense (and may also be out of bounds themselves).
512 * Saying 12 months == 1 year should be non-controversial.
513 */
514 if (*m < 1 || *m > 12) {
515 --*m;
516 normalize_pair(y, m, 12);
517 ++*m;
518 /* |y| can't be bigger than about
519 * |original y| + |original m|/12 now.
520 */
521 }
522 assert(1 <= *m && *m <= 12);
Tim Peters2a799bf2002-12-16 20:18:38 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* Now only day can be out of bounds (year may also be out of bounds
525 * for a datetime object, but we don't care about that here).
526 * If day is out of bounds, what to do is arguable, but at least the
527 * method here is principled and explainable.
528 */
529 dim = days_in_month(*y, *m);
530 if (*d < 1 || *d > dim) {
531 /* Move day-1 days from the first of the month. First try to
532 * get off cheap if we're only one day out of range
533 * (adjustments for timezone alone can't be worse than that).
534 */
535 if (*d == 0) {
536 --*m;
537 if (*m > 0)
538 *d = days_in_month(*y, *m);
539 else {
540 --*y;
541 *m = 12;
542 *d = 31;
543 }
544 }
545 else if (*d == dim + 1) {
546 /* move forward a day */
547 ++*m;
548 *d = 1;
549 if (*m > 12) {
550 *m = 1;
551 ++*y;
552 }
553 }
554 else {
555 int ordinal = ymd_to_ord(*y, *m, 1) +
556 *d - 1;
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000557 if (ordinal < 1 || ordinal > MAXORDINAL) {
558 goto error;
559 } else {
560 ord_to_ymd(ordinal, y, m, d);
561 return 0;
562 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 }
564 }
565 assert(*m > 0);
566 assert(*d > 0);
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000567 if (MINYEAR <= *y && *y <= MAXYEAR)
568 return 0;
569 error:
570 PyErr_SetString(PyExc_OverflowError,
571 "date value out of range");
572 return -1;
573
Tim Peters2a799bf2002-12-16 20:18:38 +0000574}
575
576/* Fiddle out-of-bounds months and days so that the result makes some kind
577 * of sense. The parameters are both inputs and outputs. Returns < 0 on
578 * failure, where failure means the adjusted year is out of bounds.
579 */
580static int
581normalize_date(int *year, int *month, int *day)
582{
Alexander Belopolskyf03a6162010-05-27 21:42:58 +0000583 return normalize_y_m_d(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000584}
585
586/* Force all the datetime fields into range. The parameters are both
587 * inputs and outputs. Returns < 0 on error.
588 */
589static int
590normalize_datetime(int *year, int *month, int *day,
591 int *hour, int *minute, int *second,
592 int *microsecond)
593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 normalize_pair(second, microsecond, 1000000);
595 normalize_pair(minute, second, 60);
596 normalize_pair(hour, minute, 60);
597 normalize_pair(day, hour, 24);
598 return normalize_date(year, month, day);
Tim Peters2a799bf2002-12-16 20:18:38 +0000599}
600
601/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000602 * Basic object allocation: tp_alloc implementations. These allocate
603 * Python objects of the right size and type, and do the Python object-
604 * initialization bit. If there's not enough memory, they return NULL after
605 * setting MemoryError. All data members remain uninitialized trash.
606 *
607 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000608 * member is needed. This is ugly, imprecise, and possibly insecure.
609 * tp_basicsize for the time and datetime types is set to the size of the
610 * struct that has room for the tzinfo member, so subclasses in Python will
611 * allocate enough space for a tzinfo member whether or not one is actually
612 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
613 * part is that PyType_GenericAlloc() (which subclasses in Python end up
614 * using) just happens today to effectively ignore the nitems argument
615 * when tp_itemsize is 0, which it is for these type objects. If that
616 * changes, perhaps the callers of tp_alloc slots in this file should
617 * be changed to force a 0 nitems argument unless the type being allocated
618 * is a base type implemented in this file (so that tp_alloc is time_alloc
619 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000620 */
621
622static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000623time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 self = (PyObject *)
628 PyObject_MALLOC(aware ?
629 sizeof(PyDateTime_Time) :
630 sizeof(_PyDateTime_BaseTime));
631 if (self == NULL)
632 return (PyObject *)PyErr_NoMemory();
633 PyObject_INIT(self, type);
634 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000635}
636
637static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000638datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyObject *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 self = (PyObject *)
643 PyObject_MALLOC(aware ?
644 sizeof(PyDateTime_DateTime) :
645 sizeof(_PyDateTime_BaseDateTime));
646 if (self == NULL)
647 return (PyObject *)PyErr_NoMemory();
648 PyObject_INIT(self, type);
649 return self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000650}
651
652/* ---------------------------------------------------------------------------
653 * Helpers for setting object fields. These work on pointers to the
654 * appropriate base class.
655 */
656
657/* For date and datetime. */
658static void
659set_date_fields(PyDateTime_Date *self, int y, int m, int d)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 self->hashcode = -1;
662 SET_YEAR(self, y);
663 SET_MONTH(self, m);
664 SET_DAY(self, d);
Tim Petersb0c854d2003-05-17 15:57:00 +0000665}
666
667/* ---------------------------------------------------------------------------
668 * Create various objects, mostly without range checking.
669 */
670
671/* Create a date instance with no range checking. */
672static PyObject *
673new_date_ex(int year, int month, int day, PyTypeObject *type)
674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 PyDateTime_Date *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
678 if (self != NULL)
679 set_date_fields(self, year, month, day);
680 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000681}
682
683#define new_date(year, month, day) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 new_date_ex(year, month, day, &PyDateTime_DateType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000685
686/* Create a datetime instance with no range checking. */
687static PyObject *
688new_datetime_ex(int year, int month, int day, int hour, int minute,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyDateTime_DateTime *self;
692 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
695 if (self != NULL) {
696 self->hastzinfo = aware;
697 set_date_fields((PyDateTime_Date *)self, year, month, day);
698 DATE_SET_HOUR(self, hour);
699 DATE_SET_MINUTE(self, minute);
700 DATE_SET_SECOND(self, second);
701 DATE_SET_MICROSECOND(self, usecond);
702 if (aware) {
703 Py_INCREF(tzinfo);
704 self->tzinfo = tzinfo;
705 }
706 }
707 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000708}
709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
711 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
712 &PyDateTime_DateTimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000713
714/* Create a time instance with no range checking. */
715static PyObject *
716new_time_ex(int hour, int minute, int second, int usecond,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyObject *tzinfo, PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyDateTime_Time *self;
720 char aware = tzinfo != Py_None;
Tim Petersb0c854d2003-05-17 15:57:00 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
723 if (self != NULL) {
724 self->hastzinfo = aware;
725 self->hashcode = -1;
726 TIME_SET_HOUR(self, hour);
727 TIME_SET_MINUTE(self, minute);
728 TIME_SET_SECOND(self, second);
729 TIME_SET_MICROSECOND(self, usecond);
730 if (aware) {
731 Py_INCREF(tzinfo);
732 self->tzinfo = tzinfo;
733 }
734 }
735 return (PyObject *)self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000736}
737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738#define new_time(hh, mm, ss, us, tzinfo) \
739 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000740
741/* Create a timedelta instance. Normalize the members iff normalize is
742 * true. Passing false is a speed optimization, if you know for sure
743 * that seconds and microseconds are already in their proper ranges. In any
744 * case, raises OverflowError and returns NULL if the normalized days is out
745 * of range).
746 */
747static PyObject *
748new_delta_ex(int days, int seconds, int microseconds, int normalize,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 PyTypeObject *type)
Tim Petersb0c854d2003-05-17 15:57:00 +0000750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyDateTime_Delta *self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (normalize)
754 normalize_d_s_us(&days, &seconds, &microseconds);
755 assert(0 <= seconds && seconds < 24*3600);
756 assert(0 <= microseconds && microseconds < 1000000);
Tim Petersb0c854d2003-05-17 15:57:00 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (check_delta_day_range(days) < 0)
759 return NULL;
Tim Petersb0c854d2003-05-17 15:57:00 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
762 if (self != NULL) {
763 self->hashcode = -1;
764 SET_TD_DAYS(self, days);
765 SET_TD_SECONDS(self, seconds);
766 SET_TD_MICROSECONDS(self, microseconds);
767 }
768 return (PyObject *) self;
Tim Petersb0c854d2003-05-17 15:57:00 +0000769}
770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771#define new_delta(d, s, us, normalize) \
772 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +0000773
774/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000775 * tzinfo helpers.
776 */
777
Tim Peters855fe882002-12-22 03:43:39 +0000778/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
779 * raise TypeError and return -1.
780 */
781static int
782check_tzinfo_subclass(PyObject *p)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (p == Py_None || PyTZInfo_Check(p))
785 return 0;
786 PyErr_Format(PyExc_TypeError,
787 "tzinfo argument must be None or of a tzinfo subclass, "
788 "not type '%s'",
789 Py_TYPE(p)->tp_name);
790 return -1;
Tim Peters855fe882002-12-22 03:43:39 +0000791}
792
Tim Petersbad8ff02002-12-30 20:52:32 +0000793/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000794 * If tzinfo is None, returns None.
795 */
796static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000797call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 assert(tzinfo && methname && tzinfoarg);
802 assert(check_tzinfo_subclass(tzinfo) >= 0);
803 if (tzinfo == Py_None) {
804 result = Py_None;
805 Py_INCREF(result);
806 }
807 else
808 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
809 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000810}
811
Tim Peters2a799bf2002-12-16 20:18:38 +0000812/* If self has a tzinfo member, return a BORROWED reference to it. Else
813 * return NULL, which is NOT AN ERROR. There are no error returns here,
814 * and the caller must not decref the result.
815 */
816static PyObject *
817get_tzinfo_member(PyObject *self)
818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 PyObject *tzinfo = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (PyDateTime_Check(self) && HASTZINFO(self))
822 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
823 else if (PyTime_Check(self) && HASTZINFO(self))
824 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 return tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000827}
828
Tim Petersbad8ff02002-12-30 20:52:32 +0000829/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000830 * result. tzinfo must be an instance of the tzinfo class. If the method
831 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000832 * return None or timedelta, TypeError is raised and this returns -1. If it
833 * returnsa timedelta and the value is out of range or isn't a whole number
834 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000835 * Else *none is set to 0 and the integer method result is returned.
836 */
837static int
838call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 int *none)
Tim Peters2a799bf2002-12-16 20:18:38 +0000840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 PyObject *u;
842 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 assert(tzinfo != NULL);
845 assert(PyTZInfo_Check(tzinfo));
846 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 *none = 0;
849 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
850 if (u == NULL)
851 return -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 else if (u == Py_None) {
854 result = 0;
855 *none = 1;
856 }
857 else if (PyDelta_Check(u)) {
858 const int days = GET_TD_DAYS(u);
859 if (days < -1 || days > 0)
860 result = 24*60; /* trigger ValueError below */
861 else {
862 /* next line can't overflow because we know days
863 * is -1 or 0 now
864 */
865 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
866 result = divmod(ss, 60, &ss);
867 if (ss || GET_TD_MICROSECONDS(u)) {
868 PyErr_Format(PyExc_ValueError,
869 "tzinfo.%s() must return a "
870 "whole number of minutes",
871 name);
872 result = -1;
873 }
874 }
875 }
876 else {
877 PyErr_Format(PyExc_TypeError,
878 "tzinfo.%s() must return None or "
879 "timedelta, not '%s'",
880 name, Py_TYPE(u)->tp_name);
881 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 Py_DECREF(u);
884 if (result < -1439 || result > 1439) {
885 PyErr_Format(PyExc_ValueError,
886 "tzinfo.%s() returned %d; must be in "
887 "-1439 .. 1439",
888 name, result);
889 result = -1;
890 }
891 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000892}
893
894/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
895 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
896 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000897 * doesn't return None or timedelta, TypeError is raised and this returns -1.
898 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
899 * # of minutes), ValueError is raised and this returns -1. Else *none is
900 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000901 */
902static int
903call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000906}
907
Tim Petersbad8ff02002-12-30 20:52:32 +0000908/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
909 */
Tim Peters855fe882002-12-22 03:43:39 +0000910static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000911offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 PyObject *result;
Tim Peters855fe882002-12-22 03:43:39 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 assert(tzinfo && name && tzinfoarg);
915 if (tzinfo == Py_None) {
916 result = Py_None;
917 Py_INCREF(result);
918 }
919 else {
920 int none;
921 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
922 &none);
923 if (offset < 0 && PyErr_Occurred())
924 return NULL;
925 if (none) {
926 result = Py_None;
927 Py_INCREF(result);
928 }
929 else
930 result = new_delta(0, offset * 60, 0, 1);
931 }
932 return result;
Tim Peters855fe882002-12-22 03:43:39 +0000933}
934
Tim Peters2a799bf2002-12-16 20:18:38 +0000935/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
936 * result. tzinfo must be an instance of the tzinfo class. If dst()
937 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000938 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000939 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000940 * ValueError is raised and this returns -1. Else *none is set to 0 and
941 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000942 */
943static int
944call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
Tim Peters2a799bf2002-12-16 20:18:38 +0000947}
948
Tim Petersbad8ff02002-12-30 20:52:32 +0000949/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000950 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000951 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000952 * returns NULL. If the result is a string, we ensure it is a Unicode
953 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000954 */
955static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000956call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 assert(tzinfo != NULL);
961 assert(check_tzinfo_subclass(tzinfo) >= 0);
962 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (tzinfo == Py_None) {
965 result = Py_None;
966 Py_INCREF(result);
967 }
968 else
969 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (result != NULL && result != Py_None) {
972 if (!PyUnicode_Check(result)) {
973 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
974 "return None or a string, not '%s'",
975 Py_TYPE(result)->tp_name);
976 Py_DECREF(result);
977 result = NULL;
978 }
979 else if (!PyUnicode_Check(result)) {
980 PyObject *temp = PyUnicode_FromObject(result);
981 Py_DECREF(result);
982 result = temp;
983 }
984 }
985 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000986}
987
988typedef enum {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 /* an exception has been set; the caller should pass it on */
990 OFFSET_ERROR,
Tim Peters2a799bf2002-12-16 20:18:38 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 /* type isn't date, datetime, or time subclass */
993 OFFSET_UNKNOWN,
Tim Peters2a799bf2002-12-16 20:18:38 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* date,
996 * datetime with !hastzinfo
997 * datetime with None tzinfo,
998 * datetime where utcoffset() returns None
999 * time with !hastzinfo
1000 * time with None tzinfo,
1001 * time where utcoffset() returns None
1002 */
1003 OFFSET_NAIVE,
Tim Peters2a799bf2002-12-16 20:18:38 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 /* time or datetime where utcoffset() doesn't return None */
1006 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +00001007} naivety;
1008
Tim Peters14b69412002-12-22 18:10:22 +00001009/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +00001010 * the "naivety" typedef for details. If the type is aware, *offset is set
1011 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +00001012 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +00001013 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +00001014 */
1015static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +00001016classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +00001017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 int none;
1019 PyObject *tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 assert(tzinfoarg != NULL);
1022 *offset = 0;
1023 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
1024 if (tzinfo == Py_None)
1025 return OFFSET_NAIVE;
1026 if (tzinfo == NULL) {
1027 /* note that a datetime passes the PyDate_Check test */
1028 return (PyTime_Check(op) || PyDate_Check(op)) ?
1029 OFFSET_NAIVE : OFFSET_UNKNOWN;
1030 }
1031 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1032 if (*offset == -1 && PyErr_Occurred())
1033 return OFFSET_ERROR;
1034 return none ? OFFSET_NAIVE : OFFSET_AWARE;
Tim Peters2a799bf2002-12-16 20:18:38 +00001035}
1036
Tim Peters00237032002-12-27 02:21:51 +00001037/* Classify two objects as to whether they're naive or offset-aware.
1038 * This isn't quite the same as calling classify_utcoffset() twice: for
1039 * binary operations (comparison and subtraction), we generally want to
1040 * ignore the tzinfo members if they're identical. This is by design,
1041 * so that results match "naive" expectations when mixing objects from a
1042 * single timezone. So in that case, this sets both offsets to 0 and
1043 * both naiveties to OFFSET_NAIVE.
1044 * The function returns 0 if everything's OK, and -1 on error.
1045 */
1046static int
1047classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 PyObject *tzinfoarg1,
1049 PyObject *o2, int *offset2, naivety *n2,
1050 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1053 *offset1 = *offset2 = 0;
1054 *n1 = *n2 = OFFSET_NAIVE;
1055 }
1056 else {
1057 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
1058 if (*n1 == OFFSET_ERROR)
1059 return -1;
1060 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
1061 if (*n2 == OFFSET_ERROR)
1062 return -1;
1063 }
1064 return 0;
Tim Peters00237032002-12-27 02:21:51 +00001065}
1066
Tim Peters2a799bf2002-12-16 20:18:38 +00001067/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1068 * stuff
1069 * ", tzinfo=" + repr(tzinfo)
1070 * before the closing ")".
1071 */
1072static PyObject *
1073append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyObject *temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 assert(PyUnicode_Check(repr));
1078 assert(tzinfo);
1079 if (tzinfo == Py_None)
1080 return repr;
1081 /* Get rid of the trailing ')'. */
1082 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1083 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1084 PyUnicode_GET_SIZE(repr) - 1);
1085 Py_DECREF(repr);
1086 if (temp == NULL)
1087 return NULL;
1088 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1089 Py_DECREF(temp);
1090 return repr;
Tim Peters2a799bf2002-12-16 20:18:38 +00001091}
1092
1093/* ---------------------------------------------------------------------------
1094 * String format helpers.
1095 */
1096
1097static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001098format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 static const char *DayNames[] = {
1101 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1102 };
1103 static const char *MonthNames[] = {
1104 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1105 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1106 };
Tim Peters2a799bf2002-12-16 20:18:38 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1111 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1112 GET_DAY(date), hours, minutes, seconds,
1113 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001114}
1115
1116/* Add an hours & minutes UTC offset string to buf. buf has no more than
1117 * buflen bytes remaining. The UTC offset is gotten by calling
1118 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1119 * *buf, and that's all. Else the returned value is checked for sanity (an
1120 * integer in range), and if that's OK it's converted to an hours & minutes
1121 * string of the form
1122 * sign HH sep MM
1123 * Returns 0 if everything is OK. If the return value from utcoffset() is
1124 * bogus, an appropriate exception is set and -1 is returned.
1125 */
1126static int
Tim Peters328fff72002-12-20 01:31:27 +00001127format_utcoffset(char *buf, size_t buflen, const char *sep,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 int offset;
1131 int hours;
1132 int minutes;
1133 char sign;
1134 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00001135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 assert(buflen >= 1);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1139 if (offset == -1 && PyErr_Occurred())
1140 return -1;
1141 if (none) {
1142 *buf = '\0';
1143 return 0;
1144 }
1145 sign = '+';
1146 if (offset < 0) {
1147 sign = '-';
1148 offset = - offset;
1149 }
1150 hours = divmod(offset, 60, &minutes);
1151 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1152 return 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001153}
1154
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001155static PyObject *
1156make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyObject *temp;
1159 PyObject *tzinfo = get_tzinfo_member(object);
1160 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
1161 if (Zreplacement == NULL)
1162 return NULL;
1163 if (tzinfo == Py_None || tzinfo == NULL)
1164 return Zreplacement;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 assert(tzinfoarg != NULL);
1167 temp = call_tzname(tzinfo, tzinfoarg);
1168 if (temp == NULL)
1169 goto Error;
1170 if (temp == Py_None) {
1171 Py_DECREF(temp);
1172 return Zreplacement;
1173 }
Neal Norwitzaea70e02007-08-12 04:32:26 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 assert(PyUnicode_Check(temp));
1176 /* Since the tzname is getting stuffed into the
1177 * format, we have to double any % signs so that
1178 * strftime doesn't treat them as format codes.
1179 */
1180 Py_DECREF(Zreplacement);
1181 Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1182 Py_DECREF(temp);
1183 if (Zreplacement == NULL)
1184 return NULL;
1185 if (!PyUnicode_Check(Zreplacement)) {
1186 PyErr_SetString(PyExc_TypeError,
1187 "tzname.replace() did not return a string");
1188 goto Error;
1189 }
1190 return Zreplacement;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001191
1192 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 Py_DECREF(Zreplacement);
1194 return NULL;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001195}
1196
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001197static PyObject *
1198make_freplacement(PyObject *object)
1199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 char freplacement[64];
1201 if (PyTime_Check(object))
1202 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1203 else if (PyDateTime_Check(object))
1204 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1205 else
1206 sprintf(freplacement, "%06d", 0);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001209}
1210
Tim Peters2a799bf2002-12-16 20:18:38 +00001211/* I sure don't want to reproduce the strftime code from the time module,
1212 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001213 * giving special meanings to the %z, %Z and %f format codes via a
1214 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001215 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1216 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001217 */
1218static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001219wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 PyObject *result = NULL; /* guilty until proved innocent */
Tim Peters2a799bf2002-12-16 20:18:38 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1225 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1226 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 const char *pin; /* pointer to next char in input format */
1229 Py_ssize_t flen; /* length of input format */
1230 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 PyObject *newfmt = NULL; /* py string, the output format */
1233 char *pnew; /* pointer to available byte in output format */
1234 size_t totalnew; /* number bytes total in output format buffer,
1235 exclusive of trailing \0 */
1236 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 const char *ptoappend; /* ptr to string to append to output buffer */
1239 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 assert(object && format && timetuple);
1242 assert(PyUnicode_Check(format));
1243 /* Convert the input format to a C string and size */
1244 pin = _PyUnicode_AsStringAndSize(format, &flen);
1245 if (!pin)
1246 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 /* Give up if the year is before 1900.
1249 * Python strftime() plays games with the year, and different
1250 * games depending on whether envar PYTHON2K is set. This makes
1251 * years before 1900 a nightmare, even if the platform strftime
1252 * supports them (and not all do).
1253 * We could get a lot farther here by avoiding Python's strftime
1254 * wrapper and calling the C strftime() directly, but that isn't
1255 * an option in the Python implementation of this module.
1256 */
1257 {
1258 long year;
1259 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1260 if (pyyear == NULL) return NULL;
1261 assert(PyLong_Check(pyyear));
1262 year = PyLong_AsLong(pyyear);
1263 Py_DECREF(pyyear);
1264 if (year < 1900) {
1265 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1266 "1900; the datetime strftime() "
1267 "methods require year >= 1900",
1268 year);
1269 return NULL;
1270 }
1271 }
Tim Petersd6844152002-12-22 20:58:42 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 /* Scan the input format, looking for %z/%Z/%f escapes, building
1274 * a new format. Since computing the replacements for those codes
1275 * is expensive, don't unless they're actually used.
1276 */
1277 if (flen > INT_MAX - 1) {
1278 PyErr_NoMemory();
1279 goto Done;
1280 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 totalnew = flen + 1; /* realistic if no %z/%Z */
1283 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
1284 if (newfmt == NULL) goto Done;
1285 pnew = PyBytes_AsString(newfmt);
1286 usednew = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 while ((ch = *pin++) != '\0') {
1289 if (ch != '%') {
1290 ptoappend = pin - 1;
1291 ntoappend = 1;
1292 }
1293 else if ((ch = *pin++) == '\0') {
1294 /* There's a lone trailing %; doesn't make sense. */
1295 PyErr_SetString(PyExc_ValueError, "strftime format "
1296 "ends with raw %");
1297 goto Done;
1298 }
1299 /* A % has been seen and ch is the character after it. */
1300 else if (ch == 'z') {
1301 if (zreplacement == NULL) {
1302 /* format utcoffset */
1303 char buf[100];
1304 PyObject *tzinfo = get_tzinfo_member(object);
1305 zreplacement = PyBytes_FromStringAndSize("", 0);
1306 if (zreplacement == NULL) goto Done;
1307 if (tzinfo != Py_None && tzinfo != NULL) {
1308 assert(tzinfoarg != NULL);
1309 if (format_utcoffset(buf,
1310 sizeof(buf),
1311 "",
1312 tzinfo,
1313 tzinfoarg) < 0)
1314 goto Done;
1315 Py_DECREF(zreplacement);
1316 zreplacement =
1317 PyBytes_FromStringAndSize(buf,
1318 strlen(buf));
1319 if (zreplacement == NULL)
1320 goto Done;
1321 }
1322 }
1323 assert(zreplacement != NULL);
1324 ptoappend = PyBytes_AS_STRING(zreplacement);
1325 ntoappend = PyBytes_GET_SIZE(zreplacement);
1326 }
1327 else if (ch == 'Z') {
1328 /* format tzname */
1329 if (Zreplacement == NULL) {
1330 Zreplacement = make_Zreplacement(object,
1331 tzinfoarg);
1332 if (Zreplacement == NULL)
1333 goto Done;
1334 }
1335 assert(Zreplacement != NULL);
1336 assert(PyUnicode_Check(Zreplacement));
1337 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
1338 &ntoappend);
1339 ntoappend = Py_SIZE(Zreplacement);
1340 }
1341 else if (ch == 'f') {
1342 /* format microseconds */
1343 if (freplacement == NULL) {
1344 freplacement = make_freplacement(object);
1345 if (freplacement == NULL)
1346 goto Done;
1347 }
1348 assert(freplacement != NULL);
1349 assert(PyBytes_Check(freplacement));
1350 ptoappend = PyBytes_AS_STRING(freplacement);
1351 ntoappend = PyBytes_GET_SIZE(freplacement);
1352 }
1353 else {
1354 /* percent followed by neither z nor Z */
1355 ptoappend = pin - 2;
1356 ntoappend = 2;
1357 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* Append the ntoappend chars starting at ptoappend to
1360 * the new format.
1361 */
1362 if (ntoappend == 0)
1363 continue;
1364 assert(ptoappend != NULL);
1365 assert(ntoappend > 0);
1366 while (usednew + ntoappend > totalnew) {
1367 size_t bigger = totalnew << 1;
1368 if ((bigger >> 1) != totalnew) { /* overflow */
1369 PyErr_NoMemory();
1370 goto Done;
1371 }
1372 if (_PyBytes_Resize(&newfmt, bigger) < 0)
1373 goto Done;
1374 totalnew = bigger;
1375 pnew = PyBytes_AsString(newfmt) + usednew;
1376 }
1377 memcpy(pnew, ptoappend, ntoappend);
1378 pnew += ntoappend;
1379 usednew += ntoappend;
1380 assert(usednew <= totalnew);
1381 } /* end while() */
Tim Peters2a799bf2002-12-16 20:18:38 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 if (_PyBytes_Resize(&newfmt, usednew) < 0)
1384 goto Done;
1385 {
1386 PyObject *format;
1387 PyObject *time = PyImport_ImportModuleNoBlock("time");
1388 if (time == NULL)
1389 goto Done;
1390 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1391 if (format != NULL) {
1392 result = PyObject_CallMethod(time, "strftime", "OO",
1393 format, timetuple);
1394 Py_DECREF(format);
1395 }
1396 Py_DECREF(time);
1397 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001398 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_XDECREF(freplacement);
1400 Py_XDECREF(zreplacement);
1401 Py_XDECREF(Zreplacement);
1402 Py_XDECREF(newfmt);
1403 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001404}
1405
Tim Peters2a799bf2002-12-16 20:18:38 +00001406/* ---------------------------------------------------------------------------
1407 * Wrap functions from the time module. These aren't directly available
1408 * from C. Perhaps they should be.
1409 */
1410
1411/* Call time.time() and return its result (a Python float). */
1412static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001413time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PyObject *result = NULL;
1416 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (time != NULL) {
1419 result = PyObject_CallMethod(time, "time", "()");
1420 Py_DECREF(time);
1421 }
1422 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001423}
1424
1425/* Build a time.struct_time. The weekday and day number are automatically
1426 * computed from the y,m,d args.
1427 */
1428static PyObject *
1429build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyObject *time;
1432 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 time = PyImport_ImportModuleNoBlock("time");
1435 if (time != NULL) {
1436 result = PyObject_CallMethod(time, "struct_time",
1437 "((iiiiiiiii))",
1438 y, m, d,
1439 hh, mm, ss,
1440 weekday(y, m, d),
1441 days_before_month(y, m) + d,
1442 dstflag);
1443 Py_DECREF(time);
1444 }
1445 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001446}
1447
1448/* ---------------------------------------------------------------------------
1449 * Miscellaneous helpers.
1450 */
1451
Mark Dickinsone94c6792009-02-02 20:36:42 +00001452/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001453 * The comparisons here all most naturally compute a cmp()-like result.
1454 * This little helper turns that into a bool result for rich comparisons.
1455 */
1456static PyObject *
1457diff_to_bool(int diff, int op)
1458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 PyObject *result;
1460 int istrue;
Tim Peters2a799bf2002-12-16 20:18:38 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 switch (op) {
1463 case Py_EQ: istrue = diff == 0; break;
1464 case Py_NE: istrue = diff != 0; break;
1465 case Py_LE: istrue = diff <= 0; break;
1466 case Py_GE: istrue = diff >= 0; break;
1467 case Py_LT: istrue = diff < 0; break;
1468 case Py_GT: istrue = diff > 0; break;
1469 default:
1470 assert(! "op unknown");
1471 istrue = 0; /* To shut up compiler */
1472 }
1473 result = istrue ? Py_True : Py_False;
1474 Py_INCREF(result);
1475 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001476}
1477
Tim Peters07534a62003-02-07 22:50:28 +00001478/* Raises a "can't compare" TypeError and returns NULL. */
1479static PyObject *
1480cmperror(PyObject *a, PyObject *b)
1481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 PyErr_Format(PyExc_TypeError,
1483 "can't compare %s to %s",
1484 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1485 return NULL;
Tim Peters07534a62003-02-07 22:50:28 +00001486}
1487
Tim Peters2a799bf2002-12-16 20:18:38 +00001488/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001489 * Cached Python objects; these are set by the module init function.
1490 */
1491
1492/* Conversion factors. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493static PyObject *us_per_us = NULL; /* 1 */
1494static PyObject *us_per_ms = NULL; /* 1000 */
1495static PyObject *us_per_second = NULL; /* 1000000 */
1496static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1497static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1498static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1499static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
Tim Peters2a799bf2002-12-16 20:18:38 +00001500static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1501
Tim Peters2a799bf2002-12-16 20:18:38 +00001502/* ---------------------------------------------------------------------------
1503 * Class implementations.
1504 */
1505
1506/*
1507 * PyDateTime_Delta implementation.
1508 */
1509
1510/* Convert a timedelta to a number of us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
Tim Peters2a799bf2002-12-16 20:18:38 +00001512 * as a Python int or long.
1513 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1514 * due to ubiquitous overflow possibilities.
1515 */
1516static PyObject *
1517delta_to_microseconds(PyDateTime_Delta *self)
1518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyObject *x1 = NULL;
1520 PyObject *x2 = NULL;
1521 PyObject *x3 = NULL;
1522 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 x1 = PyLong_FromLong(GET_TD_DAYS(self));
1525 if (x1 == NULL)
1526 goto Done;
1527 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1528 if (x2 == NULL)
1529 goto Done;
1530 Py_DECREF(x1);
1531 x1 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 /* x2 has days in seconds */
1534 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
1535 if (x1 == NULL)
1536 goto Done;
1537 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1538 if (x3 == NULL)
1539 goto Done;
1540 Py_DECREF(x1);
1541 Py_DECREF(x2);
1542 x1 = x2 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 /* x3 has days+seconds in seconds */
1545 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1546 if (x1 == NULL)
1547 goto Done;
1548 Py_DECREF(x3);
1549 x3 = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 /* x1 has days+seconds in us */
1552 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
1553 if (x2 == NULL)
1554 goto Done;
1555 result = PyNumber_Add(x1, x2);
Tim Peters2a799bf2002-12-16 20:18:38 +00001556
1557Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 Py_XDECREF(x1);
1559 Py_XDECREF(x2);
1560 Py_XDECREF(x3);
1561 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001562}
1563
1564/* Convert a number of us (as a Python int or long) to a timedelta.
1565 */
1566static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001567microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 int us;
1570 int s;
1571 int d;
1572 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 PyObject *tuple = NULL;
1575 PyObject *num = NULL;
1576 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 tuple = PyNumber_Divmod(pyus, us_per_second);
1579 if (tuple == NULL)
1580 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 num = PyTuple_GetItem(tuple, 1); /* us */
1583 if (num == NULL)
1584 goto Done;
1585 temp = PyLong_AsLong(num);
1586 num = NULL;
1587 if (temp == -1 && PyErr_Occurred())
1588 goto Done;
1589 assert(0 <= temp && temp < 1000000);
1590 us = (int)temp;
1591 if (us < 0) {
1592 /* The divisor was positive, so this must be an error. */
1593 assert(PyErr_Occurred());
1594 goto Done;
1595 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1598 if (num == NULL)
1599 goto Done;
1600 Py_INCREF(num);
1601 Py_DECREF(tuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 tuple = PyNumber_Divmod(num, seconds_per_day);
1604 if (tuple == NULL)
1605 goto Done;
1606 Py_DECREF(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 num = PyTuple_GetItem(tuple, 1); /* seconds */
1609 if (num == NULL)
1610 goto Done;
1611 temp = PyLong_AsLong(num);
1612 num = NULL;
1613 if (temp == -1 && PyErr_Occurred())
1614 goto Done;
1615 assert(0 <= temp && temp < 24*3600);
1616 s = (int)temp;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (s < 0) {
1619 /* The divisor was positive, so this must be an error. */
1620 assert(PyErr_Occurred());
1621 goto Done;
1622 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1625 if (num == NULL)
1626 goto Done;
1627 Py_INCREF(num);
1628 temp = PyLong_AsLong(num);
1629 if (temp == -1 && PyErr_Occurred())
1630 goto Done;
1631 d = (int)temp;
1632 if ((long)d != temp) {
1633 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1634 "large to fit in a C int");
1635 goto Done;
1636 }
1637 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001638
1639Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 Py_XDECREF(tuple);
1641 Py_XDECREF(num);
1642 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001643}
1644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645#define microseconds_to_delta(pymicros) \
1646 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
Tim Petersb0c854d2003-05-17 15:57:00 +00001647
Tim Peters2a799bf2002-12-16 20:18:38 +00001648static PyObject *
1649multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 PyObject *pyus_in;
1652 PyObject *pyus_out;
1653 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 pyus_in = delta_to_microseconds(delta);
1656 if (pyus_in == NULL)
1657 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1660 Py_DECREF(pyus_in);
1661 if (pyus_out == NULL)
1662 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 result = microseconds_to_delta(pyus_out);
1665 Py_DECREF(pyus_out);
1666 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001667}
1668
1669static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001670multiply_float_timedelta(PyObject *floatobj, PyDateTime_Delta *delta)
1671{
1672 PyObject *result = NULL;
1673 PyObject *pyus_in = NULL, *temp, *pyus_out;
1674 PyObject *ratio = NULL;
1675
1676 pyus_in = delta_to_microseconds(delta);
1677 if (pyus_in == NULL)
1678 return NULL;
1679 ratio = PyObject_CallMethod(floatobj, "as_integer_ratio", NULL);
1680 if (ratio == NULL)
1681 goto error;
1682 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 0));
1683 Py_DECREF(pyus_in);
1684 pyus_in = NULL;
1685 if (temp == NULL)
1686 goto error;
1687 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 1));
1688 Py_DECREF(temp);
1689 if (pyus_out == NULL)
1690 goto error;
1691 result = microseconds_to_delta(pyus_out);
1692 Py_DECREF(pyus_out);
1693 error:
1694 Py_XDECREF(pyus_in);
1695 Py_XDECREF(ratio);
1696
1697 return result;
1698}
1699
1700static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001701divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyObject *pyus_in;
1704 PyObject *pyus_out;
1705 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 pyus_in = delta_to_microseconds(delta);
1708 if (pyus_in == NULL)
1709 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1712 Py_DECREF(pyus_in);
1713 if (pyus_out == NULL)
1714 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 result = microseconds_to_delta(pyus_out);
1717 Py_DECREF(pyus_out);
1718 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001719}
1720
1721static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001722divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 PyObject *pyus_left;
1725 PyObject *pyus_right;
1726 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 pyus_left = delta_to_microseconds(left);
1729 if (pyus_left == NULL)
1730 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 pyus_right = delta_to_microseconds(right);
1733 if (pyus_right == NULL) {
1734 Py_DECREF(pyus_left);
1735 return NULL;
1736 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1739 Py_DECREF(pyus_left);
1740 Py_DECREF(pyus_right);
1741 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001742}
1743
1744static PyObject *
1745truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 PyObject *pyus_left;
1748 PyObject *pyus_right;
1749 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 pyus_left = delta_to_microseconds(left);
1752 if (pyus_left == NULL)
1753 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 pyus_right = delta_to_microseconds(right);
1756 if (pyus_right == NULL) {
1757 Py_DECREF(pyus_left);
1758 return NULL;
1759 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1762 Py_DECREF(pyus_left);
1763 Py_DECREF(pyus_right);
1764 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001765}
1766
1767static PyObject *
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001768truedivide_timedelta_float(PyDateTime_Delta *delta, PyObject *f)
1769{
1770 PyObject *result = NULL;
1771 PyObject *pyus_in = NULL, *temp, *pyus_out;
1772 PyObject *ratio = NULL;
1773
1774 pyus_in = delta_to_microseconds(delta);
1775 if (pyus_in == NULL)
1776 return NULL;
1777 ratio = PyObject_CallMethod(f, "as_integer_ratio", NULL);
1778 if (ratio == NULL)
1779 goto error;
1780 temp = PyNumber_Multiply(pyus_in, PyTuple_GET_ITEM(ratio, 1));
1781 Py_DECREF(pyus_in);
1782 pyus_in = NULL;
1783 if (temp == NULL)
1784 goto error;
1785 pyus_out = divide_nearest(temp, PyTuple_GET_ITEM(ratio, 0));
1786 Py_DECREF(temp);
1787 if (pyus_out == NULL)
1788 goto error;
1789 result = microseconds_to_delta(pyus_out);
1790 Py_DECREF(pyus_out);
1791 error:
1792 Py_XDECREF(pyus_in);
1793 Py_XDECREF(ratio);
1794
1795 return result;
1796}
1797
1798static PyObject *
1799truedivide_timedelta_int(PyDateTime_Delta *delta, PyObject *i)
1800{
1801 PyObject *result;
1802 PyObject *pyus_in, *pyus_out;
1803 pyus_in = delta_to_microseconds(delta);
1804 if (pyus_in == NULL)
1805 return NULL;
1806 pyus_out = divide_nearest(pyus_in, i);
1807 Py_DECREF(pyus_in);
1808 if (pyus_out == NULL)
1809 return NULL;
1810 result = microseconds_to_delta(pyus_out);
1811 Py_DECREF(pyus_out);
1812
1813 return result;
1814}
1815
1816static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001817delta_add(PyObject *left, PyObject *right)
1818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1822 /* delta + delta */
1823 /* The C-level additions can't overflow because of the
1824 * invariant bounds.
1825 */
1826 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1827 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1828 int microseconds = GET_TD_MICROSECONDS(left) +
1829 GET_TD_MICROSECONDS(right);
1830 result = new_delta(days, seconds, microseconds, 1);
1831 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (result == Py_NotImplemented)
1834 Py_INCREF(result);
1835 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001836}
1837
1838static PyObject *
1839delta_negative(PyDateTime_Delta *self)
1840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 return new_delta(-GET_TD_DAYS(self),
1842 -GET_TD_SECONDS(self),
1843 -GET_TD_MICROSECONDS(self),
1844 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001845}
1846
1847static PyObject *
1848delta_positive(PyDateTime_Delta *self)
1849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 /* Could optimize this (by returning self) if this isn't a
1851 * subclass -- but who uses unary + ? Approximately nobody.
1852 */
1853 return new_delta(GET_TD_DAYS(self),
1854 GET_TD_SECONDS(self),
1855 GET_TD_MICROSECONDS(self),
1856 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001857}
1858
1859static PyObject *
1860delta_abs(PyDateTime_Delta *self)
1861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 assert(GET_TD_MICROSECONDS(self) >= 0);
1865 assert(GET_TD_SECONDS(self) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (GET_TD_DAYS(self) < 0)
1868 result = delta_negative(self);
1869 else
1870 result = delta_positive(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001873}
1874
1875static PyObject *
1876delta_subtract(PyObject *left, PyObject *right)
1877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1881 /* delta - delta */
1882 PyObject *minus_right = PyNumber_Negative(right);
1883 if (minus_right) {
1884 result = delta_add(left, minus_right);
1885 Py_DECREF(minus_right);
1886 }
1887 else
1888 result = NULL;
1889 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 if (result == Py_NotImplemented)
1892 Py_INCREF(result);
1893 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001894}
1895
Tim Peters2a799bf2002-12-16 20:18:38 +00001896static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001897delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 if (PyDelta_Check(other)) {
1900 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1901 if (diff == 0) {
1902 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1903 if (diff == 0)
1904 diff = GET_TD_MICROSECONDS(self) -
1905 GET_TD_MICROSECONDS(other);
1906 }
1907 return diff_to_bool(diff, op);
1908 }
1909 else {
1910 Py_INCREF(Py_NotImplemented);
1911 return Py_NotImplemented;
1912 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001913}
1914
1915static PyObject *delta_getstate(PyDateTime_Delta *self);
1916
1917static long
1918delta_hash(PyDateTime_Delta *self)
1919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 if (self->hashcode == -1) {
1921 PyObject *temp = delta_getstate(self);
1922 if (temp != NULL) {
1923 self->hashcode = PyObject_Hash(temp);
1924 Py_DECREF(temp);
1925 }
1926 }
1927 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00001928}
1929
1930static PyObject *
1931delta_multiply(PyObject *left, PyObject *right)
1932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 if (PyDelta_Check(left)) {
1936 /* delta * ??? */
1937 if (PyLong_Check(right))
1938 result = multiply_int_timedelta(right,
1939 (PyDateTime_Delta *) left);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001940 else if (PyFloat_Check(right))
1941 result = multiply_float_timedelta(right,
1942 (PyDateTime_Delta *) left);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
1944 else if (PyLong_Check(left))
1945 result = multiply_int_timedelta(left,
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001946 (PyDateTime_Delta *) right);
1947 else if (PyFloat_Check(left))
1948 result = multiply_float_timedelta(left,
1949 (PyDateTime_Delta *) right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 if (result == Py_NotImplemented)
1952 Py_INCREF(result);
1953 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001954}
1955
1956static PyObject *
1957delta_divide(PyObject *left, PyObject *right)
1958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 if (PyDelta_Check(left)) {
1962 /* delta * ??? */
1963 if (PyLong_Check(right))
1964 result = divide_timedelta_int(
1965 (PyDateTime_Delta *)left,
1966 right);
1967 else if (PyDelta_Check(right))
1968 result = divide_timedelta_timedelta(
1969 (PyDateTime_Delta *)left,
1970 (PyDateTime_Delta *)right);
1971 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (result == Py_NotImplemented)
1974 Py_INCREF(result);
1975 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00001976}
1977
Mark Dickinson7c186e22010-04-20 22:32:49 +00001978static PyObject *
1979delta_truedivide(PyObject *left, PyObject *right)
1980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject *result = Py_NotImplemented;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (PyDelta_Check(left)) {
1984 if (PyDelta_Check(right))
1985 result = truedivide_timedelta_timedelta(
1986 (PyDateTime_Delta *)left,
1987 (PyDateTime_Delta *)right);
Alexander Belopolsky1790bc42010-05-31 17:33:47 +00001988 else if (PyFloat_Check(right))
1989 result = truedivide_timedelta_float(
1990 (PyDateTime_Delta *)left, right);
1991 else if (PyLong_Check(right))
1992 result = truedivide_timedelta_int(
1993 (PyDateTime_Delta *)left, right);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (result == Py_NotImplemented)
1997 Py_INCREF(result);
1998 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001999}
2000
2001static PyObject *
2002delta_remainder(PyObject *left, PyObject *right)
2003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyObject *pyus_left;
2005 PyObject *pyus_right;
2006 PyObject *pyus_remainder;
2007 PyObject *remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
2010 Py_INCREF(Py_NotImplemented);
2011 return Py_NotImplemented;
2012 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2015 if (pyus_left == NULL)
2016 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2019 if (pyus_right == NULL) {
2020 Py_DECREF(pyus_left);
2021 return NULL;
2022 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
2025 Py_DECREF(pyus_left);
2026 Py_DECREF(pyus_right);
2027 if (pyus_remainder == NULL)
2028 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 remainder = microseconds_to_delta(pyus_remainder);
2031 Py_DECREF(pyus_remainder);
2032 if (remainder == NULL)
2033 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 return remainder;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002036}
2037
2038static PyObject *
2039delta_divmod(PyObject *left, PyObject *right)
2040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 PyObject *pyus_left;
2042 PyObject *pyus_right;
2043 PyObject *divmod;
2044 PyObject *delta;
2045 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
2048 Py_INCREF(Py_NotImplemented);
2049 return Py_NotImplemented;
2050 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
2053 if (pyus_left == NULL)
2054 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
2057 if (pyus_right == NULL) {
2058 Py_DECREF(pyus_left);
2059 return NULL;
2060 }
Mark Dickinson7c186e22010-04-20 22:32:49 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 divmod = PyNumber_Divmod(pyus_left, pyus_right);
2063 Py_DECREF(pyus_left);
2064 Py_DECREF(pyus_right);
2065 if (divmod == NULL)
2066 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 assert(PyTuple_Size(divmod) == 2);
2069 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
2070 if (delta == NULL) {
2071 Py_DECREF(divmod);
2072 return NULL;
2073 }
2074 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
2075 Py_DECREF(delta);
2076 Py_DECREF(divmod);
2077 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00002078}
2079
Tim Peters2a799bf2002-12-16 20:18:38 +00002080/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
2081 * timedelta constructor. sofar is the # of microseconds accounted for
2082 * so far, and there are factor microseconds per current unit, the number
2083 * of which is given by num. num * factor is added to sofar in a
2084 * numerically careful way, and that's the result. Any fractional
2085 * microseconds left over (this can happen if num is a float type) are
2086 * added into *leftover.
2087 * Note that there are many ways this can give an error (NULL) return.
2088 */
2089static PyObject *
2090accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
2091 double *leftover)
2092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 PyObject *prod;
2094 PyObject *sum;
Tim Peters2a799bf2002-12-16 20:18:38 +00002095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 assert(num != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 if (PyLong_Check(num)) {
2099 prod = PyNumber_Multiply(num, factor);
2100 if (prod == NULL)
2101 return NULL;
2102 sum = PyNumber_Add(sofar, prod);
2103 Py_DECREF(prod);
2104 return sum;
2105 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (PyFloat_Check(num)) {
2108 double dnum;
2109 double fracpart;
2110 double intpart;
2111 PyObject *x;
2112 PyObject *y;
Tim Peters2a799bf2002-12-16 20:18:38 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* The Plan: decompose num into an integer part and a
2115 * fractional part, num = intpart + fracpart.
2116 * Then num * factor ==
2117 * intpart * factor + fracpart * factor
2118 * and the LHS can be computed exactly in long arithmetic.
2119 * The RHS is again broken into an int part and frac part.
2120 * and the frac part is added into *leftover.
2121 */
2122 dnum = PyFloat_AsDouble(num);
2123 if (dnum == -1.0 && PyErr_Occurred())
2124 return NULL;
2125 fracpart = modf(dnum, &intpart);
2126 x = PyLong_FromDouble(intpart);
2127 if (x == NULL)
2128 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 prod = PyNumber_Multiply(x, factor);
2131 Py_DECREF(x);
2132 if (prod == NULL)
2133 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 sum = PyNumber_Add(sofar, prod);
2136 Py_DECREF(prod);
2137 if (sum == NULL)
2138 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (fracpart == 0.0)
2141 return sum;
2142 /* So far we've lost no information. Dealing with the
2143 * fractional part requires float arithmetic, and may
2144 * lose a little info.
2145 */
2146 assert(PyLong_Check(factor));
2147 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 dnum *= fracpart;
2150 fracpart = modf(dnum, &intpart);
2151 x = PyLong_FromDouble(intpart);
2152 if (x == NULL) {
2153 Py_DECREF(sum);
2154 return NULL;
2155 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 y = PyNumber_Add(sum, x);
2158 Py_DECREF(sum);
2159 Py_DECREF(x);
2160 *leftover += fracpart;
2161 return y;
2162 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyErr_Format(PyExc_TypeError,
2165 "unsupported type for timedelta %s component: %s",
2166 tag, Py_TYPE(num)->tp_name);
2167 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002168}
2169
2170static PyObject *
2171delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyObject *self = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* Argument objects. */
2176 PyObject *day = NULL;
2177 PyObject *second = NULL;
2178 PyObject *us = NULL;
2179 PyObject *ms = NULL;
2180 PyObject *minute = NULL;
2181 PyObject *hour = NULL;
2182 PyObject *week = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 PyObject *x = NULL; /* running sum of microseconds */
2185 PyObject *y = NULL; /* temp sum of microseconds */
2186 double leftover_us = 0.0;
Tim Peters2a799bf2002-12-16 20:18:38 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 static char *keywords[] = {
2189 "days", "seconds", "microseconds", "milliseconds",
2190 "minutes", "hours", "weeks", NULL
2191 };
Tim Peters2a799bf2002-12-16 20:18:38 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2194 keywords,
2195 &day, &second, &us,
2196 &ms, &minute, &hour, &week) == 0)
2197 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 x = PyLong_FromLong(0);
2200 if (x == NULL)
2201 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203#define CLEANUP \
2204 Py_DECREF(x); \
2205 x = y; \
2206 if (x == NULL) \
2207 goto Done
Tim Peters2a799bf2002-12-16 20:18:38 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 if (us) {
2210 y = accum("microseconds", x, us, us_per_us, &leftover_us);
2211 CLEANUP;
2212 }
2213 if (ms) {
2214 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2215 CLEANUP;
2216 }
2217 if (second) {
2218 y = accum("seconds", x, second, us_per_second, &leftover_us);
2219 CLEANUP;
2220 }
2221 if (minute) {
2222 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2223 CLEANUP;
2224 }
2225 if (hour) {
2226 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2227 CLEANUP;
2228 }
2229 if (day) {
2230 y = accum("days", x, day, us_per_day, &leftover_us);
2231 CLEANUP;
2232 }
2233 if (week) {
2234 y = accum("weeks", x, week, us_per_week, &leftover_us);
2235 CLEANUP;
2236 }
2237 if (leftover_us) {
2238 /* Round to nearest whole # of us, and add into x. */
2239 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
2240 if (temp == NULL) {
2241 Py_DECREF(x);
2242 goto Done;
2243 }
2244 y = PyNumber_Add(x, temp);
2245 Py_DECREF(temp);
2246 CLEANUP;
2247 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 self = microseconds_to_delta_ex(x, type);
2250 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00002251Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002253
2254#undef CLEANUP
2255}
2256
2257static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002258delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 return (GET_TD_DAYS(self) != 0
2261 || GET_TD_SECONDS(self) != 0
2262 || GET_TD_MICROSECONDS(self) != 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002263}
2264
2265static PyObject *
2266delta_repr(PyDateTime_Delta *self)
2267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if (GET_TD_MICROSECONDS(self) != 0)
2269 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2270 Py_TYPE(self)->tp_name,
2271 GET_TD_DAYS(self),
2272 GET_TD_SECONDS(self),
2273 GET_TD_MICROSECONDS(self));
2274 if (GET_TD_SECONDS(self) != 0)
2275 return PyUnicode_FromFormat("%s(%d, %d)",
2276 Py_TYPE(self)->tp_name,
2277 GET_TD_DAYS(self),
2278 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 return PyUnicode_FromFormat("%s(%d)",
2281 Py_TYPE(self)->tp_name,
2282 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002283}
2284
2285static PyObject *
2286delta_str(PyDateTime_Delta *self)
2287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 int us = GET_TD_MICROSECONDS(self);
2289 int seconds = GET_TD_SECONDS(self);
2290 int minutes = divmod(seconds, 60, &seconds);
2291 int hours = divmod(minutes, 60, &minutes);
2292 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 if (days) {
2295 if (us)
2296 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2297 days, (days == 1 || days == -1) ? "" : "s",
2298 hours, minutes, seconds, us);
2299 else
2300 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2301 days, (days == 1 || days == -1) ? "" : "s",
2302 hours, minutes, seconds);
2303 } else {
2304 if (us)
2305 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2306 hours, minutes, seconds, us);
2307 else
2308 return PyUnicode_FromFormat("%d:%02d:%02d",
2309 hours, minutes, seconds);
2310 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002311
Tim Peters2a799bf2002-12-16 20:18:38 +00002312}
2313
Tim Peters371935f2003-02-01 01:52:50 +00002314/* Pickle support, a simple use of __reduce__. */
2315
Tim Petersb57f8f02003-02-01 02:54:15 +00002316/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002317static PyObject *
2318delta_getstate(PyDateTime_Delta *self)
2319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 return Py_BuildValue("iii", GET_TD_DAYS(self),
2321 GET_TD_SECONDS(self),
2322 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002323}
2324
Tim Peters2a799bf2002-12-16 20:18:38 +00002325static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002326delta_total_seconds(PyObject *self)
2327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 PyObject *total_seconds;
2329 PyObject *total_microseconds;
2330 PyObject *one_million;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2333 if (total_microseconds == NULL)
2334 return NULL;
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 one_million = PyLong_FromLong(1000000L);
2337 if (one_million == NULL) {
2338 Py_DECREF(total_microseconds);
2339 return NULL;
2340 }
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
Mark Dickinson0381e3f2010-05-08 14:35:02 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 Py_DECREF(total_microseconds);
2345 Py_DECREF(one_million);
2346 return total_seconds;
Antoine Pitroube6859d2009-11-25 23:02:32 +00002347}
2348
2349static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002350delta_reduce(PyDateTime_Delta* self)
2351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002353}
2354
2355#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2356
2357static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 {"days", T_INT, OFFSET(days), READONLY,
2360 PyDoc_STR("Number of days.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 {"seconds", T_INT, OFFSET(seconds), READONLY,
2363 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2366 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2367 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002368};
2369
2370static PyMethodDef delta_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2372 PyDoc_STR("Total seconds in the duration.")},
Antoine Pitroube6859d2009-11-25 23:02:32 +00002373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2375 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 {NULL, NULL},
Tim Peters2a799bf2002-12-16 20:18:38 +00002378};
2379
2380static char delta_doc[] =
2381PyDoc_STR("Difference between two datetime values.");
2382
2383static PyNumberMethods delta_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 delta_add, /* nb_add */
2385 delta_subtract, /* nb_subtract */
2386 delta_multiply, /* nb_multiply */
2387 delta_remainder, /* nb_remainder */
2388 delta_divmod, /* nb_divmod */
2389 0, /* nb_power */
2390 (unaryfunc)delta_negative, /* nb_negative */
2391 (unaryfunc)delta_positive, /* nb_positive */
2392 (unaryfunc)delta_abs, /* nb_absolute */
2393 (inquiry)delta_bool, /* nb_bool */
2394 0, /*nb_invert*/
2395 0, /*nb_lshift*/
2396 0, /*nb_rshift*/
2397 0, /*nb_and*/
2398 0, /*nb_xor*/
2399 0, /*nb_or*/
2400 0, /*nb_int*/
2401 0, /*nb_reserved*/
2402 0, /*nb_float*/
2403 0, /*nb_inplace_add*/
2404 0, /*nb_inplace_subtract*/
2405 0, /*nb_inplace_multiply*/
2406 0, /*nb_inplace_remainder*/
2407 0, /*nb_inplace_power*/
2408 0, /*nb_inplace_lshift*/
2409 0, /*nb_inplace_rshift*/
2410 0, /*nb_inplace_and*/
2411 0, /*nb_inplace_xor*/
2412 0, /*nb_inplace_or*/
2413 delta_divide, /* nb_floor_divide */
2414 delta_truedivide, /* nb_true_divide */
2415 0, /* nb_inplace_floor_divide */
2416 0, /* nb_inplace_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002417};
2418
2419static PyTypeObject PyDateTime_DeltaType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 PyVarObject_HEAD_INIT(NULL, 0)
2421 "datetime.timedelta", /* tp_name */
2422 sizeof(PyDateTime_Delta), /* tp_basicsize */
2423 0, /* tp_itemsize */
2424 0, /* tp_dealloc */
2425 0, /* tp_print */
2426 0, /* tp_getattr */
2427 0, /* tp_setattr */
2428 0, /* tp_reserved */
2429 (reprfunc)delta_repr, /* tp_repr */
2430 &delta_as_number, /* tp_as_number */
2431 0, /* tp_as_sequence */
2432 0, /* tp_as_mapping */
2433 (hashfunc)delta_hash, /* tp_hash */
2434 0, /* tp_call */
2435 (reprfunc)delta_str, /* tp_str */
2436 PyObject_GenericGetAttr, /* tp_getattro */
2437 0, /* tp_setattro */
2438 0, /* tp_as_buffer */
2439 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2440 delta_doc, /* tp_doc */
2441 0, /* tp_traverse */
2442 0, /* tp_clear */
2443 delta_richcompare, /* tp_richcompare */
2444 0, /* tp_weaklistoffset */
2445 0, /* tp_iter */
2446 0, /* tp_iternext */
2447 delta_methods, /* tp_methods */
2448 delta_members, /* tp_members */
2449 0, /* tp_getset */
2450 0, /* tp_base */
2451 0, /* tp_dict */
2452 0, /* tp_descr_get */
2453 0, /* tp_descr_set */
2454 0, /* tp_dictoffset */
2455 0, /* tp_init */
2456 0, /* tp_alloc */
2457 delta_new, /* tp_new */
2458 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002459};
2460
2461/*
2462 * PyDateTime_Date implementation.
2463 */
2464
2465/* Accessor properties. */
2466
2467static PyObject *
2468date_year(PyDateTime_Date *self, void *unused)
2469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002471}
2472
2473static PyObject *
2474date_month(PyDateTime_Date *self, void *unused)
2475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002477}
2478
2479static PyObject *
2480date_day(PyDateTime_Date *self, void *unused)
2481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002483}
2484
2485static PyGetSetDef date_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 {"year", (getter)date_year},
2487 {"month", (getter)date_month},
2488 {"day", (getter)date_day},
2489 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002490};
2491
2492/* Constructors. */
2493
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002494static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002495
Tim Peters2a799bf2002-12-16 20:18:38 +00002496static PyObject *
2497date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 PyObject *self = NULL;
2500 PyObject *state;
2501 int year;
2502 int month;
2503 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 /* Check for invocation from pickle with __getstate__ state */
2506 if (PyTuple_GET_SIZE(args) == 1 &&
2507 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2508 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2509 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
2510 {
2511 PyDateTime_Date *me;
Tim Peters70533e22003-02-01 04:40:04 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2514 if (me != NULL) {
2515 char *pdata = PyBytes_AS_STRING(state);
2516 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2517 me->hashcode = -1;
2518 }
2519 return (PyObject *)me;
2520 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2523 &year, &month, &day)) {
2524 if (check_date_args(year, month, day) < 0)
2525 return NULL;
2526 self = new_date_ex(year, month, day, type);
2527 }
2528 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00002529}
2530
2531/* Return new date from localtime(t). */
2532static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002533date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 struct tm *tm;
2536 time_t t;
2537 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 t = _PyTime_DoubleToTimet(ts);
2540 if (t == (time_t)-1 && PyErr_Occurred())
2541 return NULL;
2542 tm = localtime(&t);
2543 if (tm)
2544 result = PyObject_CallFunction(cls, "iii",
2545 tm->tm_year + 1900,
2546 tm->tm_mon + 1,
2547 tm->tm_mday);
2548 else
2549 PyErr_SetString(PyExc_ValueError,
2550 "timestamp out of range for "
2551 "platform localtime() function");
2552 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002553}
2554
2555/* Return new date from current time.
2556 * We say this is equivalent to fromtimestamp(time.time()), and the
2557 * only way to be sure of that is to *call* time.time(). That's not
2558 * generally the same as calling C's time.
2559 */
2560static PyObject *
2561date_today(PyObject *cls, PyObject *dummy)
2562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 PyObject *time;
2564 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 time = time_time();
2567 if (time == NULL)
2568 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 /* Note well: today() is a class method, so this may not call
2571 * date.fromtimestamp. For example, it may call
2572 * datetime.fromtimestamp. That's why we need all the accuracy
2573 * time.time() delivers; if someone were gonzo about optimization,
2574 * date.today() could get away with plain C time().
2575 */
2576 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2577 Py_DECREF(time);
2578 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002579}
2580
2581/* Return new date from given timestamp (Python timestamp -- a double). */
2582static PyObject *
2583date_fromtimestamp(PyObject *cls, PyObject *args)
2584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 double timestamp;
2586 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2589 result = date_local_from_time_t(cls, timestamp);
2590 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002591}
2592
2593/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2594 * the ordinal is out of range.
2595 */
2596static PyObject *
2597date_fromordinal(PyObject *cls, PyObject *args)
2598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 PyObject *result = NULL;
2600 int ordinal;
Tim Peters2a799bf2002-12-16 20:18:38 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2603 int year;
2604 int month;
2605 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 if (ordinal < 1)
2608 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2609 ">= 1");
2610 else {
2611 ord_to_ymd(ordinal, &year, &month, &day);
2612 result = PyObject_CallFunction(cls, "iii",
2613 year, month, day);
2614 }
2615 }
2616 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002617}
2618
2619/*
2620 * Date arithmetic.
2621 */
2622
2623/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2624 * instead.
2625 */
2626static PyObject *
2627add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 PyObject *result = NULL;
2630 int year = GET_YEAR(date);
2631 int month = GET_MONTH(date);
2632 int deltadays = GET_TD_DAYS(delta);
2633 /* C-level overflow is impossible because |deltadays| < 1e9. */
2634 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
Tim Peters2a799bf2002-12-16 20:18:38 +00002635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 if (normalize_date(&year, &month, &day) >= 0)
2637 result = new_date(year, month, day);
2638 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002639}
2640
2641static PyObject *
2642date_add(PyObject *left, PyObject *right)
2643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2645 Py_INCREF(Py_NotImplemented);
2646 return Py_NotImplemented;
2647 }
2648 if (PyDate_Check(left)) {
2649 /* date + ??? */
2650 if (PyDelta_Check(right))
2651 /* date + delta */
2652 return add_date_timedelta((PyDateTime_Date *) left,
2653 (PyDateTime_Delta *) right,
2654 0);
2655 }
2656 else {
2657 /* ??? + date
2658 * 'right' must be one of us, or we wouldn't have been called
2659 */
2660 if (PyDelta_Check(left))
2661 /* delta + date */
2662 return add_date_timedelta((PyDateTime_Date *) right,
2663 (PyDateTime_Delta *) left,
2664 0);
2665 }
2666 Py_INCREF(Py_NotImplemented);
2667 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002668}
2669
2670static PyObject *
2671date_subtract(PyObject *left, PyObject *right)
2672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2674 Py_INCREF(Py_NotImplemented);
2675 return Py_NotImplemented;
2676 }
2677 if (PyDate_Check(left)) {
2678 if (PyDate_Check(right)) {
2679 /* date - date */
2680 int left_ord = ymd_to_ord(GET_YEAR(left),
2681 GET_MONTH(left),
2682 GET_DAY(left));
2683 int right_ord = ymd_to_ord(GET_YEAR(right),
2684 GET_MONTH(right),
2685 GET_DAY(right));
2686 return new_delta(left_ord - right_ord, 0, 0, 0);
2687 }
2688 if (PyDelta_Check(right)) {
2689 /* date - delta */
2690 return add_date_timedelta((PyDateTime_Date *) left,
2691 (PyDateTime_Delta *) right,
2692 1);
2693 }
2694 }
2695 Py_INCREF(Py_NotImplemented);
2696 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002697}
2698
2699
2700/* Various ways to turn a date into a string. */
2701
2702static PyObject *
2703date_repr(PyDateTime_Date *self)
2704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2706 Py_TYPE(self)->tp_name,
2707 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002708}
2709
2710static PyObject *
2711date_isoformat(PyDateTime_Date *self)
2712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 return PyUnicode_FromFormat("%04d-%02d-%02d",
2714 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002715}
2716
Tim Peterse2df5ff2003-05-02 18:39:55 +00002717/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002718static PyObject *
2719date_str(PyDateTime_Date *self)
2720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters2a799bf2002-12-16 20:18:38 +00002722}
2723
2724
2725static PyObject *
2726date_ctime(PyDateTime_Date *self)
2727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 return format_ctime(self, 0, 0, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002729}
2730
2731static PyObject *
2732date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 /* This method can be inherited, and needs to call the
2735 * timetuple() method appropriate to self's class.
2736 */
2737 PyObject *result;
2738 PyObject *tuple;
2739 PyObject *format;
2740 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
2743 &format))
2744 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2747 if (tuple == NULL)
2748 return NULL;
2749 result = wrap_strftime((PyObject *)self, format, tuple,
2750 (PyObject *)self);
2751 Py_DECREF(tuple);
2752 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002753}
2754
Eric Smith1ba31142007-09-11 18:06:02 +00002755static PyObject *
2756date_format(PyDateTime_Date *self, PyObject *args)
2757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 PyObject *format;
Eric Smith1ba31142007-09-11 18:06:02 +00002759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2761 return NULL;
Eric Smith1ba31142007-09-11 18:06:02 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 /* if the format is zero length, return str(self) */
2764 if (PyUnicode_GetSize(format) == 0)
2765 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
Eric Smith1ba31142007-09-11 18:06:02 +00002768}
2769
Tim Peters2a799bf2002-12-16 20:18:38 +00002770/* ISO methods. */
2771
2772static PyObject *
2773date_isoweekday(PyDateTime_Date *self)
2774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002778}
2779
2780static PyObject *
2781date_isocalendar(PyDateTime_Date *self)
2782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 int year = GET_YEAR(self);
2784 int week1_monday = iso_week1_monday(year);
2785 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2786 int week;
2787 int day;
Tim Peters2a799bf2002-12-16 20:18:38 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 week = divmod(today - week1_monday, 7, &day);
2790 if (week < 0) {
2791 --year;
2792 week1_monday = iso_week1_monday(year);
2793 week = divmod(today - week1_monday, 7, &day);
2794 }
2795 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2796 ++year;
2797 week = 0;
2798 }
2799 return Py_BuildValue("iii", year, week + 1, day + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002800}
2801
2802/* Miscellaneous methods. */
2803
Tim Peters2a799bf2002-12-16 20:18:38 +00002804static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002805date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 if (PyDate_Check(other)) {
2808 int diff = memcmp(((PyDateTime_Date *)self)->data,
2809 ((PyDateTime_Date *)other)->data,
2810 _PyDateTime_DATE_DATASIZE);
2811 return diff_to_bool(diff, op);
2812 }
2813 else {
2814 Py_INCREF(Py_NotImplemented);
2815 return Py_NotImplemented;
2816 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002817}
2818
2819static PyObject *
2820date_timetuple(PyDateTime_Date *self)
2821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 return build_struct_time(GET_YEAR(self),
2823 GET_MONTH(self),
2824 GET_DAY(self),
2825 0, 0, 0, -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002826}
2827
Tim Peters12bf3392002-12-24 05:41:27 +00002828static PyObject *
2829date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 PyObject *clone;
2832 PyObject *tuple;
2833 int year = GET_YEAR(self);
2834 int month = GET_MONTH(self);
2835 int day = GET_DAY(self);
Tim Peters12bf3392002-12-24 05:41:27 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2838 &year, &month, &day))
2839 return NULL;
2840 tuple = Py_BuildValue("iii", year, month, day);
2841 if (tuple == NULL)
2842 return NULL;
2843 clone = date_new(Py_TYPE(self), tuple, NULL);
2844 Py_DECREF(tuple);
2845 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00002846}
2847
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002848/*
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 Borrowed from stringobject.c, originally it was string_hash()
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002850*/
2851static long
2852generic_hash(unsigned char *data, int len)
2853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 register unsigned char *p;
2855 register long x;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 p = (unsigned char *) data;
2858 x = *p << 7;
2859 while (--len >= 0)
2860 x = (1000003*x) ^ *p++;
2861 x ^= len;
2862 if (x == -1)
2863 x = -2;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 return x;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002866}
2867
2868
2869static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002870
2871static long
2872date_hash(PyDateTime_Date *self)
2873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 if (self->hashcode == -1)
2875 self->hashcode = generic_hash(
2876 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 return self->hashcode;
Tim Peters2a799bf2002-12-16 20:18:38 +00002879}
2880
2881static PyObject *
2882date_toordinal(PyDateTime_Date *self)
2883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2885 GET_DAY(self)));
Tim Peters2a799bf2002-12-16 20:18:38 +00002886}
2887
2888static PyObject *
2889date_weekday(PyDateTime_Date *self)
2890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002894}
2895
Tim Peters371935f2003-02-01 01:52:50 +00002896/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002897
Tim Petersb57f8f02003-02-01 02:54:15 +00002898/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002899static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002900date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 PyObject* field;
2903 field = PyBytes_FromStringAndSize((char*)self->data,
2904 _PyDateTime_DATE_DATASIZE);
2905 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002906}
2907
2908static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002909date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002912}
2913
2914static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2919 METH_CLASS,
2920 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2921 "time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2924 METH_CLASS,
2925 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2926 "ordinal.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002928 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2929 PyDoc_STR("Current date or datetime: same as "
2930 "self.__class__.fromtimestamp(time.time()).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 /* Instance methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2935 PyDoc_STR("Return ctime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
2938 PyDoc_STR("format -> strftime() style string.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2941 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2944 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2947 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2948 "weekday.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2951 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2954 PyDoc_STR("Return the day of the week represented by the date.\n"
2955 "Monday == 1 ... Sunday == 7")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2958 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2959 "1 is day 1.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2962 PyDoc_STR("Return the day of the week represented by the date.\n"
2963 "Monday == 0 ... Sunday == 6")},
Tim Peters2a799bf2002-12-16 20:18:38 +00002964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
2966 PyDoc_STR("Return date with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2969 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00002972};
2973
2974static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002975PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002976
2977static PyNumberMethods date_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 date_add, /* nb_add */
2979 date_subtract, /* nb_subtract */
2980 0, /* nb_multiply */
2981 0, /* nb_remainder */
2982 0, /* nb_divmod */
2983 0, /* nb_power */
2984 0, /* nb_negative */
2985 0, /* nb_positive */
2986 0, /* nb_absolute */
2987 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002988};
2989
2990static PyTypeObject PyDateTime_DateType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 PyVarObject_HEAD_INIT(NULL, 0)
2992 "datetime.date", /* tp_name */
2993 sizeof(PyDateTime_Date), /* tp_basicsize */
2994 0, /* tp_itemsize */
2995 0, /* tp_dealloc */
2996 0, /* tp_print */
2997 0, /* tp_getattr */
2998 0, /* tp_setattr */
2999 0, /* tp_reserved */
3000 (reprfunc)date_repr, /* tp_repr */
3001 &date_as_number, /* tp_as_number */
3002 0, /* tp_as_sequence */
3003 0, /* tp_as_mapping */
3004 (hashfunc)date_hash, /* tp_hash */
3005 0, /* tp_call */
3006 (reprfunc)date_str, /* tp_str */
3007 PyObject_GenericGetAttr, /* tp_getattro */
3008 0, /* tp_setattro */
3009 0, /* tp_as_buffer */
3010 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3011 date_doc, /* tp_doc */
3012 0, /* tp_traverse */
3013 0, /* tp_clear */
3014 date_richcompare, /* tp_richcompare */
3015 0, /* tp_weaklistoffset */
3016 0, /* tp_iter */
3017 0, /* tp_iternext */
3018 date_methods, /* tp_methods */
3019 0, /* tp_members */
3020 date_getset, /* tp_getset */
3021 0, /* tp_base */
3022 0, /* tp_dict */
3023 0, /* tp_descr_get */
3024 0, /* tp_descr_set */
3025 0, /* tp_dictoffset */
3026 0, /* tp_init */
3027 0, /* tp_alloc */
3028 date_new, /* tp_new */
3029 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003030};
3031
3032/*
Tim Peters2a799bf2002-12-16 20:18:38 +00003033 * PyDateTime_TZInfo implementation.
3034 */
3035
3036/* This is a pure abstract base class, so doesn't do anything beyond
3037 * raising NotImplemented exceptions. Real tzinfo classes need
3038 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00003039 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00003040 * be subclasses of this tzinfo class, which is easy and quick to check).
3041 *
3042 * Note: For reasons having to do with pickling of subclasses, we have
3043 * to allow tzinfo objects to be instantiated. This wasn't an issue
3044 * in the Python implementation (__init__() could raise NotImplementedError
3045 * there without ill effect), but doing so in the C implementation hit a
3046 * brick wall.
3047 */
3048
3049static PyObject *
3050tzinfo_nogo(const char* methodname)
3051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 PyErr_Format(PyExc_NotImplementedError,
3053 "a tzinfo subclass must implement %s()",
3054 methodname);
3055 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003056}
3057
3058/* Methods. A subclass must implement these. */
3059
Tim Peters52dcce22003-01-23 16:36:11 +00003060static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003061tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 return tzinfo_nogo("tzname");
Tim Peters2a799bf2002-12-16 20:18:38 +00003064}
3065
Tim Peters52dcce22003-01-23 16:36:11 +00003066static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003067tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 return tzinfo_nogo("utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00003070}
3071
Tim Peters52dcce22003-01-23 16:36:11 +00003072static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003073tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 return tzinfo_nogo("dst");
Tim Peters2a799bf2002-12-16 20:18:38 +00003076}
3077
Tim Peters52dcce22003-01-23 16:36:11 +00003078static PyObject *
3079tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
3080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 int y, m, d, hh, mm, ss, us;
Tim Peters52dcce22003-01-23 16:36:11 +00003082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 PyObject *result;
3084 int off, dst;
3085 int none;
3086 int delta;
Tim Peters52dcce22003-01-23 16:36:11 +00003087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 if (! PyDateTime_Check(dt)) {
3089 PyErr_SetString(PyExc_TypeError,
3090 "fromutc: argument must be a datetime");
3091 return NULL;
3092 }
3093 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
3094 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
3095 "is not self");
3096 return NULL;
3097 }
Tim Peters52dcce22003-01-23 16:36:11 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
3100 if (off == -1 && PyErr_Occurred())
3101 return NULL;
3102 if (none) {
3103 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3104 "utcoffset() result required");
3105 return NULL;
3106 }
Tim Peters52dcce22003-01-23 16:36:11 +00003107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
3109 if (dst == -1 && PyErr_Occurred())
3110 return NULL;
3111 if (none) {
3112 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
3113 "dst() result required");
3114 return NULL;
3115 }
Tim Peters52dcce22003-01-23 16:36:11 +00003116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 y = GET_YEAR(dt);
3118 m = GET_MONTH(dt);
3119 d = GET_DAY(dt);
3120 hh = DATE_GET_HOUR(dt);
3121 mm = DATE_GET_MINUTE(dt);
3122 ss = DATE_GET_SECOND(dt);
3123 us = DATE_GET_MICROSECOND(dt);
Tim Peters52dcce22003-01-23 16:36:11 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 delta = off - dst;
3126 mm += delta;
3127 if ((mm < 0 || mm >= 60) &&
3128 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
3129 return NULL;
3130 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
3131 if (result == NULL)
3132 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 dst = call_dst(dt->tzinfo, result, &none);
3135 if (dst == -1 && PyErr_Occurred())
3136 goto Fail;
3137 if (none)
3138 goto Inconsistent;
3139 if (dst == 0)
3140 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 mm += dst;
3143 if ((mm < 0 || mm >= 60) &&
3144 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
3145 goto Fail;
3146 Py_DECREF(result);
3147 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
3148 return result;
Tim Peters52dcce22003-01-23 16:36:11 +00003149
3150Inconsistent:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3152 "inconsistent results; cannot convert");
Tim Peters52dcce22003-01-23 16:36:11 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 /* fall thru to failure */
Tim Peters52dcce22003-01-23 16:36:11 +00003155Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 Py_DECREF(result);
3157 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003158}
3159
Tim Peters2a799bf2002-12-16 20:18:38 +00003160/*
3161 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003162 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003163 */
3164
Guido van Rossum177e41a2003-01-30 22:06:23 +00003165static PyObject *
3166tzinfo_reduce(PyObject *self)
3167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 PyObject *args, *state, *tmp;
3169 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 tmp = PyTuple_New(0);
3172 if (tmp == NULL)
3173 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
3176 if (getinitargs != NULL) {
3177 args = PyObject_CallObject(getinitargs, tmp);
3178 Py_DECREF(getinitargs);
3179 if (args == NULL) {
3180 Py_DECREF(tmp);
3181 return NULL;
3182 }
3183 }
3184 else {
3185 PyErr_Clear();
3186 args = tmp;
3187 Py_INCREF(args);
3188 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 getstate = PyObject_GetAttrString(self, "__getstate__");
3191 if (getstate != NULL) {
3192 state = PyObject_CallObject(getstate, tmp);
3193 Py_DECREF(getstate);
3194 if (state == NULL) {
3195 Py_DECREF(args);
3196 Py_DECREF(tmp);
3197 return NULL;
3198 }
3199 }
3200 else {
3201 PyObject **dictptr;
3202 PyErr_Clear();
3203 state = Py_None;
3204 dictptr = _PyObject_GetDictPtr(self);
3205 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3206 state = *dictptr;
3207 Py_INCREF(state);
3208 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 Py_DECREF(tmp);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 if (state == Py_None) {
3213 Py_DECREF(state);
3214 return Py_BuildValue("(ON)", Py_TYPE(self), args);
3215 }
3216 else
3217 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003218}
Tim Peters2a799bf2002-12-16 20:18:38 +00003219
3220static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3223 PyDoc_STR("datetime -> string name of time zone.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
Sean Reifscheiderdeda8cb2010-06-04 01:51:38 +00003226 PyDoc_STR("datetime -> timedelta showing offset from UTC, negative "
3227 "values indicating West of UTC")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3230 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
3233 PyDoc_STR("datetime in UTC -> datetime in local time.")},
Tim Peters52dcce22003-01-23 16:36:11 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3236 PyDoc_STR("-> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003239};
3240
3241static char tzinfo_doc[] =
3242PyDoc_STR("Abstract base class for time zone info objects.");
3243
Neal Norwitz227b5332006-03-22 09:28:35 +00003244static PyTypeObject PyDateTime_TZInfoType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 PyVarObject_HEAD_INIT(NULL, 0)
3246 "datetime.tzinfo", /* tp_name */
3247 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3248 0, /* tp_itemsize */
3249 0, /* tp_dealloc */
3250 0, /* tp_print */
3251 0, /* tp_getattr */
3252 0, /* tp_setattr */
3253 0, /* tp_reserved */
3254 0, /* tp_repr */
3255 0, /* tp_as_number */
3256 0, /* tp_as_sequence */
3257 0, /* tp_as_mapping */
3258 0, /* tp_hash */
3259 0, /* tp_call */
3260 0, /* tp_str */
3261 PyObject_GenericGetAttr, /* tp_getattro */
3262 0, /* tp_setattro */
3263 0, /* tp_as_buffer */
3264 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3265 tzinfo_doc, /* tp_doc */
3266 0, /* tp_traverse */
3267 0, /* tp_clear */
3268 0, /* tp_richcompare */
3269 0, /* tp_weaklistoffset */
3270 0, /* tp_iter */
3271 0, /* tp_iternext */
3272 tzinfo_methods, /* tp_methods */
3273 0, /* tp_members */
3274 0, /* tp_getset */
3275 0, /* tp_base */
3276 0, /* tp_dict */
3277 0, /* tp_descr_get */
3278 0, /* tp_descr_set */
3279 0, /* tp_dictoffset */
3280 0, /* tp_init */
3281 0, /* tp_alloc */
3282 PyType_GenericNew, /* tp_new */
3283 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003284};
3285
3286/*
Tim Peters37f39822003-01-10 03:49:02 +00003287 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003288 */
3289
Tim Peters37f39822003-01-10 03:49:02 +00003290/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003291 */
3292
3293static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003294time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003297}
3298
Tim Peters37f39822003-01-10 03:49:02 +00003299static PyObject *
3300time_minute(PyDateTime_Time *self, void *unused)
3301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003303}
3304
3305/* The name time_second conflicted with some platform header file. */
3306static PyObject *
3307py_time_second(PyDateTime_Time *self, void *unused)
3308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003310}
3311
3312static PyObject *
3313time_microsecond(PyDateTime_Time *self, void *unused)
3314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003316}
3317
3318static PyObject *
3319time_tzinfo(PyDateTime_Time *self, void *unused)
3320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3322 Py_INCREF(result);
3323 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003324}
3325
3326static PyGetSetDef time_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 {"hour", (getter)time_hour},
3328 {"minute", (getter)time_minute},
3329 {"second", (getter)py_time_second},
3330 {"microsecond", (getter)time_microsecond},
3331 {"tzinfo", (getter)time_tzinfo},
3332 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003333};
3334
3335/*
3336 * Constructors.
3337 */
3338
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003339static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003341
Tim Peters2a799bf2002-12-16 20:18:38 +00003342static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003343time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 PyObject *self = NULL;
3346 PyObject *state;
3347 int hour = 0;
3348 int minute = 0;
3349 int second = 0;
3350 int usecond = 0;
3351 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 /* Check for invocation from pickle with __getstate__ state */
3354 if (PyTuple_GET_SIZE(args) >= 1 &&
3355 PyTuple_GET_SIZE(args) <= 2 &&
3356 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3357 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3358 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
3359 {
3360 PyDateTime_Time *me;
3361 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 if (PyTuple_GET_SIZE(args) == 2) {
3364 tzinfo = PyTuple_GET_ITEM(args, 1);
3365 if (check_tzinfo_subclass(tzinfo) < 0) {
3366 PyErr_SetString(PyExc_TypeError, "bad "
3367 "tzinfo state arg");
3368 return NULL;
3369 }
3370 }
3371 aware = (char)(tzinfo != Py_None);
3372 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3373 if (me != NULL) {
3374 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3377 me->hashcode = -1;
3378 me->hastzinfo = aware;
3379 if (aware) {
3380 Py_INCREF(tzinfo);
3381 me->tzinfo = tzinfo;
3382 }
3383 }
3384 return (PyObject *)me;
3385 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3388 &hour, &minute, &second, &usecond,
3389 &tzinfo)) {
3390 if (check_time_args(hour, minute, second, usecond) < 0)
3391 return NULL;
3392 if (check_tzinfo_subclass(tzinfo) < 0)
3393 return NULL;
3394 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3395 type);
3396 }
3397 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003398}
3399
3400/*
3401 * Destructor.
3402 */
3403
3404static void
Tim Peters37f39822003-01-10 03:49:02 +00003405time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 if (HASTZINFO(self)) {
3408 Py_XDECREF(self->tzinfo);
3409 }
3410 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003411}
3412
3413/*
Tim Peters855fe882002-12-22 03:43:39 +00003414 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003415 */
3416
Tim Peters2a799bf2002-12-16 20:18:38 +00003417/* These are all METH_NOARGS, so don't need to check the arglist. */
3418static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003419time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3421 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003422}
3423
3424static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003425time_dst(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3427 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003428}
3429
3430static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003431time_tzname(PyDateTime_Time *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3433 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003434}
3435
3436/*
Tim Peters37f39822003-01-10 03:49:02 +00003437 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003438 */
3439
3440static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003441time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 const char *type_name = Py_TYPE(self)->tp_name;
3444 int h = TIME_GET_HOUR(self);
3445 int m = TIME_GET_MINUTE(self);
3446 int s = TIME_GET_SECOND(self);
3447 int us = TIME_GET_MICROSECOND(self);
3448 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 if (us)
3451 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3452 type_name, h, m, s, us);
3453 else if (s)
3454 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3455 type_name, h, m, s);
3456 else
3457 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
3458 if (result != NULL && HASTZINFO(self))
3459 result = append_keyword_tzinfo(result, self->tzinfo);
3460 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003461}
3462
Tim Peters37f39822003-01-10 03:49:02 +00003463static PyObject *
3464time_str(PyDateTime_Time *self)
3465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
Tim Peters37f39822003-01-10 03:49:02 +00003467}
Tim Peters2a799bf2002-12-16 20:18:38 +00003468
3469static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003470time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 char buf[100];
3473 PyObject *result;
3474 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 if (us)
3477 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3478 TIME_GET_HOUR(self),
3479 TIME_GET_MINUTE(self),
3480 TIME_GET_SECOND(self),
3481 us);
3482 else
3483 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3484 TIME_GET_HOUR(self),
3485 TIME_GET_MINUTE(self),
3486 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
3489 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 /* We need to append the UTC offset. */
3492 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3493 Py_None) < 0) {
3494 Py_DECREF(result);
3495 return NULL;
3496 }
3497 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
3498 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003499}
3500
Tim Peters37f39822003-01-10 03:49:02 +00003501static PyObject *
3502time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 PyObject *result;
3505 PyObject *tuple;
3506 PyObject *format;
3507 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
3510 &format))
3511 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 /* Python's strftime does insane things with the year part of the
3514 * timetuple. The year is forced to (the otherwise nonsensical)
3515 * 1900 to worm around that.
3516 */
3517 tuple = Py_BuildValue("iiiiiiiii",
3518 1900, 1, 1, /* year, month, day */
3519 TIME_GET_HOUR(self),
3520 TIME_GET_MINUTE(self),
3521 TIME_GET_SECOND(self),
3522 0, 1, -1); /* weekday, daynum, dst */
3523 if (tuple == NULL)
3524 return NULL;
3525 assert(PyTuple_Size(tuple) == 9);
3526 result = wrap_strftime((PyObject *)self, format, tuple,
3527 Py_None);
3528 Py_DECREF(tuple);
3529 return result;
Tim Peters37f39822003-01-10 03:49:02 +00003530}
Tim Peters2a799bf2002-12-16 20:18:38 +00003531
3532/*
3533 * Miscellaneous methods.
3534 */
3535
Tim Peters37f39822003-01-10 03:49:02 +00003536static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003537time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 int diff;
3540 naivety n1, n2;
3541 int offset1, offset2;
Tim Peters37f39822003-01-10 03:49:02 +00003542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 if (! PyTime_Check(other)) {
3544 Py_INCREF(Py_NotImplemented);
3545 return Py_NotImplemented;
3546 }
3547 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3548 other, &offset2, &n2, Py_None) < 0)
3549 return NULL;
3550 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3551 /* If they're both naive, or both aware and have the same offsets,
3552 * we get off cheap. Note that if they're both naive, offset1 ==
3553 * offset2 == 0 at this point.
3554 */
3555 if (n1 == n2 && offset1 == offset2) {
3556 diff = memcmp(((PyDateTime_Time *)self)->data,
3557 ((PyDateTime_Time *)other)->data,
3558 _PyDateTime_TIME_DATASIZE);
3559 return diff_to_bool(diff, op);
3560 }
Tim Peters37f39822003-01-10 03:49:02 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3563 assert(offset1 != offset2); /* else last "if" handled it */
3564 /* Convert everything except microseconds to seconds. These
3565 * can't overflow (no more than the # of seconds in 2 days).
3566 */
3567 offset1 = TIME_GET_HOUR(self) * 3600 +
3568 (TIME_GET_MINUTE(self) - offset1) * 60 +
3569 TIME_GET_SECOND(self);
3570 offset2 = TIME_GET_HOUR(other) * 3600 +
3571 (TIME_GET_MINUTE(other) - offset2) * 60 +
3572 TIME_GET_SECOND(other);
3573 diff = offset1 - offset2;
3574 if (diff == 0)
3575 diff = TIME_GET_MICROSECOND(self) -
3576 TIME_GET_MICROSECOND(other);
3577 return diff_to_bool(diff, op);
3578 }
Tim Peters37f39822003-01-10 03:49:02 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 assert(n1 != n2);
3581 PyErr_SetString(PyExc_TypeError,
3582 "can't compare offset-naive and "
3583 "offset-aware times");
3584 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003585}
3586
3587static long
3588time_hash(PyDateTime_Time *self)
3589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 if (self->hashcode == -1) {
3591 naivety n;
3592 int offset;
3593 PyObject *temp;
Tim Peters37f39822003-01-10 03:49:02 +00003594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3596 assert(n != OFFSET_UNKNOWN);
3597 if (n == OFFSET_ERROR)
3598 return -1;
Tim Peters37f39822003-01-10 03:49:02 +00003599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 /* Reduce this to a hash of another object. */
3601 if (offset == 0) {
3602 self->hashcode = generic_hash(
3603 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3604 return self->hashcode;
3605 }
3606 else {
3607 int hour;
3608 int minute;
Tim Peters37f39822003-01-10 03:49:02 +00003609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 assert(n == OFFSET_AWARE);
3611 assert(HASTZINFO(self));
3612 hour = divmod(TIME_GET_HOUR(self) * 60 +
3613 TIME_GET_MINUTE(self) - offset,
3614 60,
3615 &minute);
3616 if (0 <= hour && hour < 24)
3617 temp = new_time(hour, minute,
3618 TIME_GET_SECOND(self),
3619 TIME_GET_MICROSECOND(self),
3620 Py_None);
3621 else
3622 temp = Py_BuildValue("iiii",
3623 hour, minute,
3624 TIME_GET_SECOND(self),
3625 TIME_GET_MICROSECOND(self));
3626 }
3627 if (temp != NULL) {
3628 self->hashcode = PyObject_Hash(temp);
3629 Py_DECREF(temp);
3630 }
3631 }
3632 return self->hashcode;
Tim Peters37f39822003-01-10 03:49:02 +00003633}
Tim Peters2a799bf2002-12-16 20:18:38 +00003634
Tim Peters12bf3392002-12-24 05:41:27 +00003635static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003636time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 PyObject *clone;
3639 PyObject *tuple;
3640 int hh = TIME_GET_HOUR(self);
3641 int mm = TIME_GET_MINUTE(self);
3642 int ss = TIME_GET_SECOND(self);
3643 int us = TIME_GET_MICROSECOND(self);
3644 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3647 time_kws,
3648 &hh, &mm, &ss, &us, &tzinfo))
3649 return NULL;
3650 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3651 if (tuple == NULL)
3652 return NULL;
3653 clone = time_new(Py_TYPE(self), tuple, NULL);
3654 Py_DECREF(tuple);
3655 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00003656}
3657
Tim Peters2a799bf2002-12-16 20:18:38 +00003658static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003659time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 int offset;
3662 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00003663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3665 /* Since utcoffset is in whole minutes, nothing can
3666 * alter the conclusion that this is nonzero.
3667 */
3668 return 1;
3669 }
3670 offset = 0;
3671 if (HASTZINFO(self) && self->tzinfo != Py_None) {
3672 offset = call_utcoffset(self->tzinfo, Py_None, &none);
3673 if (offset == -1 && PyErr_Occurred())
3674 return -1;
3675 }
3676 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00003677}
3678
Tim Peters371935f2003-02-01 01:52:50 +00003679/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003680
Tim Peters33e0f382003-01-10 02:05:14 +00003681/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003682 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3683 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003684 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003685 */
3686static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003687time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 PyObject *basestate;
3690 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 basestate = PyBytes_FromStringAndSize((char *)self->data,
3693 _PyDateTime_TIME_DATASIZE);
3694 if (basestate != NULL) {
3695 if (! HASTZINFO(self) || self->tzinfo == Py_None)
3696 result = PyTuple_Pack(1, basestate);
3697 else
3698 result = PyTuple_Pack(2, basestate, self->tzinfo);
3699 Py_DECREF(basestate);
3700 }
3701 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003702}
3703
3704static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003705time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003708}
3709
Tim Peters37f39822003-01-10 03:49:02 +00003710static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
3713 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3714 "[+HH:MM].")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
3717 PyDoc_STR("format -> strftime() style string.")},
Tim Peters37f39822003-01-10 03:49:02 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3720 PyDoc_STR("Formats self with strftime.")},
Eric Smith1ba31142007-09-11 18:06:02 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
3723 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
3726 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 {"dst", (PyCFunction)time_dst, METH_NOARGS,
3729 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00003730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
3732 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3735 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00003736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003738};
3739
Tim Peters37f39822003-01-10 03:49:02 +00003740static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003741PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3742\n\
3743All arguments are optional. tzinfo may be None, or an instance of\n\
3744a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003745
Tim Peters37f39822003-01-10 03:49:02 +00003746static PyNumberMethods time_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 0, /* nb_add */
3748 0, /* nb_subtract */
3749 0, /* nb_multiply */
3750 0, /* nb_remainder */
3751 0, /* nb_divmod */
3752 0, /* nb_power */
3753 0, /* nb_negative */
3754 0, /* nb_positive */
3755 0, /* nb_absolute */
3756 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003757};
3758
Neal Norwitz227b5332006-03-22 09:28:35 +00003759static PyTypeObject PyDateTime_TimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 PyVarObject_HEAD_INIT(NULL, 0)
3761 "datetime.time", /* tp_name */
3762 sizeof(PyDateTime_Time), /* tp_basicsize */
3763 0, /* tp_itemsize */
3764 (destructor)time_dealloc, /* tp_dealloc */
3765 0, /* tp_print */
3766 0, /* tp_getattr */
3767 0, /* tp_setattr */
3768 0, /* tp_reserved */
3769 (reprfunc)time_repr, /* tp_repr */
3770 &time_as_number, /* tp_as_number */
3771 0, /* tp_as_sequence */
3772 0, /* tp_as_mapping */
3773 (hashfunc)time_hash, /* tp_hash */
3774 0, /* tp_call */
3775 (reprfunc)time_str, /* tp_str */
3776 PyObject_GenericGetAttr, /* tp_getattro */
3777 0, /* tp_setattro */
3778 0, /* tp_as_buffer */
3779 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3780 time_doc, /* tp_doc */
3781 0, /* tp_traverse */
3782 0, /* tp_clear */
3783 time_richcompare, /* tp_richcompare */
3784 0, /* tp_weaklistoffset */
3785 0, /* tp_iter */
3786 0, /* tp_iternext */
3787 time_methods, /* tp_methods */
3788 0, /* tp_members */
3789 time_getset, /* tp_getset */
3790 0, /* tp_base */
3791 0, /* tp_dict */
3792 0, /* tp_descr_get */
3793 0, /* tp_descr_set */
3794 0, /* tp_dictoffset */
3795 0, /* tp_init */
3796 time_alloc, /* tp_alloc */
3797 time_new, /* tp_new */
3798 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003799};
3800
3801/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003802 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003803 */
3804
Tim Petersa9bc1682003-01-11 03:39:11 +00003805/* Accessor properties. Properties for day, month, and year are inherited
3806 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003807 */
3808
3809static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003810datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003813}
3814
Tim Petersa9bc1682003-01-11 03:39:11 +00003815static PyObject *
3816datetime_minute(PyDateTime_DateTime *self, void *unused)
3817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003819}
3820
3821static PyObject *
3822datetime_second(PyDateTime_DateTime *self, void *unused)
3823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003825}
3826
3827static PyObject *
3828datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003831}
3832
3833static PyObject *
3834datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3837 Py_INCREF(result);
3838 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003839}
3840
3841static PyGetSetDef datetime_getset[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 {"hour", (getter)datetime_hour},
3843 {"minute", (getter)datetime_minute},
3844 {"second", (getter)datetime_second},
3845 {"microsecond", (getter)datetime_microsecond},
3846 {"tzinfo", (getter)datetime_tzinfo},
3847 {NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003848};
3849
3850/*
3851 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003852 */
3853
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003854static char *datetime_kws[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 "year", "month", "day", "hour", "minute", "second",
3856 "microsecond", "tzinfo", NULL
Tim Peters12bf3392002-12-24 05:41:27 +00003857};
3858
Tim Peters2a799bf2002-12-16 20:18:38 +00003859static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003860datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 PyObject *self = NULL;
3863 PyObject *state;
3864 int year;
3865 int month;
3866 int day;
3867 int hour = 0;
3868 int minute = 0;
3869 int second = 0;
3870 int usecond = 0;
3871 PyObject *tzinfo = Py_None;
Tim Peters2a799bf2002-12-16 20:18:38 +00003872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 /* Check for invocation from pickle with __getstate__ state */
3874 if (PyTuple_GET_SIZE(args) >= 1 &&
3875 PyTuple_GET_SIZE(args) <= 2 &&
3876 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3877 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3878 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
3879 {
3880 PyDateTime_DateTime *me;
3881 char aware;
Tim Peters70533e22003-02-01 04:40:04 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 if (PyTuple_GET_SIZE(args) == 2) {
3884 tzinfo = PyTuple_GET_ITEM(args, 1);
3885 if (check_tzinfo_subclass(tzinfo) < 0) {
3886 PyErr_SetString(PyExc_TypeError, "bad "
3887 "tzinfo state arg");
3888 return NULL;
3889 }
3890 }
3891 aware = (char)(tzinfo != Py_None);
3892 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
3893 if (me != NULL) {
3894 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3897 me->hashcode = -1;
3898 me->hastzinfo = aware;
3899 if (aware) {
3900 Py_INCREF(tzinfo);
3901 me->tzinfo = tzinfo;
3902 }
3903 }
3904 return (PyObject *)me;
3905 }
Guido van Rossum177e41a2003-01-30 22:06:23 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
3908 &year, &month, &day, &hour, &minute,
3909 &second, &usecond, &tzinfo)) {
3910 if (check_date_args(year, month, day) < 0)
3911 return NULL;
3912 if (check_time_args(hour, minute, second, usecond) < 0)
3913 return NULL;
3914 if (check_tzinfo_subclass(tzinfo) < 0)
3915 return NULL;
3916 self = new_datetime_ex(year, month, day,
3917 hour, minute, second, usecond,
3918 tzinfo, type);
3919 }
3920 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003921}
3922
Tim Petersa9bc1682003-01-11 03:39:11 +00003923/* TM_FUNC is the shared type of localtime() and gmtime(). */
3924typedef struct tm *(*TM_FUNC)(const time_t *timer);
3925
3926/* Internal helper.
3927 * Build datetime from a time_t and a distinct count of microseconds.
3928 * Pass localtime or gmtime for f, to control the interpretation of timet.
3929 */
3930static PyObject *
3931datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 struct tm *tm;
3935 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00003936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003937 tm = f(&timet);
3938 if (tm) {
3939 /* The platform localtime/gmtime may insert leap seconds,
3940 * indicated by tm->tm_sec > 59. We don't care about them,
3941 * except to the extent that passing them on to the datetime
3942 * constructor would raise ValueError for a reason that
3943 * made no sense to the user.
3944 */
3945 if (tm->tm_sec > 59)
3946 tm->tm_sec = 59;
3947 result = PyObject_CallFunction(cls, "iiiiiiiO",
3948 tm->tm_year + 1900,
3949 tm->tm_mon + 1,
3950 tm->tm_mday,
3951 tm->tm_hour,
3952 tm->tm_min,
3953 tm->tm_sec,
3954 us,
3955 tzinfo);
3956 }
3957 else
3958 PyErr_SetString(PyExc_ValueError,
3959 "timestamp out of range for "
3960 "platform localtime()/gmtime() function");
3961 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00003962}
3963
3964/* Internal helper.
3965 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3966 * to control the interpretation of the timestamp. Since a double doesn't
3967 * have enough bits to cover a datetime's full range of precision, it's
3968 * better to call datetime_from_timet_and_us provided you have a way
3969 * to get that much precision (e.g., C time() isn't good enough).
3970 */
3971static PyObject *
3972datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 PyObject *tzinfo)
Tim Petersa9bc1682003-01-11 03:39:11 +00003974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 time_t timet;
3976 double fraction;
3977 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 timet = _PyTime_DoubleToTimet(timestamp);
3980 if (timet == (time_t)-1 && PyErr_Occurred())
3981 return NULL;
3982 fraction = timestamp - (double)timet;
3983 us = (int)round_to_long(fraction * 1e6);
3984 if (us < 0) {
3985 /* Truncation towards zero is not what we wanted
3986 for negative numbers (Python's mod semantics) */
3987 timet -= 1;
3988 us += 1000000;
3989 }
3990 /* If timestamp is less than one microsecond smaller than a
3991 * full second, round up. Otherwise, ValueErrors are raised
3992 * for some floats. */
3993 if (us == 1000000) {
3994 timet += 1;
3995 us = 0;
3996 }
3997 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00003998}
3999
4000/* Internal helper.
4001 * Build most accurate possible datetime for current time. Pass localtime or
4002 * gmtime for f as appropriate.
4003 */
4004static PyObject *
4005datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
4006{
4007#ifdef HAVE_GETTIMEOFDAY
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 struct timeval t;
Tim Petersa9bc1682003-01-11 03:39:11 +00004009
4010#ifdef GETTIMEOFDAY_NO_TZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 gettimeofday(&t);
Tim Petersa9bc1682003-01-11 03:39:11 +00004012#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 gettimeofday(&t, (struct timezone *)NULL);
Tim Petersa9bc1682003-01-11 03:39:11 +00004014#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
4016 tzinfo);
Tim Petersa9bc1682003-01-11 03:39:11 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018#else /* ! HAVE_GETTIMEOFDAY */
4019 /* No flavor of gettimeofday exists on this platform. Python's
4020 * time.time() does a lot of other platform tricks to get the
4021 * best time it can on the platform, and we're not going to do
4022 * better than that (if we could, the better code would belong
4023 * in time.time()!) We're limited by the precision of a double,
4024 * though.
4025 */
4026 PyObject *time;
4027 double dtime;
Tim Petersa9bc1682003-01-11 03:39:11 +00004028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004029 time = time_time();
4030 if (time == NULL)
4031 return NULL;
4032 dtime = PyFloat_AsDouble(time);
4033 Py_DECREF(time);
4034 if (dtime == -1.0 && PyErr_Occurred())
4035 return NULL;
4036 return datetime_from_timestamp(cls, f, dtime, tzinfo);
4037#endif /* ! HAVE_GETTIMEOFDAY */
Tim Petersa9bc1682003-01-11 03:39:11 +00004038}
4039
Tim Peters2a799bf2002-12-16 20:18:38 +00004040/* Return best possible local time -- this isn't constrained by the
4041 * precision of a timestamp.
4042 */
4043static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004044datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 PyObject *self;
4047 PyObject *tzinfo = Py_None;
4048 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
4051 &tzinfo))
4052 return NULL;
4053 if (check_tzinfo_subclass(tzinfo) < 0)
4054 return NULL;
Tim Peters10cadce2003-01-23 19:58:02 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 self = datetime_best_possible(cls,
4057 tzinfo == Py_None ? localtime : gmtime,
4058 tzinfo);
4059 if (self != NULL && tzinfo != Py_None) {
4060 /* Convert UTC to tzinfo's zone. */
4061 PyObject *temp = self;
4062 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
4063 Py_DECREF(temp);
4064 }
4065 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004066}
4067
Tim Petersa9bc1682003-01-11 03:39:11 +00004068/* Return best possible UTC time -- this isn't constrained by the
4069 * precision of a timestamp.
4070 */
4071static PyObject *
4072datetime_utcnow(PyObject *cls, PyObject *dummy)
4073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 return datetime_best_possible(cls, gmtime, Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004075}
4076
Tim Peters2a799bf2002-12-16 20:18:38 +00004077/* Return new local datetime from timestamp (Python timestamp -- a double). */
4078static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004079datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 PyObject *self;
4082 double timestamp;
4083 PyObject *tzinfo = Py_None;
4084 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
4087 keywords, &timestamp, &tzinfo))
4088 return NULL;
4089 if (check_tzinfo_subclass(tzinfo) < 0)
4090 return NULL;
Tim Peters2a44a8d2003-01-23 20:53:10 +00004091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 self = datetime_from_timestamp(cls,
4093 tzinfo == Py_None ? localtime : gmtime,
4094 timestamp,
4095 tzinfo);
4096 if (self != NULL && tzinfo != Py_None) {
4097 /* Convert UTC to tzinfo's zone. */
4098 PyObject *temp = self;
4099 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
4100 Py_DECREF(temp);
4101 }
4102 return self;
Tim Peters2a799bf2002-12-16 20:18:38 +00004103}
4104
Tim Petersa9bc1682003-01-11 03:39:11 +00004105/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
4106static PyObject *
4107datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
4108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 double timestamp;
4110 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
4113 result = datetime_from_timestamp(cls, gmtime, timestamp,
4114 Py_None);
4115 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004116}
4117
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004118/* Return new datetime from time.strptime(). */
4119static PyObject *
4120datetime_strptime(PyObject *cls, PyObject *args)
4121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004122 static PyObject *module = NULL;
4123 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
4124 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
4127 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 if (module == NULL &&
4130 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
4131 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004133 /* _strptime._strptime returns a two-element tuple. The first
4134 element is a time.struct_time object. The second is the
4135 microseconds (which are not defined for time.struct_time). */
4136 obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
4137 if (obj != NULL) {
4138 int i, good_timetuple = 1;
4139 long int ia[7];
4140 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
4141 st = PySequence_GetItem(obj, 0);
4142 frac = PySequence_GetItem(obj, 1);
4143 if (st == NULL || frac == NULL)
4144 good_timetuple = 0;
4145 /* copy y/m/d/h/m/s values out of the
4146 time.struct_time */
4147 if (good_timetuple &&
4148 PySequence_Check(st) &&
4149 PySequence_Size(st) >= 6) {
4150 for (i=0; i < 6; i++) {
4151 PyObject *p = PySequence_GetItem(st, i);
4152 if (p == NULL) {
4153 good_timetuple = 0;
4154 break;
4155 }
4156 if (PyLong_Check(p))
4157 ia[i] = PyLong_AsLong(p);
4158 else
4159 good_timetuple = 0;
4160 Py_DECREF(p);
4161 }
4162/* if (PyLong_CheckExact(p)) {
4163 ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
4164 if (overflow)
4165 good_timetuple = 0;
4166 }
4167 else
4168 good_timetuple = 0;
4169 Py_DECREF(p);
4170*/ }
4171 else
4172 good_timetuple = 0;
4173 /* follow that up with a little dose of microseconds */
4174 if (PyLong_Check(frac))
4175 ia[6] = PyLong_AsLong(frac);
4176 else
4177 good_timetuple = 0;
4178 }
4179 else
4180 good_timetuple = 0;
4181 if (good_timetuple)
4182 result = PyObject_CallFunction(cls, "iiiiiii",
4183 ia[0], ia[1], ia[2],
4184 ia[3], ia[4], ia[5],
4185 ia[6]);
4186 else
4187 PyErr_SetString(PyExc_ValueError,
4188 "unexpected value from _strptime._strptime");
4189 }
4190 Py_XDECREF(obj);
4191 Py_XDECREF(st);
4192 Py_XDECREF(frac);
4193 return result;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004194}
4195
Tim Petersa9bc1682003-01-11 03:39:11 +00004196/* Return new datetime from date/datetime and time arguments. */
4197static PyObject *
4198datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 static char *keywords[] = {"date", "time", NULL};
4201 PyObject *date;
4202 PyObject *time;
4203 PyObject *result = NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4206 &PyDateTime_DateType, &date,
4207 &PyDateTime_TimeType, &time)) {
4208 PyObject *tzinfo = Py_None;
Tim Petersa9bc1682003-01-11 03:39:11 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 if (HASTZINFO(time))
4211 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4212 result = PyObject_CallFunction(cls, "iiiiiiiO",
4213 GET_YEAR(date),
4214 GET_MONTH(date),
4215 GET_DAY(date),
4216 TIME_GET_HOUR(time),
4217 TIME_GET_MINUTE(time),
4218 TIME_GET_SECOND(time),
4219 TIME_GET_MICROSECOND(time),
4220 tzinfo);
4221 }
4222 return result;
Tim Petersa9bc1682003-01-11 03:39:11 +00004223}
Tim Peters2a799bf2002-12-16 20:18:38 +00004224
4225/*
4226 * Destructor.
4227 */
4228
4229static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004230datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 if (HASTZINFO(self)) {
4233 Py_XDECREF(self->tzinfo);
4234 }
4235 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004236}
4237
4238/*
4239 * Indirect access to tzinfo methods.
4240 */
4241
Tim Peters2a799bf2002-12-16 20:18:38 +00004242/* These are all METH_NOARGS, so don't need to check the arglist. */
4243static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004244datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4246 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004247}
4248
4249static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004250datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004251 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4252 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00004253}
4254
4255static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004256datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
4258 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004259}
4260
4261/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004262 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004263 */
4264
Tim Petersa9bc1682003-01-11 03:39:11 +00004265/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4266 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004267 */
4268static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004269add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 /* Note that the C-level additions can't overflow, because of
4273 * invariant bounds on the member values.
4274 */
4275 int year = GET_YEAR(date);
4276 int month = GET_MONTH(date);
4277 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4278 int hour = DATE_GET_HOUR(date);
4279 int minute = DATE_GET_MINUTE(date);
4280 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4281 int microsecond = DATE_GET_MICROSECOND(date) +
4282 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 assert(factor == 1 || factor == -1);
4285 if (normalize_datetime(&year, &month, &day,
4286 &hour, &minute, &second, &microsecond) < 0)
4287 return NULL;
4288 else
4289 return new_datetime(year, month, day,
4290 hour, minute, second, microsecond,
4291 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004292}
4293
4294static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004295datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 if (PyDateTime_Check(left)) {
4298 /* datetime + ??? */
4299 if (PyDelta_Check(right))
4300 /* datetime + delta */
4301 return add_datetime_timedelta(
4302 (PyDateTime_DateTime *)left,
4303 (PyDateTime_Delta *)right,
4304 1);
4305 }
4306 else if (PyDelta_Check(left)) {
4307 /* delta + datetime */
4308 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4309 (PyDateTime_Delta *) left,
4310 1);
4311 }
4312 Py_INCREF(Py_NotImplemented);
4313 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004314}
4315
4316static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004317datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 PyObject *result = Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 if (PyDateTime_Check(left)) {
4322 /* datetime - ??? */
4323 if (PyDateTime_Check(right)) {
4324 /* datetime - datetime */
4325 naivety n1, n2;
4326 int offset1, offset2;
4327 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004329 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4330 right, &offset2, &n2,
4331 right) < 0)
4332 return NULL;
4333 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4334 if (n1 != n2) {
4335 PyErr_SetString(PyExc_TypeError,
4336 "can't subtract offset-naive and "
4337 "offset-aware datetimes");
4338 return NULL;
4339 }
4340 delta_d = ymd_to_ord(GET_YEAR(left),
4341 GET_MONTH(left),
4342 GET_DAY(left)) -
4343 ymd_to_ord(GET_YEAR(right),
4344 GET_MONTH(right),
4345 GET_DAY(right));
4346 /* These can't overflow, since the values are
4347 * normalized. At most this gives the number of
4348 * seconds in one day.
4349 */
4350 delta_s = (DATE_GET_HOUR(left) -
4351 DATE_GET_HOUR(right)) * 3600 +
4352 (DATE_GET_MINUTE(left) -
4353 DATE_GET_MINUTE(right)) * 60 +
4354 (DATE_GET_SECOND(left) -
4355 DATE_GET_SECOND(right));
4356 delta_us = DATE_GET_MICROSECOND(left) -
4357 DATE_GET_MICROSECOND(right);
4358 /* (left - offset1) - (right - offset2) =
4359 * (left - right) + (offset2 - offset1)
4360 */
4361 delta_s += (offset2 - offset1) * 60;
4362 result = new_delta(delta_d, delta_s, delta_us, 1);
4363 }
4364 else if (PyDelta_Check(right)) {
4365 /* datetime - delta */
4366 result = add_datetime_timedelta(
4367 (PyDateTime_DateTime *)left,
4368 (PyDateTime_Delta *)right,
4369 -1);
4370 }
4371 }
Tim Peters2a799bf2002-12-16 20:18:38 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 if (result == Py_NotImplemented)
4374 Py_INCREF(result);
4375 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004376}
4377
4378/* Various ways to turn a datetime into a string. */
4379
4380static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004381datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 const char *type_name = Py_TYPE(self)->tp_name;
4384 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 if (DATE_GET_MICROSECOND(self)) {
4387 baserepr = PyUnicode_FromFormat(
4388 "%s(%d, %d, %d, %d, %d, %d, %d)",
4389 type_name,
4390 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4391 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4392 DATE_GET_SECOND(self),
4393 DATE_GET_MICROSECOND(self));
4394 }
4395 else if (DATE_GET_SECOND(self)) {
4396 baserepr = PyUnicode_FromFormat(
4397 "%s(%d, %d, %d, %d, %d, %d)",
4398 type_name,
4399 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4400 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4401 DATE_GET_SECOND(self));
4402 }
4403 else {
4404 baserepr = PyUnicode_FromFormat(
4405 "%s(%d, %d, %d, %d, %d)",
4406 type_name,
4407 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4408 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4409 }
4410 if (baserepr == NULL || ! HASTZINFO(self))
4411 return baserepr;
4412 return append_keyword_tzinfo(baserepr, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004413}
4414
Tim Petersa9bc1682003-01-11 03:39:11 +00004415static PyObject *
4416datetime_str(PyDateTime_DateTime *self)
4417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
Tim Petersa9bc1682003-01-11 03:39:11 +00004419}
Tim Peters2a799bf2002-12-16 20:18:38 +00004420
4421static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004422datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 int sep = 'T';
4425 static char *keywords[] = {"sep", NULL};
4426 char buffer[100];
4427 PyObject *result;
4428 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
4431 return NULL;
4432 if (us)
4433 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4434 GET_YEAR(self), GET_MONTH(self),
4435 GET_DAY(self), (int)sep,
4436 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4437 DATE_GET_SECOND(self), us);
4438 else
4439 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4440 GET_YEAR(self), GET_MONTH(self),
4441 GET_DAY(self), (int)sep,
4442 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4443 DATE_GET_SECOND(self));
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 if (!result || !HASTZINFO(self))
4446 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 /* We need to append the UTC offset. */
4449 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4450 (PyObject *)self) < 0) {
4451 Py_DECREF(result);
4452 return NULL;
4453 }
4454 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
4455 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004456}
4457
Tim Petersa9bc1682003-01-11 03:39:11 +00004458static PyObject *
4459datetime_ctime(PyDateTime_DateTime *self)
4460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 return format_ctime((PyDateTime_Date *)self,
4462 DATE_GET_HOUR(self),
4463 DATE_GET_MINUTE(self),
4464 DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004465}
4466
Tim Peters2a799bf2002-12-16 20:18:38 +00004467/* Miscellaneous methods. */
4468
Tim Petersa9bc1682003-01-11 03:39:11 +00004469static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004470datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 int diff;
4473 naivety n1, n2;
4474 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 if (! PyDateTime_Check(other)) {
4477 if (PyDate_Check(other)) {
4478 /* Prevent invocation of date_richcompare. We want to
4479 return NotImplemented here to give the other object
4480 a chance. But since DateTime is a subclass of
4481 Date, if the other object is a Date, it would
4482 compute an ordering based on the date part alone,
4483 and we don't want that. So force unequal or
4484 uncomparable here in that case. */
4485 if (op == Py_EQ)
4486 Py_RETURN_FALSE;
4487 if (op == Py_NE)
4488 Py_RETURN_TRUE;
4489 return cmperror(self, other);
4490 }
4491 Py_INCREF(Py_NotImplemented);
4492 return Py_NotImplemented;
4493 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4496 other, &offset2, &n2, other) < 0)
4497 return NULL;
4498 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4499 /* If they're both naive, or both aware and have the same offsets,
4500 * we get off cheap. Note that if they're both naive, offset1 ==
4501 * offset2 == 0 at this point.
4502 */
4503 if (n1 == n2 && offset1 == offset2) {
4504 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4505 ((PyDateTime_DateTime *)other)->data,
4506 _PyDateTime_DATETIME_DATASIZE);
4507 return diff_to_bool(diff, op);
4508 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4511 PyDateTime_Delta *delta;
Tim Petersa9bc1682003-01-11 03:39:11 +00004512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004513 assert(offset1 != offset2); /* else last "if" handled it */
4514 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4515 other);
4516 if (delta == NULL)
4517 return NULL;
4518 diff = GET_TD_DAYS(delta);
4519 if (diff == 0)
4520 diff = GET_TD_SECONDS(delta) |
4521 GET_TD_MICROSECONDS(delta);
4522 Py_DECREF(delta);
4523 return diff_to_bool(diff, op);
4524 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 assert(n1 != n2);
4527 PyErr_SetString(PyExc_TypeError,
4528 "can't compare offset-naive and "
4529 "offset-aware datetimes");
4530 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004531}
4532
4533static long
4534datetime_hash(PyDateTime_DateTime *self)
4535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 if (self->hashcode == -1) {
4537 naivety n;
4538 int offset;
4539 PyObject *temp;
Tim Petersa9bc1682003-01-11 03:39:11 +00004540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4542 &offset);
4543 assert(n != OFFSET_UNKNOWN);
4544 if (n == OFFSET_ERROR)
4545 return -1;
Tim Petersa9bc1682003-01-11 03:39:11 +00004546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 /* Reduce this to a hash of another object. */
4548 if (n == OFFSET_NAIVE) {
4549 self->hashcode = generic_hash(
4550 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4551 return self->hashcode;
4552 }
4553 else {
4554 int days;
4555 int seconds;
Tim Petersa9bc1682003-01-11 03:39:11 +00004556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 assert(n == OFFSET_AWARE);
4558 assert(HASTZINFO(self));
4559 days = ymd_to_ord(GET_YEAR(self),
4560 GET_MONTH(self),
4561 GET_DAY(self));
4562 seconds = DATE_GET_HOUR(self) * 3600 +
4563 (DATE_GET_MINUTE(self) - offset) * 60 +
4564 DATE_GET_SECOND(self);
4565 temp = new_delta(days,
4566 seconds,
4567 DATE_GET_MICROSECOND(self),
4568 1);
4569 }
4570 if (temp != NULL) {
4571 self->hashcode = PyObject_Hash(temp);
4572 Py_DECREF(temp);
4573 }
4574 }
4575 return self->hashcode;
Tim Petersa9bc1682003-01-11 03:39:11 +00004576}
Tim Peters2a799bf2002-12-16 20:18:38 +00004577
4578static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004579datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 PyObject *clone;
4582 PyObject *tuple;
4583 int y = GET_YEAR(self);
4584 int m = GET_MONTH(self);
4585 int d = GET_DAY(self);
4586 int hh = DATE_GET_HOUR(self);
4587 int mm = DATE_GET_MINUTE(self);
4588 int ss = DATE_GET_SECOND(self);
4589 int us = DATE_GET_MICROSECOND(self);
4590 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4593 datetime_kws,
4594 &y, &m, &d, &hh, &mm, &ss, &us,
4595 &tzinfo))
4596 return NULL;
4597 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4598 if (tuple == NULL)
4599 return NULL;
4600 clone = datetime_new(Py_TYPE(self), tuple, NULL);
4601 Py_DECREF(tuple);
4602 return clone;
Tim Peters12bf3392002-12-24 05:41:27 +00004603}
4604
4605static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004606datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004608 int y, m, d, hh, mm, ss, us;
4609 PyObject *result;
4610 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 PyObject *tzinfo;
4613 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4616 &PyDateTime_TZInfoType, &tzinfo))
4617 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4620 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 /* Conversion to self's own time zone is a NOP. */
4623 if (self->tzinfo == tzinfo) {
4624 Py_INCREF(self);
4625 return (PyObject *)self;
4626 }
Tim Peters521fc152002-12-31 17:36:56 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 /* Convert self to UTC. */
4629 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4630 if (offset == -1 && PyErr_Occurred())
4631 return NULL;
4632 if (none)
4633 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 y = GET_YEAR(self);
4636 m = GET_MONTH(self);
4637 d = GET_DAY(self);
4638 hh = DATE_GET_HOUR(self);
4639 mm = DATE_GET_MINUTE(self);
4640 ss = DATE_GET_SECOND(self);
4641 us = DATE_GET_MICROSECOND(self);
Tim Peters52dcce22003-01-23 16:36:11 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 mm -= offset;
4644 if ((mm < 0 || mm >= 60) &&
4645 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
4646 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00004647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 /* Attach new tzinfo and let fromutc() do the rest. */
4649 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4650 if (result != NULL) {
4651 PyObject *temp = result;
Tim Peters52dcce22003-01-23 16:36:11 +00004652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4654 Py_DECREF(temp);
4655 }
4656 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004657
Tim Peters52dcce22003-01-23 16:36:11 +00004658NeedAware:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4660 "a naive datetime");
4661 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004662}
4663
4664static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004665datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 int dstflag = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4670 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4673 if (dstflag == -1 && PyErr_Occurred())
4674 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 if (none)
4677 dstflag = -1;
4678 else if (dstflag != 0)
4679 dstflag = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00004680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 }
4682 return build_struct_time(GET_YEAR(self),
4683 GET_MONTH(self),
4684 GET_DAY(self),
4685 DATE_GET_HOUR(self),
4686 DATE_GET_MINUTE(self),
4687 DATE_GET_SECOND(self),
4688 dstflag);
Tim Peters2a799bf2002-12-16 20:18:38 +00004689}
4690
4691static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004692datetime_getdate(PyDateTime_DateTime *self)
4693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 return new_date(GET_YEAR(self),
4695 GET_MONTH(self),
4696 GET_DAY(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00004697}
4698
4699static PyObject *
4700datetime_gettime(PyDateTime_DateTime *self)
4701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 return new_time(DATE_GET_HOUR(self),
4703 DATE_GET_MINUTE(self),
4704 DATE_GET_SECOND(self),
4705 DATE_GET_MICROSECOND(self),
4706 Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004707}
4708
4709static PyObject *
4710datetime_gettimetz(PyDateTime_DateTime *self)
4711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 return new_time(DATE_GET_HOUR(self),
4713 DATE_GET_MINUTE(self),
4714 DATE_GET_SECOND(self),
4715 DATE_GET_MICROSECOND(self),
4716 HASTZINFO(self) ? self->tzinfo : Py_None);
Tim Petersa9bc1682003-01-11 03:39:11 +00004717}
4718
4719static PyObject *
4720datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004722 int y = GET_YEAR(self);
4723 int m = GET_MONTH(self);
4724 int d = GET_DAY(self);
4725 int hh = DATE_GET_HOUR(self);
4726 int mm = DATE_GET_MINUTE(self);
4727 int ss = DATE_GET_SECOND(self);
4728 int us = 0; /* microseconds are ignored in a timetuple */
4729 int offset = 0;
Tim Peters2a799bf2002-12-16 20:18:38 +00004730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 if (HASTZINFO(self) && self->tzinfo != Py_None) {
4732 int none;
Tim Peters2a799bf2002-12-16 20:18:38 +00004733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4735 if (offset == -1 && PyErr_Occurred())
4736 return NULL;
4737 }
4738 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4739 * 0 in a UTC timetuple regardless of what dst() says.
4740 */
4741 if (offset) {
4742 /* Subtract offset minutes & normalize. */
4743 int stat;
Tim Peters2a799bf2002-12-16 20:18:38 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 mm -= offset;
4746 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4747 if (stat < 0) {
4748 /* At the edges, it's possible we overflowed
4749 * beyond MINYEAR or MAXYEAR.
4750 */
4751 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4752 PyErr_Clear();
4753 else
4754 return NULL;
4755 }
4756 }
4757 return build_struct_time(y, m, d, hh, mm, ss, 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00004758}
4759
Tim Peters371935f2003-02-01 01:52:50 +00004760/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004761
Tim Petersa9bc1682003-01-11 03:39:11 +00004762/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004763 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4764 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004765 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004766 */
4767static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004768datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 PyObject *basestate;
4771 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773 basestate = PyBytes_FromStringAndSize((char *)self->data,
4774 _PyDateTime_DATETIME_DATASIZE);
4775 if (basestate != NULL) {
4776 if (! HASTZINFO(self) || self->tzinfo == Py_None)
4777 result = PyTuple_Pack(1, basestate);
4778 else
4779 result = PyTuple_Pack(2, basestate, self->tzinfo);
4780 Py_DECREF(basestate);
4781 }
4782 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004783}
4784
4785static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004786datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004789}
4790
Tim Petersa9bc1682003-01-11 03:39:11 +00004791static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 {"now", (PyCFunction)datetime_now,
4796 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4797 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 {"utcnow", (PyCFunction)datetime_utcnow,
4800 METH_NOARGS | METH_CLASS,
4801 PyDoc_STR("Return a new datetime representing UTC day and time.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4804 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4805 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4808 METH_VARARGS | METH_CLASS,
4809 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4810 "(like time.time()).")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 {"strptime", (PyCFunction)datetime_strptime,
4813 METH_VARARGS | METH_CLASS,
4814 PyDoc_STR("string, format -> new datetime parsed from a string "
4815 "(like time.strptime()).")},
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 {"combine", (PyCFunction)datetime_combine,
4818 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4819 PyDoc_STR("date, time -> datetime with same date and time fields")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4824 PyDoc_STR("Return date object with same year, month and day.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4827 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4830 PyDoc_STR("Return time object with same time and tzinfo.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4833 PyDoc_STR("Return ctime() style string.")},
Tim Petersa9bc1682003-01-11 03:39:11 +00004834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
4836 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4839 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004841 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
4842 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4843 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4844 "sep is used to separate the year from the time, and "
4845 "defaults to 'T'.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
4848 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
4851 PyDoc_STR("Return self.tzinfo.tzname(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
4854 PyDoc_STR("Return self.tzinfo.dst(self).")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
4857 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
4860 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
Tim Peters80475bb2002-12-25 07:40:55 +00004861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4863 PyDoc_STR("__reduce__() -> (cls, state)")},
Guido van Rossum177e41a2003-01-30 22:06:23 +00004864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004865 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004866};
4867
Tim Petersa9bc1682003-01-11 03:39:11 +00004868static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004869PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4870\n\
4871The year, month and day arguments are required. tzinfo may be None, or an\n\
4872instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004873
Tim Petersa9bc1682003-01-11 03:39:11 +00004874static PyNumberMethods datetime_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 datetime_add, /* nb_add */
4876 datetime_subtract, /* nb_subtract */
4877 0, /* nb_multiply */
4878 0, /* nb_remainder */
4879 0, /* nb_divmod */
4880 0, /* nb_power */
4881 0, /* nb_negative */
4882 0, /* nb_positive */
4883 0, /* nb_absolute */
4884 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004885};
4886
Neal Norwitz227b5332006-03-22 09:28:35 +00004887static PyTypeObject PyDateTime_DateTimeType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 PyVarObject_HEAD_INIT(NULL, 0)
4889 "datetime.datetime", /* tp_name */
4890 sizeof(PyDateTime_DateTime), /* tp_basicsize */
4891 0, /* tp_itemsize */
4892 (destructor)datetime_dealloc, /* tp_dealloc */
4893 0, /* tp_print */
4894 0, /* tp_getattr */
4895 0, /* tp_setattr */
4896 0, /* tp_reserved */
4897 (reprfunc)datetime_repr, /* tp_repr */
4898 &datetime_as_number, /* tp_as_number */
4899 0, /* tp_as_sequence */
4900 0, /* tp_as_mapping */
4901 (hashfunc)datetime_hash, /* tp_hash */
4902 0, /* tp_call */
4903 (reprfunc)datetime_str, /* tp_str */
4904 PyObject_GenericGetAttr, /* tp_getattro */
4905 0, /* tp_setattro */
4906 0, /* tp_as_buffer */
4907 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
4908 datetime_doc, /* tp_doc */
4909 0, /* tp_traverse */
4910 0, /* tp_clear */
4911 datetime_richcompare, /* tp_richcompare */
4912 0, /* tp_weaklistoffset */
4913 0, /* tp_iter */
4914 0, /* tp_iternext */
4915 datetime_methods, /* tp_methods */
4916 0, /* tp_members */
4917 datetime_getset, /* tp_getset */
4918 &PyDateTime_DateType, /* tp_base */
4919 0, /* tp_dict */
4920 0, /* tp_descr_get */
4921 0, /* tp_descr_set */
4922 0, /* tp_dictoffset */
4923 0, /* tp_init */
4924 datetime_alloc, /* tp_alloc */
4925 datetime_new, /* tp_new */
4926 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004927};
4928
4929/* ---------------------------------------------------------------------------
4930 * Module methods and initialization.
4931 */
4932
4933static PyMethodDef module_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00004935};
4936
Tim Peters9ddf40b2004-06-20 22:41:32 +00004937/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4938 * datetime.h.
4939 */
4940static PyDateTime_CAPI CAPI = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004941 &PyDateTime_DateType,
4942 &PyDateTime_DateTimeType,
4943 &PyDateTime_TimeType,
4944 &PyDateTime_DeltaType,
4945 &PyDateTime_TZInfoType,
4946 new_date_ex,
4947 new_datetime_ex,
4948 new_time_ex,
4949 new_delta_ex,
4950 datetime_fromtimestamp,
4951 date_fromtimestamp
Tim Peters9ddf40b2004-06-20 22:41:32 +00004952};
4953
4954
Martin v. Löwis1a214512008-06-11 05:26:20 +00004955
4956static struct PyModuleDef datetimemodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004957 PyModuleDef_HEAD_INIT,
4958 "datetime",
4959 "Fast implementation of the datetime type.",
4960 -1,
4961 module_methods,
4962 NULL,
4963 NULL,
4964 NULL,
4965 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004966};
4967
Tim Peters2a799bf2002-12-16 20:18:38 +00004968PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004969PyInit_datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00004970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004971 PyObject *m; /* a module object */
4972 PyObject *d; /* its dict */
4973 PyObject *x;
Tim Peters2a799bf2002-12-16 20:18:38 +00004974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 m = PyModule_Create(&datetimemodule);
4976 if (m == NULL)
4977 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 if (PyType_Ready(&PyDateTime_DateType) < 0)
4980 return NULL;
4981 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4982 return NULL;
4983 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4984 return NULL;
4985 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4986 return NULL;
4987 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4988 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 /* timedelta values */
4991 d = PyDateTime_DeltaType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 x = new_delta(0, 0, 1, 0);
4994 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4995 return NULL;
4996 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00004997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4999 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5000 return NULL;
5001 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5004 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5005 return NULL;
5006 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 /* date values */
5009 d = PyDateTime_DateType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 x = new_date(1, 1, 1);
5012 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5013 return NULL;
5014 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 x = new_date(MAXYEAR, 12, 31);
5017 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5018 return NULL;
5019 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 x = new_delta(1, 0, 0, 0);
5022 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5023 return NULL;
5024 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 /* time values */
5027 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 x = new_time(0, 0, 0, 0, Py_None);
5030 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5031 return NULL;
5032 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 x = new_time(23, 59, 59, 999999, Py_None);
5035 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5036 return NULL;
5037 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 x = new_delta(0, 0, 1, 0);
5040 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5041 return NULL;
5042 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 /* datetime values */
5045 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00005046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
5048 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5049 return NULL;
5050 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5053 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5054 return NULL;
5055 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 x = new_delta(0, 0, 1, 0);
5058 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5059 return NULL;
5060 Py_DECREF(x);
Tim Peters2a799bf2002-12-16 20:18:38 +00005061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 /* module initialization */
5063 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
5064 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
Tim Peters2a799bf2002-12-16 20:18:38 +00005065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 Py_INCREF(&PyDateTime_DateType);
5067 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 Py_INCREF(&PyDateTime_DateTimeType);
5070 PyModule_AddObject(m, "datetime",
5071 (PyObject *)&PyDateTime_DateTimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 Py_INCREF(&PyDateTime_TimeType);
5074 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
Tim Petersa9bc1682003-01-11 03:39:11 +00005075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 Py_INCREF(&PyDateTime_DeltaType);
5077 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 Py_INCREF(&PyDateTime_TZInfoType);
5080 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
Tim Peters2a799bf2002-12-16 20:18:38 +00005081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
5083 if (x == NULL)
5084 return NULL;
5085 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00005086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 /* A 4-year cycle has an extra leap day over what we'd get from
5088 * pasting together 4 single years.
5089 */
5090 assert(DI4Y == 4 * 365 + 1);
5091 assert(DI4Y == days_before_year(4+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5094 * get from pasting together 4 100-year cycles.
5095 */
5096 assert(DI400Y == 4 * DI100Y + 1);
5097 assert(DI400Y == days_before_year(400+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5100 * pasting together 25 4-year cycles.
5101 */
5102 assert(DI100Y == 25 * DI4Y - 1);
5103 assert(DI100Y == days_before_year(100+1));
Tim Peters2a799bf2002-12-16 20:18:38 +00005104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 us_per_us = PyLong_FromLong(1);
5106 us_per_ms = PyLong_FromLong(1000);
5107 us_per_second = PyLong_FromLong(1000000);
5108 us_per_minute = PyLong_FromLong(60000000);
5109 seconds_per_day = PyLong_FromLong(24 * 3600);
5110 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5111 us_per_minute == NULL || seconds_per_day == NULL)
5112 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00005113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 /* The rest are too big for 32-bit ints, but even
5115 * us_per_week fits in 40 bits, so doubles should be exact.
5116 */
5117 us_per_hour = PyLong_FromDouble(3600000000.0);
5118 us_per_day = PyLong_FromDouble(86400000000.0);
5119 us_per_week = PyLong_FromDouble(604800000000.0);
5120 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5121 return NULL;
5122 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00005123}
Tim Petersf3615152003-01-01 21:51:37 +00005124
5125/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00005126Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00005127 x.n = x stripped of its timezone -- its naive time.
5128 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 return None
Tim Petersf3615152003-01-01 21:51:37 +00005130 x.d = x.dst(), and assuming that doesn't raise an exception or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005131 return None
Tim Petersf3615152003-01-01 21:51:37 +00005132 x.s = x's standard offset, x.o - x.d
5133
5134Now some derived rules, where k is a duration (timedelta).
5135
51361. x.o = x.s + x.d
5137 This follows from the definition of x.s.
5138
Tim Petersc5dc4da2003-01-02 17:55:03 +000051392. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005140 This is actually a requirement, an assumption we need to make about
5141 sane tzinfo classes.
5142
51433. The naive UTC time corresponding to x is x.n - x.o.
5144 This is again a requirement for a sane tzinfo class.
5145
51464. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005147 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005148
Tim Petersc5dc4da2003-01-02 17:55:03 +000051495. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005150 Again follows from how arithmetic is defined.
5151
Tim Peters8bb5ad22003-01-24 02:44:45 +00005152Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005153(meaning that the various tzinfo methods exist, and don't blow up or return
5154None when called).
5155
Tim Petersa9bc1682003-01-11 03:39:11 +00005156The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005157x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005158
5159By #3, we want
5160
Tim Peters8bb5ad22003-01-24 02:44:45 +00005161 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005162
5163The algorithm starts by attaching tz to x.n, and calling that y. So
5164x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5165becomes true; in effect, we want to solve [2] for k:
5166
Tim Peters8bb5ad22003-01-24 02:44:45 +00005167 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005168
5169By #1, this is the same as
5170
Tim Peters8bb5ad22003-01-24 02:44:45 +00005171 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005172
5173By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5174Substituting that into [3],
5175
Tim Peters8bb5ad22003-01-24 02:44:45 +00005176 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5177 k - (y+k).s - (y+k).d = 0; rearranging,
5178 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5179 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005180
Tim Peters8bb5ad22003-01-24 02:44:45 +00005181On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5182approximate k by ignoring the (y+k).d term at first. Note that k can't be
5183very large, since all offset-returning methods return a duration of magnitude
5184less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5185be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005186
5187In any case, the new value is
5188
Tim Peters8bb5ad22003-01-24 02:44:45 +00005189 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005190
Tim Peters8bb5ad22003-01-24 02:44:45 +00005191It's helpful to step back at look at [4] from a higher level: it's simply
5192mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005193
5194At this point, if
5195
Tim Peters8bb5ad22003-01-24 02:44:45 +00005196 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005197
5198we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005199at the start of daylight time. Picture US Eastern for concreteness. The wall
5200time 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 +00005201sense then. The docs ask that an Eastern tzinfo class consider such a time to
5202be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5203on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005204the only spelling that makes sense on the local wall clock.
5205
Tim Petersc5dc4da2003-01-02 17:55:03 +00005206In fact, if [5] holds at this point, we do have the standard-time spelling,
5207but that takes a bit of proof. We first prove a stronger result. What's the
5208difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005209
Tim Peters8bb5ad22003-01-24 02:44:45 +00005210 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005211
Tim Petersc5dc4da2003-01-02 17:55:03 +00005212Now
5213 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005214 (y + y.s).n = by #5
5215 y.n + y.s = since y.n = x.n
5216 x.n + y.s = since z and y are have the same tzinfo member,
5217 y.s = z.s by #2
5218 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005219
Tim Petersc5dc4da2003-01-02 17:55:03 +00005220Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005221
Tim Petersc5dc4da2003-01-02 17:55:03 +00005222 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005223 x.n - ((x.n + z.s) - z.o) = expanding
5224 x.n - x.n - z.s + z.o = cancelling
5225 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005226 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005227
Tim Petersc5dc4da2003-01-02 17:55:03 +00005228So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005229
Tim Petersc5dc4da2003-01-02 17:55:03 +00005230If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005231spelling we wanted in the endcase described above. We're done. Contrarily,
5232if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005233
Tim Petersc5dc4da2003-01-02 17:55:03 +00005234If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5235add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005236local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005237
Tim Petersc5dc4da2003-01-02 17:55:03 +00005238Let
Tim Petersf3615152003-01-01 21:51:37 +00005239
Tim Peters4fede1a2003-01-04 00:26:59 +00005240 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005241
Tim Peters4fede1a2003-01-04 00:26:59 +00005242and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005243
Tim Peters8bb5ad22003-01-24 02:44:45 +00005244 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005245
Tim Peters8bb5ad22003-01-24 02:44:45 +00005246If so, we're done. If not, the tzinfo class is insane, according to the
5247assumptions we've made. This also requires a bit of proof. As before, let's
5248compute the difference between the LHS and RHS of [8] (and skipping some of
5249the justifications for the kinds of substitutions we've done several times
5250already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005251
Tim Peters8bb5ad22003-01-24 02:44:45 +00005252 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005253 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5254 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5255 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5256 - z.n + z.n - z.o + z'.o = cancel z.n
5257 - z.o + z'.o = #1 twice
5258 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5259 z'.d - z.d
Tim Peters4fede1a2003-01-04 00:26:59 +00005260
5261So 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 +00005262we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5263return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005264
Tim Peters8bb5ad22003-01-24 02:44:45 +00005265How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5266a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5267would have to change the result dst() returns: we start in DST, and moving
5268a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005269
Tim Peters8bb5ad22003-01-24 02:44:45 +00005270There isn't a sane case where this can happen. The closest it gets is at
5271the end of DST, where there's an hour in UTC with no spelling in a hybrid
5272tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5273that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5274UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5275time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5276clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5277standard time. Since that's what the local clock *does*, we want to map both
5278UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005279in local time, but so it goes -- it's the way the local clock works.
5280
Tim Peters8bb5ad22003-01-24 02:44:45 +00005281When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5282so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5283z' = 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 +00005284(correctly) concludes that z' is not UTC-equivalent to x.
5285
5286Because we know z.d said z was in daylight time (else [5] would have held and
5287we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005288and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005289return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5290but the reasoning doesn't depend on the example -- it depends on there being
5291two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005292z' must be in standard time, and is the spelling we want in this case.
5293
5294Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5295concerned (because it takes z' as being in standard time rather than the
5296daylight time we intend here), but returning it gives the real-life "local
5297clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5298tz.
5299
5300When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5301the 1:MM standard time spelling we want.
5302
5303So how can this break? One of the assumptions must be violated. Two
5304possibilities:
5305
53061) [2] effectively says that y.s is invariant across all y belong to a given
5307 time zone. This isn't true if, for political reasons or continental drift,
5308 a region decides to change its base offset from UTC.
5309
53102) There may be versions of "double daylight" time where the tail end of
5311 the analysis gives up a step too early. I haven't thought about that
5312 enough to say.
5313
5314In any case, it's clear that the default fromutc() is strong enough to handle
5315"almost all" time zones: so long as the standard offset is invariant, it
5316doesn't matter if daylight time transition points change from year to year, or
5317if daylight time is skipped in some years; it doesn't matter how large or
5318small dst() may get within its bounds; and it doesn't even matter if some
5319perverse time zone returns a negative dst()). So a breaking case must be
5320pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005321--------------------------------------------------------------------------- */