blob: d7c6005acd1dfb816023c4ff1df84d18fe99f124 [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
11#include "datetime.h"
12
13/* We require that C int be at least 32 bits, and use int virtually
14 * everywhere. In just a few cases we use a temp long, where a Python
15 * API returns a C long. In such cases, we have to ensure that the
16 * final result fits in a C int (this can be an issue on 64-bit boxes).
17 */
18#if SIZEOF_INT < 4
19# error "datetime.c requires that C int have at least 32 bits"
20#endif
21
22#define MINYEAR 1
23#define MAXYEAR 9999
24
25/* Nine decimal digits is easy to communicate, and leaves enough room
26 * so that two delta days can be added w/o fear of overflowing a signed
27 * 32-bit int, and with plenty of room left over to absorb any possible
28 * carries from adding seconds.
29 */
30#define MAX_DELTA_DAYS 999999999
31
32/* Rename the long macros in datetime.h to more reasonable short names. */
33#define GET_YEAR PyDateTime_GET_YEAR
34#define GET_MONTH PyDateTime_GET_MONTH
35#define GET_DAY PyDateTime_GET_DAY
36#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
37#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
38#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
39#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
40
41/* Date accessors for date and datetime. */
42#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
43 ((o)->data[1] = ((v) & 0x00ff)))
44#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
45#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
46
47/* Date/Time accessors for datetime. */
48#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
49#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
50#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
51#define DATE_SET_MICROSECOND(o, v) \
52 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
53 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
54 ((o)->data[9] = ((v) & 0x0000ff)))
55
56/* Time accessors for time. */
57#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
58#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
59#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
60#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
61#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
62#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
63#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
64#define TIME_SET_MICROSECOND(o, v) \
65 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
66 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
67 ((o)->data[5] = ((v) & 0x0000ff)))
68
69/* Delta accessors for timedelta. */
70#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
71#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
72#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
73
74#define SET_TD_DAYS(o, v) ((o)->days = (v))
75#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
76#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
77
78/* Forward declarations. */
79static PyTypeObject PyDateTime_DateType;
80static PyTypeObject PyDateTime_DateTimeType;
81static PyTypeObject PyDateTime_DateTimeTZType;
82static PyTypeObject PyDateTime_DeltaType;
83static PyTypeObject PyDateTime_TimeType;
84static PyTypeObject PyDateTime_TZInfoType;
85static PyTypeObject PyDateTime_TimeTZType;
86
87/* ---------------------------------------------------------------------------
88 * Math utilities.
89 */
90
91/* k = i+j overflows iff k differs in sign from both inputs,
92 * iff k^i has sign bit set and k^j has sign bit set,
93 * iff (k^i)&(k^j) has sign bit set.
94 */
95#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
96 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
97
98/* Compute Python divmod(x, y), returning the quotient and storing the
99 * remainder into *r. The quotient is the floor of x/y, and that's
100 * the real point of this. C will probably truncate instead (C99
101 * requires truncation; C89 left it implementation-defined).
102 * Simplification: we *require* that y > 0 here. That's appropriate
103 * for all the uses made of it. This simplifies the code and makes
104 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
105 * overflow case).
106 */
107static int
108divmod(int x, int y, int *r)
109{
110 int quo;
111
112 assert(y > 0);
113 quo = x / y;
114 *r = x - quo * y;
115 if (*r < 0) {
116 --quo;
117 *r += y;
118 }
119 assert(0 <= *r && *r < y);
120 return quo;
121}
122
123/* ---------------------------------------------------------------------------
124 * General calendrical helper functions
125 */
126
127/* For each month ordinal in 1..12, the number of days in that month,
128 * and the number of days before that month in the same year. These
129 * are correct for non-leap years only.
130 */
131static int _days_in_month[] = {
132 0, /* unused; this vector uses 1-based indexing */
133 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
134};
135
136static int _days_before_month[] = {
137 0, /* unused; this vector uses 1-based indexing */
138 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
139};
140
141/* year -> 1 if leap year, else 0. */
142static int
143is_leap(int year)
144{
145 /* Cast year to unsigned. The result is the same either way, but
146 * C can generate faster code for unsigned mod than for signed
147 * mod (especially for % 4 -- a good compiler should just grab
148 * the last 2 bits when the LHS is unsigned).
149 */
150 const unsigned int ayear = (unsigned int)year;
151 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
152}
153
154/* year, month -> number of days in that month in that year */
155static int
156days_in_month(int year, int month)
157{
158 assert(month >= 1);
159 assert(month <= 12);
160 if (month == 2 && is_leap(year))
161 return 29;
162 else
163 return _days_in_month[month];
164}
165
166/* year, month -> number of days in year preceeding first day of month */
167static int
168days_before_month(int year, int month)
169{
170 int days;
171
172 assert(month >= 1);
173 assert(month <= 12);
174 days = _days_before_month[month];
175 if (month > 2 && is_leap(year))
176 ++days;
177 return days;
178}
179
180/* year -> number of days before January 1st of year. Remember that we
181 * start with year 1, so days_before_year(1) == 0.
182 */
183static int
184days_before_year(int year)
185{
186 int y = year - 1;
187 /* This is incorrect if year <= 0; we really want the floor
188 * here. But so long as MINYEAR is 1, the smallest year this
189 * can see is 0 (this can happen in some normalization endcases),
190 * so we'll just special-case that.
191 */
192 assert (year >= 0);
193 if (y >= 0)
194 return y*365 + y/4 - y/100 + y/400;
195 else {
196 assert(y == -1);
197 return -366;
198 }
199}
200
201/* Number of days in 4, 100, and 400 year cycles. That these have
202 * the correct values is asserted in the module init function.
203 */
204#define DI4Y 1461 /* days_before_year(5); days in 4 years */
205#define DI100Y 36524 /* days_before_year(101); days in 100 years */
206#define DI400Y 146097 /* days_before_year(401); days in 400 years */
207
208/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
209static void
210ord_to_ymd(int ordinal, int *year, int *month, int *day)
211{
212 int n, n1, n4, n100, n400, leapyear, preceding;
213
214 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
215 * leap years repeats exactly every 400 years. The basic strategy is
216 * to find the closest 400-year boundary at or before ordinal, then
217 * work with the offset from that boundary to ordinal. Life is much
218 * clearer if we subtract 1 from ordinal first -- then the values
219 * of ordinal at 400-year boundaries are exactly those divisible
220 * by DI400Y:
221 *
222 * D M Y n n-1
223 * -- --- ---- ---------- ----------------
224 * 31 Dec -400 -DI400Y -DI400Y -1
225 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
226 * ...
227 * 30 Dec 000 -1 -2
228 * 31 Dec 000 0 -1
229 * 1 Jan 001 1 0 400-year boundary
230 * 2 Jan 001 2 1
231 * 3 Jan 001 3 2
232 * ...
233 * 31 Dec 400 DI400Y DI400Y -1
234 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
235 */
236 assert(ordinal >= 1);
237 --ordinal;
238 n400 = ordinal / DI400Y;
239 n = ordinal % DI400Y;
240 *year = n400 * 400 + 1;
241
242 /* Now n is the (non-negative) offset, in days, from January 1 of
243 * year, to the desired date. Now compute how many 100-year cycles
244 * precede n.
245 * Note that it's possible for n100 to equal 4! In that case 4 full
246 * 100-year cycles precede the desired day, which implies the
247 * desired day is December 31 at the end of a 400-year cycle.
248 */
249 n100 = n / DI100Y;
250 n = n % DI100Y;
251
252 /* Now compute how many 4-year cycles precede it. */
253 n4 = n / DI4Y;
254 n = n % DI4Y;
255
256 /* And now how many single years. Again n1 can be 4, and again
257 * meaning that the desired day is December 31 at the end of the
258 * 4-year cycle.
259 */
260 n1 = n / 365;
261 n = n % 365;
262
263 *year += n100 * 100 + n4 * 4 + n1;
264 if (n1 == 4 || n100 == 4) {
265 assert(n == 0);
266 *year -= 1;
267 *month = 12;
268 *day = 31;
269 return;
270 }
271
272 /* Now the year is correct, and n is the offset from January 1. We
273 * find the month via an estimate that's either exact or one too
274 * large.
275 */
276 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
277 assert(leapyear == is_leap(*year));
278 *month = (n + 50) >> 5;
279 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
280 if (preceding > n) {
281 /* estimate is too large */
282 *month -= 1;
283 preceding -= days_in_month(*year, *month);
284 }
285 n -= preceding;
286 assert(0 <= n);
287 assert(n < days_in_month(*year, *month));
288
289 *day = n + 1;
290}
291
292/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
293static int
294ymd_to_ord(int year, int month, int day)
295{
296 return days_before_year(year) + days_before_month(year, month) + day;
297}
298
299/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
300static int
301weekday(int year, int month, int day)
302{
303 return (ymd_to_ord(year, month, day) + 6) % 7;
304}
305
306/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
307 * first calendar week containing a Thursday.
308 */
309static int
310iso_week1_monday(int year)
311{
312 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
313 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
314 int first_weekday = (first_day + 6) % 7;
315 /* ordinal of closest Monday at or before 1/1 */
316 int week1_monday = first_day - first_weekday;
317
318 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
319 week1_monday += 7;
320 return week1_monday;
321}
322
323/* ---------------------------------------------------------------------------
324 * Range checkers.
325 */
326
327/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
328 * If not, raise OverflowError and return -1.
329 */
330static int
331check_delta_day_range(int days)
332{
333 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
334 return 0;
335 PyErr_Format(PyExc_OverflowError,
336 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000337 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000338 return -1;
339}
340
341/* Check that date arguments are in range. Return 0 if they are. If they
342 * aren't, raise ValueError and return -1.
343 */
344static int
345check_date_args(int year, int month, int day)
346{
347
348 if (year < MINYEAR || year > MAXYEAR) {
349 PyErr_SetString(PyExc_ValueError,
350 "year is out of range");
351 return -1;
352 }
353 if (month < 1 || month > 12) {
354 PyErr_SetString(PyExc_ValueError,
355 "month must be in 1..12");
356 return -1;
357 }
358 if (day < 1 || day > days_in_month(year, month)) {
359 PyErr_SetString(PyExc_ValueError,
360 "day is out of range for month");
361 return -1;
362 }
363 return 0;
364}
365
366/* Check that time arguments are in range. Return 0 if they are. If they
367 * aren't, raise ValueError and return -1.
368 */
369static int
370check_time_args(int h, int m, int s, int us)
371{
372 if (h < 0 || h > 23) {
373 PyErr_SetString(PyExc_ValueError,
374 "hour must be in 0..23");
375 return -1;
376 }
377 if (m < 0 || m > 59) {
378 PyErr_SetString(PyExc_ValueError,
379 "minute must be in 0..59");
380 return -1;
381 }
382 if (s < 0 || s > 59) {
383 PyErr_SetString(PyExc_ValueError,
384 "second must be in 0..59");
385 return -1;
386 }
387 if (us < 0 || us > 999999) {
388 PyErr_SetString(PyExc_ValueError,
389 "microsecond must be in 0..999999");
390 return -1;
391 }
392 return 0;
393}
394
395/* ---------------------------------------------------------------------------
396 * Normalization utilities.
397 */
398
399/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
400 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
401 * at least factor, enough of *lo is converted into "hi" units so that
402 * 0 <= *lo < factor. The input values must be such that int overflow
403 * is impossible.
404 */
405static void
406normalize_pair(int *hi, int *lo, int factor)
407{
408 assert(factor > 0);
409 assert(lo != hi);
410 if (*lo < 0 || *lo >= factor) {
411 const int num_hi = divmod(*lo, factor, lo);
412 const int new_hi = *hi + num_hi;
413 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
414 *hi = new_hi;
415 }
416 assert(0 <= *lo && *lo < factor);
417}
418
419/* Fiddle days (d), seconds (s), and microseconds (us) so that
420 * 0 <= *s < 24*3600
421 * 0 <= *us < 1000000
422 * The input values must be such that the internals don't overflow.
423 * The way this routine is used, we don't get close.
424 */
425static void
426normalize_d_s_us(int *d, int *s, int *us)
427{
428 if (*us < 0 || *us >= 1000000) {
429 normalize_pair(s, us, 1000000);
430 /* |s| can't be bigger than about
431 * |original s| + |original us|/1000000 now.
432 */
433
434 }
435 if (*s < 0 || *s >= 24*3600) {
436 normalize_pair(d, s, 24*3600);
437 /* |d| can't be bigger than about
438 * |original d| +
439 * (|original s| + |original us|/1000000) / (24*3600) now.
440 */
441 }
442 assert(0 <= *s && *s < 24*3600);
443 assert(0 <= *us && *us < 1000000);
444}
445
446/* Fiddle years (y), months (m), and days (d) so that
447 * 1 <= *m <= 12
448 * 1 <= *d <= days_in_month(*y, *m)
449 * The input values must be such that the internals don't overflow.
450 * The way this routine is used, we don't get close.
451 */
452static void
453normalize_y_m_d(int *y, int *m, int *d)
454{
455 int dim; /* # of days in month */
456
457 /* This gets muddy: the proper range for day can't be determined
458 * without knowing the correct month and year, but if day is, e.g.,
459 * plus or minus a million, the current month and year values make
460 * no sense (and may also be out of bounds themselves).
461 * Saying 12 months == 1 year should be non-controversial.
462 */
463 if (*m < 1 || *m > 12) {
464 --*m;
465 normalize_pair(y, m, 12);
466 ++*m;
467 /* |y| can't be bigger than about
468 * |original y| + |original m|/12 now.
469 */
470 }
471 assert(1 <= *m && *m <= 12);
472
473 /* Now only day can be out of bounds (year may also be out of bounds
474 * for a datetime object, but we don't care about that here).
475 * If day is out of bounds, what to do is arguable, but at least the
476 * method here is principled and explainable.
477 */
478 dim = days_in_month(*y, *m);
479 if (*d < 1 || *d > dim) {
480 /* Move day-1 days from the first of the month. First try to
481 * get off cheap if we're only one day out of range
482 * (adjustments for timezone alone can't be worse than that).
483 */
484 if (*d == 0) {
485 --*m;
486 if (*m > 0)
487 *d = days_in_month(*y, *m);
488 else {
489 --*y;
490 *m = 12;
491 *d = 31;
492 }
493 }
494 else if (*d == dim + 1) {
495 /* move forward a day */
496 ++*m;
497 *d = 1;
498 if (*m > 12) {
499 *m = 1;
500 ++*y;
501 }
502 }
503 else {
504 int ordinal = ymd_to_ord(*y, *m, 1) +
505 *d - 1;
506 ord_to_ymd(ordinal, y, m, d);
507 }
508 }
509 assert(*m > 0);
510 assert(*d > 0);
511}
512
513/* Fiddle out-of-bounds months and days so that the result makes some kind
514 * of sense. The parameters are both inputs and outputs. Returns < 0 on
515 * failure, where failure means the adjusted year is out of bounds.
516 */
517static int
518normalize_date(int *year, int *month, int *day)
519{
520 int result;
521
522 normalize_y_m_d(year, month, day);
523 if (MINYEAR <= *year && *year <= MAXYEAR)
524 result = 0;
525 else {
526 PyErr_SetString(PyExc_OverflowError,
527 "date value out of range");
528 result = -1;
529 }
530 return result;
531}
532
533/* Force all the datetime fields into range. The parameters are both
534 * inputs and outputs. Returns < 0 on error.
535 */
536static int
537normalize_datetime(int *year, int *month, int *day,
538 int *hour, int *minute, int *second,
539 int *microsecond)
540{
541 normalize_pair(second, microsecond, 1000000);
542 normalize_pair(minute, second, 60);
543 normalize_pair(hour, minute, 60);
544 normalize_pair(day, hour, 24);
545 return normalize_date(year, month, day);
546}
547
548/* ---------------------------------------------------------------------------
549 * tzinfo helpers.
550 */
551
Tim Peters855fe882002-12-22 03:43:39 +0000552/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
553 * raise TypeError and return -1.
554 */
555static int
556check_tzinfo_subclass(PyObject *p)
557{
558 if (p == Py_None || PyTZInfo_Check(p))
559 return 0;
560 PyErr_Format(PyExc_TypeError,
561 "tzinfo argument must be None or of a tzinfo subclass, "
562 "not type '%s'",
563 p->ob_type->tp_name);
564 return -1;
565}
566
567/* Return tzinfo.methname(self), without any checking of results.
568 * If tzinfo is None, returns None.
569 */
570static PyObject *
571call_tzinfo_method(PyObject *self, PyObject *tzinfo, char *methname)
572{
573 PyObject *result;
574
575 assert(self && tzinfo && methname);
576 assert(check_tzinfo_subclass(tzinfo) >= 0);
577 if (tzinfo == Py_None) {
578 result = Py_None;
579 Py_INCREF(result);
580 }
581 else
582 result = PyObject_CallMethod(tzinfo, methname, "O", self);
583 return result;
584}
585
Tim Peters2a799bf2002-12-16 20:18:38 +0000586/* If self has a tzinfo member, return a BORROWED reference to it. Else
587 * return NULL, which is NOT AN ERROR. There are no error returns here,
588 * and the caller must not decref the result.
589 */
590static PyObject *
591get_tzinfo_member(PyObject *self)
592{
593 PyObject *tzinfo = NULL;
594
595 if (PyDateTimeTZ_Check(self))
596 tzinfo = ((PyDateTime_DateTimeTZ *)self)->tzinfo;
597 else if (PyTimeTZ_Check(self))
598 tzinfo = ((PyDateTime_TimeTZ *)self)->tzinfo;
599
600 return tzinfo;
601}
602
Tim Peters80475bb2002-12-25 07:40:55 +0000603/* self is a datetimetz. Replace its tzinfo member. */
604void
605replace_tzinfo(PyObject *self, PyObject *newtzinfo)
606{
607 assert(self != NULL);
608 assert(PyDateTimeTZ_Check(self));
609 assert(check_tzinfo_subclass(newtzinfo) >= 0);
610 Py_INCREF(newtzinfo);
611 Py_DECREF(((PyDateTime_DateTimeTZ *)self)->tzinfo);
612 ((PyDateTime_DateTimeTZ *)self)->tzinfo = newtzinfo;
613}
614
Tim Peters2a799bf2002-12-16 20:18:38 +0000615/* Internal helper.
616 * Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
617 * result. tzinfo must be an instance of the tzinfo class. If the method
618 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters855fe882002-12-22 03:43:39 +0000619 * return a Python int or long or timedelta, TypeError is raised and this
620 * returns -1. If it returns an int or long, but is outside the valid
621 * range for a UTC minute offset, or it returns a timedelta and the value is
622 * out of range or isn't a whole number of minutes, ValueError is raised and
623 * this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000624 * Else *none is set to 0 and the integer method result is returned.
625 */
626static int
627call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
628 int *none)
629{
630 PyObject *u;
631 long result = -1; /* Py{Int,Long}_AsLong return long */
632
633 assert(tzinfo != NULL);
634 assert(PyTZInfo_Check(tzinfo));
635 assert(tzinfoarg != NULL);
636
637 *none = 0;
Tim Peters855fe882002-12-22 03:43:39 +0000638 u = call_tzinfo_method(tzinfoarg, tzinfo, name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000639 if (u == NULL)
640 return -1;
641
Tim Peters27362852002-12-23 16:17:39 +0000642 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000643 result = 0;
644 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000645 }
Tim Peters27362852002-12-23 16:17:39 +0000646 else if (PyInt_Check(u))
Tim Peters2a799bf2002-12-16 20:18:38 +0000647 result = PyInt_AS_LONG(u);
Tim Peters855fe882002-12-22 03:43:39 +0000648
Tim Peters2a799bf2002-12-16 20:18:38 +0000649 else if (PyLong_Check(u))
650 result = PyLong_AsLong(u);
Tim Peters855fe882002-12-22 03:43:39 +0000651
652 else if (PyDelta_Check(u)) {
653 const int days = GET_TD_DAYS(u);
654 if (days < -1 || days > 0)
655 result = 24*60; /* trigger ValueError below */
656 else {
657 /* next line can't overflow because we know days
658 * is -1 or 0 now
659 */
660 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
661 result = divmod(ss, 60, &ss);
662 if (ss || GET_TD_MICROSECONDS(u)) {
663 PyErr_Format(PyExc_ValueError,
664 "tzinfo.%s() must return a "
665 "whole number of minutes",
666 name);
667 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000668 }
669 }
670 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000671 else {
672 PyErr_Format(PyExc_TypeError,
Tim Peters855fe882002-12-22 03:43:39 +0000673 "tzinfo.%s() must return None, integer or "
674 "timedelta, not '%s'",
675 name, u->ob_type->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000676 }
677
Tim Peters2a799bf2002-12-16 20:18:38 +0000678 Py_DECREF(u);
679 if (result < -1439 || result > 1439) {
680 PyErr_Format(PyExc_ValueError,
681 "tzinfo.%s() returned %ld; must be in "
682 "-1439 .. 1439",
683 name, result);
684 result = -1;
685 }
686 return (int)result;
687}
688
689/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
690 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
691 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
692 & doesn't return a Python int or long, TypeError is raised and this
693 * returns -1. If utcoffset() returns an int outside the legitimate range
694 * for a UTC offset, ValueError is raised and this returns -1. Else
695 * *none is set to 0 and the offset is returned.
696 */
697static int
698call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
699{
700 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
701}
702
Tim Peters855fe882002-12-22 03:43:39 +0000703static PyObject *new_delta(int d, int sec, int usec, int normalize);
704
705/* Call tzinfo.name(self) and return the offset as a timedelta or None. */
706static PyObject *
707offset_as_timedelta(PyObject *self, PyObject *tzinfo, char *name) {
708 PyObject *result;
709
710 if (tzinfo == Py_None) {
711 result = Py_None;
712 Py_INCREF(result);
713 }
714 else {
715 int none;
716 int offset = call_utc_tzinfo_method(tzinfo, name, self, &none);
717 if (offset < 0 && PyErr_Occurred())
718 return NULL;
719 if (none) {
720 result = Py_None;
721 Py_INCREF(result);
722 }
723 else
724 result = new_delta(0, offset * 60, 0, 1);
725 }
726 return result;
727}
728
Tim Peters2a799bf2002-12-16 20:18:38 +0000729/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
730 * result. tzinfo must be an instance of the tzinfo class. If dst()
731 * returns None, call_dst returns 0 and sets *none to 1. If dst()
732 & doesn't return a Python int or long, TypeError is raised and this
733 * returns -1. If dst() returns an int outside the legitimate range
734 * for a UTC offset, ValueError is raised and this returns -1. Else
735 * *none is set to 0 and the offset is returned.
736 */
737static int
738call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
739{
740 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
741}
742
Tim Peters855fe882002-12-22 03:43:39 +0000743/* Call tzinfo.tzname(self), and return the result. tzinfo must be
744 * an instance of the tzinfo class or None. If tzinfo isn't None, and
745 * tzname() doesn't return None ora string, TypeError is raised and this
746 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000747 */
748static PyObject *
Tim Peters855fe882002-12-22 03:43:39 +0000749call_tzname(PyObject *self, PyObject *tzinfo)
Tim Peters2a799bf2002-12-16 20:18:38 +0000750{
751 PyObject *result;
752
Tim Peters855fe882002-12-22 03:43:39 +0000753 assert(self != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000754 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000755 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Peters2a799bf2002-12-16 20:18:38 +0000756
Tim Peters855fe882002-12-22 03:43:39 +0000757 if (tzinfo == Py_None) {
758 result = Py_None;
759 Py_INCREF(result);
760 }
761 else
762 result = PyObject_CallMethod(tzinfo, "tzname", "O", self);
763
764 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
765 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
Tim Peters2a799bf2002-12-16 20:18:38 +0000766 "return None or a string, not '%s'",
767 result->ob_type->tp_name);
768 Py_DECREF(result);
769 result = NULL;
770 }
771 return result;
772}
773
774typedef enum {
775 /* an exception has been set; the caller should pass it on */
776 OFFSET_ERROR,
777
778 /* type isn't date, datetime, datetimetz subclass, time, or
779 * timetz subclass
780 */
781 OFFSET_UNKNOWN,
782
783 /* date,
784 * datetime,
785 * datetimetz with None tzinfo,
Tim Peters855fe882002-12-22 03:43:39 +0000786 * datetimetz where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000787 * time,
788 * timetz with None tzinfo,
789 * timetz where utcoffset() returns None
790 */
791 OFFSET_NAIVE,
792
793 /* timetz where utcoffset() doesn't return None,
794 * datetimetz where utcoffset() doesn't return None
795 */
796 OFFSET_AWARE,
797} naivety;
798
Tim Peters14b69412002-12-22 18:10:22 +0000799/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000800 * the "naivety" typedef for details. If the type is aware, *offset is set
801 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000802 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peters2a799bf2002-12-16 20:18:38 +0000803 */
804static naivety
Tim Peters14b69412002-12-22 18:10:22 +0000805classify_utcoffset(PyObject *op, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000806{
807 int none;
808 PyObject *tzinfo;
809
810 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +0000811 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +0000812 if (tzinfo == Py_None)
813 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +0000814 if (tzinfo == NULL) {
815 /* note that a datetime passes the PyDate_Check test */
816 return (PyTime_Check(op) || PyDate_Check(op)) ?
817 OFFSET_NAIVE : OFFSET_UNKNOWN;
818 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000819 *offset = call_utcoffset(tzinfo, op, &none);
820 if (*offset == -1 && PyErr_Occurred())
821 return OFFSET_ERROR;
822 return none ? OFFSET_NAIVE : OFFSET_AWARE;
823}
824
825/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
826 * stuff
827 * ", tzinfo=" + repr(tzinfo)
828 * before the closing ")".
829 */
830static PyObject *
831append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
832{
833 PyObject *temp;
834
835 assert(PyString_Check(repr));
836 assert(tzinfo);
837 if (tzinfo == Py_None)
838 return repr;
839 /* Get rid of the trailing ')'. */
840 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
841 temp = PyString_FromStringAndSize(PyString_AsString(repr),
842 PyString_Size(repr) - 1);
843 Py_DECREF(repr);
844 if (temp == NULL)
845 return NULL;
846 repr = temp;
847
848 /* Append ", tzinfo=". */
849 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
850
851 /* Append repr(tzinfo). */
852 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
853
854 /* Add a closing paren. */
855 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
856 return repr;
857}
858
859/* ---------------------------------------------------------------------------
860 * String format helpers.
861 */
862
863static PyObject *
864format_ctime(PyDateTime_Date *date,
865 int hours, int minutes, int seconds)
866{
867 static char *DayNames[] = {
868 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
869 };
870 static char *MonthNames[] = {
871 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
872 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
873 };
874
875 char buffer[128];
876 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
877
878 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
879 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
880 GET_DAY(date), hours, minutes, seconds,
881 GET_YEAR(date));
882 return PyString_FromString(buffer);
883}
884
885/* Add an hours & minutes UTC offset string to buf. buf has no more than
886 * buflen bytes remaining. The UTC offset is gotten by calling
887 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
888 * *buf, and that's all. Else the returned value is checked for sanity (an
889 * integer in range), and if that's OK it's converted to an hours & minutes
890 * string of the form
891 * sign HH sep MM
892 * Returns 0 if everything is OK. If the return value from utcoffset() is
893 * bogus, an appropriate exception is set and -1 is returned.
894 */
895static int
Tim Peters328fff72002-12-20 01:31:27 +0000896format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +0000897 PyObject *tzinfo, PyObject *tzinfoarg)
898{
899 int offset;
900 int hours;
901 int minutes;
902 char sign;
903 int none;
904
905 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
906 if (offset == -1 && PyErr_Occurred())
907 return -1;
908 if (none) {
909 *buf = '\0';
910 return 0;
911 }
912 sign = '+';
913 if (offset < 0) {
914 sign = '-';
915 offset = - offset;
916 }
917 hours = divmod(offset, 60, &minutes);
918 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
919 return 0;
920}
921
922/* I sure don't want to reproduce the strftime code from the time module,
923 * so this imports the module and calls it. All the hair is due to
924 * giving special meanings to the %z and %Z format codes via a preprocessing
925 * step on the format string.
926 */
927static PyObject *
928wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple)
929{
930 PyObject *result = NULL; /* guilty until proved innocent */
931
932 PyObject *zreplacement = NULL; /* py string, replacement for %z */
933 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
934
935 char *pin; /* pointer to next char in input format */
936 char ch; /* next char in input format */
937
938 PyObject *newfmt = NULL; /* py string, the output format */
939 char *pnew; /* pointer to available byte in output format */
940 char totalnew; /* number bytes total in output format buffer,
941 exclusive of trailing \0 */
942 char usednew; /* number bytes used so far in output format buffer */
943
944 char *ptoappend; /* pointer to string to append to output buffer */
945 int ntoappend; /* # of bytes to append to output buffer */
946
Tim Peters2a799bf2002-12-16 20:18:38 +0000947 assert(object && format && timetuple);
948 assert(PyString_Check(format));
949
Tim Petersd6844152002-12-22 20:58:42 +0000950 /* Give up if the year is before 1900.
951 * Python strftime() plays games with the year, and different
952 * games depending on whether envar PYTHON2K is set. This makes
953 * years before 1900 a nightmare, even if the platform strftime
954 * supports them (and not all do).
955 * We could get a lot farther here by avoiding Python's strftime
956 * wrapper and calling the C strftime() directly, but that isn't
957 * an option in the Python implementation of this module.
958 */
959 {
960 long year;
961 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
962 if (pyyear == NULL) return NULL;
963 assert(PyInt_Check(pyyear));
964 year = PyInt_AsLong(pyyear);
965 Py_DECREF(pyyear);
966 if (year < 1900) {
967 PyErr_Format(PyExc_ValueError, "year=%ld is before "
968 "1900; the datetime strftime() "
969 "methods require year >= 1900",
970 year);
971 return NULL;
972 }
973 }
974
Tim Peters2a799bf2002-12-16 20:18:38 +0000975 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +0000976 * a new format. Since computing the replacements for those codes
977 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +0000978 */
979 totalnew = PyString_Size(format); /* realistic if no %z/%Z */
980 newfmt = PyString_FromStringAndSize(NULL, totalnew);
981 if (newfmt == NULL) goto Done;
982 pnew = PyString_AsString(newfmt);
983 usednew = 0;
984
985 pin = PyString_AsString(format);
986 while ((ch = *pin++) != '\0') {
987 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +0000988 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000989 ntoappend = 1;
990 }
991 else if ((ch = *pin++) == '\0') {
992 /* There's a lone trailing %; doesn't make sense. */
993 PyErr_SetString(PyExc_ValueError, "strftime format "
994 "ends with raw %");
995 goto Done;
996 }
997 /* A % has been seen and ch is the character after it. */
998 else if (ch == 'z') {
999 if (zreplacement == NULL) {
1000 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001001 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 PyObject *tzinfo = get_tzinfo_member(object);
1003 zreplacement = PyString_FromString("");
1004 if (zreplacement == NULL) goto Done;
1005 if (tzinfo != Py_None && tzinfo != NULL) {
1006 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001007 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001008 "",
1009 tzinfo,
1010 object) < 0)
1011 goto Done;
1012 Py_DECREF(zreplacement);
1013 zreplacement = PyString_FromString(buf);
1014 if (zreplacement == NULL) goto Done;
1015 }
1016 }
1017 assert(zreplacement != NULL);
1018 ptoappend = PyString_AsString(zreplacement);
1019 ntoappend = PyString_Size(zreplacement);
1020 }
1021 else if (ch == 'Z') {
1022 /* format tzname */
1023 if (Zreplacement == NULL) {
1024 PyObject *tzinfo = get_tzinfo_member(object);
1025 Zreplacement = PyString_FromString("");
1026 if (Zreplacement == NULL) goto Done;
1027 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Peters855fe882002-12-22 03:43:39 +00001028 PyObject *temp = call_tzname(object,
1029 tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00001030 if (temp == NULL) goto Done;
1031 if (temp != Py_None) {
1032 assert(PyString_Check(temp));
1033 /* Since the tzname is getting
1034 * stuffed into the format, we
1035 * have to double any % signs
1036 * so that strftime doesn't
1037 * treat them as format codes.
1038 */
1039 Py_DECREF(Zreplacement);
1040 Zreplacement = PyObject_CallMethod(
1041 temp, "replace",
1042 "ss", "%", "%%");
1043 Py_DECREF(temp);
1044 if (Zreplacement == NULL)
1045 goto Done;
1046 }
1047 else
1048 Py_DECREF(temp);
1049 }
1050 }
1051 assert(Zreplacement != NULL);
1052 ptoappend = PyString_AsString(Zreplacement);
1053 ntoappend = PyString_Size(Zreplacement);
1054 }
1055 else {
Tim Peters328fff72002-12-20 01:31:27 +00001056 /* percent followed by neither z nor Z */
1057 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001058 ntoappend = 2;
1059 }
1060
1061 /* Append the ntoappend chars starting at ptoappend to
1062 * the new format.
1063 */
1064 assert(ntoappend >= 0);
1065 if (ntoappend == 0)
1066 continue;
1067 while (usednew + ntoappend > totalnew) {
1068 int bigger = totalnew << 1;
1069 if ((bigger >> 1) != totalnew) { /* overflow */
1070 PyErr_NoMemory();
1071 goto Done;
1072 }
1073 if (_PyString_Resize(&newfmt, bigger) < 0)
1074 goto Done;
1075 totalnew = bigger;
1076 pnew = PyString_AsString(newfmt) + usednew;
1077 }
1078 memcpy(pnew, ptoappend, ntoappend);
1079 pnew += ntoappend;
1080 usednew += ntoappend;
1081 assert(usednew <= totalnew);
1082 } /* end while() */
1083
1084 if (_PyString_Resize(&newfmt, usednew) < 0)
1085 goto Done;
1086 {
1087 PyObject *time = PyImport_ImportModule("time");
1088 if (time == NULL)
1089 goto Done;
1090 result = PyObject_CallMethod(time, "strftime", "OO",
1091 newfmt, timetuple);
1092 Py_DECREF(time);
1093 }
1094 Done:
1095 Py_XDECREF(zreplacement);
1096 Py_XDECREF(Zreplacement);
1097 Py_XDECREF(newfmt);
1098 return result;
1099}
1100
1101static char *
1102isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1103{
1104 int x;
1105 x = PyOS_snprintf(buffer, bufflen,
1106 "%04d-%02d-%02d",
1107 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1108 return buffer + x;
1109}
1110
1111static void
1112isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1113{
1114 int us = DATE_GET_MICROSECOND(dt);
1115
1116 PyOS_snprintf(buffer, bufflen,
1117 "%02d:%02d:%02d", /* 8 characters */
1118 DATE_GET_HOUR(dt),
1119 DATE_GET_MINUTE(dt),
1120 DATE_GET_SECOND(dt));
1121 if (us)
1122 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1123}
1124
1125/* ---------------------------------------------------------------------------
1126 * Wrap functions from the time module. These aren't directly available
1127 * from C. Perhaps they should be.
1128 */
1129
1130/* Call time.time() and return its result (a Python float). */
1131static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001132time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001133{
1134 PyObject *result = NULL;
1135 PyObject *time = PyImport_ImportModule("time");
1136
1137 if (time != NULL) {
1138 result = PyObject_CallMethod(time, "time", "()");
1139 Py_DECREF(time);
1140 }
1141 return result;
1142}
1143
1144/* Build a time.struct_time. The weekday and day number are automatically
1145 * computed from the y,m,d args.
1146 */
1147static PyObject *
1148build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1149{
1150 PyObject *time;
1151 PyObject *result = NULL;
1152
1153 time = PyImport_ImportModule("time");
1154 if (time != NULL) {
1155 result = PyObject_CallMethod(time, "struct_time",
1156 "((iiiiiiiii))",
1157 y, m, d,
1158 hh, mm, ss,
1159 weekday(y, m, d),
1160 days_before_month(y, m) + d,
1161 dstflag);
1162 Py_DECREF(time);
1163 }
1164 return result;
1165}
1166
1167/* ---------------------------------------------------------------------------
1168 * Miscellaneous helpers.
1169 */
1170
1171/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1172 * The comparisons here all most naturally compute a cmp()-like result.
1173 * This little helper turns that into a bool result for rich comparisons.
1174 */
1175static PyObject *
1176diff_to_bool(int diff, int op)
1177{
1178 PyObject *result;
1179 int istrue;
1180
1181 switch (op) {
1182 case Py_EQ: istrue = diff == 0; break;
1183 case Py_NE: istrue = diff != 0; break;
1184 case Py_LE: istrue = diff <= 0; break;
1185 case Py_GE: istrue = diff >= 0; break;
1186 case Py_LT: istrue = diff < 0; break;
1187 case Py_GT: istrue = diff > 0; break;
1188 default:
1189 assert(! "op unknown");
1190 istrue = 0; /* To shut up compiler */
1191 }
1192 result = istrue ? Py_True : Py_False;
1193 Py_INCREF(result);
1194 return result;
1195}
1196
1197/* ---------------------------------------------------------------------------
1198 * Helpers for setting object fields. These work on pointers to the
1199 * appropriate base class.
1200 */
1201
1202/* For date, datetime and datetimetz. */
1203static void
1204set_date_fields(PyDateTime_Date *self, int y, int m, int d)
1205{
1206 self->hashcode = -1;
1207 SET_YEAR(self, y);
1208 SET_MONTH(self, m);
1209 SET_DAY(self, d);
1210}
1211
1212/* For datetime and datetimetz. */
1213static void
1214set_datetime_time_fields(PyDateTime_Date *self, int h, int m, int s, int us)
1215{
1216 DATE_SET_HOUR(self, h);
1217 DATE_SET_MINUTE(self, m);
1218 DATE_SET_SECOND(self, s);
1219 DATE_SET_MICROSECOND(self, us);
1220}
1221
1222/* For time and timetz. */
1223static void
1224set_time_fields(PyDateTime_Time *self, int h, int m, int s, int us)
1225{
1226 self->hashcode = -1;
1227 TIME_SET_HOUR(self, h);
1228 TIME_SET_MINUTE(self, m);
1229 TIME_SET_SECOND(self, s);
1230 TIME_SET_MICROSECOND(self, us);
1231}
1232
1233/* ---------------------------------------------------------------------------
1234 * Create various objects, mostly without range checking.
1235 */
1236
1237/* Create a date instance with no range checking. */
1238static PyObject *
1239new_date(int year, int month, int day)
1240{
1241 PyDateTime_Date *self;
1242
1243 self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType);
1244 if (self != NULL)
1245 set_date_fields(self, year, month, day);
1246 return (PyObject *) self;
1247}
1248
1249/* Create a datetime instance with no range checking. */
1250static PyObject *
1251new_datetime(int year, int month, int day, int hour, int minute,
1252 int second, int usecond)
1253{
1254 PyDateTime_DateTime *self;
1255
1256 self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType);
1257 if (self != NULL) {
1258 set_date_fields((PyDateTime_Date *)self, year, month, day);
1259 set_datetime_time_fields((PyDateTime_Date *)self,
1260 hour, minute, second, usecond);
1261 }
1262 return (PyObject *) self;
1263}
1264
1265/* Create a datetimetz instance with no range checking. */
1266static PyObject *
1267new_datetimetz(int year, int month, int day, int hour, int minute,
1268 int second, int usecond, PyObject *tzinfo)
1269{
1270 PyDateTime_DateTimeTZ *self;
1271
1272 self = PyObject_New(PyDateTime_DateTimeTZ, &PyDateTime_DateTimeTZType);
1273 if (self != NULL) {
1274 set_date_fields((PyDateTime_Date *)self, year, month, day);
1275 set_datetime_time_fields((PyDateTime_Date *)self,
1276 hour, minute, second, usecond);
1277 Py_INCREF(tzinfo);
1278 self->tzinfo = tzinfo;
1279 }
1280 return (PyObject *) self;
1281}
1282
1283/* Create a time instance with no range checking. */
1284static PyObject *
1285new_time(int hour, int minute, int second, int usecond)
1286{
1287 PyDateTime_Time *self;
1288
1289 self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType);
1290 if (self != NULL)
1291 set_time_fields(self, hour, minute, second, usecond);
1292 return (PyObject *) self;
1293}
1294
1295/* Create a timetz instance with no range checking. */
1296static PyObject *
1297new_timetz(int hour, int minute, int second, int usecond, PyObject *tzinfo)
1298{
1299 PyDateTime_TimeTZ *self;
1300
1301 self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType);
1302 if (self != NULL) {
1303 set_time_fields((PyDateTime_Time *)self,
1304 hour, minute, second, usecond);
1305 Py_INCREF(tzinfo);
1306 self->tzinfo = tzinfo;
1307 }
1308 return (PyObject *) self;
1309}
1310
1311/* Create a timedelta instance. Normalize the members iff normalize is
1312 * true. Passing false is a speed optimization, if you know for sure
1313 * that seconds and microseconds are already in their proper ranges. In any
1314 * case, raises OverflowError and returns NULL if the normalized days is out
1315 * of range).
1316 */
1317static PyObject *
1318new_delta(int days, int seconds, int microseconds, int normalize)
1319{
1320 PyDateTime_Delta *self;
1321
1322 if (normalize)
1323 normalize_d_s_us(&days, &seconds, &microseconds);
1324 assert(0 <= seconds && seconds < 24*3600);
1325 assert(0 <= microseconds && microseconds < 1000000);
1326
1327 if (check_delta_day_range(days) < 0)
1328 return NULL;
1329
1330 self = PyObject_New(PyDateTime_Delta, &PyDateTime_DeltaType);
1331 if (self != NULL) {
1332 self->hashcode = -1;
1333 SET_TD_DAYS(self, days);
1334 SET_TD_SECONDS(self, seconds);
1335 SET_TD_MICROSECONDS(self, microseconds);
1336 }
1337 return (PyObject *) self;
1338}
1339
1340
1341/* ---------------------------------------------------------------------------
1342 * Cached Python objects; these are set by the module init function.
1343 */
1344
1345/* Conversion factors. */
1346static PyObject *us_per_us = NULL; /* 1 */
1347static PyObject *us_per_ms = NULL; /* 1000 */
1348static PyObject *us_per_second = NULL; /* 1000000 */
1349static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1350static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1351static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1352static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1353static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1354
1355/* Callables to support unpickling. */
1356static PyObject *date_unpickler_object = NULL;
1357static PyObject *datetime_unpickler_object = NULL;
1358static PyObject *datetimetz_unpickler_object = NULL;
1359static PyObject *tzinfo_unpickler_object = NULL;
1360static PyObject *time_unpickler_object = NULL;
1361static PyObject *timetz_unpickler_object = NULL;
1362
1363/* ---------------------------------------------------------------------------
1364 * Class implementations.
1365 */
1366
1367/*
1368 * PyDateTime_Delta implementation.
1369 */
1370
1371/* Convert a timedelta to a number of us,
1372 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1373 * as a Python int or long.
1374 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1375 * due to ubiquitous overflow possibilities.
1376 */
1377static PyObject *
1378delta_to_microseconds(PyDateTime_Delta *self)
1379{
1380 PyObject *x1 = NULL;
1381 PyObject *x2 = NULL;
1382 PyObject *x3 = NULL;
1383 PyObject *result = NULL;
1384
1385 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1386 if (x1 == NULL)
1387 goto Done;
1388 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1389 if (x2 == NULL)
1390 goto Done;
1391 Py_DECREF(x1);
1392 x1 = NULL;
1393
1394 /* x2 has days in seconds */
1395 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1396 if (x1 == NULL)
1397 goto Done;
1398 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1399 if (x3 == NULL)
1400 goto Done;
1401 Py_DECREF(x1);
1402 Py_DECREF(x2);
1403 x1 = x2 = NULL;
1404
1405 /* x3 has days+seconds in seconds */
1406 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1407 if (x1 == NULL)
1408 goto Done;
1409 Py_DECREF(x3);
1410 x3 = NULL;
1411
1412 /* x1 has days+seconds in us */
1413 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1414 if (x2 == NULL)
1415 goto Done;
1416 result = PyNumber_Add(x1, x2);
1417
1418Done:
1419 Py_XDECREF(x1);
1420 Py_XDECREF(x2);
1421 Py_XDECREF(x3);
1422 return result;
1423}
1424
1425/* Convert a number of us (as a Python int or long) to a timedelta.
1426 */
1427static PyObject *
1428microseconds_to_delta(PyObject *pyus)
1429{
1430 int us;
1431 int s;
1432 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001433 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001434
1435 PyObject *tuple = NULL;
1436 PyObject *num = NULL;
1437 PyObject *result = NULL;
1438
1439 tuple = PyNumber_Divmod(pyus, us_per_second);
1440 if (tuple == NULL)
1441 goto Done;
1442
1443 num = PyTuple_GetItem(tuple, 1); /* us */
1444 if (num == NULL)
1445 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001446 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001447 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001448 if (temp == -1 && PyErr_Occurred())
1449 goto Done;
1450 assert(0 <= temp && temp < 1000000);
1451 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001452 if (us < 0) {
1453 /* The divisor was positive, so this must be an error. */
1454 assert(PyErr_Occurred());
1455 goto Done;
1456 }
1457
1458 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1459 if (num == NULL)
1460 goto Done;
1461 Py_INCREF(num);
1462 Py_DECREF(tuple);
1463
1464 tuple = PyNumber_Divmod(num, seconds_per_day);
1465 if (tuple == NULL)
1466 goto Done;
1467 Py_DECREF(num);
1468
1469 num = PyTuple_GetItem(tuple, 1); /* seconds */
1470 if (num == NULL)
1471 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001472 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001473 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001474 if (temp == -1 && PyErr_Occurred())
1475 goto Done;
1476 assert(0 <= temp && temp < 24*3600);
1477 s = (int)temp;
1478
Tim Peters2a799bf2002-12-16 20:18:38 +00001479 if (s < 0) {
1480 /* The divisor was positive, so this must be an error. */
1481 assert(PyErr_Occurred());
1482 goto Done;
1483 }
1484
1485 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1486 if (num == NULL)
1487 goto Done;
1488 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001489 temp = PyLong_AsLong(num);
1490 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001491 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001492 d = (int)temp;
1493 if ((long)d != temp) {
1494 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1495 "large to fit in a C int");
1496 goto Done;
1497 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001498 result = new_delta(d, s, us, 0);
1499
1500Done:
1501 Py_XDECREF(tuple);
1502 Py_XDECREF(num);
1503 return result;
1504}
1505
1506static PyObject *
1507multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1508{
1509 PyObject *pyus_in;
1510 PyObject *pyus_out;
1511 PyObject *result;
1512
1513 pyus_in = delta_to_microseconds(delta);
1514 if (pyus_in == NULL)
1515 return NULL;
1516
1517 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1518 Py_DECREF(pyus_in);
1519 if (pyus_out == NULL)
1520 return NULL;
1521
1522 result = microseconds_to_delta(pyus_out);
1523 Py_DECREF(pyus_out);
1524 return result;
1525}
1526
1527static PyObject *
1528divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1529{
1530 PyObject *pyus_in;
1531 PyObject *pyus_out;
1532 PyObject *result;
1533
1534 pyus_in = delta_to_microseconds(delta);
1535 if (pyus_in == NULL)
1536 return NULL;
1537
1538 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1539 Py_DECREF(pyus_in);
1540 if (pyus_out == NULL)
1541 return NULL;
1542
1543 result = microseconds_to_delta(pyus_out);
1544 Py_DECREF(pyus_out);
1545 return result;
1546}
1547
1548static PyObject *
1549delta_add(PyObject *left, PyObject *right)
1550{
1551 PyObject *result = Py_NotImplemented;
1552
1553 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1554 /* delta + delta */
1555 /* The C-level additions can't overflow because of the
1556 * invariant bounds.
1557 */
1558 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1559 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1560 int microseconds = GET_TD_MICROSECONDS(left) +
1561 GET_TD_MICROSECONDS(right);
1562 result = new_delta(days, seconds, microseconds, 1);
1563 }
1564
1565 if (result == Py_NotImplemented)
1566 Py_INCREF(result);
1567 return result;
1568}
1569
1570static PyObject *
1571delta_negative(PyDateTime_Delta *self)
1572{
1573 return new_delta(-GET_TD_DAYS(self),
1574 -GET_TD_SECONDS(self),
1575 -GET_TD_MICROSECONDS(self),
1576 1);
1577}
1578
1579static PyObject *
1580delta_positive(PyDateTime_Delta *self)
1581{
1582 /* Could optimize this (by returning self) if this isn't a
1583 * subclass -- but who uses unary + ? Approximately nobody.
1584 */
1585 return new_delta(GET_TD_DAYS(self),
1586 GET_TD_SECONDS(self),
1587 GET_TD_MICROSECONDS(self),
1588 0);
1589}
1590
1591static PyObject *
1592delta_abs(PyDateTime_Delta *self)
1593{
1594 PyObject *result;
1595
1596 assert(GET_TD_MICROSECONDS(self) >= 0);
1597 assert(GET_TD_SECONDS(self) >= 0);
1598
1599 if (GET_TD_DAYS(self) < 0)
1600 result = delta_negative(self);
1601 else
1602 result = delta_positive(self);
1603
1604 return result;
1605}
1606
1607static PyObject *
1608delta_subtract(PyObject *left, PyObject *right)
1609{
1610 PyObject *result = Py_NotImplemented;
1611
1612 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1613 /* delta - delta */
1614 PyObject *minus_right = PyNumber_Negative(right);
1615 if (minus_right) {
1616 result = delta_add(left, minus_right);
1617 Py_DECREF(minus_right);
1618 }
1619 else
1620 result = NULL;
1621 }
1622
1623 if (result == Py_NotImplemented)
1624 Py_INCREF(result);
1625 return result;
1626}
1627
1628/* This is more natural as a tp_compare, but doesn't work then: for whatever
1629 * reason, Python's try_3way_compare ignores tp_compare unless
1630 * PyInstance_Check returns true, but these aren't old-style classes.
1631 */
1632static PyObject *
1633delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1634{
1635 int diff;
1636
1637 if (! PyDelta_CheckExact(other)) {
1638 PyErr_Format(PyExc_TypeError,
1639 "can't compare %s to %s instance",
1640 self->ob_type->tp_name, other->ob_type->tp_name);
1641 return NULL;
1642 }
1643 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1644 if (diff == 0) {
1645 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1646 if (diff == 0)
1647 diff = GET_TD_MICROSECONDS(self) -
1648 GET_TD_MICROSECONDS(other);
1649 }
1650 return diff_to_bool(diff, op);
1651}
1652
1653static PyObject *delta_getstate(PyDateTime_Delta *self);
1654
1655static long
1656delta_hash(PyDateTime_Delta *self)
1657{
1658 if (self->hashcode == -1) {
1659 PyObject *temp = delta_getstate(self);
1660 if (temp != NULL) {
1661 self->hashcode = PyObject_Hash(temp);
1662 Py_DECREF(temp);
1663 }
1664 }
1665 return self->hashcode;
1666}
1667
1668static PyObject *
1669delta_multiply(PyObject *left, PyObject *right)
1670{
1671 PyObject *result = Py_NotImplemented;
1672
1673 if (PyDelta_Check(left)) {
1674 /* delta * ??? */
1675 if (PyInt_Check(right) || PyLong_Check(right))
1676 result = multiply_int_timedelta(right,
1677 (PyDateTime_Delta *) left);
1678 }
1679 else if (PyInt_Check(left) || PyLong_Check(left))
1680 result = multiply_int_timedelta(left,
1681 (PyDateTime_Delta *) right);
1682
1683 if (result == Py_NotImplemented)
1684 Py_INCREF(result);
1685 return result;
1686}
1687
1688static PyObject *
1689delta_divide(PyObject *left, PyObject *right)
1690{
1691 PyObject *result = Py_NotImplemented;
1692
1693 if (PyDelta_Check(left)) {
1694 /* delta * ??? */
1695 if (PyInt_Check(right) || PyLong_Check(right))
1696 result = divide_timedelta_int(
1697 (PyDateTime_Delta *)left,
1698 right);
1699 }
1700
1701 if (result == Py_NotImplemented)
1702 Py_INCREF(result);
1703 return result;
1704}
1705
1706/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1707 * timedelta constructor. sofar is the # of microseconds accounted for
1708 * so far, and there are factor microseconds per current unit, the number
1709 * of which is given by num. num * factor is added to sofar in a
1710 * numerically careful way, and that's the result. Any fractional
1711 * microseconds left over (this can happen if num is a float type) are
1712 * added into *leftover.
1713 * Note that there are many ways this can give an error (NULL) return.
1714 */
1715static PyObject *
1716accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1717 double *leftover)
1718{
1719 PyObject *prod;
1720 PyObject *sum;
1721
1722 assert(num != NULL);
1723
1724 if (PyInt_Check(num) || PyLong_Check(num)) {
1725 prod = PyNumber_Multiply(num, factor);
1726 if (prod == NULL)
1727 return NULL;
1728 sum = PyNumber_Add(sofar, prod);
1729 Py_DECREF(prod);
1730 return sum;
1731 }
1732
1733 if (PyFloat_Check(num)) {
1734 double dnum;
1735 double fracpart;
1736 double intpart;
1737 PyObject *x;
1738 PyObject *y;
1739
1740 /* The Plan: decompose num into an integer part and a
1741 * fractional part, num = intpart + fracpart.
1742 * Then num * factor ==
1743 * intpart * factor + fracpart * factor
1744 * and the LHS can be computed exactly in long arithmetic.
1745 * The RHS is again broken into an int part and frac part.
1746 * and the frac part is added into *leftover.
1747 */
1748 dnum = PyFloat_AsDouble(num);
1749 if (dnum == -1.0 && PyErr_Occurred())
1750 return NULL;
1751 fracpart = modf(dnum, &intpart);
1752 x = PyLong_FromDouble(intpart);
1753 if (x == NULL)
1754 return NULL;
1755
1756 prod = PyNumber_Multiply(x, factor);
1757 Py_DECREF(x);
1758 if (prod == NULL)
1759 return NULL;
1760
1761 sum = PyNumber_Add(sofar, prod);
1762 Py_DECREF(prod);
1763 if (sum == NULL)
1764 return NULL;
1765
1766 if (fracpart == 0.0)
1767 return sum;
1768 /* So far we've lost no information. Dealing with the
1769 * fractional part requires float arithmetic, and may
1770 * lose a little info.
1771 */
1772 assert(PyInt_Check(factor) || PyLong_Check(factor));
1773 if (PyInt_Check(factor))
1774 dnum = (double)PyInt_AsLong(factor);
1775 else
1776 dnum = PyLong_AsDouble(factor);
1777
1778 dnum *= fracpart;
1779 fracpart = modf(dnum, &intpart);
1780 x = PyLong_FromDouble(intpart);
1781 if (x == NULL) {
1782 Py_DECREF(sum);
1783 return NULL;
1784 }
1785
1786 y = PyNumber_Add(sum, x);
1787 Py_DECREF(sum);
1788 Py_DECREF(x);
1789 *leftover += fracpart;
1790 return y;
1791 }
1792
1793 PyErr_Format(PyExc_TypeError,
1794 "unsupported type for timedelta %s component: %s",
1795 tag, num->ob_type->tp_name);
1796 return NULL;
1797}
1798
1799static PyObject *
1800delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1801{
1802 PyObject *self = NULL;
1803
1804 /* Argument objects. */
1805 PyObject *day = NULL;
1806 PyObject *second = NULL;
1807 PyObject *us = NULL;
1808 PyObject *ms = NULL;
1809 PyObject *minute = NULL;
1810 PyObject *hour = NULL;
1811 PyObject *week = NULL;
1812
1813 PyObject *x = NULL; /* running sum of microseconds */
1814 PyObject *y = NULL; /* temp sum of microseconds */
1815 double leftover_us = 0.0;
1816
1817 static char *keywords[] = {
1818 "days", "seconds", "microseconds", "milliseconds",
1819 "minutes", "hours", "weeks", NULL
1820 };
1821
1822 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1823 keywords,
1824 &day, &second, &us,
1825 &ms, &minute, &hour, &week) == 0)
1826 goto Done;
1827
1828 x = PyInt_FromLong(0);
1829 if (x == NULL)
1830 goto Done;
1831
1832#define CLEANUP \
1833 Py_DECREF(x); \
1834 x = y; \
1835 if (x == NULL) \
1836 goto Done
1837
1838 if (us) {
1839 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1840 CLEANUP;
1841 }
1842 if (ms) {
1843 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1844 CLEANUP;
1845 }
1846 if (second) {
1847 y = accum("seconds", x, second, us_per_second, &leftover_us);
1848 CLEANUP;
1849 }
1850 if (minute) {
1851 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1852 CLEANUP;
1853 }
1854 if (hour) {
1855 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1856 CLEANUP;
1857 }
1858 if (day) {
1859 y = accum("days", x, day, us_per_day, &leftover_us);
1860 CLEANUP;
1861 }
1862 if (week) {
1863 y = accum("weeks", x, week, us_per_week, &leftover_us);
1864 CLEANUP;
1865 }
1866 if (leftover_us) {
1867 /* Round to nearest whole # of us, and add into x. */
1868 PyObject *temp;
1869 if (leftover_us >= 0.0)
1870 leftover_us = floor(leftover_us + 0.5);
1871 else
1872 leftover_us = ceil(leftover_us - 0.5);
1873 temp = PyLong_FromDouble(leftover_us);
1874 if (temp == NULL) {
1875 Py_DECREF(x);
1876 goto Done;
1877 }
1878 y = PyNumber_Add(x, temp);
1879 Py_DECREF(temp);
1880 CLEANUP;
1881 }
1882
1883 self = microseconds_to_delta(x);
1884 Py_DECREF(x);
1885Done:
1886 return self;
1887
1888#undef CLEANUP
1889}
1890
1891static int
1892delta_nonzero(PyDateTime_Delta *self)
1893{
1894 return (GET_TD_DAYS(self) != 0
1895 || GET_TD_SECONDS(self) != 0
1896 || GET_TD_MICROSECONDS(self) != 0);
1897}
1898
1899static PyObject *
1900delta_repr(PyDateTime_Delta *self)
1901{
1902 if (GET_TD_MICROSECONDS(self) != 0)
1903 return PyString_FromFormat("%s(%d, %d, %d)",
1904 self->ob_type->tp_name,
1905 GET_TD_DAYS(self),
1906 GET_TD_SECONDS(self),
1907 GET_TD_MICROSECONDS(self));
1908 if (GET_TD_SECONDS(self) != 0)
1909 return PyString_FromFormat("%s(%d, %d)",
1910 self->ob_type->tp_name,
1911 GET_TD_DAYS(self),
1912 GET_TD_SECONDS(self));
1913
1914 return PyString_FromFormat("%s(%d)",
1915 self->ob_type->tp_name,
1916 GET_TD_DAYS(self));
1917}
1918
1919static PyObject *
1920delta_str(PyDateTime_Delta *self)
1921{
1922 int days = GET_TD_DAYS(self);
1923 int seconds = GET_TD_SECONDS(self);
1924 int us = GET_TD_MICROSECONDS(self);
1925 int hours;
1926 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00001927 char buf[100];
1928 char *pbuf = buf;
1929 size_t buflen = sizeof(buf);
1930 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001931
1932 minutes = divmod(seconds, 60, &seconds);
1933 hours = divmod(minutes, 60, &minutes);
1934
1935 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00001936 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
1937 (days == 1 || days == -1) ? "" : "s");
1938 if (n < 0 || (size_t)n >= buflen)
1939 goto Fail;
1940 pbuf += n;
1941 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001942 }
1943
Tim Petersba873472002-12-18 20:19:21 +00001944 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
1945 hours, minutes, seconds);
1946 if (n < 0 || (size_t)n >= buflen)
1947 goto Fail;
1948 pbuf += n;
1949 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001950
1951 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00001952 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
1953 if (n < 0 || (size_t)n >= buflen)
1954 goto Fail;
1955 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001956 }
1957
Tim Petersba873472002-12-18 20:19:21 +00001958 return PyString_FromStringAndSize(buf, pbuf - buf);
1959
1960 Fail:
1961 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
1962 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001963}
1964
1965/* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed
1966 * in the Python implementation, the C implementation also requires
1967 * __reduce__, and a __safe_for_unpickling__ attr in the type object.
1968 */
1969static PyObject *
1970delta_getstate(PyDateTime_Delta *self)
1971{
1972 return Py_BuildValue("iii", GET_TD_DAYS(self),
1973 GET_TD_SECONDS(self),
1974 GET_TD_MICROSECONDS(self));
1975}
1976
1977static PyObject *
1978delta_setstate(PyDateTime_Delta *self, PyObject *state)
1979{
1980 int day;
1981 int second;
1982 int us;
1983
1984 if (!PyArg_ParseTuple(state, "iii:__setstate__", &day, &second, &us))
1985 return NULL;
1986
1987 self->hashcode = -1;
1988 SET_TD_DAYS(self, day);
1989 SET_TD_SECONDS(self, second);
1990 SET_TD_MICROSECONDS(self, us);
1991
1992 Py_INCREF(Py_None);
1993 return Py_None;
1994}
1995
1996static PyObject *
1997delta_reduce(PyDateTime_Delta* self)
1998{
1999 PyObject* result = NULL;
2000 PyObject* state = delta_getstate(self);
2001
2002 if (state != NULL) {
2003 /* The funky "()" in the format string creates an empty
2004 * tuple as the 2nd component of the result 3-tuple.
2005 */
2006 result = Py_BuildValue("O()O", self->ob_type, state);
2007 Py_DECREF(state);
2008 }
2009 return result;
2010}
2011
2012#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2013
2014static PyMemberDef delta_members[] = {
Neal Norwitzdfb80862002-12-19 02:30:56 +00002015 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002016 PyDoc_STR("Number of days.")},
2017
Neal Norwitzdfb80862002-12-19 02:30:56 +00002018 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002019 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2020
Neal Norwitzdfb80862002-12-19 02:30:56 +00002021 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002022 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2023 {NULL}
2024};
2025
2026static PyMethodDef delta_methods[] = {
2027 {"__setstate__", (PyCFunction)delta_setstate, METH_O,
2028 PyDoc_STR("__setstate__(state)")},
2029
2030 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2031 PyDoc_STR("__setstate__(state)")},
2032
2033 {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS,
2034 PyDoc_STR("__getstate__() -> state")},
2035 {NULL, NULL},
2036};
2037
2038static char delta_doc[] =
2039PyDoc_STR("Difference between two datetime values.");
2040
2041static PyNumberMethods delta_as_number = {
2042 delta_add, /* nb_add */
2043 delta_subtract, /* nb_subtract */
2044 delta_multiply, /* nb_multiply */
2045 delta_divide, /* nb_divide */
2046 0, /* nb_remainder */
2047 0, /* nb_divmod */
2048 0, /* nb_power */
2049 (unaryfunc)delta_negative, /* nb_negative */
2050 (unaryfunc)delta_positive, /* nb_positive */
2051 (unaryfunc)delta_abs, /* nb_absolute */
2052 (inquiry)delta_nonzero, /* nb_nonzero */
2053 0, /*nb_invert*/
2054 0, /*nb_lshift*/
2055 0, /*nb_rshift*/
2056 0, /*nb_and*/
2057 0, /*nb_xor*/
2058 0, /*nb_or*/
2059 0, /*nb_coerce*/
2060 0, /*nb_int*/
2061 0, /*nb_long*/
2062 0, /*nb_float*/
2063 0, /*nb_oct*/
2064 0, /*nb_hex*/
2065 0, /*nb_inplace_add*/
2066 0, /*nb_inplace_subtract*/
2067 0, /*nb_inplace_multiply*/
2068 0, /*nb_inplace_divide*/
2069 0, /*nb_inplace_remainder*/
2070 0, /*nb_inplace_power*/
2071 0, /*nb_inplace_lshift*/
2072 0, /*nb_inplace_rshift*/
2073 0, /*nb_inplace_and*/
2074 0, /*nb_inplace_xor*/
2075 0, /*nb_inplace_or*/
2076 delta_divide, /* nb_floor_divide */
2077 0, /* nb_true_divide */
2078 0, /* nb_inplace_floor_divide */
2079 0, /* nb_inplace_true_divide */
2080};
2081
2082static PyTypeObject PyDateTime_DeltaType = {
2083 PyObject_HEAD_INIT(NULL)
2084 0, /* ob_size */
2085 "datetime.timedelta", /* tp_name */
2086 sizeof(PyDateTime_Delta), /* tp_basicsize */
2087 0, /* tp_itemsize */
2088 0, /* tp_dealloc */
2089 0, /* tp_print */
2090 0, /* tp_getattr */
2091 0, /* tp_setattr */
2092 0, /* tp_compare */
2093 (reprfunc)delta_repr, /* tp_repr */
2094 &delta_as_number, /* tp_as_number */
2095 0, /* tp_as_sequence */
2096 0, /* tp_as_mapping */
2097 (hashfunc)delta_hash, /* tp_hash */
2098 0, /* tp_call */
2099 (reprfunc)delta_str, /* tp_str */
2100 PyObject_GenericGetAttr, /* tp_getattro */
2101 0, /* tp_setattro */
2102 0, /* tp_as_buffer */
2103 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
2104 delta_doc, /* tp_doc */
2105 0, /* tp_traverse */
2106 0, /* tp_clear */
2107 (richcmpfunc)delta_richcompare, /* tp_richcompare */
2108 0, /* tp_weaklistoffset */
2109 0, /* tp_iter */
2110 0, /* tp_iternext */
2111 delta_methods, /* tp_methods */
2112 delta_members, /* tp_members */
2113 0, /* tp_getset */
2114 0, /* tp_base */
2115 0, /* tp_dict */
2116 0, /* tp_descr_get */
2117 0, /* tp_descr_set */
2118 0, /* tp_dictoffset */
2119 0, /* tp_init */
2120 0, /* tp_alloc */
2121 delta_new, /* tp_new */
2122 _PyObject_Del, /* tp_free */
2123};
2124
2125/*
2126 * PyDateTime_Date implementation.
2127 */
2128
2129/* Accessor properties. */
2130
2131static PyObject *
2132date_year(PyDateTime_Date *self, void *unused)
2133{
2134 return PyInt_FromLong(GET_YEAR(self));
2135}
2136
2137static PyObject *
2138date_month(PyDateTime_Date *self, void *unused)
2139{
2140 return PyInt_FromLong(GET_MONTH(self));
2141}
2142
2143static PyObject *
2144date_day(PyDateTime_Date *self, void *unused)
2145{
2146 return PyInt_FromLong(GET_DAY(self));
2147}
2148
2149static PyGetSetDef date_getset[] = {
2150 {"year", (getter)date_year},
2151 {"month", (getter)date_month},
2152 {"day", (getter)date_day},
2153 {NULL}
2154};
2155
2156/* Constructors. */
2157
Tim Peters12bf3392002-12-24 05:41:27 +00002158static char *date_kws[] = {"year", "month", "day", NULL};
2159
Tim Peters2a799bf2002-12-16 20:18:38 +00002160static PyObject *
2161date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2162{
2163 PyObject *self = NULL;
2164 int year;
2165 int month;
2166 int day;
2167
Tim Peters12bf3392002-12-24 05:41:27 +00002168 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002169 &year, &month, &day)) {
2170 if (check_date_args(year, month, day) < 0)
2171 return NULL;
2172 self = new_date(year, month, day);
2173 }
2174 return self;
2175}
2176
2177/* Return new date from localtime(t). */
2178static PyObject *
2179date_local_from_time_t(PyObject *cls, time_t t)
2180{
2181 struct tm *tm;
2182 PyObject *result = NULL;
2183
2184 tm = localtime(&t);
2185 if (tm)
2186 result = PyObject_CallFunction(cls, "iii",
2187 tm->tm_year + 1900,
2188 tm->tm_mon + 1,
2189 tm->tm_mday);
2190 else
2191 PyErr_SetString(PyExc_ValueError,
2192 "timestamp out of range for "
2193 "platform localtime() function");
2194 return result;
2195}
2196
2197/* Return new date from current time.
2198 * We say this is equivalent to fromtimestamp(time.time()), and the
2199 * only way to be sure of that is to *call* time.time(). That's not
2200 * generally the same as calling C's time.
2201 */
2202static PyObject *
2203date_today(PyObject *cls, PyObject *dummy)
2204{
2205 PyObject *time;
2206 PyObject *result;
2207
2208 time = time_time();
2209 if (time == NULL)
2210 return NULL;
2211
2212 /* Note well: today() is a class method, so this may not call
2213 * date.fromtimestamp. For example, it may call
2214 * datetime.fromtimestamp. That's why we need all the accuracy
2215 * time.time() delivers; if someone were gonzo about optimization,
2216 * date.today() could get away with plain C time().
2217 */
2218 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2219 Py_DECREF(time);
2220 return result;
2221}
2222
2223/* Return new date from given timestamp (Python timestamp -- a double). */
2224static PyObject *
2225date_fromtimestamp(PyObject *cls, PyObject *args)
2226{
2227 double timestamp;
2228 PyObject *result = NULL;
2229
2230 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2231 result = date_local_from_time_t(cls, (time_t)timestamp);
2232 return result;
2233}
2234
2235/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2236 * the ordinal is out of range.
2237 */
2238static PyObject *
2239date_fromordinal(PyObject *cls, PyObject *args)
2240{
2241 PyObject *result = NULL;
2242 int ordinal;
2243
2244 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2245 int year;
2246 int month;
2247 int day;
2248
2249 if (ordinal < 1)
2250 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2251 ">= 1");
2252 else {
2253 ord_to_ymd(ordinal, &year, &month, &day);
2254 result = PyObject_CallFunction(cls, "iii",
2255 year, month, day);
2256 }
2257 }
2258 return result;
2259}
2260
2261/*
2262 * Date arithmetic.
2263 */
2264
2265/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2266 * instead.
2267 */
2268static PyObject *
2269add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2270{
2271 PyObject *result = NULL;
2272 int year = GET_YEAR(date);
2273 int month = GET_MONTH(date);
2274 int deltadays = GET_TD_DAYS(delta);
2275 /* C-level overflow is impossible because |deltadays| < 1e9. */
2276 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2277
2278 if (normalize_date(&year, &month, &day) >= 0)
2279 result = new_date(year, month, day);
2280 return result;
2281}
2282
2283static PyObject *
2284date_add(PyObject *left, PyObject *right)
2285{
2286 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2287 Py_INCREF(Py_NotImplemented);
2288 return Py_NotImplemented;
2289 }
2290 if (PyDate_CheckExact(left)) {
2291 /* date + ??? */
2292 if (PyDelta_Check(right))
2293 /* date + delta */
2294 return add_date_timedelta((PyDateTime_Date *) left,
2295 (PyDateTime_Delta *) right,
2296 0);
2297 }
2298 else {
2299 /* ??? + date
2300 * 'right' must be one of us, or we wouldn't have been called
2301 */
2302 if (PyDelta_Check(left))
2303 /* delta + date */
2304 return add_date_timedelta((PyDateTime_Date *) right,
2305 (PyDateTime_Delta *) left,
2306 0);
2307 }
2308 Py_INCREF(Py_NotImplemented);
2309 return Py_NotImplemented;
2310}
2311
2312static PyObject *
2313date_subtract(PyObject *left, PyObject *right)
2314{
2315 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2316 Py_INCREF(Py_NotImplemented);
2317 return Py_NotImplemented;
2318 }
2319 if (PyDate_CheckExact(left)) {
2320 if (PyDate_CheckExact(right)) {
2321 /* date - date */
2322 int left_ord = ymd_to_ord(GET_YEAR(left),
2323 GET_MONTH(left),
2324 GET_DAY(left));
2325 int right_ord = ymd_to_ord(GET_YEAR(right),
2326 GET_MONTH(right),
2327 GET_DAY(right));
2328 return new_delta(left_ord - right_ord, 0, 0, 0);
2329 }
2330 if (PyDelta_Check(right)) {
2331 /* date - delta */
2332 return add_date_timedelta((PyDateTime_Date *) left,
2333 (PyDateTime_Delta *) right,
2334 1);
2335 }
2336 }
2337 Py_INCREF(Py_NotImplemented);
2338 return Py_NotImplemented;
2339}
2340
2341
2342/* Various ways to turn a date into a string. */
2343
2344static PyObject *
2345date_repr(PyDateTime_Date *self)
2346{
2347 char buffer[1028];
2348 char *typename;
2349
2350 typename = self->ob_type->tp_name;
2351 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
2352 typename,
2353 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2354
2355 return PyString_FromString(buffer);
2356}
2357
2358static PyObject *
2359date_isoformat(PyDateTime_Date *self)
2360{
2361 char buffer[128];
2362
2363 isoformat_date(self, buffer, sizeof(buffer));
2364 return PyString_FromString(buffer);
2365}
2366
2367/* str() calls the appropriate isofomat() method. */
2368static PyObject *
2369date_str(PyDateTime_Date *self)
2370{
2371 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2372}
2373
2374
2375static PyObject *
2376date_ctime(PyDateTime_Date *self)
2377{
2378 return format_ctime(self, 0, 0, 0);
2379}
2380
2381static PyObject *
2382date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2383{
2384 /* This method can be inherited, and needs to call the
2385 * timetuple() method appropriate to self's class.
2386 */
2387 PyObject *result;
2388 PyObject *format;
2389 PyObject *tuple;
2390 static char *keywords[] = {"format", NULL};
2391
2392 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2393 &PyString_Type, &format))
2394 return NULL;
2395
2396 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2397 if (tuple == NULL)
2398 return NULL;
2399 result = wrap_strftime((PyObject *)self, format, tuple);
2400 Py_DECREF(tuple);
2401 return result;
2402}
2403
2404/* ISO methods. */
2405
2406static PyObject *
2407date_isoweekday(PyDateTime_Date *self)
2408{
2409 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2410
2411 return PyInt_FromLong(dow + 1);
2412}
2413
2414static PyObject *
2415date_isocalendar(PyDateTime_Date *self)
2416{
2417 int year = GET_YEAR(self);
2418 int week1_monday = iso_week1_monday(year);
2419 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2420 int week;
2421 int day;
2422
2423 week = divmod(today - week1_monday, 7, &day);
2424 if (week < 0) {
2425 --year;
2426 week1_monday = iso_week1_monday(year);
2427 week = divmod(today - week1_monday, 7, &day);
2428 }
2429 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2430 ++year;
2431 week = 0;
2432 }
2433 return Py_BuildValue("iii", year, week + 1, day + 1);
2434}
2435
2436/* Miscellaneous methods. */
2437
2438/* This is more natural as a tp_compare, but doesn't work then: for whatever
2439 * reason, Python's try_3way_compare ignores tp_compare unless
2440 * PyInstance_Check returns true, but these aren't old-style classes.
2441 */
2442static PyObject *
2443date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2444{
2445 int diff;
2446
2447 if (! PyDate_Check(other)) {
2448 PyErr_Format(PyExc_TypeError,
2449 "can't compare date to %s instance",
2450 other->ob_type->tp_name);
2451 return NULL;
2452 }
2453 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2454 _PyDateTime_DATE_DATASIZE);
2455 return diff_to_bool(diff, op);
2456}
2457
2458static PyObject *
2459date_timetuple(PyDateTime_Date *self)
2460{
2461 return build_struct_time(GET_YEAR(self),
2462 GET_MONTH(self),
2463 GET_DAY(self),
2464 0, 0, 0, -1);
2465}
2466
Tim Peters12bf3392002-12-24 05:41:27 +00002467static PyObject *
2468date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2469{
2470 PyObject *clone;
2471 PyObject *tuple;
2472 int year = GET_YEAR(self);
2473 int month = GET_MONTH(self);
2474 int day = GET_DAY(self);
2475
2476 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2477 &year, &month, &day))
2478 return NULL;
2479 tuple = Py_BuildValue("iii", year, month, day);
2480 if (tuple == NULL)
2481 return NULL;
2482 clone = date_new(self->ob_type, tuple, NULL);
2483 Py_DECREF(tuple);
2484 return clone;
2485}
2486
Tim Peters2a799bf2002-12-16 20:18:38 +00002487static PyObject *date_getstate(PyDateTime_Date *self);
2488
2489static long
2490date_hash(PyDateTime_Date *self)
2491{
2492 if (self->hashcode == -1) {
2493 PyObject *temp = date_getstate(self);
2494 if (temp != NULL) {
2495 self->hashcode = PyObject_Hash(temp);
2496 Py_DECREF(temp);
2497 }
2498 }
2499 return self->hashcode;
2500}
2501
2502static PyObject *
2503date_toordinal(PyDateTime_Date *self)
2504{
2505 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2506 GET_DAY(self)));
2507}
2508
2509static PyObject *
2510date_weekday(PyDateTime_Date *self)
2511{
2512 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2513
2514 return PyInt_FromLong(dow);
2515}
2516
2517/* Pickle support. Quite a maze! */
2518
2519static PyObject *
2520date_getstate(PyDateTime_Date *self)
2521{
2522 return PyString_FromStringAndSize(self->data,
2523 _PyDateTime_DATE_DATASIZE);
2524}
2525
2526static PyObject *
2527date_setstate(PyDateTime_Date *self, PyObject *state)
2528{
2529 const int len = PyString_Size(state);
2530 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
2531
2532 if (! PyString_Check(state) ||
2533 len != _PyDateTime_DATE_DATASIZE) {
2534 PyErr_SetString(PyExc_TypeError,
2535 "bad argument to date.__setstate__");
2536 return NULL;
2537 }
2538 memcpy(self->data, pdata, _PyDateTime_DATE_DATASIZE);
2539 self->hashcode = -1;
2540
2541 Py_INCREF(Py_None);
2542 return Py_None;
2543}
2544
2545/* XXX This seems a ridiculously inefficient way to pickle a short string. */
2546static PyObject *
2547date_pickler(PyObject *module, PyDateTime_Date *date)
2548{
2549 PyObject *state;
2550 PyObject *result = NULL;
2551
2552 if (! PyDate_CheckExact(date)) {
2553 PyErr_Format(PyExc_TypeError,
2554 "bad type passed to date pickler: %s",
2555 date->ob_type->tp_name);
2556 return NULL;
2557 }
2558 state = date_getstate(date);
2559 if (state) {
2560 result = Py_BuildValue("O(O)", date_unpickler_object, state);
2561 Py_DECREF(state);
2562 }
2563 return result;
2564}
2565
2566static PyObject *
2567date_unpickler(PyObject *module, PyObject *arg)
2568{
2569 PyDateTime_Date *self;
2570
2571 if (! PyString_CheckExact(arg)) {
2572 PyErr_Format(PyExc_TypeError,
2573 "bad type passed to date unpickler: %s",
2574 arg->ob_type->tp_name);
2575 return NULL;
2576 }
2577 self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType);
2578 if (self != NULL) {
2579 PyObject *res = date_setstate(self, arg);
2580 if (res == NULL) {
2581 Py_DECREF(self);
2582 return NULL;
2583 }
2584 Py_DECREF(res);
2585 }
2586 return (PyObject *)self;
2587}
2588
2589static PyMethodDef date_methods[] = {
2590 /* Class methods: */
2591 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2592 METH_CLASS,
2593 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2594 "time.time()).")},
2595
2596 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2597 METH_CLASS,
2598 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2599 "ordinal.")},
2600
2601 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2602 PyDoc_STR("Current date or datetime: same as "
2603 "self.__class__.fromtimestamp(time.time()).")},
2604
2605 /* Instance methods: */
2606
2607 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2608 PyDoc_STR("Return ctime() style string.")},
2609
2610 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2611 PyDoc_STR("format -> strftime() style string.")},
2612
2613 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2614 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2615
2616 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2617 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2618 "weekday.")},
2619
2620 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2621 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2622
2623 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2624 PyDoc_STR("Return the day of the week represented by the date.\n"
2625 "Monday == 1 ... Sunday == 7")},
2626
2627 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2628 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2629 "1 is day 1.")},
2630
2631 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2632 PyDoc_STR("Return the day of the week represented by the date.\n"
2633 "Monday == 0 ... Sunday == 6")},
2634
Tim Peters12bf3392002-12-24 05:41:27 +00002635 {"replace", (PyCFunction)date_replace, METH_KEYWORDS,
2636 PyDoc_STR("Return date with new specified fields.")},
2637
Tim Peters2a799bf2002-12-16 20:18:38 +00002638 {"__setstate__", (PyCFunction)date_setstate, METH_O,
2639 PyDoc_STR("__setstate__(state)")},
2640
2641 {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS,
2642 PyDoc_STR("__getstate__() -> state")},
2643
2644 {NULL, NULL}
2645};
2646
2647static char date_doc[] =
2648PyDoc_STR("Basic date type.");
2649
2650static PyNumberMethods date_as_number = {
2651 date_add, /* nb_add */
2652 date_subtract, /* nb_subtract */
2653 0, /* nb_multiply */
2654 0, /* nb_divide */
2655 0, /* nb_remainder */
2656 0, /* nb_divmod */
2657 0, /* nb_power */
2658 0, /* nb_negative */
2659 0, /* nb_positive */
2660 0, /* nb_absolute */
2661 0, /* nb_nonzero */
2662};
2663
2664static PyTypeObject PyDateTime_DateType = {
2665 PyObject_HEAD_INIT(NULL)
2666 0, /* ob_size */
2667 "datetime.date", /* tp_name */
2668 sizeof(PyDateTime_Date), /* tp_basicsize */
2669 0, /* tp_itemsize */
2670 (destructor)PyObject_Del, /* tp_dealloc */
2671 0, /* tp_print */
2672 0, /* tp_getattr */
2673 0, /* tp_setattr */
2674 0, /* tp_compare */
2675 (reprfunc)date_repr, /* tp_repr */
2676 &date_as_number, /* tp_as_number */
2677 0, /* tp_as_sequence */
2678 0, /* tp_as_mapping */
2679 (hashfunc)date_hash, /* tp_hash */
2680 0, /* tp_call */
2681 (reprfunc)date_str, /* tp_str */
2682 PyObject_GenericGetAttr, /* tp_getattro */
2683 0, /* tp_setattro */
2684 0, /* tp_as_buffer */
2685 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2686 Py_TPFLAGS_BASETYPE, /* tp_flags */
2687 date_doc, /* tp_doc */
2688 0, /* tp_traverse */
2689 0, /* tp_clear */
2690 (richcmpfunc)date_richcompare, /* tp_richcompare */
2691 0, /* tp_weaklistoffset */
2692 0, /* tp_iter */
2693 0, /* tp_iternext */
2694 date_methods, /* tp_methods */
2695 0, /* tp_members */
2696 date_getset, /* tp_getset */
2697 0, /* tp_base */
2698 0, /* tp_dict */
2699 0, /* tp_descr_get */
2700 0, /* tp_descr_set */
2701 0, /* tp_dictoffset */
2702 0, /* tp_init */
2703 0, /* tp_alloc */
2704 date_new, /* tp_new */
2705 _PyObject_Del, /* tp_free */
2706};
2707
2708/*
2709 * PyDateTime_DateTime implementation.
2710 */
2711
2712/* Accessor properties. */
2713
2714static PyObject *
2715datetime_hour(PyDateTime_DateTime *self, void *unused)
2716{
2717 return PyInt_FromLong(DATE_GET_HOUR(self));
2718}
2719
2720static PyObject *
2721datetime_minute(PyDateTime_DateTime *self, void *unused)
2722{
2723 return PyInt_FromLong(DATE_GET_MINUTE(self));
2724}
2725
2726static PyObject *
2727datetime_second(PyDateTime_DateTime *self, void *unused)
2728{
2729 return PyInt_FromLong(DATE_GET_SECOND(self));
2730}
2731
2732static PyObject *
2733datetime_microsecond(PyDateTime_DateTime *self, void *unused)
2734{
2735 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
2736}
2737
2738static PyGetSetDef datetime_getset[] = {
2739 {"hour", (getter)datetime_hour},
2740 {"minute", (getter)datetime_minute},
2741 {"second", (getter)datetime_second},
2742 {"microsecond", (getter)datetime_microsecond},
2743 {NULL}
2744};
2745
2746/* Constructors. */
2747
Tim Peters12bf3392002-12-24 05:41:27 +00002748
2749static char *datetime_kws[] = {"year", "month", "day",
2750 "hour", "minute", "second", "microsecond",
2751 NULL};
2752
Tim Peters2a799bf2002-12-16 20:18:38 +00002753static PyObject *
2754datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2755{
2756 PyObject *self = NULL;
2757 int year;
2758 int month;
2759 int day;
2760 int hour = 0;
2761 int minute = 0;
2762 int second = 0;
2763 int usecond = 0;
2764
Tim Peters12bf3392002-12-24 05:41:27 +00002765 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiii", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002766 &year, &month, &day, &hour, &minute,
2767 &second, &usecond)) {
2768 if (check_date_args(year, month, day) < 0)
2769 return NULL;
2770 if (check_time_args(hour, minute, second, usecond) < 0)
2771 return NULL;
2772 self = new_datetime(year, month, day,
2773 hour, minute, second, usecond);
2774 }
2775 return self;
2776}
2777
2778
2779/* TM_FUNC is the shared type of localtime() and gmtime(). */
2780typedef struct tm *(*TM_FUNC)(const time_t *timer);
2781
2782/* Internal helper.
2783 * Build datetime from a time_t and a distinct count of microseconds.
2784 * Pass localtime or gmtime for f, to control the interpretation of timet.
2785 */
2786static PyObject *
2787datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us)
2788{
2789 struct tm *tm;
2790 PyObject *result = NULL;
2791
2792 tm = f(&timet);
2793 if (tm)
2794 result = PyObject_CallFunction(cls, "iiiiiii",
2795 tm->tm_year + 1900,
2796 tm->tm_mon + 1,
2797 tm->tm_mday,
2798 tm->tm_hour,
2799 tm->tm_min,
2800 tm->tm_sec,
2801 us);
2802 else
2803 PyErr_SetString(PyExc_ValueError,
2804 "timestamp out of range for "
2805 "platform localtime()/gmtime() function");
2806 return result;
2807}
2808
2809/* Internal helper.
2810 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
2811 * to control the interpretation of the timestamp. Since a double doesn't
2812 * have enough bits to cover a datetime's full range of precision, it's
2813 * better to call datetime_from_timet_and_us provided you have a way
2814 * to get that much precision (e.g., C time() isn't good enough).
2815 */
2816static PyObject *
2817datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp)
2818{
2819 time_t timet = (time_t)timestamp;
2820 int us = (int)((timestamp - (double)timet) * 1e6);
2821
2822 return datetime_from_timet_and_us(cls, f, timet, us);
2823}
2824
2825/* Internal helper.
2826 * Build most accurate possible datetime for current time. Pass localtime or
2827 * gmtime for f as appropriate.
2828 */
2829static PyObject *
2830datetime_best_possible(PyObject *cls, TM_FUNC f)
2831{
2832#ifdef HAVE_GETTIMEOFDAY
2833 struct timeval t;
2834
2835#ifdef GETTIMEOFDAY_NO_TZ
2836 gettimeofday(&t);
2837#else
2838 gettimeofday(&t, (struct timezone *)NULL);
2839#endif
2840 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec);
2841
2842#else /* ! HAVE_GETTIMEOFDAY */
2843 /* No flavor of gettimeofday exists on this platform. Python's
2844 * time.time() does a lot of other platform tricks to get the
2845 * best time it can on the platform, and we're not going to do
2846 * better than that (if we could, the better code would belong
2847 * in time.time()!) We're limited by the precision of a double,
2848 * though.
2849 */
2850 PyObject *time;
2851 double dtime;
2852
2853 time = time_time();
2854 if (time == NULL)
2855 return NULL;
2856 dtime = PyFloat_AsDouble(time);
2857 Py_DECREF(time);
2858 if (dtime == -1.0 && PyErr_Occurred())
2859 return NULL;
2860 return datetime_from_timestamp(cls, f, dtime);
2861#endif /* ! HAVE_GETTIMEOFDAY */
2862}
2863
2864/* Return new local datetime from timestamp (Python timestamp -- a double). */
2865static PyObject *
2866datetime_fromtimestamp(PyObject *cls, PyObject *args)
2867{
2868 double timestamp;
2869 PyObject *result = NULL;
2870
2871 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2872 result = datetime_from_timestamp(cls, localtime, timestamp);
2873 return result;
2874}
2875
2876/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
2877static PyObject *
2878datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
2879{
2880 double timestamp;
2881 PyObject *result = NULL;
2882
2883 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
2884 result = datetime_from_timestamp(cls, gmtime, timestamp);
2885 return result;
2886}
2887
2888/* Return best possible local time -- this isn't constrained by the
2889 * precision of a timestamp.
2890 */
2891static PyObject *
2892datetime_now(PyObject *cls, PyObject *dummy)
2893{
2894 return datetime_best_possible(cls, localtime);
2895}
2896
2897/* Return best possible UTC time -- this isn't constrained by the
2898 * precision of a timestamp.
2899 */
2900static PyObject *
2901datetime_utcnow(PyObject *cls, PyObject *dummy)
2902{
2903 return datetime_best_possible(cls, gmtime);
2904}
2905
2906/* Return new datetime or datetimetz from date/datetime/datetimetz and
2907 * time/timetz arguments.
2908 */
2909static PyObject *
2910datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
2911{
2912 static char *keywords[] = {"date", "time", NULL};
2913 PyObject *date;
2914 PyObject *time;
2915 PyObject *result = NULL;
2916
2917 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
2918 &PyDateTime_DateType, &date,
2919 &PyDateTime_TimeType, &time))
2920 result = PyObject_CallFunction(cls, "iiiiiii",
2921 GET_YEAR(date),
2922 GET_MONTH(date),
2923 GET_DAY(date),
2924 TIME_GET_HOUR(time),
2925 TIME_GET_MINUTE(time),
2926 TIME_GET_SECOND(time),
2927 TIME_GET_MICROSECOND(time));
2928 if (result && PyTimeTZ_Check(time) && PyDateTimeTZ_Check(result)) {
2929 /* Copy the tzinfo field. */
Tim Peters80475bb2002-12-25 07:40:55 +00002930 replace_tzinfo(result, ((PyDateTime_TimeTZ *)time)->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00002931 }
2932 return result;
2933}
2934
2935/* datetime arithmetic. */
2936
2937static PyObject *
2938add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta)
2939{
2940 /* Note that the C-level additions can't overflow, because of
2941 * invariant bounds on the member values.
2942 */
2943 int year = GET_YEAR(date);
2944 int month = GET_MONTH(date);
2945 int day = GET_DAY(date) + GET_TD_DAYS(delta);
2946 int hour = DATE_GET_HOUR(date);
2947 int minute = DATE_GET_MINUTE(date);
2948 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta);
2949 int microsecond = DATE_GET_MICROSECOND(date) +
2950 GET_TD_MICROSECONDS(delta);
2951
2952 if (normalize_datetime(&year, &month, &day,
2953 &hour, &minute, &second, &microsecond) < 0)
2954 return NULL;
2955 else
2956 return new_datetime(year, month, day,
2957 hour, minute, second, microsecond);
2958}
2959
2960static PyObject *
2961sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta)
2962{
2963 /* Note that the C-level subtractions can't overflow, because of
2964 * invariant bounds on the member values.
2965 */
2966 int year = GET_YEAR(date);
2967 int month = GET_MONTH(date);
2968 int day = GET_DAY(date) - GET_TD_DAYS(delta);
2969 int hour = DATE_GET_HOUR(date);
2970 int minute = DATE_GET_MINUTE(date);
2971 int second = DATE_GET_SECOND(date) - GET_TD_SECONDS(delta);
2972 int microsecond = DATE_GET_MICROSECOND(date) -
2973 GET_TD_MICROSECONDS(delta);
2974
2975 if (normalize_datetime(&year, &month, &day,
2976 &hour, &minute, &second, &microsecond) < 0)
2977 return NULL;
2978 else
2979 return new_datetime(year, month, day,
2980 hour, minute, second, microsecond);
2981}
2982
2983static PyObject *
2984sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right)
2985{
2986 int days1 = ymd_to_ord(GET_YEAR(left), GET_MONTH(left), GET_DAY(left));
2987 int days2 = ymd_to_ord(GET_YEAR(right),
2988 GET_MONTH(right),
2989 GET_DAY(right));
2990 /* These can't overflow, since the values are normalized. At most
2991 * this gives the number of seconds in one day.
2992 */
2993 int delta_s = (DATE_GET_HOUR(left) - DATE_GET_HOUR(right)) * 3600 +
2994 (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 +
2995 DATE_GET_SECOND(left) - DATE_GET_SECOND(right);
2996 int delta_us = DATE_GET_MICROSECOND(left) -
2997 DATE_GET_MICROSECOND(right);
2998
2999 return new_delta(days1 - days2, delta_s, delta_us, 1);
3000}
3001
3002static PyObject *
3003datetime_add(PyObject *left, PyObject *right)
3004{
3005 if (PyDateTime_Check(left)) {
3006 /* datetime + ??? */
3007 if (PyDelta_Check(right))
3008 /* datetime + delta */
3009 return add_datetime_timedelta(
3010 (PyDateTime_DateTime *)left,
3011 (PyDateTime_Delta *)right);
3012 }
3013 else if (PyDelta_Check(left)) {
3014 /* delta + datetime */
3015 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3016 (PyDateTime_Delta *) left);
3017 }
3018 Py_INCREF(Py_NotImplemented);
3019 return Py_NotImplemented;
3020}
3021
3022static PyObject *
3023datetime_subtract(PyObject *left, PyObject *right)
3024{
3025 PyObject *result = Py_NotImplemented;
3026
3027 if (PyDateTime_Check(left)) {
3028 /* datetime - ??? */
3029 if (PyDateTime_Check(right)) {
3030 /* datetime - datetime */
3031 result = sub_datetime_datetime(
3032 (PyDateTime_DateTime *)left,
3033 (PyDateTime_DateTime *)right);
3034 }
3035 else if (PyDelta_Check(right)) {
3036 /* datetime - delta */
3037 result = sub_datetime_timedelta(
3038 (PyDateTime_DateTime *)left,
3039 (PyDateTime_Delta *)right);
3040 }
3041 }
3042
3043 if (result == Py_NotImplemented)
3044 Py_INCREF(result);
3045 return result;
3046}
3047
3048/* Various ways to turn a datetime into a string. */
3049
3050static PyObject *
3051datetime_repr(PyDateTime_DateTime *self)
3052{
3053 char buffer[1000];
3054 char *typename = self->ob_type->tp_name;
3055
3056 if (DATE_GET_MICROSECOND(self)) {
3057 PyOS_snprintf(buffer, sizeof(buffer),
3058 "%s(%d, %d, %d, %d, %d, %d, %d)",
3059 typename,
3060 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
3061 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
3062 DATE_GET_SECOND(self),
3063 DATE_GET_MICROSECOND(self));
3064 }
3065 else if (DATE_GET_SECOND(self)) {
3066 PyOS_snprintf(buffer, sizeof(buffer),
3067 "%s(%d, %d, %d, %d, %d, %d)",
3068 typename,
3069 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
3070 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
3071 DATE_GET_SECOND(self));
3072 }
3073 else {
3074 PyOS_snprintf(buffer, sizeof(buffer),
3075 "%s(%d, %d, %d, %d, %d)",
3076 typename,
3077 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
3078 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
3079 }
3080 return PyString_FromString(buffer);
3081}
3082
3083static PyObject *
3084datetime_str(PyDateTime_DateTime *self)
3085{
3086 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
3087}
3088
3089static PyObject *
3090datetime_isoformat(PyDateTime_DateTime *self,
3091 PyObject *args, PyObject *kw)
3092{
3093 char sep = 'T';
3094 static char *keywords[] = {"sep", NULL};
3095 char buffer[100];
3096 char *cp;
3097
3098 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
3099 &sep))
3100 return NULL;
3101 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
3102 assert(cp != NULL);
3103 *cp++ = sep;
3104 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
3105 return PyString_FromString(buffer);
3106}
3107
3108static PyObject *
3109datetime_ctime(PyDateTime_DateTime *self)
3110{
3111 return format_ctime((PyDateTime_Date *)self,
3112 DATE_GET_HOUR(self),
3113 DATE_GET_MINUTE(self),
3114 DATE_GET_SECOND(self));
3115}
3116
3117/* Miscellaneous methods. */
3118
3119/* This is more natural as a tp_compare, but doesn't work then: for whatever
3120 * reason, Python's try_3way_compare ignores tp_compare unless
3121 * PyInstance_Check returns true, but these aren't old-style classes.
3122 * Note that this routine handles all comparisons for datetime and datetimetz.
3123 */
3124static PyObject *
3125datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
3126{
3127 int diff;
3128 naivety n1, n2;
3129 int offset1, offset2;
3130
3131 if (! PyDateTime_Check(other)) {
3132 /* Stop this from falling back to address comparison. */
3133 PyErr_Format(PyExc_TypeError,
3134 "can't compare '%s' to '%s'",
3135 self->ob_type->tp_name,
3136 other->ob_type->tp_name);
3137 return NULL;
3138 }
Tim Peters14b69412002-12-22 18:10:22 +00003139 n1 = classify_utcoffset((PyObject *)self, &offset1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003140 assert(n1 != OFFSET_UNKNOWN);
3141 if (n1 == OFFSET_ERROR)
3142 return NULL;
3143
Tim Peters14b69412002-12-22 18:10:22 +00003144 n2 = classify_utcoffset(other, &offset2);
Tim Peters2a799bf2002-12-16 20:18:38 +00003145 assert(n2 != OFFSET_UNKNOWN);
3146 if (n2 == OFFSET_ERROR)
3147 return NULL;
3148
3149 /* If they're both naive, or both aware and have the same offsets,
3150 * we get off cheap. Note that if they're both naive, offset1 ==
3151 * offset2 == 0 at this point.
3152 */
3153 if (n1 == n2 && offset1 == offset2) {
3154 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
3155 _PyDateTime_DATETIME_DATASIZE);
3156 return diff_to_bool(diff, op);
3157 }
3158
3159 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3160 /* We want the sign of
3161 * (self - offset1 minutes) - (other - offset2 minutes) =
3162 * (self - other) + (offset2 - offset1) minutes.
3163 */
3164 PyDateTime_Delta *delta;
3165 int days, seconds, us;
3166
3167 assert(offset1 != offset2); /* else last "if" handled it */
3168 delta = (PyDateTime_Delta *)sub_datetime_datetime(self,
3169 (PyDateTime_DateTime *)other);
3170 if (delta == NULL)
3171 return NULL;
3172 days = delta->days;
3173 seconds = delta->seconds + (offset2 - offset1) * 60;
3174 us = delta->microseconds;
3175 Py_DECREF(delta);
3176 normalize_d_s_us(&days, &seconds, &us);
3177 diff = days;
3178 if (diff == 0)
3179 diff = seconds | us;
3180 return diff_to_bool(diff, op);
3181 }
3182
3183 assert(n1 != n2);
3184 PyErr_SetString(PyExc_TypeError,
3185 "can't compare offset-naive and "
3186 "offset-aware datetimes");
3187 return NULL;
3188}
3189
3190static PyObject *datetime_getstate(PyDateTime_DateTime *self);
3191
3192static long
3193datetime_hash(PyDateTime_DateTime *self)
3194{
3195 if (self->hashcode == -1) {
3196 naivety n;
3197 int offset;
3198 PyObject *temp;
3199
Tim Peters14b69412002-12-22 18:10:22 +00003200 n = classify_utcoffset((PyObject *)self, &offset);
Tim Peters2a799bf2002-12-16 20:18:38 +00003201 assert(n != OFFSET_UNKNOWN);
3202 if (n == OFFSET_ERROR)
3203 return -1;
3204
3205 /* Reduce this to a hash of another object. */
3206 if (n == OFFSET_NAIVE)
3207 temp = datetime_getstate(self);
3208 else {
3209 int days;
3210 int seconds;
3211
3212 assert(n == OFFSET_AWARE);
3213 assert(PyDateTimeTZ_Check(self));
3214 days = ymd_to_ord(GET_YEAR(self),
3215 GET_MONTH(self),
3216 GET_DAY(self));
3217 seconds = DATE_GET_HOUR(self) * 3600 +
3218 (DATE_GET_MINUTE(self) - offset) * 60 +
3219 DATE_GET_SECOND(self);
3220 temp = new_delta(days,
3221 seconds,
3222 DATE_GET_MICROSECOND(self),
3223 1);
3224 }
3225 if (temp != NULL) {
3226 self->hashcode = PyObject_Hash(temp);
3227 Py_DECREF(temp);
3228 }
3229 }
3230 return self->hashcode;
3231}
3232
3233static PyObject *
Tim Peters12bf3392002-12-24 05:41:27 +00003234datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
3235{
3236 PyObject *clone;
3237 PyObject *tuple;
3238 int y = GET_YEAR(self);
3239 int m = GET_MONTH(self);
3240 int d = GET_DAY(self);
3241 int hh = DATE_GET_HOUR(self);
3242 int mm = DATE_GET_MINUTE(self);
3243 int ss = DATE_GET_SECOND(self);
3244 int us = DATE_GET_MICROSECOND(self);
3245
3246 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiii:replace",
3247 datetime_kws,
3248 &y, &m, &d, &hh, &mm, &ss, &us))
3249 return NULL;
3250 tuple = Py_BuildValue("iiiiiii", y, m, d, hh, mm, ss, us);
3251 if (tuple == NULL)
3252 return NULL;
3253 clone = datetime_new(self->ob_type, tuple, NULL);
3254 Py_DECREF(tuple);
3255 return clone;
3256}
3257
3258static PyObject *
Tim Peters80475bb2002-12-25 07:40:55 +00003259datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
3260{
3261 PyObject *tzinfo;
3262 static char *keywords[] = {"tz", NULL};
3263
3264 if (! PyArg_ParseTupleAndKeywords(args, kw, "O:astimezone", keywords,
3265 &tzinfo))
3266 return NULL;
3267 if (check_tzinfo_subclass(tzinfo) < 0)
3268 return NULL;
3269 return new_datetimetz(GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
3270 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
3271 DATE_GET_SECOND(self),
3272 DATE_GET_MICROSECOND(self),
3273 tzinfo);
3274}
3275
3276static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00003277datetime_timetuple(PyDateTime_DateTime *self)
3278{
3279 return build_struct_time(GET_YEAR(self),
3280 GET_MONTH(self),
3281 GET_DAY(self),
3282 DATE_GET_HOUR(self),
3283 DATE_GET_MINUTE(self),
3284 DATE_GET_SECOND(self),
3285 -1);
3286}
3287
3288static PyObject *
3289datetime_getdate(PyDateTime_DateTime *self)
3290{
3291 return new_date(GET_YEAR(self),
3292 GET_MONTH(self),
3293 GET_DAY(self));
3294}
3295
3296static PyObject *
3297datetime_gettime(PyDateTime_DateTime *self)
3298{
3299 return new_time(DATE_GET_HOUR(self),
3300 DATE_GET_MINUTE(self),
3301 DATE_GET_SECOND(self),
3302 DATE_GET_MICROSECOND(self));
3303}
3304
3305/* Pickle support. Quite a maze! */
3306
3307static PyObject *
3308datetime_getstate(PyDateTime_DateTime *self)
3309{
3310 return PyString_FromStringAndSize(self->data,
3311 _PyDateTime_DATETIME_DATASIZE);
3312}
3313
3314static PyObject *
3315datetime_setstate(PyDateTime_DateTime *self, PyObject *state)
3316{
3317 const int len = PyString_Size(state);
3318 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
3319
3320 if (! PyString_Check(state) ||
3321 len != _PyDateTime_DATETIME_DATASIZE) {
3322 PyErr_SetString(PyExc_TypeError,
3323 "bad argument to datetime.__setstate__");
3324 return NULL;
3325 }
3326 memcpy(self->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3327 self->hashcode = -1;
3328
3329 Py_INCREF(Py_None);
3330 return Py_None;
3331}
3332
3333/* XXX This seems a ridiculously inefficient way to pickle a short string. */
3334static PyObject *
3335datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime)
3336{
3337 PyObject *state;
3338 PyObject *result = NULL;
3339
3340 if (! PyDateTime_CheckExact(datetime)) {
3341 PyErr_Format(PyExc_TypeError,
3342 "bad type passed to datetime pickler: %s",
3343 datetime->ob_type->tp_name);
3344 return NULL;
3345 }
3346 state = datetime_getstate(datetime);
3347 if (state) {
3348 result = Py_BuildValue("O(O)",
3349 datetime_unpickler_object,
3350 state);
3351 Py_DECREF(state);
3352 }
3353 return result;
3354}
3355
3356static PyObject *
3357datetime_unpickler(PyObject *module, PyObject *arg)
3358{
3359 PyDateTime_DateTime *self;
3360
3361 if (! PyString_CheckExact(arg)) {
3362 PyErr_Format(PyExc_TypeError,
3363 "bad type passed to datetime unpickler: %s",
3364 arg->ob_type->tp_name);
3365 return NULL;
3366 }
3367 self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType);
3368 if (self != NULL) {
3369 PyObject *res = datetime_setstate(self, arg);
3370 if (res == NULL) {
3371 Py_DECREF(self);
3372 return NULL;
3373 }
3374 Py_DECREF(res);
3375 }
3376 return (PyObject *)self;
3377}
3378
3379static PyMethodDef datetime_methods[] = {
3380 /* Class methods: */
3381 {"now", (PyCFunction)datetime_now,
3382 METH_NOARGS | METH_CLASS,
3383 PyDoc_STR("Return a new datetime representing local day and time.")},
3384
3385 {"utcnow", (PyCFunction)datetime_utcnow,
3386 METH_NOARGS | METH_CLASS,
3387 PyDoc_STR("Return a new datetime representing UTC day and time.")},
3388
3389 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
3390 METH_VARARGS | METH_CLASS,
3391 PyDoc_STR("timestamp -> local datetime from a POSIX timestamp "
3392 "(like time.time()).")},
3393
3394 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
3395 METH_VARARGS | METH_CLASS,
3396 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
3397 "(like time.time()).")},
3398
3399 {"combine", (PyCFunction)datetime_combine,
3400 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3401 PyDoc_STR("date, time -> datetime with same date and time fields")},
3402
3403 /* Instance methods: */
3404 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
3405 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
3406
3407 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
3408 PyDoc_STR("Return date object with same year, month and day.")},
3409
3410 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
3411 PyDoc_STR("Return time object with same hour, minute, second and "
3412 "microsecond.")},
3413
3414 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
3415 PyDoc_STR("Return ctime() style string.")},
3416
3417 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
3418 PyDoc_STR("[sep] -> string in ISO 8601 format, "
3419 "YYYY-MM-DDTHH:MM:SS[.mmmmmm].\n\n"
3420 "sep is used to separate the year from the time, and "
3421 "defaults\n"
3422 "to 'T'.")},
3423
Tim Peters12bf3392002-12-24 05:41:27 +00003424 {"replace", (PyCFunction)datetime_replace, METH_KEYWORDS,
3425 PyDoc_STR("Return datetime with new specified fields.")},
3426
Tim Peters80475bb2002-12-25 07:40:55 +00003427 {"astimezone", (PyCFunction)datetime_astimezone, METH_KEYWORDS,
3428 PyDoc_STR("tz -> datetimetz with same date & time, and tzinfo=tz\n")},
3429
Tim Peters2a799bf2002-12-16 20:18:38 +00003430 {"__setstate__", (PyCFunction)datetime_setstate, METH_O,
3431 PyDoc_STR("__setstate__(state)")},
3432
3433 {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS,
3434 PyDoc_STR("__getstate__() -> state")},
3435 {NULL, NULL}
3436};
3437
3438static char datetime_doc[] =
3439PyDoc_STR("Basic date/time type.");
3440
3441static PyNumberMethods datetime_as_number = {
3442 datetime_add, /* nb_add */
3443 datetime_subtract, /* nb_subtract */
3444 0, /* nb_multiply */
3445 0, /* nb_divide */
3446 0, /* nb_remainder */
3447 0, /* nb_divmod */
3448 0, /* nb_power */
3449 0, /* nb_negative */
3450 0, /* nb_positive */
3451 0, /* nb_absolute */
3452 0, /* nb_nonzero */
3453};
3454
3455statichere PyTypeObject PyDateTime_DateTimeType = {
3456 PyObject_HEAD_INIT(NULL)
3457 0, /* ob_size */
3458 "datetime.datetime", /* tp_name */
3459 sizeof(PyDateTime_DateTime), /* tp_basicsize */
3460 0, /* tp_itemsize */
3461 (destructor)PyObject_Del, /* tp_dealloc */
3462 0, /* tp_print */
3463 0, /* tp_getattr */
3464 0, /* tp_setattr */
3465 0, /* tp_compare */
3466 (reprfunc)datetime_repr, /* tp_repr */
3467 &datetime_as_number, /* tp_as_number */
3468 0, /* tp_as_sequence */
3469 0, /* tp_as_mapping */
3470 (hashfunc)datetime_hash, /* tp_hash */
3471 0, /* tp_call */
3472 (reprfunc)datetime_str, /* tp_str */
3473 PyObject_GenericGetAttr, /* tp_getattro */
3474 0, /* tp_setattro */
3475 0, /* tp_as_buffer */
3476 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3477 Py_TPFLAGS_BASETYPE, /* tp_flags */
3478 datetime_doc, /* tp_doc */
3479 0, /* tp_traverse */
3480 0, /* tp_clear */
3481 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
3482 0, /* tp_weaklistoffset */
3483 0, /* tp_iter */
3484 0, /* tp_iternext */
3485 datetime_methods, /* tp_methods */
3486 0, /* tp_members */
3487 datetime_getset, /* tp_getset */
3488 &PyDateTime_DateType, /* tp_base */
3489 0, /* tp_dict */
3490 0, /* tp_descr_get */
3491 0, /* tp_descr_set */
3492 0, /* tp_dictoffset */
3493 0, /* tp_init */
3494 0, /* tp_alloc */
3495 datetime_new, /* tp_new */
3496 _PyObject_Del, /* tp_free */
3497};
3498
3499/*
3500 * PyDateTime_Time implementation.
3501 */
3502
3503/* Accessor properties. */
3504
3505static PyObject *
3506time_hour(PyDateTime_Time *self, void *unused)
3507{
3508 return PyInt_FromLong(TIME_GET_HOUR(self));
3509}
3510
3511static PyObject *
3512time_minute(PyDateTime_Time *self, void *unused)
3513{
3514 return PyInt_FromLong(TIME_GET_MINUTE(self));
3515}
3516
3517static PyObject *
Jack Jansen51cd8a22002-12-17 20:57:24 +00003518py_time_second(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003519{
3520 return PyInt_FromLong(TIME_GET_SECOND(self));
3521}
3522
3523static PyObject *
3524time_microsecond(PyDateTime_Time *self, void *unused)
3525{
3526 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3527}
3528
3529static PyGetSetDef time_getset[] = {
3530 {"hour", (getter)time_hour},
3531 {"minute", (getter)time_minute},
Jack Jansen51cd8a22002-12-17 20:57:24 +00003532 {"second", (getter)py_time_second},
Tim Peters2a799bf2002-12-16 20:18:38 +00003533 {"microsecond", (getter)time_microsecond},
3534 {NULL}
3535};
3536
3537/* Constructors. */
3538
Tim Peters12bf3392002-12-24 05:41:27 +00003539static char *time_kws[] = {"hour", "minute", "second", "microsecond", NULL};
3540
Tim Peters2a799bf2002-12-16 20:18:38 +00003541static PyObject *
3542time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3543{
3544 PyObject *self = NULL;
3545 int hour = 0;
3546 int minute = 0;
3547 int second = 0;
3548 int usecond = 0;
3549
Tim Peters2a799bf2002-12-16 20:18:38 +00003550
Tim Peters12bf3392002-12-24 05:41:27 +00003551 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiii", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003552 &hour, &minute, &second, &usecond)) {
3553 if (check_time_args(hour, minute, second, usecond) < 0)
3554 return NULL;
3555 self = new_time(hour, minute, second, usecond);
3556 }
3557 return self;
3558}
3559
3560/* Various ways to turn a time into a string. */
3561
3562static PyObject *
3563time_repr(PyDateTime_Time *self)
3564{
3565 char buffer[100];
3566 char *typename = self->ob_type->tp_name;
3567 int h = TIME_GET_HOUR(self);
3568 int m = TIME_GET_MINUTE(self);
3569 int s = TIME_GET_SECOND(self);
3570 int us = TIME_GET_MICROSECOND(self);
3571
3572 if (us)
3573 PyOS_snprintf(buffer, sizeof(buffer),
3574 "%s(%d, %d, %d, %d)", typename, h, m, s, us);
3575 else if (s)
3576 PyOS_snprintf(buffer, sizeof(buffer),
3577 "%s(%d, %d, %d)", typename, h, m, s);
3578 else
3579 PyOS_snprintf(buffer, sizeof(buffer),
3580 "%s(%d, %d)", typename, h, m);
3581 return PyString_FromString(buffer);
3582}
3583
3584static PyObject *
3585time_str(PyDateTime_Time *self)
3586{
3587 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3588}
3589
3590static PyObject *
3591time_isoformat(PyDateTime_Time *self)
3592{
3593 char buffer[100];
3594 /* Reuse the time format code from the datetime type. */
3595 PyDateTime_DateTime datetime;
3596 PyDateTime_DateTime *pdatetime = &datetime;
3597
3598 /* Copy over just the time bytes. */
3599 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3600 self->data,
3601 _PyDateTime_TIME_DATASIZE);
3602
3603 isoformat_time(pdatetime, buffer, sizeof(buffer));
3604 return PyString_FromString(buffer);
3605}
3606
3607static PyObject *
3608time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3609{
3610 PyObject *result;
3611 PyObject *format;
3612 PyObject *tuple;
3613 static char *keywords[] = {"format", NULL};
3614
3615 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3616 &PyString_Type, &format))
3617 return NULL;
3618
Tim Peters83b85f12002-12-22 20:34:46 +00003619 /* Python's strftime does insane things with the year part of the
3620 * timetuple. The year is forced to (the otherwise nonsensical)
3621 * 1900 to worm around that.
3622 */
Tim Peters2a799bf2002-12-16 20:18:38 +00003623 tuple = Py_BuildValue("iiiiiiiii",
Tim Peters83b85f12002-12-22 20:34:46 +00003624 1900, 0, 0, /* year, month, day */
Tim Peters2a799bf2002-12-16 20:18:38 +00003625 TIME_GET_HOUR(self),
3626 TIME_GET_MINUTE(self),
3627 TIME_GET_SECOND(self),
3628 0, 0, -1); /* weekday, daynum, dst */
3629 if (tuple == NULL)
3630 return NULL;
3631 assert(PyTuple_Size(tuple) == 9);
3632 result = wrap_strftime((PyObject *)self, format, tuple);
3633 Py_DECREF(tuple);
3634 return result;
3635}
3636
3637/* Miscellaneous methods. */
3638
3639/* This is more natural as a tp_compare, but doesn't work then: for whatever
3640 * reason, Python's try_3way_compare ignores tp_compare unless
3641 * PyInstance_Check returns true, but these aren't old-style classes.
3642 * Note that this routine handles all comparisons for time and timetz.
3643 */
3644static PyObject *
3645time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3646{
3647 int diff;
3648 naivety n1, n2;
3649 int offset1, offset2;
3650
3651 if (! PyTime_Check(other)) {
3652 /* Stop this from falling back to address comparison. */
3653 PyErr_Format(PyExc_TypeError,
3654 "can't compare '%s' to '%s'",
3655 self->ob_type->tp_name,
3656 other->ob_type->tp_name);
3657 return NULL;
3658 }
Tim Peters14b69412002-12-22 18:10:22 +00003659 n1 = classify_utcoffset((PyObject *)self, &offset1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003660 assert(n1 != OFFSET_UNKNOWN);
3661 if (n1 == OFFSET_ERROR)
3662 return NULL;
3663
Tim Peters14b69412002-12-22 18:10:22 +00003664 n2 = classify_utcoffset(other, &offset2);
Tim Peters2a799bf2002-12-16 20:18:38 +00003665 assert(n2 != OFFSET_UNKNOWN);
3666 if (n2 == OFFSET_ERROR)
3667 return NULL;
3668
3669 /* If they're both naive, or both aware and have the same offsets,
3670 * we get off cheap. Note that if they're both naive, offset1 ==
3671 * offset2 == 0 at this point.
3672 */
3673 if (n1 == n2 && offset1 == offset2) {
3674 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3675 _PyDateTime_TIME_DATASIZE);
3676 return diff_to_bool(diff, op);
3677 }
3678
3679 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3680 assert(offset1 != offset2); /* else last "if" handled it */
3681 /* Convert everything except microseconds to seconds. These
3682 * can't overflow (no more than the # of seconds in 2 days).
3683 */
3684 offset1 = TIME_GET_HOUR(self) * 3600 +
3685 (TIME_GET_MINUTE(self) - offset1) * 60 +
3686 TIME_GET_SECOND(self);
3687 offset2 = TIME_GET_HOUR(other) * 3600 +
3688 (TIME_GET_MINUTE(other) - offset2) * 60 +
3689 TIME_GET_SECOND(other);
3690 diff = offset1 - offset2;
3691 if (diff == 0)
3692 diff = TIME_GET_MICROSECOND(self) -
3693 TIME_GET_MICROSECOND(other);
3694 return diff_to_bool(diff, op);
3695 }
3696
3697 assert(n1 != n2);
3698 PyErr_SetString(PyExc_TypeError,
3699 "can't compare offset-naive and "
3700 "offset-aware times");
3701 return NULL;
3702}
3703
3704static PyObject *time_getstate(PyDateTime_Time *self);
3705
3706static long
3707time_hash(PyDateTime_Time *self)
3708{
3709 if (self->hashcode == -1) {
3710 naivety n;
3711 int offset;
3712 PyObject *temp;
3713
Tim Peters14b69412002-12-22 18:10:22 +00003714 n = classify_utcoffset((PyObject *)self, &offset);
Tim Peters2a799bf2002-12-16 20:18:38 +00003715 assert(n != OFFSET_UNKNOWN);
3716 if (n == OFFSET_ERROR)
3717 return -1;
3718
3719 /* Reduce this to a hash of another object. */
3720 if (offset == 0)
3721 temp = time_getstate(self);
3722 else {
3723 int hour;
3724 int minute;
3725
3726 assert(n == OFFSET_AWARE);
3727 assert(PyTimeTZ_Check(self));
3728 hour = divmod(TIME_GET_HOUR(self) * 60 +
3729 TIME_GET_MINUTE(self) - offset,
3730 60,
3731 &minute);
3732 if (0 <= hour && hour < 24)
3733 temp = new_time(hour, minute,
3734 TIME_GET_SECOND(self),
3735 TIME_GET_MICROSECOND(self));
3736 else
3737 temp = Py_BuildValue("iiii",
3738 hour, minute,
3739 TIME_GET_SECOND(self),
3740 TIME_GET_MICROSECOND(self));
3741 }
3742 if (temp != NULL) {
3743 self->hashcode = PyObject_Hash(temp);
3744 Py_DECREF(temp);
3745 }
3746 }
3747 return self->hashcode;
3748}
3749
Tim Peters12bf3392002-12-24 05:41:27 +00003750static PyObject *
3751time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3752{
3753 PyObject *clone;
3754 PyObject *tuple;
3755 int hh = TIME_GET_HOUR(self);
3756 int mm = TIME_GET_MINUTE(self);
3757 int ss = TIME_GET_SECOND(self);
3758 int us = TIME_GET_MICROSECOND(self);
3759
3760 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiii:replace",
3761 time_kws,
3762 &hh, &mm, &ss, &us))
3763 return NULL;
3764 tuple = Py_BuildValue("iiii", hh, mm, ss, us);
3765 if (tuple == NULL)
3766 return NULL;
3767 clone = time_new(self->ob_type, tuple, NULL);
3768 Py_DECREF(tuple);
3769 return clone;
3770}
3771
Tim Peters2a799bf2002-12-16 20:18:38 +00003772static int
3773time_nonzero(PyDateTime_Time *self)
3774{
3775 return TIME_GET_HOUR(self) ||
3776 TIME_GET_MINUTE(self) ||
3777 TIME_GET_SECOND(self) ||
3778 TIME_GET_MICROSECOND(self);
3779}
3780
3781/* Pickle support. Quite a maze! */
3782
3783static PyObject *
3784time_getstate(PyDateTime_Time *self)
3785{
3786 return PyString_FromStringAndSize(self->data,
3787 _PyDateTime_TIME_DATASIZE);
3788}
3789
3790static PyObject *
3791time_setstate(PyDateTime_Time *self, PyObject *state)
3792{
3793 const int len = PyString_Size(state);
3794 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
3795
3796 if (! PyString_Check(state) ||
3797 len != _PyDateTime_TIME_DATASIZE) {
3798 PyErr_SetString(PyExc_TypeError,
3799 "bad argument to time.__setstate__");
3800 return NULL;
3801 }
3802 memcpy(self->data, pdata, _PyDateTime_TIME_DATASIZE);
3803 self->hashcode = -1;
3804
3805 Py_INCREF(Py_None);
3806 return Py_None;
3807}
3808
3809/* XXX This seems a ridiculously inefficient way to pickle a short string. */
3810static PyObject *
3811time_pickler(PyObject *module, PyDateTime_Time *time)
3812{
3813 PyObject *state;
3814 PyObject *result = NULL;
3815
3816 if (! PyTime_CheckExact(time)) {
3817 PyErr_Format(PyExc_TypeError,
3818 "bad type passed to time pickler: %s",
3819 time->ob_type->tp_name);
3820 return NULL;
3821 }
3822 state = time_getstate(time);
3823 if (state) {
3824 result = Py_BuildValue("O(O)",
3825 time_unpickler_object,
3826 state);
3827 Py_DECREF(state);
3828 }
3829 return result;
3830}
3831
3832static PyObject *
3833time_unpickler(PyObject *module, PyObject *arg)
3834{
3835 PyDateTime_Time *self;
3836
3837 if (! PyString_CheckExact(arg)) {
3838 PyErr_Format(PyExc_TypeError,
3839 "bad type passed to time unpickler: %s",
3840 arg->ob_type->tp_name);
3841 return NULL;
3842 }
3843 self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType);
3844 if (self != NULL) {
3845 PyObject *res = time_setstate(self, arg);
3846 if (res == NULL) {
3847 Py_DECREF(self);
3848 return NULL;
3849 }
3850 Py_DECREF(res);
3851 }
3852 return (PyObject *)self;
3853}
3854
3855static PyMethodDef time_methods[] = {
3856 {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
3857 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm].")},
3858
3859 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3860 PyDoc_STR("format -> strftime() style string.")},
3861
Tim Peters12bf3392002-12-24 05:41:27 +00003862 {"replace", (PyCFunction)time_replace, METH_KEYWORDS,
3863 PyDoc_STR("Return datetime with new specified fields.")},
3864
Tim Peters2a799bf2002-12-16 20:18:38 +00003865 {"__setstate__", (PyCFunction)time_setstate, METH_O,
3866 PyDoc_STR("__setstate__(state)")},
3867
3868 {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS,
3869 PyDoc_STR("__getstate__() -> state")},
3870 {NULL, NULL}
3871};
3872
3873static char time_doc[] =
3874PyDoc_STR("Basic time type.");
3875
3876static PyNumberMethods time_as_number = {
3877 0, /* nb_add */
3878 0, /* nb_subtract */
3879 0, /* nb_multiply */
3880 0, /* nb_divide */
3881 0, /* nb_remainder */
3882 0, /* nb_divmod */
3883 0, /* nb_power */
3884 0, /* nb_negative */
3885 0, /* nb_positive */
3886 0, /* nb_absolute */
3887 (inquiry)time_nonzero, /* nb_nonzero */
3888};
3889
3890statichere PyTypeObject PyDateTime_TimeType = {
3891 PyObject_HEAD_INIT(NULL)
3892 0, /* ob_size */
3893 "datetime.time", /* tp_name */
3894 sizeof(PyDateTime_Time), /* tp_basicsize */
3895 0, /* tp_itemsize */
3896 (destructor)PyObject_Del, /* tp_dealloc */
3897 0, /* tp_print */
3898 0, /* tp_getattr */
3899 0, /* tp_setattr */
3900 0, /* tp_compare */
3901 (reprfunc)time_repr, /* tp_repr */
3902 &time_as_number, /* tp_as_number */
3903 0, /* tp_as_sequence */
3904 0, /* tp_as_mapping */
3905 (hashfunc)time_hash, /* tp_hash */
3906 0, /* tp_call */
3907 (reprfunc)time_str, /* tp_str */
3908 PyObject_GenericGetAttr, /* tp_getattro */
3909 0, /* tp_setattro */
3910 0, /* tp_as_buffer */
3911 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3912 Py_TPFLAGS_BASETYPE, /* tp_flags */
3913 time_doc, /* tp_doc */
3914 0, /* tp_traverse */
3915 0, /* tp_clear */
3916 (richcmpfunc)time_richcompare, /* tp_richcompare */
3917 0, /* tp_weaklistoffset */
3918 0, /* tp_iter */
3919 0, /* tp_iternext */
3920 time_methods, /* tp_methods */
3921 0, /* tp_members */
3922 time_getset, /* tp_getset */
3923 0, /* tp_base */
3924 0, /* tp_dict */
3925 0, /* tp_descr_get */
3926 0, /* tp_descr_set */
3927 0, /* tp_dictoffset */
3928 0, /* tp_init */
3929 0, /* tp_alloc */
3930 time_new, /* tp_new */
3931 _PyObject_Del, /* tp_free */
3932};
3933
3934/*
3935 * PyDateTime_TZInfo implementation.
3936 */
3937
3938/* This is a pure abstract base class, so doesn't do anything beyond
3939 * raising NotImplemented exceptions. Real tzinfo classes need
3940 * to derive from this. This is mostly for clarity, and for efficiency in
3941 * datetimetz and timetz constructors (their tzinfo arguments need to
3942 * be subclasses of this tzinfo class, which is easy and quick to check).
3943 *
3944 * Note: For reasons having to do with pickling of subclasses, we have
3945 * to allow tzinfo objects to be instantiated. This wasn't an issue
3946 * in the Python implementation (__init__() could raise NotImplementedError
3947 * there without ill effect), but doing so in the C implementation hit a
3948 * brick wall.
3949 */
3950
3951static PyObject *
3952tzinfo_nogo(const char* methodname)
3953{
3954 PyErr_Format(PyExc_NotImplementedError,
3955 "a tzinfo subclass must implement %s()",
3956 methodname);
3957 return NULL;
3958}
3959
3960/* Methods. A subclass must implement these. */
3961
3962static PyObject*
3963tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3964{
3965 return tzinfo_nogo("tzname");
3966}
3967
3968static PyObject*
3969tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3970{
3971 return tzinfo_nogo("utcoffset");
3972}
3973
3974static PyObject*
3975tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3976{
3977 return tzinfo_nogo("dst");
3978}
3979
3980/*
3981 * Pickle support. This is solely so that tzinfo subclasses can use
3982 * pickling -- tzinfo itself is supposed to be uninstantiable. The
3983 * pickler and unpickler functions are given module-level private
3984 * names, and registered with copy_reg, by the module init function.
3985 */
3986
3987static PyObject*
3988tzinfo_pickler(PyDateTime_TZInfo *self) {
3989 return Py_BuildValue("O()", tzinfo_unpickler_object);
3990}
3991
3992static PyObject*
3993tzinfo_unpickler(PyObject * unused) {
3994 return PyType_GenericNew(&PyDateTime_TZInfoType, NULL, NULL);
3995}
3996
3997
3998static PyMethodDef tzinfo_methods[] = {
3999 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
4000 PyDoc_STR("datetime -> string name of time zone.")},
4001
4002 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
4003 PyDoc_STR("datetime -> minutes east of UTC (negative for "
4004 "west of UTC).")},
4005
4006 {"dst", (PyCFunction)tzinfo_dst, METH_O,
4007 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
4008
4009 {NULL, NULL}
4010};
4011
4012static char tzinfo_doc[] =
4013PyDoc_STR("Abstract base class for time zone info objects.");
4014
4015 statichere PyTypeObject PyDateTime_TZInfoType = {
4016 PyObject_HEAD_INIT(NULL)
4017 0, /* ob_size */
4018 "datetime.tzinfo", /* tp_name */
4019 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
4020 0, /* tp_itemsize */
4021 0, /* tp_dealloc */
4022 0, /* tp_print */
4023 0, /* tp_getattr */
4024 0, /* tp_setattr */
4025 0, /* tp_compare */
4026 0, /* tp_repr */
4027 0, /* tp_as_number */
4028 0, /* tp_as_sequence */
4029 0, /* tp_as_mapping */
4030 0, /* tp_hash */
4031 0, /* tp_call */
4032 0, /* tp_str */
4033 PyObject_GenericGetAttr, /* tp_getattro */
4034 0, /* tp_setattro */
4035 0, /* tp_as_buffer */
4036 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4037 Py_TPFLAGS_BASETYPE, /* tp_flags */
4038 tzinfo_doc, /* tp_doc */
4039 0, /* tp_traverse */
4040 0, /* tp_clear */
4041 0, /* tp_richcompare */
4042 0, /* tp_weaklistoffset */
4043 0, /* tp_iter */
4044 0, /* tp_iternext */
4045 tzinfo_methods, /* tp_methods */
4046 0, /* tp_members */
4047 0, /* tp_getset */
4048 0, /* tp_base */
4049 0, /* tp_dict */
4050 0, /* tp_descr_get */
4051 0, /* tp_descr_set */
4052 0, /* tp_dictoffset */
4053 0, /* tp_init */
4054 0, /* tp_alloc */
4055 PyType_GenericNew, /* tp_new */
4056 0, /* tp_free */
4057};
4058
4059/*
4060 * PyDateTime_TimeTZ implementation.
4061 */
4062
4063/* Accessor properties. Properties for hour, minute, second and microsecond
4064 * are inherited from time.
4065 */
4066
4067static PyObject *
4068timetz_tzinfo(PyDateTime_TimeTZ *self, void *unused)
4069{
4070 Py_INCREF(self->tzinfo);
4071 return self->tzinfo;
4072}
4073
4074static PyGetSetDef timetz_getset[] = {
4075 {"tzinfo", (getter)timetz_tzinfo},
4076 {NULL}
4077};
4078
4079/*
4080 * Constructors.
4081 */
4082
Tim Peters12bf3392002-12-24 05:41:27 +00004083static char *timetz_kws[] = {"hour", "minute", "second", "microsecond",
4084 "tzinfo", NULL};
4085
Tim Peters2a799bf2002-12-16 20:18:38 +00004086static PyObject *
4087timetz_new(PyTypeObject *type, PyObject *args, PyObject *kw)
4088{
4089 PyObject *self = NULL;
4090 int hour = 0;
4091 int minute = 0;
4092 int second = 0;
4093 int usecond = 0;
4094 PyObject *tzinfo = Py_None;
4095
Tim Peters12bf3392002-12-24 05:41:27 +00004096 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", timetz_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00004097 &hour, &minute, &second, &usecond,
4098 &tzinfo)) {
4099 if (check_time_args(hour, minute, second, usecond) < 0)
4100 return NULL;
4101 if (check_tzinfo_subclass(tzinfo) < 0)
4102 return NULL;
4103 self = new_timetz(hour, minute, second, usecond, tzinfo);
4104 }
4105 return self;
4106}
4107
4108/*
4109 * Destructor.
4110 */
4111
4112static void
4113timetz_dealloc(PyDateTime_TimeTZ *self)
4114{
4115 Py_XDECREF(self->tzinfo);
4116 self->ob_type->tp_free((PyObject *)self);
4117}
4118
4119/*
Tim Peters855fe882002-12-22 03:43:39 +00004120 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00004121 */
4122
Tim Peters2a799bf2002-12-16 20:18:38 +00004123/* These are all METH_NOARGS, so don't need to check the arglist. */
4124static PyObject *
4125timetz_utcoffset(PyDateTime_TimeTZ *self, PyObject *unused) {
Tim Peters855fe882002-12-22 03:43:39 +00004126 return offset_as_timedelta((PyObject *)self, self->tzinfo,
4127 "utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00004128}
4129
4130static PyObject *
4131timetz_dst(PyDateTime_TimeTZ *self, PyObject *unused) {
Tim Peters855fe882002-12-22 03:43:39 +00004132 return offset_as_timedelta((PyObject *)self, self->tzinfo, "dst");
4133}
4134
4135static PyObject *
4136timetz_tzname(PyDateTime_TimeTZ *self, PyObject *unused) {
4137 return call_tzname((PyObject *)self, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004138}
4139
4140/*
4141 * Various ways to turn a timetz into a string.
4142 */
4143
4144static PyObject *
4145timetz_repr(PyDateTime_TimeTZ *self)
4146{
4147 PyObject *baserepr = time_repr((PyDateTime_Time *)self);
4148
4149 if (baserepr == NULL)
4150 return NULL;
4151 return append_keyword_tzinfo(baserepr, self->tzinfo);
4152}
4153
4154/* Note: tp_str is inherited from time. */
4155
4156static PyObject *
4157timetz_isoformat(PyDateTime_TimeTZ *self)
4158{
4159 char buf[100];
4160 PyObject *result = time_isoformat((PyDateTime_Time *)self);
4161
4162 if (result == NULL || self->tzinfo == Py_None)
4163 return result;
4164
4165 /* We need to append the UTC offset. */
4166 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4167 (PyObject *)self) < 0) {
4168 Py_DECREF(result);
4169 return NULL;
4170 }
4171 PyString_ConcatAndDel(&result, PyString_FromString(buf));
4172 return result;
4173}
4174
4175/* Note: strftime() is inherited from time. */
4176
4177/*
4178 * Miscellaneous methods.
4179 */
4180
4181/* Note: tp_richcompare and tp_hash are inherited from time. */
4182
Tim Peters12bf3392002-12-24 05:41:27 +00004183static PyObject *
4184timetz_replace(PyDateTime_TimeTZ *self, PyObject *args, PyObject *kw)
4185{
4186 PyObject *clone;
4187 PyObject *tuple;
4188 int hh = TIME_GET_HOUR(self);
4189 int mm = TIME_GET_MINUTE(self);
4190 int ss = TIME_GET_SECOND(self);
4191 int us = TIME_GET_MICROSECOND(self);
4192 PyObject *tzinfo = self->tzinfo;
4193
4194 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
4195 timetz_kws,
4196 &hh, &mm, &ss, &us, &tzinfo))
4197 return NULL;
4198 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
4199 if (tuple == NULL)
4200 return NULL;
4201 clone = timetz_new(self->ob_type, tuple, NULL);
4202 Py_DECREF(tuple);
4203 return clone;
4204}
4205
Tim Peters2a799bf2002-12-16 20:18:38 +00004206static int
4207timetz_nonzero(PyDateTime_TimeTZ *self)
4208{
4209 int offset;
4210 int none;
4211
4212 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
4213 /* Since utcoffset is in whole minutes, nothing can
4214 * alter the conclusion that this is nonzero.
4215 */
4216 return 1;
4217 }
4218 offset = 0;
4219 if (self->tzinfo != Py_None) {
4220 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4221 if (offset == -1 && PyErr_Occurred())
4222 return -1;
4223 }
4224 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
4225}
4226
4227/*
4228 * Pickle support. Quite a maze!
4229 */
4230
4231/* Let basestate be the state string returned by time_getstate.
4232 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4233 * So it's a tuple in any (non-error) case.
4234 */
4235static PyObject *
4236timetz_getstate(PyDateTime_TimeTZ *self)
4237{
4238 PyObject *basestate;
4239 PyObject *result = NULL;
4240
4241 basestate = time_getstate((PyDateTime_Time *)self);
4242 if (basestate != NULL) {
4243 if (self->tzinfo == Py_None)
4244 result = Py_BuildValue("(O)", basestate);
4245 else
4246 result = Py_BuildValue("OO", basestate, self->tzinfo);
4247 Py_DECREF(basestate);
4248 }
4249 return result;
4250}
4251
4252static PyObject *
4253timetz_setstate(PyDateTime_TimeTZ *self, PyObject *state)
4254{
4255 PyObject *temp;
4256 PyObject *basestate;
4257 PyObject *tzinfo = Py_None;
4258
4259 if (! PyArg_ParseTuple(state, "O!|O:__setstate__",
4260 &PyString_Type, &basestate,
4261 &tzinfo))
4262 return NULL;
4263 temp = time_setstate((PyDateTime_Time *)self, basestate);
4264 if (temp == NULL)
4265 return NULL;
4266 Py_DECREF(temp);
4267
4268 Py_INCREF(tzinfo);
4269 Py_XDECREF(self->tzinfo);
4270 self->tzinfo = tzinfo;
4271
4272 Py_INCREF(Py_None);
4273 return Py_None;
4274}
4275
4276static PyObject *
4277timetz_pickler(PyObject *module, PyDateTime_TimeTZ *timetz)
4278{
4279 PyObject *state;
4280 PyObject *result = NULL;
4281
4282 if (! PyTimeTZ_CheckExact(timetz)) {
4283 PyErr_Format(PyExc_TypeError,
4284 "bad type passed to timetz pickler: %s",
4285 timetz->ob_type->tp_name);
4286 return NULL;
4287 }
4288 state = timetz_getstate(timetz);
4289 if (state) {
4290 result = Py_BuildValue("O(O)",
4291 timetz_unpickler_object,
4292 state);
4293 Py_DECREF(state);
4294 }
4295 return result;
4296}
4297
4298static PyObject *
4299timetz_unpickler(PyObject *module, PyObject *arg)
4300{
4301 PyDateTime_TimeTZ *self;
4302
4303 self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType);
4304 if (self != NULL) {
4305 PyObject *res;
4306
4307 self->tzinfo = NULL;
4308 res = timetz_setstate(self, arg);
4309 if (res == NULL) {
4310 Py_DECREF(self);
4311 return NULL;
4312 }
4313 Py_DECREF(res);
4314 }
4315 return (PyObject *)self;
4316}
4317
4318static PyMethodDef timetz_methods[] = {
4319 {"isoformat", (PyCFunction)timetz_isoformat, METH_KEYWORDS,
4320 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
4321 "[+HH:MM].")},
4322
4323 {"utcoffset", (PyCFunction)timetz_utcoffset, METH_NOARGS,
4324 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4325
4326 {"tzname", (PyCFunction)timetz_tzname, METH_NOARGS,
4327 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4328
4329 {"dst", (PyCFunction)timetz_dst, METH_NOARGS,
4330 PyDoc_STR("Return self.tzinfo.dst(self).")},
4331
Tim Peters12bf3392002-12-24 05:41:27 +00004332 {"replace", (PyCFunction)timetz_replace, METH_KEYWORDS,
4333 PyDoc_STR("Return timetz with new specified fields.")},
4334
Tim Peters2a799bf2002-12-16 20:18:38 +00004335 {"__setstate__", (PyCFunction)timetz_setstate, METH_O,
4336 PyDoc_STR("__setstate__(state)")},
4337
4338 {"__getstate__", (PyCFunction)timetz_getstate, METH_NOARGS,
4339 PyDoc_STR("__getstate__() -> state")},
4340 {NULL, NULL}
4341
4342};
4343
4344static char timetz_doc[] =
4345PyDoc_STR("Time type.");
4346
4347static PyNumberMethods timetz_as_number = {
4348 0, /* nb_add */
4349 0, /* nb_subtract */
4350 0, /* nb_multiply */
4351 0, /* nb_divide */
4352 0, /* nb_remainder */
4353 0, /* nb_divmod */
4354 0, /* nb_power */
4355 0, /* nb_negative */
4356 0, /* nb_positive */
4357 0, /* nb_absolute */
4358 (inquiry)timetz_nonzero, /* nb_nonzero */
4359};
4360
4361statichere PyTypeObject PyDateTime_TimeTZType = {
4362 PyObject_HEAD_INIT(NULL)
4363 0, /* ob_size */
4364 "datetime.timetz", /* tp_name */
4365 sizeof(PyDateTime_TimeTZ), /* tp_basicsize */
4366 0, /* tp_itemsize */
4367 (destructor)timetz_dealloc, /* tp_dealloc */
4368 0, /* tp_print */
4369 0, /* tp_getattr */
4370 0, /* tp_setattr */
4371 0, /* tp_compare */
4372 (reprfunc)timetz_repr, /* tp_repr */
4373 &timetz_as_number, /* tp_as_number */
4374 0, /* tp_as_sequence */
4375 0, /* tp_as_mapping */
4376 0, /* tp_hash */
4377 0, /* tp_call */
4378 0, /* tp_str */
4379 PyObject_GenericGetAttr, /* tp_getattro */
4380 0, /* tp_setattro */
4381 0, /* tp_as_buffer */
4382 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4383 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumbd43e912002-12-16 20:34:55 +00004384 timetz_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004385 0, /* tp_traverse */
4386 0, /* tp_clear */
4387 0, /* tp_richcompare */
4388 0, /* tp_weaklistoffset */
4389 0, /* tp_iter */
4390 0, /* tp_iternext */
4391 timetz_methods, /* tp_methods */
4392 0, /* tp_members */
4393 timetz_getset, /* tp_getset */
4394 &PyDateTime_TimeType, /* tp_base */
4395 0, /* tp_dict */
4396 0, /* tp_descr_get */
4397 0, /* tp_descr_set */
4398 0, /* tp_dictoffset */
4399 0, /* tp_init */
4400 0, /* tp_alloc */
4401 timetz_new, /* tp_new */
4402 _PyObject_Del, /* tp_free */
4403};
4404
4405/*
4406 * PyDateTime_DateTimeTZ implementation.
4407 */
4408
4409/* Accessor properties. Properties for day, month, year, hour, minute,
4410 * second and microsecond are inherited from datetime.
4411 */
4412
4413static PyObject *
4414datetimetz_tzinfo(PyDateTime_DateTimeTZ *self, void *unused)
4415{
4416 Py_INCREF(self->tzinfo);
4417 return self->tzinfo;
4418}
4419
4420static PyGetSetDef datetimetz_getset[] = {
4421 {"tzinfo", (getter)datetimetz_tzinfo},
4422 {NULL}
4423};
4424
4425/*
4426 * Constructors.
4427 * These are like the datetime methods of the same names, but allow an
4428 * optional tzinfo argument.
4429 */
4430
Tim Peters12bf3392002-12-24 05:41:27 +00004431static char *datetimetz_kws[] = {
4432 "year", "month", "day", "hour", "minute", "second",
4433 "microsecond", "tzinfo", NULL
4434};
4435
Tim Peters2a799bf2002-12-16 20:18:38 +00004436static PyObject *
4437datetimetz_new(PyTypeObject *type, PyObject *args, PyObject *kw)
4438{
4439 PyObject *self = NULL;
4440 int year;
4441 int month;
4442 int day;
4443 int hour = 0;
4444 int minute = 0;
4445 int second = 0;
4446 int usecond = 0;
4447 PyObject *tzinfo = Py_None;
4448
Tim Peters12bf3392002-12-24 05:41:27 +00004449 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetimetz_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00004450 &year, &month, &day, &hour, &minute,
4451 &second, &usecond, &tzinfo)) {
4452 if (check_date_args(year, month, day) < 0)
4453 return NULL;
4454 if (check_time_args(hour, minute, second, usecond) < 0)
4455 return NULL;
4456 if (check_tzinfo_subclass(tzinfo) < 0)
4457 return NULL;
4458 self = new_datetimetz(year, month, day,
4459 hour, minute, second, usecond,
4460 tzinfo);
4461 }
4462 return self;
4463}
4464
4465/* Return best possible local time -- this isn't constrained by the
4466 * precision of a timestamp.
4467 */
4468static PyObject *
4469datetimetz_now(PyObject *cls, PyObject *args, PyObject *kw)
4470{
4471 PyObject *self = NULL;
4472 PyObject *tzinfo = Py_None;
4473 static char *keywords[] = {"tzinfo", NULL};
4474
4475 if (PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
4476 &tzinfo)) {
4477 if (check_tzinfo_subclass(tzinfo) < 0)
4478 return NULL;
4479 self = datetime_best_possible(cls, localtime);
4480 if (self != NULL)
4481 replace_tzinfo(self, tzinfo);
4482 }
4483 return self;
4484}
4485
4486/* Return new local datetime from timestamp (Python timestamp -- a double). */
4487static PyObject *
4488datetimetz_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
4489{
4490 PyObject *self = NULL;
4491 double timestamp;
4492 PyObject *tzinfo = Py_None;
4493 static char *keywords[] = {"timestamp", "tzinfo", NULL};
4494
4495 if (PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
4496 keywords, &timestamp, &tzinfo)) {
4497 if (check_tzinfo_subclass(tzinfo) < 0)
4498 return NULL;
4499 self = datetime_from_timestamp(cls, localtime, timestamp);
4500 if (self != NULL)
4501 replace_tzinfo(self, tzinfo);
4502 }
4503 return self;
4504}
4505
4506/* Note: utcnow() is inherited, and doesn't accept tzinfo.
4507 * Ditto utcfromtimestamp(). Ditto combine().
4508 */
4509
4510
4511/*
4512 * Destructor.
4513 */
4514
4515static void
4516datetimetz_dealloc(PyDateTime_DateTimeTZ *self)
4517{
4518 Py_XDECREF(self->tzinfo);
4519 self->ob_type->tp_free((PyObject *)self);
4520}
4521
4522/*
4523 * Indirect access to tzinfo methods.
4524 */
4525
Tim Peters2a799bf2002-12-16 20:18:38 +00004526/* These are all METH_NOARGS, so don't need to check the arglist. */
4527static PyObject *
4528datetimetz_utcoffset(PyDateTime_DateTimeTZ *self, PyObject *unused) {
Tim Peters855fe882002-12-22 03:43:39 +00004529 return offset_as_timedelta((PyObject *)self, self->tzinfo,
4530 "utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00004531}
4532
4533static PyObject *
4534datetimetz_dst(PyDateTime_DateTimeTZ *self, PyObject *unused) {
Tim Peters855fe882002-12-22 03:43:39 +00004535 return offset_as_timedelta((PyObject *)self, self->tzinfo, "dst");
4536}
4537
4538static PyObject *
4539datetimetz_tzname(PyDateTime_DateTimeTZ *self, PyObject *unused) {
4540 return call_tzname((PyObject *)self, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004541}
4542
4543/*
4544 * datetimetz arithmetic.
4545 */
4546
4547/* If base is Py_NotImplemented or NULL, just return it.
4548 * Else base is a datetime, exactly one of {left, right} is a datetimetz,
4549 * and we want to create a datetimetz with the same date and time fields
4550 * as base, and with the tzinfo field from left or right. Do that,
4551 * return it, and decref base. This is used to transform the result of
4552 * a binary datetime operation (base) into a datetimetz result.
4553 */
4554static PyObject *
4555attach_tzinfo(PyObject *base, PyObject *left, PyObject *right)
4556{
4557 PyDateTime_DateTimeTZ *self;
4558 PyDateTime_DateTimeTZ *result;
4559
4560 if (base == NULL || base == Py_NotImplemented)
4561 return base;
4562
4563 assert(PyDateTime_CheckExact(base));
4564
4565 if (PyDateTimeTZ_Check(left)) {
4566 assert(! PyDateTimeTZ_Check(right));
4567 self = (PyDateTime_DateTimeTZ *)left;
4568 }
4569 else {
4570 assert(PyDateTimeTZ_Check(right));
4571 self = (PyDateTime_DateTimeTZ *)right;
4572 }
4573 result = PyObject_New(PyDateTime_DateTimeTZ,
4574 &PyDateTime_DateTimeTZType);
4575 if (result != NULL) {
4576 memcpy(result->data, ((PyDateTime_DateTime *)base)->data,
4577 _PyDateTime_DATETIME_DATASIZE);
4578 Py_INCREF(self->tzinfo);
4579 result->tzinfo = self->tzinfo;
4580 }
4581 Py_DECREF(base);
4582 return (PyObject *)result;
4583}
4584
4585static PyObject *
4586datetimetz_add(PyObject *left, PyObject *right)
4587{
4588 return attach_tzinfo(datetime_add(left, right), left, right);
4589}
4590
4591static PyObject *
4592datetimetz_subtract(PyObject *left, PyObject *right)
4593{
4594 PyObject *result = Py_NotImplemented;
4595
4596 if (PyDateTime_Check(left)) {
4597 /* datetime - ??? */
4598 if (PyDateTime_Check(right)) {
4599 /* datetime - datetime */
4600 naivety n1, n2;
4601 int offset1, offset2;
4602 PyDateTime_Delta *delta;
4603
Tim Peters14b69412002-12-22 18:10:22 +00004604 n1 = classify_utcoffset(left, &offset1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004605 assert(n1 != OFFSET_UNKNOWN);
4606 if (n1 == OFFSET_ERROR)
4607 return NULL;
4608
Tim Peters14b69412002-12-22 18:10:22 +00004609 n2 = classify_utcoffset(right, &offset2);
Tim Peters2a799bf2002-12-16 20:18:38 +00004610 assert(n2 != OFFSET_UNKNOWN);
4611 if (n2 == OFFSET_ERROR)
4612 return NULL;
4613
4614 if (n1 != n2) {
4615 PyErr_SetString(PyExc_TypeError,
4616 "can't subtract offset-naive and "
4617 "offset-aware datetimes");
4618 return NULL;
4619 }
4620 delta = (PyDateTime_Delta *)sub_datetime_datetime(
4621 (PyDateTime_DateTime *)left,
4622 (PyDateTime_DateTime *)right);
4623 if (delta == NULL || offset1 == offset2)
4624 return (PyObject *)delta;
4625 /* (left - offset1) - (right - offset2) =
4626 * (left - right) + (offset2 - offset1)
4627 */
4628 result = new_delta(delta->days,
4629 delta->seconds +
4630 (offset2 - offset1) * 60,
4631 delta->microseconds,
4632 1);
4633 Py_DECREF(delta);
4634 }
4635 else if (PyDelta_Check(right)) {
4636 /* datetimetz - delta */
4637 result = sub_datetime_timedelta(
4638 (PyDateTime_DateTime *)left,
4639 (PyDateTime_Delta *)right);
4640 result = attach_tzinfo(result, left, right);
4641 }
4642 }
4643
4644 if (result == Py_NotImplemented)
4645 Py_INCREF(result);
4646 return result;
4647}
4648
4649/* Various ways to turn a datetime into a string. */
4650
4651static PyObject *
4652datetimetz_repr(PyDateTime_DateTimeTZ *self)
4653{
4654 PyObject *baserepr = datetime_repr((PyDateTime_DateTime *)self);
4655
4656 if (baserepr == NULL)
4657 return NULL;
4658 return append_keyword_tzinfo(baserepr, self->tzinfo);
4659}
4660
4661/* Note: tp_str is inherited from datetime. */
4662
4663static PyObject *
4664datetimetz_isoformat(PyDateTime_DateTimeTZ *self,
4665 PyObject *args, PyObject *kw)
4666{
4667 char buf[100];
4668 PyObject *result = datetime_isoformat((PyDateTime_DateTime *)self,
4669 args, kw);
4670
4671 if (result == NULL || self->tzinfo == Py_None)
4672 return result;
4673
4674 /* We need to append the UTC offset. */
4675 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4676 (PyObject *)self) < 0) {
4677 Py_DECREF(result);
4678 return NULL;
4679 }
4680 PyString_ConcatAndDel(&result, PyString_FromString(buf));
4681 return result;
4682}
4683
4684/* Miscellaneous methods. */
4685
4686/* Note: tp_richcompare and tp_hash are inherited from datetime. */
4687
4688static PyObject *
Tim Peters12bf3392002-12-24 05:41:27 +00004689datetimetz_replace(PyDateTime_DateTimeTZ *self, PyObject *args, PyObject *kw)
4690{
4691 PyObject *clone;
4692 PyObject *tuple;
4693 int y = GET_YEAR(self);
4694 int m = GET_MONTH(self);
4695 int d = GET_DAY(self);
4696 int hh = DATE_GET_HOUR(self);
4697 int mm = DATE_GET_MINUTE(self);
4698 int ss = DATE_GET_SECOND(self);
4699 int us = DATE_GET_MICROSECOND(self);
4700 PyObject *tzinfo = self->tzinfo;
4701
4702 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4703 datetimetz_kws,
4704 &y, &m, &d, &hh, &mm, &ss, &us,
4705 &tzinfo))
4706 return NULL;
4707 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4708 if (tuple == NULL)
4709 return NULL;
4710 clone = datetimetz_new(self->ob_type, tuple, NULL);
4711 Py_DECREF(tuple);
4712 return clone;
4713}
4714
4715static PyObject *
Tim Peters80475bb2002-12-25 07:40:55 +00004716datetimetz_astimezone(PyDateTime_DateTimeTZ *self, PyObject *args,
4717 PyObject *kw)
4718{
4719 int y = GET_YEAR(self);
4720 int m = GET_MONTH(self);
4721 int d = GET_DAY(self);
4722 int hh = DATE_GET_HOUR(self);
4723 int mm = DATE_GET_MINUTE(self);
4724 int ss = DATE_GET_SECOND(self);
4725 int us = DATE_GET_MICROSECOND(self);
4726
4727 PyObject *tzinfo;
4728 static char *keywords[] = {"tz", NULL};
4729
4730 if (! PyArg_ParseTupleAndKeywords(args, kw, "O:astimezone", keywords,
4731 &tzinfo))
4732 return NULL;
4733 if (check_tzinfo_subclass(tzinfo) < 0)
4734 return NULL;
4735
4736 if (tzinfo != Py_None && self->tzinfo != Py_None) {
4737 int none;
4738 int selfoffset;
4739 selfoffset = call_utcoffset(self->tzinfo,
4740 (PyObject *)self,
4741 &none);
4742 if (selfoffset == -1 && PyErr_Occurred())
4743 return NULL;
4744 if (! none) {
4745 int tzoffset;
4746 tzoffset = call_utcoffset(tzinfo,
4747 (PyObject *)self,
4748 &none);
4749 if (tzoffset == -1 && PyErr_Occurred())
4750 return NULL;
4751 if (! none) {
4752 mm -= selfoffset - tzoffset;
4753 if (normalize_datetime(&y, &m, &d,
4754 &hh, &mm, &ss, &us) < 0)
4755 return NULL;
4756 }
4757 }
4758 }
4759 return new_datetimetz(y, m, d, hh, mm, ss, us, tzinfo);
4760}
4761
4762static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00004763datetimetz_timetuple(PyDateTime_DateTimeTZ *self)
4764{
4765 int dstflag = -1;
4766
4767 if (self->tzinfo != Py_None) {
4768 int none;
4769
4770 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4771 if (dstflag == -1 && PyErr_Occurred())
4772 return NULL;
4773
4774 if (none)
4775 dstflag = -1;
4776 else if (dstflag != 0)
4777 dstflag = 1;
4778
4779 }
4780 return build_struct_time(GET_YEAR(self),
4781 GET_MONTH(self),
4782 GET_DAY(self),
4783 DATE_GET_HOUR(self),
4784 DATE_GET_MINUTE(self),
4785 DATE_GET_SECOND(self),
4786 dstflag);
4787}
4788
4789static PyObject *
4790datetimetz_utctimetuple(PyDateTime_DateTimeTZ *self)
4791{
4792 int y = GET_YEAR(self);
4793 int m = GET_MONTH(self);
4794 int d = GET_DAY(self);
4795 int hh = DATE_GET_HOUR(self);
4796 int mm = DATE_GET_MINUTE(self);
4797 int ss = DATE_GET_SECOND(self);
4798 int us = 0; /* microseconds are ignored in a timetuple */
4799 int offset = 0;
4800
4801 if (self->tzinfo != Py_None) {
4802 int none;
4803
4804 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4805 if (offset == -1 && PyErr_Occurred())
4806 return NULL;
4807 }
4808 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4809 * 0 in a UTC timetuple regardless of what dst() says.
4810 */
4811 if (offset) {
4812 /* Subtract offset minutes & normalize. */
4813 int stat;
4814
4815 mm -= offset;
4816 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4817 if (stat < 0) {
4818 /* At the edges, it's possible we overflowed
4819 * beyond MINYEAR or MAXYEAR.
4820 */
4821 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4822 PyErr_Clear();
4823 else
4824 return NULL;
4825 }
4826 }
4827 return build_struct_time(y, m, d, hh, mm, ss, 0);
4828}
4829
4830static PyObject *
4831datetimetz_gettimetz(PyDateTime_DateTimeTZ *self)
4832{
4833 return new_timetz(DATE_GET_HOUR(self),
4834 DATE_GET_MINUTE(self),
4835 DATE_GET_SECOND(self),
4836 DATE_GET_MICROSECOND(self),
4837 self->tzinfo);
4838}
4839
4840/*
4841 * Pickle support. Quite a maze!
4842 */
4843
4844/* Let basestate be the state string returned by datetime_getstate.
4845 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4846 * So it's a tuple in any (non-error) case.
4847 */
4848static PyObject *
4849datetimetz_getstate(PyDateTime_DateTimeTZ *self)
4850{
4851 PyObject *basestate;
4852 PyObject *result = NULL;
4853
4854 basestate = datetime_getstate((PyDateTime_DateTime *)self);
4855 if (basestate != NULL) {
4856 if (self->tzinfo == Py_None)
4857 result = Py_BuildValue("(O)", basestate);
4858 else
4859 result = Py_BuildValue("OO", basestate, self->tzinfo);
4860 Py_DECREF(basestate);
4861 }
4862 return result;
4863}
4864
4865static PyObject *
4866datetimetz_setstate(PyDateTime_DateTimeTZ *self, PyObject *state)
4867{
4868 PyObject *temp;
4869 PyObject *basestate;
4870 PyObject *tzinfo = Py_None;
4871
4872 if (! PyArg_ParseTuple(state, "O!|O:__setstate__",
4873 &PyString_Type, &basestate,
4874 &tzinfo))
4875 return NULL;
4876 temp = datetime_setstate((PyDateTime_DateTime *)self, basestate);
4877 if (temp == NULL)
4878 return NULL;
4879 Py_DECREF(temp);
4880
4881 Py_INCREF(tzinfo);
4882 Py_XDECREF(self->tzinfo);
4883 self->tzinfo = tzinfo;
4884
4885 Py_INCREF(Py_None);
4886 return Py_None;
4887}
4888
4889static PyObject *
4890datetimetz_pickler(PyObject *module, PyDateTime_DateTimeTZ *datetimetz)
4891{
4892 PyObject *state;
4893 PyObject *result = NULL;
4894
4895 if (! PyDateTimeTZ_CheckExact(datetimetz)) {
4896 PyErr_Format(PyExc_TypeError,
4897 "bad type passed to datetimetz pickler: %s",
4898 datetimetz->ob_type->tp_name);
4899 return NULL;
4900 }
4901 state = datetimetz_getstate(datetimetz);
4902 if (state) {
4903 result = Py_BuildValue("O(O)",
4904 datetimetz_unpickler_object,
4905 state);
4906 Py_DECREF(state);
4907 }
4908 return result;
4909}
4910
4911static PyObject *
4912datetimetz_unpickler(PyObject *module, PyObject *arg)
4913{
4914 PyDateTime_DateTimeTZ *self;
4915
4916 self = PyObject_New(PyDateTime_DateTimeTZ, &PyDateTime_DateTimeTZType);
4917 if (self != NULL) {
4918 PyObject *res;
4919
4920 self->tzinfo = NULL;
4921 res = datetimetz_setstate(self, arg);
4922 if (res == NULL) {
4923 Py_DECREF(self);
4924 return NULL;
4925 }
4926 Py_DECREF(res);
4927 }
4928 return (PyObject *)self;
4929}
4930
4931
4932static PyMethodDef datetimetz_methods[] = {
4933 /* Class methods: */
4934 /* Inherited: combine(), utcnow(), utcfromtimestamp() */
4935
4936 {"now", (PyCFunction)datetimetz_now,
4937 METH_KEYWORDS | METH_CLASS,
4938 PyDoc_STR("[tzinfo] -> new datetimetz with local day and time.")},
4939
4940 {"fromtimestamp", (PyCFunction)datetimetz_fromtimestamp,
4941 METH_KEYWORDS | METH_CLASS,
4942 PyDoc_STR("timestamp[, tzinfo] -> local time from POSIX timestamp.")},
4943
4944 /* Instance methods: */
4945 /* Inherited: date(), time(), ctime(). */
4946 {"timetuple", (PyCFunction)datetimetz_timetuple, METH_NOARGS,
4947 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4948
4949 {"utctimetuple", (PyCFunction)datetimetz_utctimetuple, METH_NOARGS,
4950 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4951
4952 {"timetz", (PyCFunction)datetimetz_gettimetz, METH_NOARGS,
4953 PyDoc_STR("Return timetz object with same hour, minute, second, "
4954 "microsecond, and tzinfo.")},
4955
4956 {"isoformat", (PyCFunction)datetimetz_isoformat, METH_KEYWORDS,
4957 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4958 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4959 "sep is used to separate the year from the time, and "
4960 "defaults to 'T'.")},
4961
4962 {"utcoffset", (PyCFunction)datetimetz_utcoffset, METH_NOARGS,
4963 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4964
4965 {"tzname", (PyCFunction)datetimetz_tzname, METH_NOARGS,
4966 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4967
4968 {"dst", (PyCFunction)datetimetz_dst, METH_NOARGS,
4969 PyDoc_STR("Return self.tzinfo.dst(self).")},
4970
Tim Peters12bf3392002-12-24 05:41:27 +00004971 {"replace", (PyCFunction)datetimetz_replace, METH_KEYWORDS,
4972 PyDoc_STR("Return datetimetz with new specified fields.")},
4973
Tim Peters80475bb2002-12-25 07:40:55 +00004974 {"astimezone", (PyCFunction)datetimetz_astimezone, METH_KEYWORDS,
4975 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4976
Tim Peters2a799bf2002-12-16 20:18:38 +00004977 {"__setstate__", (PyCFunction)datetimetz_setstate, METH_O,
4978 PyDoc_STR("__setstate__(state)")},
4979
4980 {"__getstate__", (PyCFunction)datetimetz_getstate, METH_NOARGS,
4981 PyDoc_STR("__getstate__() -> state")},
4982 {NULL, NULL}
4983};
4984
4985static char datetimetz_doc[] =
4986PyDoc_STR("date/time type.");
4987
4988static PyNumberMethods datetimetz_as_number = {
4989 datetimetz_add, /* nb_add */
4990 datetimetz_subtract, /* nb_subtract */
4991 0, /* nb_multiply */
4992 0, /* nb_divide */
4993 0, /* nb_remainder */
4994 0, /* nb_divmod */
4995 0, /* nb_power */
4996 0, /* nb_negative */
4997 0, /* nb_positive */
4998 0, /* nb_absolute */
4999 0, /* nb_nonzero */
5000};
5001
5002statichere PyTypeObject PyDateTime_DateTimeTZType = {
5003 PyObject_HEAD_INIT(NULL)
5004 0, /* ob_size */
5005 "datetime.datetimetz", /* tp_name */
5006 sizeof(PyDateTime_DateTimeTZ), /* tp_basicsize */
5007 0, /* tp_itemsize */
5008 (destructor)datetimetz_dealloc, /* tp_dealloc */
5009 0, /* tp_print */
5010 0, /* tp_getattr */
5011 0, /* tp_setattr */
5012 0, /* tp_compare */
5013 (reprfunc)datetimetz_repr, /* tp_repr */
5014 &datetimetz_as_number, /* tp_as_number */
5015 0, /* tp_as_sequence */
5016 0, /* tp_as_mapping */
5017 0, /* tp_hash */
5018 0, /* tp_call */
5019 0, /* tp_str */
5020 PyObject_GenericGetAttr, /* tp_getattro */
5021 0, /* tp_setattro */
5022 0, /* tp_as_buffer */
5023 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
5024 Py_TPFLAGS_BASETYPE, /* tp_flags */
5025 datetimetz_doc, /* tp_doc */
5026 0, /* tp_traverse */
5027 0, /* tp_clear */
5028 0, /* tp_richcompare */
5029 0, /* tp_weaklistoffset */
5030 0, /* tp_iter */
5031 0, /* tp_iternext */
5032 datetimetz_methods, /* tp_methods */
5033 0, /* tp_members */
5034 datetimetz_getset, /* tp_getset */
5035 &PyDateTime_DateTimeType, /* tp_base */
5036 0, /* tp_dict */
5037 0, /* tp_descr_get */
5038 0, /* tp_descr_set */
5039 0, /* tp_dictoffset */
5040 0, /* tp_init */
5041 0, /* tp_alloc */
5042 datetimetz_new, /* tp_new */
5043 _PyObject_Del, /* tp_free */
5044};
5045
5046/* ---------------------------------------------------------------------------
5047 * Module methods and initialization.
5048 */
5049
5050static PyMethodDef module_methods[] = {
5051 /* Private functions for pickling support, registered with the
5052 * copy_reg module by the module init function.
5053 */
5054 {"_date_pickler", (PyCFunction)date_pickler, METH_O, NULL},
5055 {"_date_unpickler", (PyCFunction)date_unpickler, METH_O, NULL},
5056 {"_datetime_pickler", (PyCFunction)datetime_pickler, METH_O, NULL},
5057 {"_datetime_unpickler", (PyCFunction)datetime_unpickler,METH_O, NULL},
5058 {"_datetimetz_pickler", (PyCFunction)datetimetz_pickler,METH_O, NULL},
5059 {"_datetimetz_unpickler",(PyCFunction)datetimetz_unpickler,METH_O, NULL},
5060 {"_time_pickler", (PyCFunction)time_pickler, METH_O, NULL},
5061 {"_time_unpickler", (PyCFunction)time_unpickler, METH_O, NULL},
5062 {"_timetz_pickler", (PyCFunction)timetz_pickler, METH_O, NULL},
5063 {"_timetz_unpickler", (PyCFunction)timetz_unpickler, METH_O, NULL},
5064 {"_tzinfo_pickler", (PyCFunction)tzinfo_pickler, METH_O, NULL},
5065 {"_tzinfo_unpickler", (PyCFunction)tzinfo_unpickler, METH_NOARGS,
5066 NULL},
5067 {NULL, NULL}
5068};
5069
5070PyMODINIT_FUNC
5071initdatetime(void)
5072{
5073 PyObject *m; /* a module object */
5074 PyObject *d; /* its dict */
5075 PyObject *x;
5076
5077 /* Types that use __reduce__ for pickling need to set the following
5078 * magical attr in the type dict, with a true value.
5079 */
5080 PyObject *safepickle = PyString_FromString("__safe_for_unpickling__");
5081 if (safepickle == NULL)
5082 return;
5083
5084 m = Py_InitModule3("datetime", module_methods,
5085 "Fast implementation of the datetime type.");
5086
5087 if (PyType_Ready(&PyDateTime_DateType) < 0)
5088 return;
5089 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
5090 return;
5091 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
5092 return;
5093 if (PyType_Ready(&PyDateTime_TimeType) < 0)
5094 return;
5095 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
5096 return;
5097 if (PyType_Ready(&PyDateTime_TimeTZType) < 0)
5098 return;
5099 if (PyType_Ready(&PyDateTime_DateTimeTZType) < 0)
5100 return;
5101
5102 /* Pickling support, via registering functions with copy_reg. */
5103 {
5104 PyObject *pickler;
5105 PyObject *copyreg = PyImport_ImportModule("copy_reg");
5106
5107 if (copyreg == NULL) return;
5108
5109 pickler = PyObject_GetAttrString(m, "_date_pickler");
5110 if (pickler == NULL) return;
5111 date_unpickler_object = PyObject_GetAttrString(m,
5112 "_date_unpickler");
5113 if (date_unpickler_object == NULL) return;
5114 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
5115 &PyDateTime_DateType,
5116 pickler,
5117 date_unpickler_object);
5118 if (x == NULL) return;
5119 Py_DECREF(x);
5120 Py_DECREF(pickler);
5121
5122 pickler = PyObject_GetAttrString(m, "_datetime_pickler");
5123 if (pickler == NULL) return;
5124 datetime_unpickler_object = PyObject_GetAttrString(m,
5125 "_datetime_unpickler");
5126 if (datetime_unpickler_object == NULL) return;
5127 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
5128 &PyDateTime_DateTimeType,
5129 pickler,
5130 datetime_unpickler_object);
5131 if (x == NULL) return;
5132 Py_DECREF(x);
5133 Py_DECREF(pickler);
5134
5135 pickler = PyObject_GetAttrString(m, "_time_pickler");
5136 if (pickler == NULL) return;
5137 time_unpickler_object = PyObject_GetAttrString(m,
5138 "_time_unpickler");
5139 if (time_unpickler_object == NULL) return;
5140 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
5141 &PyDateTime_TimeType,
5142 pickler,
5143 time_unpickler_object);
5144 if (x == NULL) return;
5145 Py_DECREF(x);
5146 Py_DECREF(pickler);
5147
5148 pickler = PyObject_GetAttrString(m, "_timetz_pickler");
5149 if (pickler == NULL) return;
5150 timetz_unpickler_object = PyObject_GetAttrString(m,
5151 "_timetz_unpickler");
5152 if (timetz_unpickler_object == NULL) return;
5153 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
5154 &PyDateTime_TimeTZType,
5155 pickler,
5156 timetz_unpickler_object);
5157 if (x == NULL) return;
5158 Py_DECREF(x);
5159 Py_DECREF(pickler);
5160
5161 pickler = PyObject_GetAttrString(m, "_tzinfo_pickler");
5162 if (pickler == NULL) return;
5163 tzinfo_unpickler_object = PyObject_GetAttrString(m,
5164 "_tzinfo_unpickler");
5165 if (tzinfo_unpickler_object == NULL) return;
5166 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
5167 &PyDateTime_TZInfoType,
5168 pickler,
5169 tzinfo_unpickler_object);
5170 if (x== NULL) return;
5171 Py_DECREF(x);
5172 Py_DECREF(pickler);
5173
5174 pickler = PyObject_GetAttrString(m, "_datetimetz_pickler");
5175 if (pickler == NULL) return;
5176 datetimetz_unpickler_object = PyObject_GetAttrString(m,
5177 "_datetimetz_unpickler");
5178 if (datetimetz_unpickler_object == NULL) return;
5179 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
5180 &PyDateTime_DateTimeTZType,
5181 pickler,
5182 datetimetz_unpickler_object);
5183 if (x== NULL) return;
5184 Py_DECREF(x);
5185 Py_DECREF(pickler);
5186
5187 Py_DECREF(copyreg);
5188 }
5189
5190 /* timedelta values */
5191 d = PyDateTime_DeltaType.tp_dict;
5192
5193 if (PyDict_SetItem(d, safepickle, Py_True) < 0)
5194 return;
5195
5196 x = new_delta(0, 0, 1, 0);
5197 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5198 return;
5199 Py_DECREF(x);
5200
5201 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5202 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5203 return;
5204 Py_DECREF(x);
5205
5206 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5207 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5208 return;
5209 Py_DECREF(x);
5210
5211 /* date values */
5212 d = PyDateTime_DateType.tp_dict;
5213
5214 x = new_date(1, 1, 1);
5215 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5216 return;
5217 Py_DECREF(x);
5218
5219 x = new_date(MAXYEAR, 12, 31);
5220 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5221 return;
5222 Py_DECREF(x);
5223
5224 x = new_delta(1, 0, 0, 0);
5225 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5226 return;
5227 Py_DECREF(x);
5228
5229 /* datetime values */
5230 d = PyDateTime_DateTimeType.tp_dict;
5231
5232 x = new_datetime(1, 1, 1, 0, 0, 0, 0);
5233 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5234 return;
5235 Py_DECREF(x);
5236
5237 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999);
5238 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5239 return;
5240 Py_DECREF(x);
5241
5242 x = new_delta(0, 0, 1, 0);
5243 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5244 return;
5245 Py_DECREF(x);
5246
5247 /* time values */
5248 d = PyDateTime_TimeType.tp_dict;
5249
5250 x = new_time(0, 0, 0, 0);
5251 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5252 return;
5253 Py_DECREF(x);
5254
5255 x = new_time(23, 59, 59, 999999);
5256 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5257 return;
5258 Py_DECREF(x);
5259
5260 x = new_delta(0, 0, 1, 0);
5261 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5262 return;
5263 Py_DECREF(x);
5264
5265 /* timetz values */
5266 d = PyDateTime_TimeTZType.tp_dict;
5267
5268 x = new_timetz(0, 0, 0, 0, Py_None);
5269 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5270 return;
5271 Py_DECREF(x);
5272
5273 x = new_timetz(23, 59, 59, 999999, Py_None);
5274 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5275 return;
5276 Py_DECREF(x);
5277
5278 x = new_delta(0, 0, 1, 0);
5279 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5280 return;
5281 Py_DECREF(x);
5282
5283 /* datetimetz values */
5284 d = PyDateTime_DateTimeTZType.tp_dict;
5285
5286 x = new_datetimetz(1, 1, 1, 0, 0, 0, 0, Py_None);
5287 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5288 return;
5289 Py_DECREF(x);
5290
5291 x = new_datetimetz(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5292 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5293 return;
5294 Py_DECREF(x);
5295
5296 x = new_delta(0, 0, 1, 0);
5297 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5298 return;
5299 Py_DECREF(x);
5300
5301 Py_DECREF(safepickle);
5302
5303 /* module initialization */
5304 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
5305 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
5306
5307 Py_INCREF(&PyDateTime_DateType);
5308 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
5309
5310 Py_INCREF(&PyDateTime_DateTimeType);
5311 PyModule_AddObject(m, "datetime",
5312 (PyObject *) &PyDateTime_DateTimeType);
5313
5314 Py_INCREF(&PyDateTime_DeltaType);
5315 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
5316
5317 Py_INCREF(&PyDateTime_TimeType);
5318 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
5319
5320 Py_INCREF(&PyDateTime_TZInfoType);
5321 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
5322
5323 Py_INCREF(&PyDateTime_TimeTZType);
5324 PyModule_AddObject(m, "timetz", (PyObject *) &PyDateTime_TimeTZType);
5325
5326 Py_INCREF(&PyDateTime_DateTimeTZType);
5327 PyModule_AddObject(m, "datetimetz",
5328 (PyObject *)&PyDateTime_DateTimeTZType);
5329
5330 /* A 4-year cycle has an extra leap day over what we'd get from
5331 * pasting together 4 single years.
5332 */
5333 assert(DI4Y == 4 * 365 + 1);
5334 assert(DI4Y == days_before_year(4+1));
5335
5336 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5337 * get from pasting together 4 100-year cycles.
5338 */
5339 assert(DI400Y == 4 * DI100Y + 1);
5340 assert(DI400Y == days_before_year(400+1));
5341
5342 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5343 * pasting together 25 4-year cycles.
5344 */
5345 assert(DI100Y == 25 * DI4Y - 1);
5346 assert(DI100Y == days_before_year(100+1));
5347
5348 us_per_us = PyInt_FromLong(1);
5349 us_per_ms = PyInt_FromLong(1000);
5350 us_per_second = PyInt_FromLong(1000000);
5351 us_per_minute = PyInt_FromLong(60000000);
5352 seconds_per_day = PyInt_FromLong(24 * 3600);
5353 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5354 us_per_minute == NULL || seconds_per_day == NULL)
5355 return;
5356
5357 /* The rest are too big for 32-bit ints, but even
5358 * us_per_week fits in 40 bits, so doubles should be exact.
5359 */
5360 us_per_hour = PyLong_FromDouble(3600000000.0);
5361 us_per_day = PyLong_FromDouble(86400000000.0);
5362 us_per_week = PyLong_FromDouble(604800000000.0);
5363 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5364 return;
5365}