blob: 58af972a65439593c6bc2129c0be0ffba6474d8c [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",
337 days);
338 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
552/* If self has a tzinfo member, return a BORROWED reference to it. Else
553 * return NULL, which is NOT AN ERROR. There are no error returns here,
554 * and the caller must not decref the result.
555 */
556static PyObject *
557get_tzinfo_member(PyObject *self)
558{
559 PyObject *tzinfo = NULL;
560
561 if (PyDateTimeTZ_Check(self))
562 tzinfo = ((PyDateTime_DateTimeTZ *)self)->tzinfo;
563 else if (PyTimeTZ_Check(self))
564 tzinfo = ((PyDateTime_TimeTZ *)self)->tzinfo;
565
566 return tzinfo;
567}
568
569/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
570 * raise TypeError and return -1.
571 */
572static int
573check_tzinfo_subclass(PyObject *p)
574{
575 if (p == Py_None || PyTZInfo_Check(p))
576 return 0;
577 PyErr_Format(PyExc_TypeError,
578 "tzinfo argument must be None or of a tzinfo subclass, "
579 "not type '%s'",
580 p->ob_type->tp_name);
581 return -1;
582}
583
584/* Internal helper.
585 * Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
586 * result. tzinfo must be an instance of the tzinfo class. If the method
587 * returns None, this returns 0 and sets *none to 1. If the method doesn't
588 * return a Python int or long, TypeError is raised and this returns -1.
589 * If it does return an int or long, but is outside the valid range for
590 * a UTC minute offset, ValueError is raised and this returns -1.
591 * Else *none is set to 0 and the integer method result is returned.
592 */
593static int
594call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
595 int *none)
596{
597 PyObject *u;
598 long result = -1; /* Py{Int,Long}_AsLong return long */
599
600 assert(tzinfo != NULL);
601 assert(PyTZInfo_Check(tzinfo));
602 assert(tzinfoarg != NULL);
603
604 *none = 0;
605 u = PyObject_CallMethod(tzinfo, name, "O", tzinfoarg);
606 if (u == NULL)
607 return -1;
608
609 if (u == Py_None) {
610 result = 0;
611 *none = 1;
612 goto Done;
613 }
614
615 if (PyInt_Check(u))
616 result = PyInt_AS_LONG(u);
617 else if (PyLong_Check(u))
618 result = PyLong_AsLong(u);
619 else {
620 PyErr_Format(PyExc_TypeError,
621 "tzinfo.%s() must return None or int or long",
622 name);
623 goto Done;
624 }
625
626Done:
627 Py_DECREF(u);
628 if (result < -1439 || result > 1439) {
629 PyErr_Format(PyExc_ValueError,
630 "tzinfo.%s() returned %ld; must be in "
631 "-1439 .. 1439",
632 name, result);
633 result = -1;
634 }
635 return (int)result;
636}
637
638/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
639 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
640 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
641 & doesn't return a Python int or long, TypeError is raised and this
642 * returns -1. If utcoffset() returns an int outside the legitimate range
643 * for a UTC offset, ValueError is raised and this returns -1. Else
644 * *none is set to 0 and the offset is returned.
645 */
646static int
647call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
648{
649 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
650}
651
652/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
653 * result. tzinfo must be an instance of the tzinfo class. If dst()
654 * returns None, call_dst returns 0 and sets *none to 1. If dst()
655 & doesn't return a Python int or long, TypeError is raised and this
656 * returns -1. If dst() returns an int outside the legitimate range
657 * for a UTC offset, ValueError is raised and this returns -1. Else
658 * *none is set to 0 and the offset is returned.
659 */
660static int
661call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
662{
663 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
664}
665
666/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
667 * an instance of the tzinfo class. If tzname() doesn't return None or
668 * a string, TypeError is raised and this returns NULL.
669 */
670static PyObject *
671call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
672{
673 PyObject *result;
674
675 assert(tzinfo != NULL);
676 assert(PyTZInfo_Check(tzinfo));
677 assert(tzinfoarg != NULL);
678
679 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
680 if (result != NULL && result != Py_None && !PyString_Check(result)) {
681 PyErr_Format(PyExc_TypeError, ".tzinfo.tzname() must "
682 "return None or a string, not '%s'",
683 result->ob_type->tp_name);
684 Py_DECREF(result);
685 result = NULL;
686 }
687 return result;
688}
689
690typedef enum {
691 /* an exception has been set; the caller should pass it on */
692 OFFSET_ERROR,
693
694 /* type isn't date, datetime, datetimetz subclass, time, or
695 * timetz subclass
696 */
697 OFFSET_UNKNOWN,
698
699 /* date,
700 * datetime,
701 * datetimetz with None tzinfo,
702 * datetimetz where utcoffset() return None
703 * time,
704 * timetz with None tzinfo,
705 * timetz where utcoffset() returns None
706 */
707 OFFSET_NAIVE,
708
709 /* timetz where utcoffset() doesn't return None,
710 * datetimetz where utcoffset() doesn't return None
711 */
712 OFFSET_AWARE,
713} naivety;
714
715/* Classify a datetime object as to whether it's naive or offset-aware. See
716 * the "naivety" typedef for details. If the type is aware, *offset is set
717 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
718 * If the type is offset-naive, *offset is set to 0.
719 */
720static naivety
721classify_object(PyObject *op, int *offset)
722{
723 int none;
724 PyObject *tzinfo;
725
726 *offset = 0;
727 if (PyDateTime_CheckExact(op) ||
728 PyTime_CheckExact(op) ||
729 PyDate_CheckExact(op))
730 return OFFSET_NAIVE;
731
732 tzinfo = get_tzinfo_member(op); /* NULL means none, not error */
733 if (tzinfo == Py_None)
734 return OFFSET_NAIVE;
735 if (tzinfo == NULL)
736 return OFFSET_UNKNOWN;
737
738 *offset = call_utcoffset(tzinfo, op, &none);
739 if (*offset == -1 && PyErr_Occurred())
740 return OFFSET_ERROR;
741 return none ? OFFSET_NAIVE : OFFSET_AWARE;
742}
743
744/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
745 * stuff
746 * ", tzinfo=" + repr(tzinfo)
747 * before the closing ")".
748 */
749static PyObject *
750append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
751{
752 PyObject *temp;
753
754 assert(PyString_Check(repr));
755 assert(tzinfo);
756 if (tzinfo == Py_None)
757 return repr;
758 /* Get rid of the trailing ')'. */
759 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
760 temp = PyString_FromStringAndSize(PyString_AsString(repr),
761 PyString_Size(repr) - 1);
762 Py_DECREF(repr);
763 if (temp == NULL)
764 return NULL;
765 repr = temp;
766
767 /* Append ", tzinfo=". */
768 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
769
770 /* Append repr(tzinfo). */
771 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
772
773 /* Add a closing paren. */
774 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
775 return repr;
776}
777
778/* ---------------------------------------------------------------------------
779 * String format helpers.
780 */
781
782static PyObject *
783format_ctime(PyDateTime_Date *date,
784 int hours, int minutes, int seconds)
785{
786 static char *DayNames[] = {
787 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
788 };
789 static char *MonthNames[] = {
790 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
791 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
792 };
793
794 char buffer[128];
795 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
796
797 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
798 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
799 GET_DAY(date), hours, minutes, seconds,
800 GET_YEAR(date));
801 return PyString_FromString(buffer);
802}
803
804/* Add an hours & minutes UTC offset string to buf. buf has no more than
805 * buflen bytes remaining. The UTC offset is gotten by calling
806 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
807 * *buf, and that's all. Else the returned value is checked for sanity (an
808 * integer in range), and if that's OK it's converted to an hours & minutes
809 * string of the form
810 * sign HH sep MM
811 * Returns 0 if everything is OK. If the return value from utcoffset() is
812 * bogus, an appropriate exception is set and -1 is returned.
813 */
814static int
815format_utcoffset(char *buf, int buflen, const char *sep,
816 PyObject *tzinfo, PyObject *tzinfoarg)
817{
818 int offset;
819 int hours;
820 int minutes;
821 char sign;
822 int none;
823
824 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
825 if (offset == -1 && PyErr_Occurred())
826 return -1;
827 if (none) {
828 *buf = '\0';
829 return 0;
830 }
831 sign = '+';
832 if (offset < 0) {
833 sign = '-';
834 offset = - offset;
835 }
836 hours = divmod(offset, 60, &minutes);
837 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
838 return 0;
839}
840
841/* I sure don't want to reproduce the strftime code from the time module,
842 * so this imports the module and calls it. All the hair is due to
843 * giving special meanings to the %z and %Z format codes via a preprocessing
844 * step on the format string.
845 */
846static PyObject *
847wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple)
848{
849 PyObject *result = NULL; /* guilty until proved innocent */
850
851 PyObject *zreplacement = NULL; /* py string, replacement for %z */
852 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
853
854 char *pin; /* pointer to next char in input format */
855 char ch; /* next char in input format */
856
857 PyObject *newfmt = NULL; /* py string, the output format */
858 char *pnew; /* pointer to available byte in output format */
859 char totalnew; /* number bytes total in output format buffer,
860 exclusive of trailing \0 */
861 char usednew; /* number bytes used so far in output format buffer */
862
863 char *ptoappend; /* pointer to string to append to output buffer */
864 int ntoappend; /* # of bytes to append to output buffer */
865
866 char buf[100]; /* scratch buffer */
867
868 assert(object && format && timetuple);
869 assert(PyString_Check(format));
870
871 /* Scan the input format, looking for %z and %Z escapes, building
872 * a new format.
873 */
874 totalnew = PyString_Size(format); /* realistic if no %z/%Z */
875 newfmt = PyString_FromStringAndSize(NULL, totalnew);
876 if (newfmt == NULL) goto Done;
877 pnew = PyString_AsString(newfmt);
878 usednew = 0;
879
880 pin = PyString_AsString(format);
881 while ((ch = *pin++) != '\0') {
882 if (ch != '%') {
883 buf[0] = ch;
884 ptoappend = buf;
885 ntoappend = 1;
886 }
887 else if ((ch = *pin++) == '\0') {
888 /* There's a lone trailing %; doesn't make sense. */
889 PyErr_SetString(PyExc_ValueError, "strftime format "
890 "ends with raw %");
891 goto Done;
892 }
893 /* A % has been seen and ch is the character after it. */
894 else if (ch == 'z') {
895 if (zreplacement == NULL) {
896 /* format utcoffset */
897 PyObject *tzinfo = get_tzinfo_member(object);
898 zreplacement = PyString_FromString("");
899 if (zreplacement == NULL) goto Done;
900 if (tzinfo != Py_None && tzinfo != NULL) {
901 if (format_utcoffset(buf,
902 (int)sizeof(buf),
903 "",
904 tzinfo,
905 object) < 0)
906 goto Done;
907 Py_DECREF(zreplacement);
908 zreplacement = PyString_FromString(buf);
909 if (zreplacement == NULL) goto Done;
910 }
911 }
912 assert(zreplacement != NULL);
913 ptoappend = PyString_AsString(zreplacement);
914 ntoappend = PyString_Size(zreplacement);
915 }
916 else if (ch == 'Z') {
917 /* format tzname */
918 if (Zreplacement == NULL) {
919 PyObject *tzinfo = get_tzinfo_member(object);
920 Zreplacement = PyString_FromString("");
921 if (Zreplacement == NULL) goto Done;
922 if (tzinfo != Py_None && tzinfo != NULL) {
923 PyObject *temp = call_tzname(tzinfo,
924 object);
925 if (temp == NULL) goto Done;
926 if (temp != Py_None) {
927 assert(PyString_Check(temp));
928 /* Since the tzname is getting
929 * stuffed into the format, we
930 * have to double any % signs
931 * so that strftime doesn't
932 * treat them as format codes.
933 */
934 Py_DECREF(Zreplacement);
935 Zreplacement = PyObject_CallMethod(
936 temp, "replace",
937 "ss", "%", "%%");
938 Py_DECREF(temp);
939 if (Zreplacement == NULL)
940 goto Done;
941 }
942 else
943 Py_DECREF(temp);
944 }
945 }
946 assert(Zreplacement != NULL);
947 ptoappend = PyString_AsString(Zreplacement);
948 ntoappend = PyString_Size(Zreplacement);
949 }
950 else {
951 buf[0] = '%';
952 buf[1] = ch;
953 ptoappend = buf;
954 ntoappend = 2;
955 }
956
957 /* Append the ntoappend chars starting at ptoappend to
958 * the new format.
959 */
960 assert(ntoappend >= 0);
961 if (ntoappend == 0)
962 continue;
963 while (usednew + ntoappend > totalnew) {
964 int bigger = totalnew << 1;
965 if ((bigger >> 1) != totalnew) { /* overflow */
966 PyErr_NoMemory();
967 goto Done;
968 }
969 if (_PyString_Resize(&newfmt, bigger) < 0)
970 goto Done;
971 totalnew = bigger;
972 pnew = PyString_AsString(newfmt) + usednew;
973 }
974 memcpy(pnew, ptoappend, ntoappend);
975 pnew += ntoappend;
976 usednew += ntoappend;
977 assert(usednew <= totalnew);
978 } /* end while() */
979
980 if (_PyString_Resize(&newfmt, usednew) < 0)
981 goto Done;
982 {
983 PyObject *time = PyImport_ImportModule("time");
984 if (time == NULL)
985 goto Done;
986 result = PyObject_CallMethod(time, "strftime", "OO",
987 newfmt, timetuple);
988 Py_DECREF(time);
989 }
990 Done:
991 Py_XDECREF(zreplacement);
992 Py_XDECREF(Zreplacement);
993 Py_XDECREF(newfmt);
994 return result;
995}
996
997static char *
998isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
999{
1000 int x;
1001 x = PyOS_snprintf(buffer, bufflen,
1002 "%04d-%02d-%02d",
1003 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1004 return buffer + x;
1005}
1006
1007static void
1008isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1009{
1010 int us = DATE_GET_MICROSECOND(dt);
1011
1012 PyOS_snprintf(buffer, bufflen,
1013 "%02d:%02d:%02d", /* 8 characters */
1014 DATE_GET_HOUR(dt),
1015 DATE_GET_MINUTE(dt),
1016 DATE_GET_SECOND(dt));
1017 if (us)
1018 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1019}
1020
1021/* ---------------------------------------------------------------------------
1022 * Wrap functions from the time module. These aren't directly available
1023 * from C. Perhaps they should be.
1024 */
1025
1026/* Call time.time() and return its result (a Python float). */
1027static PyObject *
1028time_time()
1029{
1030 PyObject *result = NULL;
1031 PyObject *time = PyImport_ImportModule("time");
1032
1033 if (time != NULL) {
1034 result = PyObject_CallMethod(time, "time", "()");
1035 Py_DECREF(time);
1036 }
1037 return result;
1038}
1039
1040/* Build a time.struct_time. The weekday and day number are automatically
1041 * computed from the y,m,d args.
1042 */
1043static PyObject *
1044build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1045{
1046 PyObject *time;
1047 PyObject *result = NULL;
1048
1049 time = PyImport_ImportModule("time");
1050 if (time != NULL) {
1051 result = PyObject_CallMethod(time, "struct_time",
1052 "((iiiiiiiii))",
1053 y, m, d,
1054 hh, mm, ss,
1055 weekday(y, m, d),
1056 days_before_month(y, m) + d,
1057 dstflag);
1058 Py_DECREF(time);
1059 }
1060 return result;
1061}
1062
1063/* ---------------------------------------------------------------------------
1064 * Miscellaneous helpers.
1065 */
1066
1067/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1068 * The comparisons here all most naturally compute a cmp()-like result.
1069 * This little helper turns that into a bool result for rich comparisons.
1070 */
1071static PyObject *
1072diff_to_bool(int diff, int op)
1073{
1074 PyObject *result;
1075 int istrue;
1076
1077 switch (op) {
1078 case Py_EQ: istrue = diff == 0; break;
1079 case Py_NE: istrue = diff != 0; break;
1080 case Py_LE: istrue = diff <= 0; break;
1081 case Py_GE: istrue = diff >= 0; break;
1082 case Py_LT: istrue = diff < 0; break;
1083 case Py_GT: istrue = diff > 0; break;
1084 default:
1085 assert(! "op unknown");
1086 istrue = 0; /* To shut up compiler */
1087 }
1088 result = istrue ? Py_True : Py_False;
1089 Py_INCREF(result);
1090 return result;
1091}
1092
1093/* ---------------------------------------------------------------------------
1094 * Helpers for setting object fields. These work on pointers to the
1095 * appropriate base class.
1096 */
1097
1098/* For date, datetime and datetimetz. */
1099static void
1100set_date_fields(PyDateTime_Date *self, int y, int m, int d)
1101{
1102 self->hashcode = -1;
1103 SET_YEAR(self, y);
1104 SET_MONTH(self, m);
1105 SET_DAY(self, d);
1106}
1107
1108/* For datetime and datetimetz. */
1109static void
1110set_datetime_time_fields(PyDateTime_Date *self, int h, int m, int s, int us)
1111{
1112 DATE_SET_HOUR(self, h);
1113 DATE_SET_MINUTE(self, m);
1114 DATE_SET_SECOND(self, s);
1115 DATE_SET_MICROSECOND(self, us);
1116}
1117
1118/* For time and timetz. */
1119static void
1120set_time_fields(PyDateTime_Time *self, int h, int m, int s, int us)
1121{
1122 self->hashcode = -1;
1123 TIME_SET_HOUR(self, h);
1124 TIME_SET_MINUTE(self, m);
1125 TIME_SET_SECOND(self, s);
1126 TIME_SET_MICROSECOND(self, us);
1127}
1128
1129/* ---------------------------------------------------------------------------
1130 * Create various objects, mostly without range checking.
1131 */
1132
1133/* Create a date instance with no range checking. */
1134static PyObject *
1135new_date(int year, int month, int day)
1136{
1137 PyDateTime_Date *self;
1138
1139 self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType);
1140 if (self != NULL)
1141 set_date_fields(self, year, month, day);
1142 return (PyObject *) self;
1143}
1144
1145/* Create a datetime instance with no range checking. */
1146static PyObject *
1147new_datetime(int year, int month, int day, int hour, int minute,
1148 int second, int usecond)
1149{
1150 PyDateTime_DateTime *self;
1151
1152 self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType);
1153 if (self != NULL) {
1154 set_date_fields((PyDateTime_Date *)self, year, month, day);
1155 set_datetime_time_fields((PyDateTime_Date *)self,
1156 hour, minute, second, usecond);
1157 }
1158 return (PyObject *) self;
1159}
1160
1161/* Create a datetimetz instance with no range checking. */
1162static PyObject *
1163new_datetimetz(int year, int month, int day, int hour, int minute,
1164 int second, int usecond, PyObject *tzinfo)
1165{
1166 PyDateTime_DateTimeTZ *self;
1167
1168 self = PyObject_New(PyDateTime_DateTimeTZ, &PyDateTime_DateTimeTZType);
1169 if (self != NULL) {
1170 set_date_fields((PyDateTime_Date *)self, year, month, day);
1171 set_datetime_time_fields((PyDateTime_Date *)self,
1172 hour, minute, second, usecond);
1173 Py_INCREF(tzinfo);
1174 self->tzinfo = tzinfo;
1175 }
1176 return (PyObject *) self;
1177}
1178
1179/* Create a time instance with no range checking. */
1180static PyObject *
1181new_time(int hour, int minute, int second, int usecond)
1182{
1183 PyDateTime_Time *self;
1184
1185 self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType);
1186 if (self != NULL)
1187 set_time_fields(self, hour, minute, second, usecond);
1188 return (PyObject *) self;
1189}
1190
1191/* Create a timetz instance with no range checking. */
1192static PyObject *
1193new_timetz(int hour, int minute, int second, int usecond, PyObject *tzinfo)
1194{
1195 PyDateTime_TimeTZ *self;
1196
1197 self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType);
1198 if (self != NULL) {
1199 set_time_fields((PyDateTime_Time *)self,
1200 hour, minute, second, usecond);
1201 Py_INCREF(tzinfo);
1202 self->tzinfo = tzinfo;
1203 }
1204 return (PyObject *) self;
1205}
1206
1207/* Create a timedelta instance. Normalize the members iff normalize is
1208 * true. Passing false is a speed optimization, if you know for sure
1209 * that seconds and microseconds are already in their proper ranges. In any
1210 * case, raises OverflowError and returns NULL if the normalized days is out
1211 * of range).
1212 */
1213static PyObject *
1214new_delta(int days, int seconds, int microseconds, int normalize)
1215{
1216 PyDateTime_Delta *self;
1217
1218 if (normalize)
1219 normalize_d_s_us(&days, &seconds, &microseconds);
1220 assert(0 <= seconds && seconds < 24*3600);
1221 assert(0 <= microseconds && microseconds < 1000000);
1222
1223 if (check_delta_day_range(days) < 0)
1224 return NULL;
1225
1226 self = PyObject_New(PyDateTime_Delta, &PyDateTime_DeltaType);
1227 if (self != NULL) {
1228 self->hashcode = -1;
1229 SET_TD_DAYS(self, days);
1230 SET_TD_SECONDS(self, seconds);
1231 SET_TD_MICROSECONDS(self, microseconds);
1232 }
1233 return (PyObject *) self;
1234}
1235
1236
1237/* ---------------------------------------------------------------------------
1238 * Cached Python objects; these are set by the module init function.
1239 */
1240
1241/* Conversion factors. */
1242static PyObject *us_per_us = NULL; /* 1 */
1243static PyObject *us_per_ms = NULL; /* 1000 */
1244static PyObject *us_per_second = NULL; /* 1000000 */
1245static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1246static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1247static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1248static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1249static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1250
1251/* Callables to support unpickling. */
1252static PyObject *date_unpickler_object = NULL;
1253static PyObject *datetime_unpickler_object = NULL;
1254static PyObject *datetimetz_unpickler_object = NULL;
1255static PyObject *tzinfo_unpickler_object = NULL;
1256static PyObject *time_unpickler_object = NULL;
1257static PyObject *timetz_unpickler_object = NULL;
1258
1259/* ---------------------------------------------------------------------------
1260 * Class implementations.
1261 */
1262
1263/*
1264 * PyDateTime_Delta implementation.
1265 */
1266
1267/* Convert a timedelta to a number of us,
1268 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1269 * as a Python int or long.
1270 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1271 * due to ubiquitous overflow possibilities.
1272 */
1273static PyObject *
1274delta_to_microseconds(PyDateTime_Delta *self)
1275{
1276 PyObject *x1 = NULL;
1277 PyObject *x2 = NULL;
1278 PyObject *x3 = NULL;
1279 PyObject *result = NULL;
1280
1281 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1282 if (x1 == NULL)
1283 goto Done;
1284 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1285 if (x2 == NULL)
1286 goto Done;
1287 Py_DECREF(x1);
1288 x1 = NULL;
1289
1290 /* x2 has days in seconds */
1291 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1292 if (x1 == NULL)
1293 goto Done;
1294 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1295 if (x3 == NULL)
1296 goto Done;
1297 Py_DECREF(x1);
1298 Py_DECREF(x2);
1299 x1 = x2 = NULL;
1300
1301 /* x3 has days+seconds in seconds */
1302 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1303 if (x1 == NULL)
1304 goto Done;
1305 Py_DECREF(x3);
1306 x3 = NULL;
1307
1308 /* x1 has days+seconds in us */
1309 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1310 if (x2 == NULL)
1311 goto Done;
1312 result = PyNumber_Add(x1, x2);
1313
1314Done:
1315 Py_XDECREF(x1);
1316 Py_XDECREF(x2);
1317 Py_XDECREF(x3);
1318 return result;
1319}
1320
1321/* Convert a number of us (as a Python int or long) to a timedelta.
1322 */
1323static PyObject *
1324microseconds_to_delta(PyObject *pyus)
1325{
1326 int us;
1327 int s;
1328 int d;
1329
1330 PyObject *tuple = NULL;
1331 PyObject *num = NULL;
1332 PyObject *result = NULL;
1333
1334 tuple = PyNumber_Divmod(pyus, us_per_second);
1335 if (tuple == NULL)
1336 goto Done;
1337
1338 num = PyTuple_GetItem(tuple, 1); /* us */
1339 if (num == NULL)
1340 goto Done;
1341 us = PyLong_AsLong(num);
1342 num = NULL;
1343 if (us < 0) {
1344 /* The divisor was positive, so this must be an error. */
1345 assert(PyErr_Occurred());
1346 goto Done;
1347 }
1348
1349 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1350 if (num == NULL)
1351 goto Done;
1352 Py_INCREF(num);
1353 Py_DECREF(tuple);
1354
1355 tuple = PyNumber_Divmod(num, seconds_per_day);
1356 if (tuple == NULL)
1357 goto Done;
1358 Py_DECREF(num);
1359
1360 num = PyTuple_GetItem(tuple, 1); /* seconds */
1361 if (num == NULL)
1362 goto Done;
1363 s = PyLong_AsLong(num);
1364 num = NULL;
1365 if (s < 0) {
1366 /* The divisor was positive, so this must be an error. */
1367 assert(PyErr_Occurred());
1368 goto Done;
1369 }
1370
1371 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1372 if (num == NULL)
1373 goto Done;
1374 Py_INCREF(num);
1375
1376 d = PyLong_AsLong(num);
1377 if (d == -1 && PyErr_Occurred())
1378 goto Done;
1379 result = new_delta(d, s, us, 0);
1380
1381Done:
1382 Py_XDECREF(tuple);
1383 Py_XDECREF(num);
1384 return result;
1385}
1386
1387static PyObject *
1388multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1389{
1390 PyObject *pyus_in;
1391 PyObject *pyus_out;
1392 PyObject *result;
1393
1394 pyus_in = delta_to_microseconds(delta);
1395 if (pyus_in == NULL)
1396 return NULL;
1397
1398 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1399 Py_DECREF(pyus_in);
1400 if (pyus_out == NULL)
1401 return NULL;
1402
1403 result = microseconds_to_delta(pyus_out);
1404 Py_DECREF(pyus_out);
1405 return result;
1406}
1407
1408static PyObject *
1409divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1410{
1411 PyObject *pyus_in;
1412 PyObject *pyus_out;
1413 PyObject *result;
1414
1415 pyus_in = delta_to_microseconds(delta);
1416 if (pyus_in == NULL)
1417 return NULL;
1418
1419 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1420 Py_DECREF(pyus_in);
1421 if (pyus_out == NULL)
1422 return NULL;
1423
1424 result = microseconds_to_delta(pyus_out);
1425 Py_DECREF(pyus_out);
1426 return result;
1427}
1428
1429static PyObject *
1430delta_add(PyObject *left, PyObject *right)
1431{
1432 PyObject *result = Py_NotImplemented;
1433
1434 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1435 /* delta + delta */
1436 /* The C-level additions can't overflow because of the
1437 * invariant bounds.
1438 */
1439 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1440 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1441 int microseconds = GET_TD_MICROSECONDS(left) +
1442 GET_TD_MICROSECONDS(right);
1443 result = new_delta(days, seconds, microseconds, 1);
1444 }
1445
1446 if (result == Py_NotImplemented)
1447 Py_INCREF(result);
1448 return result;
1449}
1450
1451static PyObject *
1452delta_negative(PyDateTime_Delta *self)
1453{
1454 return new_delta(-GET_TD_DAYS(self),
1455 -GET_TD_SECONDS(self),
1456 -GET_TD_MICROSECONDS(self),
1457 1);
1458}
1459
1460static PyObject *
1461delta_positive(PyDateTime_Delta *self)
1462{
1463 /* Could optimize this (by returning self) if this isn't a
1464 * subclass -- but who uses unary + ? Approximately nobody.
1465 */
1466 return new_delta(GET_TD_DAYS(self),
1467 GET_TD_SECONDS(self),
1468 GET_TD_MICROSECONDS(self),
1469 0);
1470}
1471
1472static PyObject *
1473delta_abs(PyDateTime_Delta *self)
1474{
1475 PyObject *result;
1476
1477 assert(GET_TD_MICROSECONDS(self) >= 0);
1478 assert(GET_TD_SECONDS(self) >= 0);
1479
1480 if (GET_TD_DAYS(self) < 0)
1481 result = delta_negative(self);
1482 else
1483 result = delta_positive(self);
1484
1485 return result;
1486}
1487
1488static PyObject *
1489delta_subtract(PyObject *left, PyObject *right)
1490{
1491 PyObject *result = Py_NotImplemented;
1492
1493 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1494 /* delta - delta */
1495 PyObject *minus_right = PyNumber_Negative(right);
1496 if (minus_right) {
1497 result = delta_add(left, minus_right);
1498 Py_DECREF(minus_right);
1499 }
1500 else
1501 result = NULL;
1502 }
1503
1504 if (result == Py_NotImplemented)
1505 Py_INCREF(result);
1506 return result;
1507}
1508
1509/* This is more natural as a tp_compare, but doesn't work then: for whatever
1510 * reason, Python's try_3way_compare ignores tp_compare unless
1511 * PyInstance_Check returns true, but these aren't old-style classes.
1512 */
1513static PyObject *
1514delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1515{
1516 int diff;
1517
1518 if (! PyDelta_CheckExact(other)) {
1519 PyErr_Format(PyExc_TypeError,
1520 "can't compare %s to %s instance",
1521 self->ob_type->tp_name, other->ob_type->tp_name);
1522 return NULL;
1523 }
1524 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1525 if (diff == 0) {
1526 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1527 if (diff == 0)
1528 diff = GET_TD_MICROSECONDS(self) -
1529 GET_TD_MICROSECONDS(other);
1530 }
1531 return diff_to_bool(diff, op);
1532}
1533
1534static PyObject *delta_getstate(PyDateTime_Delta *self);
1535
1536static long
1537delta_hash(PyDateTime_Delta *self)
1538{
1539 if (self->hashcode == -1) {
1540 PyObject *temp = delta_getstate(self);
1541 if (temp != NULL) {
1542 self->hashcode = PyObject_Hash(temp);
1543 Py_DECREF(temp);
1544 }
1545 }
1546 return self->hashcode;
1547}
1548
1549static PyObject *
1550delta_multiply(PyObject *left, PyObject *right)
1551{
1552 PyObject *result = Py_NotImplemented;
1553
1554 if (PyDelta_Check(left)) {
1555 /* delta * ??? */
1556 if (PyInt_Check(right) || PyLong_Check(right))
1557 result = multiply_int_timedelta(right,
1558 (PyDateTime_Delta *) left);
1559 }
1560 else if (PyInt_Check(left) || PyLong_Check(left))
1561 result = multiply_int_timedelta(left,
1562 (PyDateTime_Delta *) right);
1563
1564 if (result == Py_NotImplemented)
1565 Py_INCREF(result);
1566 return result;
1567}
1568
1569static PyObject *
1570delta_divide(PyObject *left, PyObject *right)
1571{
1572 PyObject *result = Py_NotImplemented;
1573
1574 if (PyDelta_Check(left)) {
1575 /* delta * ??? */
1576 if (PyInt_Check(right) || PyLong_Check(right))
1577 result = divide_timedelta_int(
1578 (PyDateTime_Delta *)left,
1579 right);
1580 }
1581
1582 if (result == Py_NotImplemented)
1583 Py_INCREF(result);
1584 return result;
1585}
1586
1587/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1588 * timedelta constructor. sofar is the # of microseconds accounted for
1589 * so far, and there are factor microseconds per current unit, the number
1590 * of which is given by num. num * factor is added to sofar in a
1591 * numerically careful way, and that's the result. Any fractional
1592 * microseconds left over (this can happen if num is a float type) are
1593 * added into *leftover.
1594 * Note that there are many ways this can give an error (NULL) return.
1595 */
1596static PyObject *
1597accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1598 double *leftover)
1599{
1600 PyObject *prod;
1601 PyObject *sum;
1602
1603 assert(num != NULL);
1604
1605 if (PyInt_Check(num) || PyLong_Check(num)) {
1606 prod = PyNumber_Multiply(num, factor);
1607 if (prod == NULL)
1608 return NULL;
1609 sum = PyNumber_Add(sofar, prod);
1610 Py_DECREF(prod);
1611 return sum;
1612 }
1613
1614 if (PyFloat_Check(num)) {
1615 double dnum;
1616 double fracpart;
1617 double intpart;
1618 PyObject *x;
1619 PyObject *y;
1620
1621 /* The Plan: decompose num into an integer part and a
1622 * fractional part, num = intpart + fracpart.
1623 * Then num * factor ==
1624 * intpart * factor + fracpart * factor
1625 * and the LHS can be computed exactly in long arithmetic.
1626 * The RHS is again broken into an int part and frac part.
1627 * and the frac part is added into *leftover.
1628 */
1629 dnum = PyFloat_AsDouble(num);
1630 if (dnum == -1.0 && PyErr_Occurred())
1631 return NULL;
1632 fracpart = modf(dnum, &intpart);
1633 x = PyLong_FromDouble(intpart);
1634 if (x == NULL)
1635 return NULL;
1636
1637 prod = PyNumber_Multiply(x, factor);
1638 Py_DECREF(x);
1639 if (prod == NULL)
1640 return NULL;
1641
1642 sum = PyNumber_Add(sofar, prod);
1643 Py_DECREF(prod);
1644 if (sum == NULL)
1645 return NULL;
1646
1647 if (fracpart == 0.0)
1648 return sum;
1649 /* So far we've lost no information. Dealing with the
1650 * fractional part requires float arithmetic, and may
1651 * lose a little info.
1652 */
1653 assert(PyInt_Check(factor) || PyLong_Check(factor));
1654 if (PyInt_Check(factor))
1655 dnum = (double)PyInt_AsLong(factor);
1656 else
1657 dnum = PyLong_AsDouble(factor);
1658
1659 dnum *= fracpart;
1660 fracpart = modf(dnum, &intpart);
1661 x = PyLong_FromDouble(intpart);
1662 if (x == NULL) {
1663 Py_DECREF(sum);
1664 return NULL;
1665 }
1666
1667 y = PyNumber_Add(sum, x);
1668 Py_DECREF(sum);
1669 Py_DECREF(x);
1670 *leftover += fracpart;
1671 return y;
1672 }
1673
1674 PyErr_Format(PyExc_TypeError,
1675 "unsupported type for timedelta %s component: %s",
1676 tag, num->ob_type->tp_name);
1677 return NULL;
1678}
1679
1680static PyObject *
1681delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1682{
1683 PyObject *self = NULL;
1684
1685 /* Argument objects. */
1686 PyObject *day = NULL;
1687 PyObject *second = NULL;
1688 PyObject *us = NULL;
1689 PyObject *ms = NULL;
1690 PyObject *minute = NULL;
1691 PyObject *hour = NULL;
1692 PyObject *week = NULL;
1693
1694 PyObject *x = NULL; /* running sum of microseconds */
1695 PyObject *y = NULL; /* temp sum of microseconds */
1696 double leftover_us = 0.0;
1697
1698 static char *keywords[] = {
1699 "days", "seconds", "microseconds", "milliseconds",
1700 "minutes", "hours", "weeks", NULL
1701 };
1702
1703 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1704 keywords,
1705 &day, &second, &us,
1706 &ms, &minute, &hour, &week) == 0)
1707 goto Done;
1708
1709 x = PyInt_FromLong(0);
1710 if (x == NULL)
1711 goto Done;
1712
1713#define CLEANUP \
1714 Py_DECREF(x); \
1715 x = y; \
1716 if (x == NULL) \
1717 goto Done
1718
1719 if (us) {
1720 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1721 CLEANUP;
1722 }
1723 if (ms) {
1724 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1725 CLEANUP;
1726 }
1727 if (second) {
1728 y = accum("seconds", x, second, us_per_second, &leftover_us);
1729 CLEANUP;
1730 }
1731 if (minute) {
1732 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1733 CLEANUP;
1734 }
1735 if (hour) {
1736 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1737 CLEANUP;
1738 }
1739 if (day) {
1740 y = accum("days", x, day, us_per_day, &leftover_us);
1741 CLEANUP;
1742 }
1743 if (week) {
1744 y = accum("weeks", x, week, us_per_week, &leftover_us);
1745 CLEANUP;
1746 }
1747 if (leftover_us) {
1748 /* Round to nearest whole # of us, and add into x. */
1749 PyObject *temp;
1750 if (leftover_us >= 0.0)
1751 leftover_us = floor(leftover_us + 0.5);
1752 else
1753 leftover_us = ceil(leftover_us - 0.5);
1754 temp = PyLong_FromDouble(leftover_us);
1755 if (temp == NULL) {
1756 Py_DECREF(x);
1757 goto Done;
1758 }
1759 y = PyNumber_Add(x, temp);
1760 Py_DECREF(temp);
1761 CLEANUP;
1762 }
1763
1764 self = microseconds_to_delta(x);
1765 Py_DECREF(x);
1766Done:
1767 return self;
1768
1769#undef CLEANUP
1770}
1771
1772static int
1773delta_nonzero(PyDateTime_Delta *self)
1774{
1775 return (GET_TD_DAYS(self) != 0
1776 || GET_TD_SECONDS(self) != 0
1777 || GET_TD_MICROSECONDS(self) != 0);
1778}
1779
1780static PyObject *
1781delta_repr(PyDateTime_Delta *self)
1782{
1783 if (GET_TD_MICROSECONDS(self) != 0)
1784 return PyString_FromFormat("%s(%d, %d, %d)",
1785 self->ob_type->tp_name,
1786 GET_TD_DAYS(self),
1787 GET_TD_SECONDS(self),
1788 GET_TD_MICROSECONDS(self));
1789 if (GET_TD_SECONDS(self) != 0)
1790 return PyString_FromFormat("%s(%d, %d)",
1791 self->ob_type->tp_name,
1792 GET_TD_DAYS(self),
1793 GET_TD_SECONDS(self));
1794
1795 return PyString_FromFormat("%s(%d)",
1796 self->ob_type->tp_name,
1797 GET_TD_DAYS(self));
1798}
1799
1800static PyObject *
1801delta_str(PyDateTime_Delta *self)
1802{
1803 int days = GET_TD_DAYS(self);
1804 int seconds = GET_TD_SECONDS(self);
1805 int us = GET_TD_MICROSECONDS(self);
1806 int hours;
1807 int minutes;
1808 char buf[500];
1809 int i = 0;
1810
1811 minutes = divmod(seconds, 60, &seconds);
1812 hours = divmod(minutes, 60, &minutes);
1813
1814 if (days) {
1815 i += sprintf(buf + i, "%d day%s, ", days,
1816 (days == 1 || days == -1) ? "" : "s");
1817 assert(i < sizeof(buf));
1818 }
1819
1820 i += sprintf(buf + i, "%d:%02d:%02d", hours, minutes, seconds);
1821 assert(i < sizeof(buf));
1822
1823 if (us) {
1824 i += sprintf(buf + i, ".%06d", us);
1825 assert(i < sizeof(buf));
1826 }
1827
1828 return PyString_FromStringAndSize(buf, i);
1829}
1830
1831/* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed
1832 * in the Python implementation, the C implementation also requires
1833 * __reduce__, and a __safe_for_unpickling__ attr in the type object.
1834 */
1835static PyObject *
1836delta_getstate(PyDateTime_Delta *self)
1837{
1838 return Py_BuildValue("iii", GET_TD_DAYS(self),
1839 GET_TD_SECONDS(self),
1840 GET_TD_MICROSECONDS(self));
1841}
1842
1843static PyObject *
1844delta_setstate(PyDateTime_Delta *self, PyObject *state)
1845{
1846 int day;
1847 int second;
1848 int us;
1849
1850 if (!PyArg_ParseTuple(state, "iii:__setstate__", &day, &second, &us))
1851 return NULL;
1852
1853 self->hashcode = -1;
1854 SET_TD_DAYS(self, day);
1855 SET_TD_SECONDS(self, second);
1856 SET_TD_MICROSECONDS(self, us);
1857
1858 Py_INCREF(Py_None);
1859 return Py_None;
1860}
1861
1862static PyObject *
1863delta_reduce(PyDateTime_Delta* self)
1864{
1865 PyObject* result = NULL;
1866 PyObject* state = delta_getstate(self);
1867
1868 if (state != NULL) {
1869 /* The funky "()" in the format string creates an empty
1870 * tuple as the 2nd component of the result 3-tuple.
1871 */
1872 result = Py_BuildValue("O()O", self->ob_type, state);
1873 Py_DECREF(state);
1874 }
1875 return result;
1876}
1877
1878#define OFFSET(field) offsetof(PyDateTime_Delta, field)
1879
1880static PyMemberDef delta_members[] = {
1881 {"days", T_LONG, OFFSET(days), READONLY,
1882 PyDoc_STR("Number of days.")},
1883
1884 {"seconds", T_LONG, OFFSET(seconds), READONLY,
1885 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
1886
1887 {"microseconds", T_LONG, OFFSET(microseconds), READONLY,
1888 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
1889 {NULL}
1890};
1891
1892static PyMethodDef delta_methods[] = {
1893 {"__setstate__", (PyCFunction)delta_setstate, METH_O,
1894 PyDoc_STR("__setstate__(state)")},
1895
1896 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
1897 PyDoc_STR("__setstate__(state)")},
1898
1899 {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS,
1900 PyDoc_STR("__getstate__() -> state")},
1901 {NULL, NULL},
1902};
1903
1904static char delta_doc[] =
1905PyDoc_STR("Difference between two datetime values.");
1906
1907static PyNumberMethods delta_as_number = {
1908 delta_add, /* nb_add */
1909 delta_subtract, /* nb_subtract */
1910 delta_multiply, /* nb_multiply */
1911 delta_divide, /* nb_divide */
1912 0, /* nb_remainder */
1913 0, /* nb_divmod */
1914 0, /* nb_power */
1915 (unaryfunc)delta_negative, /* nb_negative */
1916 (unaryfunc)delta_positive, /* nb_positive */
1917 (unaryfunc)delta_abs, /* nb_absolute */
1918 (inquiry)delta_nonzero, /* nb_nonzero */
1919 0, /*nb_invert*/
1920 0, /*nb_lshift*/
1921 0, /*nb_rshift*/
1922 0, /*nb_and*/
1923 0, /*nb_xor*/
1924 0, /*nb_or*/
1925 0, /*nb_coerce*/
1926 0, /*nb_int*/
1927 0, /*nb_long*/
1928 0, /*nb_float*/
1929 0, /*nb_oct*/
1930 0, /*nb_hex*/
1931 0, /*nb_inplace_add*/
1932 0, /*nb_inplace_subtract*/
1933 0, /*nb_inplace_multiply*/
1934 0, /*nb_inplace_divide*/
1935 0, /*nb_inplace_remainder*/
1936 0, /*nb_inplace_power*/
1937 0, /*nb_inplace_lshift*/
1938 0, /*nb_inplace_rshift*/
1939 0, /*nb_inplace_and*/
1940 0, /*nb_inplace_xor*/
1941 0, /*nb_inplace_or*/
1942 delta_divide, /* nb_floor_divide */
1943 0, /* nb_true_divide */
1944 0, /* nb_inplace_floor_divide */
1945 0, /* nb_inplace_true_divide */
1946};
1947
1948static PyTypeObject PyDateTime_DeltaType = {
1949 PyObject_HEAD_INIT(NULL)
1950 0, /* ob_size */
1951 "datetime.timedelta", /* tp_name */
1952 sizeof(PyDateTime_Delta), /* tp_basicsize */
1953 0, /* tp_itemsize */
1954 0, /* tp_dealloc */
1955 0, /* tp_print */
1956 0, /* tp_getattr */
1957 0, /* tp_setattr */
1958 0, /* tp_compare */
1959 (reprfunc)delta_repr, /* tp_repr */
1960 &delta_as_number, /* tp_as_number */
1961 0, /* tp_as_sequence */
1962 0, /* tp_as_mapping */
1963 (hashfunc)delta_hash, /* tp_hash */
1964 0, /* tp_call */
1965 (reprfunc)delta_str, /* tp_str */
1966 PyObject_GenericGetAttr, /* tp_getattro */
1967 0, /* tp_setattro */
1968 0, /* tp_as_buffer */
1969 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
1970 delta_doc, /* tp_doc */
1971 0, /* tp_traverse */
1972 0, /* tp_clear */
1973 (richcmpfunc)delta_richcompare, /* tp_richcompare */
1974 0, /* tp_weaklistoffset */
1975 0, /* tp_iter */
1976 0, /* tp_iternext */
1977 delta_methods, /* tp_methods */
1978 delta_members, /* tp_members */
1979 0, /* tp_getset */
1980 0, /* tp_base */
1981 0, /* tp_dict */
1982 0, /* tp_descr_get */
1983 0, /* tp_descr_set */
1984 0, /* tp_dictoffset */
1985 0, /* tp_init */
1986 0, /* tp_alloc */
1987 delta_new, /* tp_new */
1988 _PyObject_Del, /* tp_free */
1989};
1990
1991/*
1992 * PyDateTime_Date implementation.
1993 */
1994
1995/* Accessor properties. */
1996
1997static PyObject *
1998date_year(PyDateTime_Date *self, void *unused)
1999{
2000 return PyInt_FromLong(GET_YEAR(self));
2001}
2002
2003static PyObject *
2004date_month(PyDateTime_Date *self, void *unused)
2005{
2006 return PyInt_FromLong(GET_MONTH(self));
2007}
2008
2009static PyObject *
2010date_day(PyDateTime_Date *self, void *unused)
2011{
2012 return PyInt_FromLong(GET_DAY(self));
2013}
2014
2015static PyGetSetDef date_getset[] = {
2016 {"year", (getter)date_year},
2017 {"month", (getter)date_month},
2018 {"day", (getter)date_day},
2019 {NULL}
2020};
2021
2022/* Constructors. */
2023
2024static PyObject *
2025date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2026{
2027 PyObject *self = NULL;
2028 int year;
2029 int month;
2030 int day;
2031
2032 static char *keywords[] = {
2033 "year", "month", "day", NULL
2034 };
2035
2036 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", keywords,
2037 &year, &month, &day)) {
2038 if (check_date_args(year, month, day) < 0)
2039 return NULL;
2040 self = new_date(year, month, day);
2041 }
2042 return self;
2043}
2044
2045/* Return new date from localtime(t). */
2046static PyObject *
2047date_local_from_time_t(PyObject *cls, time_t t)
2048{
2049 struct tm *tm;
2050 PyObject *result = NULL;
2051
2052 tm = localtime(&t);
2053 if (tm)
2054 result = PyObject_CallFunction(cls, "iii",
2055 tm->tm_year + 1900,
2056 tm->tm_mon + 1,
2057 tm->tm_mday);
2058 else
2059 PyErr_SetString(PyExc_ValueError,
2060 "timestamp out of range for "
2061 "platform localtime() function");
2062 return result;
2063}
2064
2065/* Return new date from current time.
2066 * We say this is equivalent to fromtimestamp(time.time()), and the
2067 * only way to be sure of that is to *call* time.time(). That's not
2068 * generally the same as calling C's time.
2069 */
2070static PyObject *
2071date_today(PyObject *cls, PyObject *dummy)
2072{
2073 PyObject *time;
2074 PyObject *result;
2075
2076 time = time_time();
2077 if (time == NULL)
2078 return NULL;
2079
2080 /* Note well: today() is a class method, so this may not call
2081 * date.fromtimestamp. For example, it may call
2082 * datetime.fromtimestamp. That's why we need all the accuracy
2083 * time.time() delivers; if someone were gonzo about optimization,
2084 * date.today() could get away with plain C time().
2085 */
2086 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2087 Py_DECREF(time);
2088 return result;
2089}
2090
2091/* Return new date from given timestamp (Python timestamp -- a double). */
2092static PyObject *
2093date_fromtimestamp(PyObject *cls, PyObject *args)
2094{
2095 double timestamp;
2096 PyObject *result = NULL;
2097
2098 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2099 result = date_local_from_time_t(cls, (time_t)timestamp);
2100 return result;
2101}
2102
2103/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2104 * the ordinal is out of range.
2105 */
2106static PyObject *
2107date_fromordinal(PyObject *cls, PyObject *args)
2108{
2109 PyObject *result = NULL;
2110 int ordinal;
2111
2112 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2113 int year;
2114 int month;
2115 int day;
2116
2117 if (ordinal < 1)
2118 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2119 ">= 1");
2120 else {
2121 ord_to_ymd(ordinal, &year, &month, &day);
2122 result = PyObject_CallFunction(cls, "iii",
2123 year, month, day);
2124 }
2125 }
2126 return result;
2127}
2128
2129/*
2130 * Date arithmetic.
2131 */
2132
2133/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2134 * instead.
2135 */
2136static PyObject *
2137add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2138{
2139 PyObject *result = NULL;
2140 int year = GET_YEAR(date);
2141 int month = GET_MONTH(date);
2142 int deltadays = GET_TD_DAYS(delta);
2143 /* C-level overflow is impossible because |deltadays| < 1e9. */
2144 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2145
2146 if (normalize_date(&year, &month, &day) >= 0)
2147 result = new_date(year, month, day);
2148 return result;
2149}
2150
2151static PyObject *
2152date_add(PyObject *left, PyObject *right)
2153{
2154 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2155 Py_INCREF(Py_NotImplemented);
2156 return Py_NotImplemented;
2157 }
2158 if (PyDate_CheckExact(left)) {
2159 /* date + ??? */
2160 if (PyDelta_Check(right))
2161 /* date + delta */
2162 return add_date_timedelta((PyDateTime_Date *) left,
2163 (PyDateTime_Delta *) right,
2164 0);
2165 }
2166 else {
2167 /* ??? + date
2168 * 'right' must be one of us, or we wouldn't have been called
2169 */
2170 if (PyDelta_Check(left))
2171 /* delta + date */
2172 return add_date_timedelta((PyDateTime_Date *) right,
2173 (PyDateTime_Delta *) left,
2174 0);
2175 }
2176 Py_INCREF(Py_NotImplemented);
2177 return Py_NotImplemented;
2178}
2179
2180static PyObject *
2181date_subtract(PyObject *left, PyObject *right)
2182{
2183 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2184 Py_INCREF(Py_NotImplemented);
2185 return Py_NotImplemented;
2186 }
2187 if (PyDate_CheckExact(left)) {
2188 if (PyDate_CheckExact(right)) {
2189 /* date - date */
2190 int left_ord = ymd_to_ord(GET_YEAR(left),
2191 GET_MONTH(left),
2192 GET_DAY(left));
2193 int right_ord = ymd_to_ord(GET_YEAR(right),
2194 GET_MONTH(right),
2195 GET_DAY(right));
2196 return new_delta(left_ord - right_ord, 0, 0, 0);
2197 }
2198 if (PyDelta_Check(right)) {
2199 /* date - delta */
2200 return add_date_timedelta((PyDateTime_Date *) left,
2201 (PyDateTime_Delta *) right,
2202 1);
2203 }
2204 }
2205 Py_INCREF(Py_NotImplemented);
2206 return Py_NotImplemented;
2207}
2208
2209
2210/* Various ways to turn a date into a string. */
2211
2212static PyObject *
2213date_repr(PyDateTime_Date *self)
2214{
2215 char buffer[1028];
2216 char *typename;
2217
2218 typename = self->ob_type->tp_name;
2219 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
2220 typename,
2221 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2222
2223 return PyString_FromString(buffer);
2224}
2225
2226static PyObject *
2227date_isoformat(PyDateTime_Date *self)
2228{
2229 char buffer[128];
2230
2231 isoformat_date(self, buffer, sizeof(buffer));
2232 return PyString_FromString(buffer);
2233}
2234
2235/* str() calls the appropriate isofomat() method. */
2236static PyObject *
2237date_str(PyDateTime_Date *self)
2238{
2239 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2240}
2241
2242
2243static PyObject *
2244date_ctime(PyDateTime_Date *self)
2245{
2246 return format_ctime(self, 0, 0, 0);
2247}
2248
2249static PyObject *
2250date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2251{
2252 /* This method can be inherited, and needs to call the
2253 * timetuple() method appropriate to self's class.
2254 */
2255 PyObject *result;
2256 PyObject *format;
2257 PyObject *tuple;
2258 static char *keywords[] = {"format", NULL};
2259
2260 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2261 &PyString_Type, &format))
2262 return NULL;
2263
2264 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2265 if (tuple == NULL)
2266 return NULL;
2267 result = wrap_strftime((PyObject *)self, format, tuple);
2268 Py_DECREF(tuple);
2269 return result;
2270}
2271
2272/* ISO methods. */
2273
2274static PyObject *
2275date_isoweekday(PyDateTime_Date *self)
2276{
2277 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2278
2279 return PyInt_FromLong(dow + 1);
2280}
2281
2282static PyObject *
2283date_isocalendar(PyDateTime_Date *self)
2284{
2285 int year = GET_YEAR(self);
2286 int week1_monday = iso_week1_monday(year);
2287 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2288 int week;
2289 int day;
2290
2291 week = divmod(today - week1_monday, 7, &day);
2292 if (week < 0) {
2293 --year;
2294 week1_monday = iso_week1_monday(year);
2295 week = divmod(today - week1_monday, 7, &day);
2296 }
2297 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2298 ++year;
2299 week = 0;
2300 }
2301 return Py_BuildValue("iii", year, week + 1, day + 1);
2302}
2303
2304/* Miscellaneous methods. */
2305
2306/* This is more natural as a tp_compare, but doesn't work then: for whatever
2307 * reason, Python's try_3way_compare ignores tp_compare unless
2308 * PyInstance_Check returns true, but these aren't old-style classes.
2309 */
2310static PyObject *
2311date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2312{
2313 int diff;
2314
2315 if (! PyDate_Check(other)) {
2316 PyErr_Format(PyExc_TypeError,
2317 "can't compare date to %s instance",
2318 other->ob_type->tp_name);
2319 return NULL;
2320 }
2321 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2322 _PyDateTime_DATE_DATASIZE);
2323 return diff_to_bool(diff, op);
2324}
2325
2326static PyObject *
2327date_timetuple(PyDateTime_Date *self)
2328{
2329 return build_struct_time(GET_YEAR(self),
2330 GET_MONTH(self),
2331 GET_DAY(self),
2332 0, 0, 0, -1);
2333}
2334
2335static PyObject *date_getstate(PyDateTime_Date *self);
2336
2337static long
2338date_hash(PyDateTime_Date *self)
2339{
2340 if (self->hashcode == -1) {
2341 PyObject *temp = date_getstate(self);
2342 if (temp != NULL) {
2343 self->hashcode = PyObject_Hash(temp);
2344 Py_DECREF(temp);
2345 }
2346 }
2347 return self->hashcode;
2348}
2349
2350static PyObject *
2351date_toordinal(PyDateTime_Date *self)
2352{
2353 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2354 GET_DAY(self)));
2355}
2356
2357static PyObject *
2358date_weekday(PyDateTime_Date *self)
2359{
2360 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2361
2362 return PyInt_FromLong(dow);
2363}
2364
2365/* Pickle support. Quite a maze! */
2366
2367static PyObject *
2368date_getstate(PyDateTime_Date *self)
2369{
2370 return PyString_FromStringAndSize(self->data,
2371 _PyDateTime_DATE_DATASIZE);
2372}
2373
2374static PyObject *
2375date_setstate(PyDateTime_Date *self, PyObject *state)
2376{
2377 const int len = PyString_Size(state);
2378 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
2379
2380 if (! PyString_Check(state) ||
2381 len != _PyDateTime_DATE_DATASIZE) {
2382 PyErr_SetString(PyExc_TypeError,
2383 "bad argument to date.__setstate__");
2384 return NULL;
2385 }
2386 memcpy(self->data, pdata, _PyDateTime_DATE_DATASIZE);
2387 self->hashcode = -1;
2388
2389 Py_INCREF(Py_None);
2390 return Py_None;
2391}
2392
2393/* XXX This seems a ridiculously inefficient way to pickle a short string. */
2394static PyObject *
2395date_pickler(PyObject *module, PyDateTime_Date *date)
2396{
2397 PyObject *state;
2398 PyObject *result = NULL;
2399
2400 if (! PyDate_CheckExact(date)) {
2401 PyErr_Format(PyExc_TypeError,
2402 "bad type passed to date pickler: %s",
2403 date->ob_type->tp_name);
2404 return NULL;
2405 }
2406 state = date_getstate(date);
2407 if (state) {
2408 result = Py_BuildValue("O(O)", date_unpickler_object, state);
2409 Py_DECREF(state);
2410 }
2411 return result;
2412}
2413
2414static PyObject *
2415date_unpickler(PyObject *module, PyObject *arg)
2416{
2417 PyDateTime_Date *self;
2418
2419 if (! PyString_CheckExact(arg)) {
2420 PyErr_Format(PyExc_TypeError,
2421 "bad type passed to date unpickler: %s",
2422 arg->ob_type->tp_name);
2423 return NULL;
2424 }
2425 self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType);
2426 if (self != NULL) {
2427 PyObject *res = date_setstate(self, arg);
2428 if (res == NULL) {
2429 Py_DECREF(self);
2430 return NULL;
2431 }
2432 Py_DECREF(res);
2433 }
2434 return (PyObject *)self;
2435}
2436
2437static PyMethodDef date_methods[] = {
2438 /* Class methods: */
2439 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2440 METH_CLASS,
2441 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2442 "time.time()).")},
2443
2444 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2445 METH_CLASS,
2446 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2447 "ordinal.")},
2448
2449 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2450 PyDoc_STR("Current date or datetime: same as "
2451 "self.__class__.fromtimestamp(time.time()).")},
2452
2453 /* Instance methods: */
2454
2455 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2456 PyDoc_STR("Return ctime() style string.")},
2457
2458 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2459 PyDoc_STR("format -> strftime() style string.")},
2460
2461 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2462 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2463
2464 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2465 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2466 "weekday.")},
2467
2468 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2469 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2470
2471 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2472 PyDoc_STR("Return the day of the week represented by the date.\n"
2473 "Monday == 1 ... Sunday == 7")},
2474
2475 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2476 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2477 "1 is day 1.")},
2478
2479 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2480 PyDoc_STR("Return the day of the week represented by the date.\n"
2481 "Monday == 0 ... Sunday == 6")},
2482
2483 {"__setstate__", (PyCFunction)date_setstate, METH_O,
2484 PyDoc_STR("__setstate__(state)")},
2485
2486 {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS,
2487 PyDoc_STR("__getstate__() -> state")},
2488
2489 {NULL, NULL}
2490};
2491
2492static char date_doc[] =
2493PyDoc_STR("Basic date type.");
2494
2495static PyNumberMethods date_as_number = {
2496 date_add, /* nb_add */
2497 date_subtract, /* nb_subtract */
2498 0, /* nb_multiply */
2499 0, /* nb_divide */
2500 0, /* nb_remainder */
2501 0, /* nb_divmod */
2502 0, /* nb_power */
2503 0, /* nb_negative */
2504 0, /* nb_positive */
2505 0, /* nb_absolute */
2506 0, /* nb_nonzero */
2507};
2508
2509static PyTypeObject PyDateTime_DateType = {
2510 PyObject_HEAD_INIT(NULL)
2511 0, /* ob_size */
2512 "datetime.date", /* tp_name */
2513 sizeof(PyDateTime_Date), /* tp_basicsize */
2514 0, /* tp_itemsize */
2515 (destructor)PyObject_Del, /* tp_dealloc */
2516 0, /* tp_print */
2517 0, /* tp_getattr */
2518 0, /* tp_setattr */
2519 0, /* tp_compare */
2520 (reprfunc)date_repr, /* tp_repr */
2521 &date_as_number, /* tp_as_number */
2522 0, /* tp_as_sequence */
2523 0, /* tp_as_mapping */
2524 (hashfunc)date_hash, /* tp_hash */
2525 0, /* tp_call */
2526 (reprfunc)date_str, /* tp_str */
2527 PyObject_GenericGetAttr, /* tp_getattro */
2528 0, /* tp_setattro */
2529 0, /* tp_as_buffer */
2530 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2531 Py_TPFLAGS_BASETYPE, /* tp_flags */
2532 date_doc, /* tp_doc */
2533 0, /* tp_traverse */
2534 0, /* tp_clear */
2535 (richcmpfunc)date_richcompare, /* tp_richcompare */
2536 0, /* tp_weaklistoffset */
2537 0, /* tp_iter */
2538 0, /* tp_iternext */
2539 date_methods, /* tp_methods */
2540 0, /* tp_members */
2541 date_getset, /* tp_getset */
2542 0, /* tp_base */
2543 0, /* tp_dict */
2544 0, /* tp_descr_get */
2545 0, /* tp_descr_set */
2546 0, /* tp_dictoffset */
2547 0, /* tp_init */
2548 0, /* tp_alloc */
2549 date_new, /* tp_new */
2550 _PyObject_Del, /* tp_free */
2551};
2552
2553/*
2554 * PyDateTime_DateTime implementation.
2555 */
2556
2557/* Accessor properties. */
2558
2559static PyObject *
2560datetime_hour(PyDateTime_DateTime *self, void *unused)
2561{
2562 return PyInt_FromLong(DATE_GET_HOUR(self));
2563}
2564
2565static PyObject *
2566datetime_minute(PyDateTime_DateTime *self, void *unused)
2567{
2568 return PyInt_FromLong(DATE_GET_MINUTE(self));
2569}
2570
2571static PyObject *
2572datetime_second(PyDateTime_DateTime *self, void *unused)
2573{
2574 return PyInt_FromLong(DATE_GET_SECOND(self));
2575}
2576
2577static PyObject *
2578datetime_microsecond(PyDateTime_DateTime *self, void *unused)
2579{
2580 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
2581}
2582
2583static PyGetSetDef datetime_getset[] = {
2584 {"hour", (getter)datetime_hour},
2585 {"minute", (getter)datetime_minute},
2586 {"second", (getter)datetime_second},
2587 {"microsecond", (getter)datetime_microsecond},
2588 {NULL}
2589};
2590
2591/* Constructors. */
2592
2593static PyObject *
2594datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2595{
2596 PyObject *self = NULL;
2597 int year;
2598 int month;
2599 int day;
2600 int hour = 0;
2601 int minute = 0;
2602 int second = 0;
2603 int usecond = 0;
2604
2605 static char *keywords[] = {
2606 "year", "month", "day", "hour", "minute", "second",
2607 "microsecond", NULL
2608 };
2609
2610 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiii", keywords,
2611 &year, &month, &day, &hour, &minute,
2612 &second, &usecond)) {
2613 if (check_date_args(year, month, day) < 0)
2614 return NULL;
2615 if (check_time_args(hour, minute, second, usecond) < 0)
2616 return NULL;
2617 self = new_datetime(year, month, day,
2618 hour, minute, second, usecond);
2619 }
2620 return self;
2621}
2622
2623
2624/* TM_FUNC is the shared type of localtime() and gmtime(). */
2625typedef struct tm *(*TM_FUNC)(const time_t *timer);
2626
2627/* Internal helper.
2628 * Build datetime from a time_t and a distinct count of microseconds.
2629 * Pass localtime or gmtime for f, to control the interpretation of timet.
2630 */
2631static PyObject *
2632datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us)
2633{
2634 struct tm *tm;
2635 PyObject *result = NULL;
2636
2637 tm = f(&timet);
2638 if (tm)
2639 result = PyObject_CallFunction(cls, "iiiiiii",
2640 tm->tm_year + 1900,
2641 tm->tm_mon + 1,
2642 tm->tm_mday,
2643 tm->tm_hour,
2644 tm->tm_min,
2645 tm->tm_sec,
2646 us);
2647 else
2648 PyErr_SetString(PyExc_ValueError,
2649 "timestamp out of range for "
2650 "platform localtime()/gmtime() function");
2651 return result;
2652}
2653
2654/* Internal helper.
2655 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
2656 * to control the interpretation of the timestamp. Since a double doesn't
2657 * have enough bits to cover a datetime's full range of precision, it's
2658 * better to call datetime_from_timet_and_us provided you have a way
2659 * to get that much precision (e.g., C time() isn't good enough).
2660 */
2661static PyObject *
2662datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp)
2663{
2664 time_t timet = (time_t)timestamp;
2665 int us = (int)((timestamp - (double)timet) * 1e6);
2666
2667 return datetime_from_timet_and_us(cls, f, timet, us);
2668}
2669
2670/* Internal helper.
2671 * Build most accurate possible datetime for current time. Pass localtime or
2672 * gmtime for f as appropriate.
2673 */
2674static PyObject *
2675datetime_best_possible(PyObject *cls, TM_FUNC f)
2676{
2677#ifdef HAVE_GETTIMEOFDAY
2678 struct timeval t;
2679
2680#ifdef GETTIMEOFDAY_NO_TZ
2681 gettimeofday(&t);
2682#else
2683 gettimeofday(&t, (struct timezone *)NULL);
2684#endif
2685 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec);
2686
2687#else /* ! HAVE_GETTIMEOFDAY */
2688 /* No flavor of gettimeofday exists on this platform. Python's
2689 * time.time() does a lot of other platform tricks to get the
2690 * best time it can on the platform, and we're not going to do
2691 * better than that (if we could, the better code would belong
2692 * in time.time()!) We're limited by the precision of a double,
2693 * though.
2694 */
2695 PyObject *time;
2696 double dtime;
2697
2698 time = time_time();
2699 if (time == NULL)
2700 return NULL;
2701 dtime = PyFloat_AsDouble(time);
2702 Py_DECREF(time);
2703 if (dtime == -1.0 && PyErr_Occurred())
2704 return NULL;
2705 return datetime_from_timestamp(cls, f, dtime);
2706#endif /* ! HAVE_GETTIMEOFDAY */
2707}
2708
2709/* Return new local datetime from timestamp (Python timestamp -- a double). */
2710static PyObject *
2711datetime_fromtimestamp(PyObject *cls, PyObject *args)
2712{
2713 double timestamp;
2714 PyObject *result = NULL;
2715
2716 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2717 result = datetime_from_timestamp(cls, localtime, timestamp);
2718 return result;
2719}
2720
2721/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
2722static PyObject *
2723datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
2724{
2725 double timestamp;
2726 PyObject *result = NULL;
2727
2728 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
2729 result = datetime_from_timestamp(cls, gmtime, timestamp);
2730 return result;
2731}
2732
2733/* Return best possible local time -- this isn't constrained by the
2734 * precision of a timestamp.
2735 */
2736static PyObject *
2737datetime_now(PyObject *cls, PyObject *dummy)
2738{
2739 return datetime_best_possible(cls, localtime);
2740}
2741
2742/* Return best possible UTC time -- this isn't constrained by the
2743 * precision of a timestamp.
2744 */
2745static PyObject *
2746datetime_utcnow(PyObject *cls, PyObject *dummy)
2747{
2748 return datetime_best_possible(cls, gmtime);
2749}
2750
2751/* Return new datetime or datetimetz from date/datetime/datetimetz and
2752 * time/timetz arguments.
2753 */
2754static PyObject *
2755datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
2756{
2757 static char *keywords[] = {"date", "time", NULL};
2758 PyObject *date;
2759 PyObject *time;
2760 PyObject *result = NULL;
2761
2762 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
2763 &PyDateTime_DateType, &date,
2764 &PyDateTime_TimeType, &time))
2765 result = PyObject_CallFunction(cls, "iiiiiii",
2766 GET_YEAR(date),
2767 GET_MONTH(date),
2768 GET_DAY(date),
2769 TIME_GET_HOUR(time),
2770 TIME_GET_MINUTE(time),
2771 TIME_GET_SECOND(time),
2772 TIME_GET_MICROSECOND(time));
2773 if (result && PyTimeTZ_Check(time) && PyDateTimeTZ_Check(result)) {
2774 /* Copy the tzinfo field. */
2775 PyObject *tzinfo = ((PyDateTime_TimeTZ *)time)->tzinfo;
2776 Py_INCREF(tzinfo);
2777 Py_DECREF(((PyDateTime_DateTimeTZ *)result)->tzinfo);
2778 ((PyDateTime_DateTimeTZ *)result)->tzinfo = tzinfo;
2779 }
2780 return result;
2781}
2782
2783/* datetime arithmetic. */
2784
2785static PyObject *
2786add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta)
2787{
2788 /* Note that the C-level additions can't overflow, because of
2789 * invariant bounds on the member values.
2790 */
2791 int year = GET_YEAR(date);
2792 int month = GET_MONTH(date);
2793 int day = GET_DAY(date) + GET_TD_DAYS(delta);
2794 int hour = DATE_GET_HOUR(date);
2795 int minute = DATE_GET_MINUTE(date);
2796 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta);
2797 int microsecond = DATE_GET_MICROSECOND(date) +
2798 GET_TD_MICROSECONDS(delta);
2799
2800 if (normalize_datetime(&year, &month, &day,
2801 &hour, &minute, &second, &microsecond) < 0)
2802 return NULL;
2803 else
2804 return new_datetime(year, month, day,
2805 hour, minute, second, microsecond);
2806}
2807
2808static PyObject *
2809sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta)
2810{
2811 /* Note that the C-level subtractions can't overflow, because of
2812 * invariant bounds on the member values.
2813 */
2814 int year = GET_YEAR(date);
2815 int month = GET_MONTH(date);
2816 int day = GET_DAY(date) - GET_TD_DAYS(delta);
2817 int hour = DATE_GET_HOUR(date);
2818 int minute = DATE_GET_MINUTE(date);
2819 int second = DATE_GET_SECOND(date) - GET_TD_SECONDS(delta);
2820 int microsecond = DATE_GET_MICROSECOND(date) -
2821 GET_TD_MICROSECONDS(delta);
2822
2823 if (normalize_datetime(&year, &month, &day,
2824 &hour, &minute, &second, &microsecond) < 0)
2825 return NULL;
2826 else
2827 return new_datetime(year, month, day,
2828 hour, minute, second, microsecond);
2829}
2830
2831static PyObject *
2832sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right)
2833{
2834 int days1 = ymd_to_ord(GET_YEAR(left), GET_MONTH(left), GET_DAY(left));
2835 int days2 = ymd_to_ord(GET_YEAR(right),
2836 GET_MONTH(right),
2837 GET_DAY(right));
2838 /* These can't overflow, since the values are normalized. At most
2839 * this gives the number of seconds in one day.
2840 */
2841 int delta_s = (DATE_GET_HOUR(left) - DATE_GET_HOUR(right)) * 3600 +
2842 (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 +
2843 DATE_GET_SECOND(left) - DATE_GET_SECOND(right);
2844 int delta_us = DATE_GET_MICROSECOND(left) -
2845 DATE_GET_MICROSECOND(right);
2846
2847 return new_delta(days1 - days2, delta_s, delta_us, 1);
2848}
2849
2850static PyObject *
2851datetime_add(PyObject *left, PyObject *right)
2852{
2853 if (PyDateTime_Check(left)) {
2854 /* datetime + ??? */
2855 if (PyDelta_Check(right))
2856 /* datetime + delta */
2857 return add_datetime_timedelta(
2858 (PyDateTime_DateTime *)left,
2859 (PyDateTime_Delta *)right);
2860 }
2861 else if (PyDelta_Check(left)) {
2862 /* delta + datetime */
2863 return add_datetime_timedelta((PyDateTime_DateTime *) right,
2864 (PyDateTime_Delta *) left);
2865 }
2866 Py_INCREF(Py_NotImplemented);
2867 return Py_NotImplemented;
2868}
2869
2870static PyObject *
2871datetime_subtract(PyObject *left, PyObject *right)
2872{
2873 PyObject *result = Py_NotImplemented;
2874
2875 if (PyDateTime_Check(left)) {
2876 /* datetime - ??? */
2877 if (PyDateTime_Check(right)) {
2878 /* datetime - datetime */
2879 result = sub_datetime_datetime(
2880 (PyDateTime_DateTime *)left,
2881 (PyDateTime_DateTime *)right);
2882 }
2883 else if (PyDelta_Check(right)) {
2884 /* datetime - delta */
2885 result = sub_datetime_timedelta(
2886 (PyDateTime_DateTime *)left,
2887 (PyDateTime_Delta *)right);
2888 }
2889 }
2890
2891 if (result == Py_NotImplemented)
2892 Py_INCREF(result);
2893 return result;
2894}
2895
2896/* Various ways to turn a datetime into a string. */
2897
2898static PyObject *
2899datetime_repr(PyDateTime_DateTime *self)
2900{
2901 char buffer[1000];
2902 char *typename = self->ob_type->tp_name;
2903
2904 if (DATE_GET_MICROSECOND(self)) {
2905 PyOS_snprintf(buffer, sizeof(buffer),
2906 "%s(%d, %d, %d, %d, %d, %d, %d)",
2907 typename,
2908 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
2909 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
2910 DATE_GET_SECOND(self),
2911 DATE_GET_MICROSECOND(self));
2912 }
2913 else if (DATE_GET_SECOND(self)) {
2914 PyOS_snprintf(buffer, sizeof(buffer),
2915 "%s(%d, %d, %d, %d, %d, %d)",
2916 typename,
2917 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
2918 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
2919 DATE_GET_SECOND(self));
2920 }
2921 else {
2922 PyOS_snprintf(buffer, sizeof(buffer),
2923 "%s(%d, %d, %d, %d, %d)",
2924 typename,
2925 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
2926 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
2927 }
2928 return PyString_FromString(buffer);
2929}
2930
2931static PyObject *
2932datetime_str(PyDateTime_DateTime *self)
2933{
2934 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
2935}
2936
2937static PyObject *
2938datetime_isoformat(PyDateTime_DateTime *self,
2939 PyObject *args, PyObject *kw)
2940{
2941 char sep = 'T';
2942 static char *keywords[] = {"sep", NULL};
2943 char buffer[100];
2944 char *cp;
2945
2946 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
2947 &sep))
2948 return NULL;
2949 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
2950 assert(cp != NULL);
2951 *cp++ = sep;
2952 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
2953 return PyString_FromString(buffer);
2954}
2955
2956static PyObject *
2957datetime_ctime(PyDateTime_DateTime *self)
2958{
2959 return format_ctime((PyDateTime_Date *)self,
2960 DATE_GET_HOUR(self),
2961 DATE_GET_MINUTE(self),
2962 DATE_GET_SECOND(self));
2963}
2964
2965/* Miscellaneous methods. */
2966
2967/* This is more natural as a tp_compare, but doesn't work then: for whatever
2968 * reason, Python's try_3way_compare ignores tp_compare unless
2969 * PyInstance_Check returns true, but these aren't old-style classes.
2970 * Note that this routine handles all comparisons for datetime and datetimetz.
2971 */
2972static PyObject *
2973datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
2974{
2975 int diff;
2976 naivety n1, n2;
2977 int offset1, offset2;
2978
2979 if (! PyDateTime_Check(other)) {
2980 /* Stop this from falling back to address comparison. */
2981 PyErr_Format(PyExc_TypeError,
2982 "can't compare '%s' to '%s'",
2983 self->ob_type->tp_name,
2984 other->ob_type->tp_name);
2985 return NULL;
2986 }
2987 n1 = classify_object((PyObject *)self, &offset1);
2988 assert(n1 != OFFSET_UNKNOWN);
2989 if (n1 == OFFSET_ERROR)
2990 return NULL;
2991
2992 n2 = classify_object(other, &offset2);
2993 assert(n2 != OFFSET_UNKNOWN);
2994 if (n2 == OFFSET_ERROR)
2995 return NULL;
2996
2997 /* If they're both naive, or both aware and have the same offsets,
2998 * we get off cheap. Note that if they're both naive, offset1 ==
2999 * offset2 == 0 at this point.
3000 */
3001 if (n1 == n2 && offset1 == offset2) {
3002 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
3003 _PyDateTime_DATETIME_DATASIZE);
3004 return diff_to_bool(diff, op);
3005 }
3006
3007 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3008 /* We want the sign of
3009 * (self - offset1 minutes) - (other - offset2 minutes) =
3010 * (self - other) + (offset2 - offset1) minutes.
3011 */
3012 PyDateTime_Delta *delta;
3013 int days, seconds, us;
3014
3015 assert(offset1 != offset2); /* else last "if" handled it */
3016 delta = (PyDateTime_Delta *)sub_datetime_datetime(self,
3017 (PyDateTime_DateTime *)other);
3018 if (delta == NULL)
3019 return NULL;
3020 days = delta->days;
3021 seconds = delta->seconds + (offset2 - offset1) * 60;
3022 us = delta->microseconds;
3023 Py_DECREF(delta);
3024 normalize_d_s_us(&days, &seconds, &us);
3025 diff = days;
3026 if (diff == 0)
3027 diff = seconds | us;
3028 return diff_to_bool(diff, op);
3029 }
3030
3031 assert(n1 != n2);
3032 PyErr_SetString(PyExc_TypeError,
3033 "can't compare offset-naive and "
3034 "offset-aware datetimes");
3035 return NULL;
3036}
3037
3038static PyObject *datetime_getstate(PyDateTime_DateTime *self);
3039
3040static long
3041datetime_hash(PyDateTime_DateTime *self)
3042{
3043 if (self->hashcode == -1) {
3044 naivety n;
3045 int offset;
3046 PyObject *temp;
3047
3048 n = classify_object((PyObject *)self, &offset);
3049 assert(n != OFFSET_UNKNOWN);
3050 if (n == OFFSET_ERROR)
3051 return -1;
3052
3053 /* Reduce this to a hash of another object. */
3054 if (n == OFFSET_NAIVE)
3055 temp = datetime_getstate(self);
3056 else {
3057 int days;
3058 int seconds;
3059
3060 assert(n == OFFSET_AWARE);
3061 assert(PyDateTimeTZ_Check(self));
3062 days = ymd_to_ord(GET_YEAR(self),
3063 GET_MONTH(self),
3064 GET_DAY(self));
3065 seconds = DATE_GET_HOUR(self) * 3600 +
3066 (DATE_GET_MINUTE(self) - offset) * 60 +
3067 DATE_GET_SECOND(self);
3068 temp = new_delta(days,
3069 seconds,
3070 DATE_GET_MICROSECOND(self),
3071 1);
3072 }
3073 if (temp != NULL) {
3074 self->hashcode = PyObject_Hash(temp);
3075 Py_DECREF(temp);
3076 }
3077 }
3078 return self->hashcode;
3079}
3080
3081static PyObject *
3082datetime_timetuple(PyDateTime_DateTime *self)
3083{
3084 return build_struct_time(GET_YEAR(self),
3085 GET_MONTH(self),
3086 GET_DAY(self),
3087 DATE_GET_HOUR(self),
3088 DATE_GET_MINUTE(self),
3089 DATE_GET_SECOND(self),
3090 -1);
3091}
3092
3093static PyObject *
3094datetime_getdate(PyDateTime_DateTime *self)
3095{
3096 return new_date(GET_YEAR(self),
3097 GET_MONTH(self),
3098 GET_DAY(self));
3099}
3100
3101static PyObject *
3102datetime_gettime(PyDateTime_DateTime *self)
3103{
3104 return new_time(DATE_GET_HOUR(self),
3105 DATE_GET_MINUTE(self),
3106 DATE_GET_SECOND(self),
3107 DATE_GET_MICROSECOND(self));
3108}
3109
3110/* Pickle support. Quite a maze! */
3111
3112static PyObject *
3113datetime_getstate(PyDateTime_DateTime *self)
3114{
3115 return PyString_FromStringAndSize(self->data,
3116 _PyDateTime_DATETIME_DATASIZE);
3117}
3118
3119static PyObject *
3120datetime_setstate(PyDateTime_DateTime *self, PyObject *state)
3121{
3122 const int len = PyString_Size(state);
3123 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
3124
3125 if (! PyString_Check(state) ||
3126 len != _PyDateTime_DATETIME_DATASIZE) {
3127 PyErr_SetString(PyExc_TypeError,
3128 "bad argument to datetime.__setstate__");
3129 return NULL;
3130 }
3131 memcpy(self->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3132 self->hashcode = -1;
3133
3134 Py_INCREF(Py_None);
3135 return Py_None;
3136}
3137
3138/* XXX This seems a ridiculously inefficient way to pickle a short string. */
3139static PyObject *
3140datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime)
3141{
3142 PyObject *state;
3143 PyObject *result = NULL;
3144
3145 if (! PyDateTime_CheckExact(datetime)) {
3146 PyErr_Format(PyExc_TypeError,
3147 "bad type passed to datetime pickler: %s",
3148 datetime->ob_type->tp_name);
3149 return NULL;
3150 }
3151 state = datetime_getstate(datetime);
3152 if (state) {
3153 result = Py_BuildValue("O(O)",
3154 datetime_unpickler_object,
3155 state);
3156 Py_DECREF(state);
3157 }
3158 return result;
3159}
3160
3161static PyObject *
3162datetime_unpickler(PyObject *module, PyObject *arg)
3163{
3164 PyDateTime_DateTime *self;
3165
3166 if (! PyString_CheckExact(arg)) {
3167 PyErr_Format(PyExc_TypeError,
3168 "bad type passed to datetime unpickler: %s",
3169 arg->ob_type->tp_name);
3170 return NULL;
3171 }
3172 self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType);
3173 if (self != NULL) {
3174 PyObject *res = datetime_setstate(self, arg);
3175 if (res == NULL) {
3176 Py_DECREF(self);
3177 return NULL;
3178 }
3179 Py_DECREF(res);
3180 }
3181 return (PyObject *)self;
3182}
3183
3184static PyMethodDef datetime_methods[] = {
3185 /* Class methods: */
3186 {"now", (PyCFunction)datetime_now,
3187 METH_NOARGS | METH_CLASS,
3188 PyDoc_STR("Return a new datetime representing local day and time.")},
3189
3190 {"utcnow", (PyCFunction)datetime_utcnow,
3191 METH_NOARGS | METH_CLASS,
3192 PyDoc_STR("Return a new datetime representing UTC day and time.")},
3193
3194 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
3195 METH_VARARGS | METH_CLASS,
3196 PyDoc_STR("timestamp -> local datetime from a POSIX timestamp "
3197 "(like time.time()).")},
3198
3199 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
3200 METH_VARARGS | METH_CLASS,
3201 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
3202 "(like time.time()).")},
3203
3204 {"combine", (PyCFunction)datetime_combine,
3205 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3206 PyDoc_STR("date, time -> datetime with same date and time fields")},
3207
3208 /* Instance methods: */
3209 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
3210 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
3211
3212 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
3213 PyDoc_STR("Return date object with same year, month and day.")},
3214
3215 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
3216 PyDoc_STR("Return time object with same hour, minute, second and "
3217 "microsecond.")},
3218
3219 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
3220 PyDoc_STR("Return ctime() style string.")},
3221
3222 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
3223 PyDoc_STR("[sep] -> string in ISO 8601 format, "
3224 "YYYY-MM-DDTHH:MM:SS[.mmmmmm].\n\n"
3225 "sep is used to separate the year from the time, and "
3226 "defaults\n"
3227 "to 'T'.")},
3228
3229 {"__setstate__", (PyCFunction)datetime_setstate, METH_O,
3230 PyDoc_STR("__setstate__(state)")},
3231
3232 {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS,
3233 PyDoc_STR("__getstate__() -> state")},
3234 {NULL, NULL}
3235};
3236
3237static char datetime_doc[] =
3238PyDoc_STR("Basic date/time type.");
3239
3240static PyNumberMethods datetime_as_number = {
3241 datetime_add, /* nb_add */
3242 datetime_subtract, /* nb_subtract */
3243 0, /* nb_multiply */
3244 0, /* nb_divide */
3245 0, /* nb_remainder */
3246 0, /* nb_divmod */
3247 0, /* nb_power */
3248 0, /* nb_negative */
3249 0, /* nb_positive */
3250 0, /* nb_absolute */
3251 0, /* nb_nonzero */
3252};
3253
3254statichere PyTypeObject PyDateTime_DateTimeType = {
3255 PyObject_HEAD_INIT(NULL)
3256 0, /* ob_size */
3257 "datetime.datetime", /* tp_name */
3258 sizeof(PyDateTime_DateTime), /* tp_basicsize */
3259 0, /* tp_itemsize */
3260 (destructor)PyObject_Del, /* tp_dealloc */
3261 0, /* tp_print */
3262 0, /* tp_getattr */
3263 0, /* tp_setattr */
3264 0, /* tp_compare */
3265 (reprfunc)datetime_repr, /* tp_repr */
3266 &datetime_as_number, /* tp_as_number */
3267 0, /* tp_as_sequence */
3268 0, /* tp_as_mapping */
3269 (hashfunc)datetime_hash, /* tp_hash */
3270 0, /* tp_call */
3271 (reprfunc)datetime_str, /* tp_str */
3272 PyObject_GenericGetAttr, /* tp_getattro */
3273 0, /* tp_setattro */
3274 0, /* tp_as_buffer */
3275 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3276 Py_TPFLAGS_BASETYPE, /* tp_flags */
3277 datetime_doc, /* tp_doc */
3278 0, /* tp_traverse */
3279 0, /* tp_clear */
3280 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
3281 0, /* tp_weaklistoffset */
3282 0, /* tp_iter */
3283 0, /* tp_iternext */
3284 datetime_methods, /* tp_methods */
3285 0, /* tp_members */
3286 datetime_getset, /* tp_getset */
3287 &PyDateTime_DateType, /* tp_base */
3288 0, /* tp_dict */
3289 0, /* tp_descr_get */
3290 0, /* tp_descr_set */
3291 0, /* tp_dictoffset */
3292 0, /* tp_init */
3293 0, /* tp_alloc */
3294 datetime_new, /* tp_new */
3295 _PyObject_Del, /* tp_free */
3296};
3297
3298/*
3299 * PyDateTime_Time implementation.
3300 */
3301
3302/* Accessor properties. */
3303
3304static PyObject *
3305time_hour(PyDateTime_Time *self, void *unused)
3306{
3307 return PyInt_FromLong(TIME_GET_HOUR(self));
3308}
3309
3310static PyObject *
3311time_minute(PyDateTime_Time *self, void *unused)
3312{
3313 return PyInt_FromLong(TIME_GET_MINUTE(self));
3314}
3315
3316static PyObject *
3317time_second(PyDateTime_Time *self, void *unused)
3318{
3319 return PyInt_FromLong(TIME_GET_SECOND(self));
3320}
3321
3322static PyObject *
3323time_microsecond(PyDateTime_Time *self, void *unused)
3324{
3325 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3326}
3327
3328static PyGetSetDef time_getset[] = {
3329 {"hour", (getter)time_hour},
3330 {"minute", (getter)time_minute},
3331 {"second", (getter)time_second},
3332 {"microsecond", (getter)time_microsecond},
3333 {NULL}
3334};
3335
3336/* Constructors. */
3337
3338static PyObject *
3339time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3340{
3341 PyObject *self = NULL;
3342 int hour = 0;
3343 int minute = 0;
3344 int second = 0;
3345 int usecond = 0;
3346
3347 static char *keywords[] = {
3348 "hour", "minute", "second", "microsecond", NULL
3349 };
3350
3351 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiii", keywords,
3352 &hour, &minute, &second, &usecond)) {
3353 if (check_time_args(hour, minute, second, usecond) < 0)
3354 return NULL;
3355 self = new_time(hour, minute, second, usecond);
3356 }
3357 return self;
3358}
3359
3360/* Various ways to turn a time into a string. */
3361
3362static PyObject *
3363time_repr(PyDateTime_Time *self)
3364{
3365 char buffer[100];
3366 char *typename = self->ob_type->tp_name;
3367 int h = TIME_GET_HOUR(self);
3368 int m = TIME_GET_MINUTE(self);
3369 int s = TIME_GET_SECOND(self);
3370 int us = TIME_GET_MICROSECOND(self);
3371
3372 if (us)
3373 PyOS_snprintf(buffer, sizeof(buffer),
3374 "%s(%d, %d, %d, %d)", typename, h, m, s, us);
3375 else if (s)
3376 PyOS_snprintf(buffer, sizeof(buffer),
3377 "%s(%d, %d, %d)", typename, h, m, s);
3378 else
3379 PyOS_snprintf(buffer, sizeof(buffer),
3380 "%s(%d, %d)", typename, h, m);
3381 return PyString_FromString(buffer);
3382}
3383
3384static PyObject *
3385time_str(PyDateTime_Time *self)
3386{
3387 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3388}
3389
3390static PyObject *
3391time_isoformat(PyDateTime_Time *self)
3392{
3393 char buffer[100];
3394 /* Reuse the time format code from the datetime type. */
3395 PyDateTime_DateTime datetime;
3396 PyDateTime_DateTime *pdatetime = &datetime;
3397
3398 /* Copy over just the time bytes. */
3399 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3400 self->data,
3401 _PyDateTime_TIME_DATASIZE);
3402
3403 isoformat_time(pdatetime, buffer, sizeof(buffer));
3404 return PyString_FromString(buffer);
3405}
3406
3407static PyObject *
3408time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3409{
3410 PyObject *result;
3411 PyObject *format;
3412 PyObject *tuple;
3413 static char *keywords[] = {"format", NULL};
3414
3415 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3416 &PyString_Type, &format))
3417 return NULL;
3418
3419 tuple = Py_BuildValue("iiiiiiiii",
3420 0, 0, 0, /* year, month, day */
3421 TIME_GET_HOUR(self),
3422 TIME_GET_MINUTE(self),
3423 TIME_GET_SECOND(self),
3424 0, 0, -1); /* weekday, daynum, dst */
3425 if (tuple == NULL)
3426 return NULL;
3427 assert(PyTuple_Size(tuple) == 9);
3428 result = wrap_strftime((PyObject *)self, format, tuple);
3429 Py_DECREF(tuple);
3430 return result;
3431}
3432
3433/* Miscellaneous methods. */
3434
3435/* This is more natural as a tp_compare, but doesn't work then: for whatever
3436 * reason, Python's try_3way_compare ignores tp_compare unless
3437 * PyInstance_Check returns true, but these aren't old-style classes.
3438 * Note that this routine handles all comparisons for time and timetz.
3439 */
3440static PyObject *
3441time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3442{
3443 int diff;
3444 naivety n1, n2;
3445 int offset1, offset2;
3446
3447 if (! PyTime_Check(other)) {
3448 /* Stop this from falling back to address comparison. */
3449 PyErr_Format(PyExc_TypeError,
3450 "can't compare '%s' to '%s'",
3451 self->ob_type->tp_name,
3452 other->ob_type->tp_name);
3453 return NULL;
3454 }
3455 n1 = classify_object((PyObject *)self, &offset1);
3456 assert(n1 != OFFSET_UNKNOWN);
3457 if (n1 == OFFSET_ERROR)
3458 return NULL;
3459
3460 n2 = classify_object(other, &offset2);
3461 assert(n2 != OFFSET_UNKNOWN);
3462 if (n2 == OFFSET_ERROR)
3463 return NULL;
3464
3465 /* If they're both naive, or both aware and have the same offsets,
3466 * we get off cheap. Note that if they're both naive, offset1 ==
3467 * offset2 == 0 at this point.
3468 */
3469 if (n1 == n2 && offset1 == offset2) {
3470 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3471 _PyDateTime_TIME_DATASIZE);
3472 return diff_to_bool(diff, op);
3473 }
3474
3475 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3476 assert(offset1 != offset2); /* else last "if" handled it */
3477 /* Convert everything except microseconds to seconds. These
3478 * can't overflow (no more than the # of seconds in 2 days).
3479 */
3480 offset1 = TIME_GET_HOUR(self) * 3600 +
3481 (TIME_GET_MINUTE(self) - offset1) * 60 +
3482 TIME_GET_SECOND(self);
3483 offset2 = TIME_GET_HOUR(other) * 3600 +
3484 (TIME_GET_MINUTE(other) - offset2) * 60 +
3485 TIME_GET_SECOND(other);
3486 diff = offset1 - offset2;
3487 if (diff == 0)
3488 diff = TIME_GET_MICROSECOND(self) -
3489 TIME_GET_MICROSECOND(other);
3490 return diff_to_bool(diff, op);
3491 }
3492
3493 assert(n1 != n2);
3494 PyErr_SetString(PyExc_TypeError,
3495 "can't compare offset-naive and "
3496 "offset-aware times");
3497 return NULL;
3498}
3499
3500static PyObject *time_getstate(PyDateTime_Time *self);
3501
3502static long
3503time_hash(PyDateTime_Time *self)
3504{
3505 if (self->hashcode == -1) {
3506 naivety n;
3507 int offset;
3508 PyObject *temp;
3509
3510 n = classify_object((PyObject *)self, &offset);
3511 assert(n != OFFSET_UNKNOWN);
3512 if (n == OFFSET_ERROR)
3513 return -1;
3514
3515 /* Reduce this to a hash of another object. */
3516 if (offset == 0)
3517 temp = time_getstate(self);
3518 else {
3519 int hour;
3520 int minute;
3521
3522 assert(n == OFFSET_AWARE);
3523 assert(PyTimeTZ_Check(self));
3524 hour = divmod(TIME_GET_HOUR(self) * 60 +
3525 TIME_GET_MINUTE(self) - offset,
3526 60,
3527 &minute);
3528 if (0 <= hour && hour < 24)
3529 temp = new_time(hour, minute,
3530 TIME_GET_SECOND(self),
3531 TIME_GET_MICROSECOND(self));
3532 else
3533 temp = Py_BuildValue("iiii",
3534 hour, minute,
3535 TIME_GET_SECOND(self),
3536 TIME_GET_MICROSECOND(self));
3537 }
3538 if (temp != NULL) {
3539 self->hashcode = PyObject_Hash(temp);
3540 Py_DECREF(temp);
3541 }
3542 }
3543 return self->hashcode;
3544}
3545
3546static int
3547time_nonzero(PyDateTime_Time *self)
3548{
3549 return TIME_GET_HOUR(self) ||
3550 TIME_GET_MINUTE(self) ||
3551 TIME_GET_SECOND(self) ||
3552 TIME_GET_MICROSECOND(self);
3553}
3554
3555/* Pickle support. Quite a maze! */
3556
3557static PyObject *
3558time_getstate(PyDateTime_Time *self)
3559{
3560 return PyString_FromStringAndSize(self->data,
3561 _PyDateTime_TIME_DATASIZE);
3562}
3563
3564static PyObject *
3565time_setstate(PyDateTime_Time *self, PyObject *state)
3566{
3567 const int len = PyString_Size(state);
3568 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
3569
3570 if (! PyString_Check(state) ||
3571 len != _PyDateTime_TIME_DATASIZE) {
3572 PyErr_SetString(PyExc_TypeError,
3573 "bad argument to time.__setstate__");
3574 return NULL;
3575 }
3576 memcpy(self->data, pdata, _PyDateTime_TIME_DATASIZE);
3577 self->hashcode = -1;
3578
3579 Py_INCREF(Py_None);
3580 return Py_None;
3581}
3582
3583/* XXX This seems a ridiculously inefficient way to pickle a short string. */
3584static PyObject *
3585time_pickler(PyObject *module, PyDateTime_Time *time)
3586{
3587 PyObject *state;
3588 PyObject *result = NULL;
3589
3590 if (! PyTime_CheckExact(time)) {
3591 PyErr_Format(PyExc_TypeError,
3592 "bad type passed to time pickler: %s",
3593 time->ob_type->tp_name);
3594 return NULL;
3595 }
3596 state = time_getstate(time);
3597 if (state) {
3598 result = Py_BuildValue("O(O)",
3599 time_unpickler_object,
3600 state);
3601 Py_DECREF(state);
3602 }
3603 return result;
3604}
3605
3606static PyObject *
3607time_unpickler(PyObject *module, PyObject *arg)
3608{
3609 PyDateTime_Time *self;
3610
3611 if (! PyString_CheckExact(arg)) {
3612 PyErr_Format(PyExc_TypeError,
3613 "bad type passed to time unpickler: %s",
3614 arg->ob_type->tp_name);
3615 return NULL;
3616 }
3617 self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType);
3618 if (self != NULL) {
3619 PyObject *res = time_setstate(self, arg);
3620 if (res == NULL) {
3621 Py_DECREF(self);
3622 return NULL;
3623 }
3624 Py_DECREF(res);
3625 }
3626 return (PyObject *)self;
3627}
3628
3629static PyMethodDef time_methods[] = {
3630 {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
3631 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm].")},
3632
3633 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3634 PyDoc_STR("format -> strftime() style string.")},
3635
3636 {"__setstate__", (PyCFunction)time_setstate, METH_O,
3637 PyDoc_STR("__setstate__(state)")},
3638
3639 {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS,
3640 PyDoc_STR("__getstate__() -> state")},
3641 {NULL, NULL}
3642};
3643
3644static char time_doc[] =
3645PyDoc_STR("Basic time type.");
3646
3647static PyNumberMethods time_as_number = {
3648 0, /* nb_add */
3649 0, /* nb_subtract */
3650 0, /* nb_multiply */
3651 0, /* nb_divide */
3652 0, /* nb_remainder */
3653 0, /* nb_divmod */
3654 0, /* nb_power */
3655 0, /* nb_negative */
3656 0, /* nb_positive */
3657 0, /* nb_absolute */
3658 (inquiry)time_nonzero, /* nb_nonzero */
3659};
3660
3661statichere PyTypeObject PyDateTime_TimeType = {
3662 PyObject_HEAD_INIT(NULL)
3663 0, /* ob_size */
3664 "datetime.time", /* tp_name */
3665 sizeof(PyDateTime_Time), /* tp_basicsize */
3666 0, /* tp_itemsize */
3667 (destructor)PyObject_Del, /* tp_dealloc */
3668 0, /* tp_print */
3669 0, /* tp_getattr */
3670 0, /* tp_setattr */
3671 0, /* tp_compare */
3672 (reprfunc)time_repr, /* tp_repr */
3673 &time_as_number, /* tp_as_number */
3674 0, /* tp_as_sequence */
3675 0, /* tp_as_mapping */
3676 (hashfunc)time_hash, /* tp_hash */
3677 0, /* tp_call */
3678 (reprfunc)time_str, /* tp_str */
3679 PyObject_GenericGetAttr, /* tp_getattro */
3680 0, /* tp_setattro */
3681 0, /* tp_as_buffer */
3682 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3683 Py_TPFLAGS_BASETYPE, /* tp_flags */
3684 time_doc, /* tp_doc */
3685 0, /* tp_traverse */
3686 0, /* tp_clear */
3687 (richcmpfunc)time_richcompare, /* tp_richcompare */
3688 0, /* tp_weaklistoffset */
3689 0, /* tp_iter */
3690 0, /* tp_iternext */
3691 time_methods, /* tp_methods */
3692 0, /* tp_members */
3693 time_getset, /* tp_getset */
3694 0, /* tp_base */
3695 0, /* tp_dict */
3696 0, /* tp_descr_get */
3697 0, /* tp_descr_set */
3698 0, /* tp_dictoffset */
3699 0, /* tp_init */
3700 0, /* tp_alloc */
3701 time_new, /* tp_new */
3702 _PyObject_Del, /* tp_free */
3703};
3704
3705/*
3706 * PyDateTime_TZInfo implementation.
3707 */
3708
3709/* This is a pure abstract base class, so doesn't do anything beyond
3710 * raising NotImplemented exceptions. Real tzinfo classes need
3711 * to derive from this. This is mostly for clarity, and for efficiency in
3712 * datetimetz and timetz constructors (their tzinfo arguments need to
3713 * be subclasses of this tzinfo class, which is easy and quick to check).
3714 *
3715 * Note: For reasons having to do with pickling of subclasses, we have
3716 * to allow tzinfo objects to be instantiated. This wasn't an issue
3717 * in the Python implementation (__init__() could raise NotImplementedError
3718 * there without ill effect), but doing so in the C implementation hit a
3719 * brick wall.
3720 */
3721
3722static PyObject *
3723tzinfo_nogo(const char* methodname)
3724{
3725 PyErr_Format(PyExc_NotImplementedError,
3726 "a tzinfo subclass must implement %s()",
3727 methodname);
3728 return NULL;
3729}
3730
3731/* Methods. A subclass must implement these. */
3732
3733static PyObject*
3734tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3735{
3736 return tzinfo_nogo("tzname");
3737}
3738
3739static PyObject*
3740tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3741{
3742 return tzinfo_nogo("utcoffset");
3743}
3744
3745static PyObject*
3746tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3747{
3748 return tzinfo_nogo("dst");
3749}
3750
3751/*
3752 * Pickle support. This is solely so that tzinfo subclasses can use
3753 * pickling -- tzinfo itself is supposed to be uninstantiable. The
3754 * pickler and unpickler functions are given module-level private
3755 * names, and registered with copy_reg, by the module init function.
3756 */
3757
3758static PyObject*
3759tzinfo_pickler(PyDateTime_TZInfo *self) {
3760 return Py_BuildValue("O()", tzinfo_unpickler_object);
3761}
3762
3763static PyObject*
3764tzinfo_unpickler(PyObject * unused) {
3765 return PyType_GenericNew(&PyDateTime_TZInfoType, NULL, NULL);
3766}
3767
3768
3769static PyMethodDef tzinfo_methods[] = {
3770 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3771 PyDoc_STR("datetime -> string name of time zone.")},
3772
3773 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
3774 PyDoc_STR("datetime -> minutes east of UTC (negative for "
3775 "west of UTC).")},
3776
3777 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3778 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
3779
3780 {NULL, NULL}
3781};
3782
3783static char tzinfo_doc[] =
3784PyDoc_STR("Abstract base class for time zone info objects.");
3785
3786 statichere PyTypeObject PyDateTime_TZInfoType = {
3787 PyObject_HEAD_INIT(NULL)
3788 0, /* ob_size */
3789 "datetime.tzinfo", /* tp_name */
3790 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3791 0, /* tp_itemsize */
3792 0, /* tp_dealloc */
3793 0, /* tp_print */
3794 0, /* tp_getattr */
3795 0, /* tp_setattr */
3796 0, /* tp_compare */
3797 0, /* tp_repr */
3798 0, /* tp_as_number */
3799 0, /* tp_as_sequence */
3800 0, /* tp_as_mapping */
3801 0, /* tp_hash */
3802 0, /* tp_call */
3803 0, /* tp_str */
3804 PyObject_GenericGetAttr, /* tp_getattro */
3805 0, /* tp_setattro */
3806 0, /* tp_as_buffer */
3807 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3808 Py_TPFLAGS_BASETYPE, /* tp_flags */
3809 tzinfo_doc, /* tp_doc */
3810 0, /* tp_traverse */
3811 0, /* tp_clear */
3812 0, /* tp_richcompare */
3813 0, /* tp_weaklistoffset */
3814 0, /* tp_iter */
3815 0, /* tp_iternext */
3816 tzinfo_methods, /* tp_methods */
3817 0, /* tp_members */
3818 0, /* tp_getset */
3819 0, /* tp_base */
3820 0, /* tp_dict */
3821 0, /* tp_descr_get */
3822 0, /* tp_descr_set */
3823 0, /* tp_dictoffset */
3824 0, /* tp_init */
3825 0, /* tp_alloc */
3826 PyType_GenericNew, /* tp_new */
3827 0, /* tp_free */
3828};
3829
3830/*
3831 * PyDateTime_TimeTZ implementation.
3832 */
3833
3834/* Accessor properties. Properties for hour, minute, second and microsecond
3835 * are inherited from time.
3836 */
3837
3838static PyObject *
3839timetz_tzinfo(PyDateTime_TimeTZ *self, void *unused)
3840{
3841 Py_INCREF(self->tzinfo);
3842 return self->tzinfo;
3843}
3844
3845static PyGetSetDef timetz_getset[] = {
3846 {"tzinfo", (getter)timetz_tzinfo},
3847 {NULL}
3848};
3849
3850/*
3851 * Constructors.
3852 */
3853
3854static PyObject *
3855timetz_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3856{
3857 PyObject *self = NULL;
3858 int hour = 0;
3859 int minute = 0;
3860 int second = 0;
3861 int usecond = 0;
3862 PyObject *tzinfo = Py_None;
3863
3864 static char *keywords[] = {
3865 "hour", "minute", "second", "microsecond", "tzinfo", NULL
3866 };
3867
3868 if (PyArg_ParseTupleAndKeywords(args, kw, "|llllO", keywords,
3869 &hour, &minute, &second, &usecond,
3870 &tzinfo)) {
3871 if (check_time_args(hour, minute, second, usecond) < 0)
3872 return NULL;
3873 if (check_tzinfo_subclass(tzinfo) < 0)
3874 return NULL;
3875 self = new_timetz(hour, minute, second, usecond, tzinfo);
3876 }
3877 return self;
3878}
3879
3880/*
3881 * Destructor.
3882 */
3883
3884static void
3885timetz_dealloc(PyDateTime_TimeTZ *self)
3886{
3887 Py_XDECREF(self->tzinfo);
3888 self->ob_type->tp_free((PyObject *)self);
3889}
3890
3891/*
3892 * Indirect access to tzinfo methods. One more "convenience function" and
3893 * it won't be possible to find the useful methods anymore <0.5 wink>.
3894 */
3895
3896static PyObject *
3897timetz_convienience(PyDateTime_TimeTZ *self, char *name)
3898{
3899 PyObject *result;
3900
3901 if (self->tzinfo == Py_None) {
3902 result = Py_None;
3903 Py_INCREF(result);
3904 }
3905 else
3906 result = PyObject_CallMethod(self->tzinfo, name, "O", self);
3907 return result;
3908}
3909
3910/* These are all METH_NOARGS, so don't need to check the arglist. */
3911static PyObject *
3912timetz_utcoffset(PyDateTime_TimeTZ *self, PyObject *unused) {
3913 return timetz_convienience(self, "utcoffset");
3914}
3915
3916static PyObject *
3917timetz_tzname(PyDateTime_TimeTZ *self, PyObject *unused) {
3918 return timetz_convienience(self, "tzname");
3919}
3920
3921static PyObject *
3922timetz_dst(PyDateTime_TimeTZ *self, PyObject *unused) {
3923 return timetz_convienience(self, "dst");
3924}
3925
3926/*
3927 * Various ways to turn a timetz into a string.
3928 */
3929
3930static PyObject *
3931timetz_repr(PyDateTime_TimeTZ *self)
3932{
3933 PyObject *baserepr = time_repr((PyDateTime_Time *)self);
3934
3935 if (baserepr == NULL)
3936 return NULL;
3937 return append_keyword_tzinfo(baserepr, self->tzinfo);
3938}
3939
3940/* Note: tp_str is inherited from time. */
3941
3942static PyObject *
3943timetz_isoformat(PyDateTime_TimeTZ *self)
3944{
3945 char buf[100];
3946 PyObject *result = time_isoformat((PyDateTime_Time *)self);
3947
3948 if (result == NULL || self->tzinfo == Py_None)
3949 return result;
3950
3951 /* We need to append the UTC offset. */
3952 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3953 (PyObject *)self) < 0) {
3954 Py_DECREF(result);
3955 return NULL;
3956 }
3957 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3958 return result;
3959}
3960
3961/* Note: strftime() is inherited from time. */
3962
3963/*
3964 * Miscellaneous methods.
3965 */
3966
3967/* Note: tp_richcompare and tp_hash are inherited from time. */
3968
3969static int
3970timetz_nonzero(PyDateTime_TimeTZ *self)
3971{
3972 int offset;
3973 int none;
3974
3975 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3976 /* Since utcoffset is in whole minutes, nothing can
3977 * alter the conclusion that this is nonzero.
3978 */
3979 return 1;
3980 }
3981 offset = 0;
3982 if (self->tzinfo != Py_None) {
3983 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
3984 if (offset == -1 && PyErr_Occurred())
3985 return -1;
3986 }
3987 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3988}
3989
3990/*
3991 * Pickle support. Quite a maze!
3992 */
3993
3994/* Let basestate be the state string returned by time_getstate.
3995 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3996 * So it's a tuple in any (non-error) case.
3997 */
3998static PyObject *
3999timetz_getstate(PyDateTime_TimeTZ *self)
4000{
4001 PyObject *basestate;
4002 PyObject *result = NULL;
4003
4004 basestate = time_getstate((PyDateTime_Time *)self);
4005 if (basestate != NULL) {
4006 if (self->tzinfo == Py_None)
4007 result = Py_BuildValue("(O)", basestate);
4008 else
4009 result = Py_BuildValue("OO", basestate, self->tzinfo);
4010 Py_DECREF(basestate);
4011 }
4012 return result;
4013}
4014
4015static PyObject *
4016timetz_setstate(PyDateTime_TimeTZ *self, PyObject *state)
4017{
4018 PyObject *temp;
4019 PyObject *basestate;
4020 PyObject *tzinfo = Py_None;
4021
4022 if (! PyArg_ParseTuple(state, "O!|O:__setstate__",
4023 &PyString_Type, &basestate,
4024 &tzinfo))
4025 return NULL;
4026 temp = time_setstate((PyDateTime_Time *)self, basestate);
4027 if (temp == NULL)
4028 return NULL;
4029 Py_DECREF(temp);
4030
4031 Py_INCREF(tzinfo);
4032 Py_XDECREF(self->tzinfo);
4033 self->tzinfo = tzinfo;
4034
4035 Py_INCREF(Py_None);
4036 return Py_None;
4037}
4038
4039static PyObject *
4040timetz_pickler(PyObject *module, PyDateTime_TimeTZ *timetz)
4041{
4042 PyObject *state;
4043 PyObject *result = NULL;
4044
4045 if (! PyTimeTZ_CheckExact(timetz)) {
4046 PyErr_Format(PyExc_TypeError,
4047 "bad type passed to timetz pickler: %s",
4048 timetz->ob_type->tp_name);
4049 return NULL;
4050 }
4051 state = timetz_getstate(timetz);
4052 if (state) {
4053 result = Py_BuildValue("O(O)",
4054 timetz_unpickler_object,
4055 state);
4056 Py_DECREF(state);
4057 }
4058 return result;
4059}
4060
4061static PyObject *
4062timetz_unpickler(PyObject *module, PyObject *arg)
4063{
4064 PyDateTime_TimeTZ *self;
4065
4066 self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType);
4067 if (self != NULL) {
4068 PyObject *res;
4069
4070 self->tzinfo = NULL;
4071 res = timetz_setstate(self, arg);
4072 if (res == NULL) {
4073 Py_DECREF(self);
4074 return NULL;
4075 }
4076 Py_DECREF(res);
4077 }
4078 return (PyObject *)self;
4079}
4080
4081static PyMethodDef timetz_methods[] = {
4082 {"isoformat", (PyCFunction)timetz_isoformat, METH_KEYWORDS,
4083 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
4084 "[+HH:MM].")},
4085
4086 {"utcoffset", (PyCFunction)timetz_utcoffset, METH_NOARGS,
4087 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4088
4089 {"tzname", (PyCFunction)timetz_tzname, METH_NOARGS,
4090 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4091
4092 {"dst", (PyCFunction)timetz_dst, METH_NOARGS,
4093 PyDoc_STR("Return self.tzinfo.dst(self).")},
4094
4095 {"__setstate__", (PyCFunction)timetz_setstate, METH_O,
4096 PyDoc_STR("__setstate__(state)")},
4097
4098 {"__getstate__", (PyCFunction)timetz_getstate, METH_NOARGS,
4099 PyDoc_STR("__getstate__() -> state")},
4100 {NULL, NULL}
4101
4102};
4103
4104static char timetz_doc[] =
4105PyDoc_STR("Time type.");
4106
4107static PyNumberMethods timetz_as_number = {
4108 0, /* nb_add */
4109 0, /* nb_subtract */
4110 0, /* nb_multiply */
4111 0, /* nb_divide */
4112 0, /* nb_remainder */
4113 0, /* nb_divmod */
4114 0, /* nb_power */
4115 0, /* nb_negative */
4116 0, /* nb_positive */
4117 0, /* nb_absolute */
4118 (inquiry)timetz_nonzero, /* nb_nonzero */
4119};
4120
4121statichere PyTypeObject PyDateTime_TimeTZType = {
4122 PyObject_HEAD_INIT(NULL)
4123 0, /* ob_size */
4124 "datetime.timetz", /* tp_name */
4125 sizeof(PyDateTime_TimeTZ), /* tp_basicsize */
4126 0, /* tp_itemsize */
4127 (destructor)timetz_dealloc, /* tp_dealloc */
4128 0, /* tp_print */
4129 0, /* tp_getattr */
4130 0, /* tp_setattr */
4131 0, /* tp_compare */
4132 (reprfunc)timetz_repr, /* tp_repr */
4133 &timetz_as_number, /* tp_as_number */
4134 0, /* tp_as_sequence */
4135 0, /* tp_as_mapping */
4136 0, /* tp_hash */
4137 0, /* tp_call */
4138 0, /* tp_str */
4139 PyObject_GenericGetAttr, /* tp_getattro */
4140 0, /* tp_setattro */
4141 0, /* tp_as_buffer */
4142 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4143 Py_TPFLAGS_BASETYPE, /* tp_flags */
4144 time_doc, /* tp_doc */
4145 0, /* tp_traverse */
4146 0, /* tp_clear */
4147 0, /* tp_richcompare */
4148 0, /* tp_weaklistoffset */
4149 0, /* tp_iter */
4150 0, /* tp_iternext */
4151 timetz_methods, /* tp_methods */
4152 0, /* tp_members */
4153 timetz_getset, /* tp_getset */
4154 &PyDateTime_TimeType, /* tp_base */
4155 0, /* tp_dict */
4156 0, /* tp_descr_get */
4157 0, /* tp_descr_set */
4158 0, /* tp_dictoffset */
4159 0, /* tp_init */
4160 0, /* tp_alloc */
4161 timetz_new, /* tp_new */
4162 _PyObject_Del, /* tp_free */
4163};
4164
4165/*
4166 * PyDateTime_DateTimeTZ implementation.
4167 */
4168
4169/* Accessor properties. Properties for day, month, year, hour, minute,
4170 * second and microsecond are inherited from datetime.
4171 */
4172
4173static PyObject *
4174datetimetz_tzinfo(PyDateTime_DateTimeTZ *self, void *unused)
4175{
4176 Py_INCREF(self->tzinfo);
4177 return self->tzinfo;
4178}
4179
4180static PyGetSetDef datetimetz_getset[] = {
4181 {"tzinfo", (getter)datetimetz_tzinfo},
4182 {NULL}
4183};
4184
4185/*
4186 * Constructors.
4187 * These are like the datetime methods of the same names, but allow an
4188 * optional tzinfo argument.
4189 */
4190
4191/* Internal helper.
4192 * self is a datetimetz. Replace its tzinfo member.
4193 */
4194void
4195replace_tzinfo(PyObject *self, PyObject *newtzinfo)
4196{
4197 assert(self != NULL);
4198 assert(newtzinfo != NULL);
4199 assert(PyDateTimeTZ_Check(self));
4200 Py_INCREF(newtzinfo);
4201 Py_DECREF(((PyDateTime_DateTimeTZ *)self)->tzinfo);
4202 ((PyDateTime_DateTimeTZ *)self)->tzinfo = newtzinfo;
4203}
4204
4205static PyObject *
4206datetimetz_new(PyTypeObject *type, PyObject *args, PyObject *kw)
4207{
4208 PyObject *self = NULL;
4209 int year;
4210 int month;
4211 int day;
4212 int hour = 0;
4213 int minute = 0;
4214 int second = 0;
4215 int usecond = 0;
4216 PyObject *tzinfo = Py_None;
4217
4218 static char *keywords[] = {
4219 "year", "month", "day", "hour", "minute", "second",
4220 "microsecond", "tzinfo", NULL
4221 };
4222
4223 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", keywords,
4224 &year, &month, &day, &hour, &minute,
4225 &second, &usecond, &tzinfo)) {
4226 if (check_date_args(year, month, day) < 0)
4227 return NULL;
4228 if (check_time_args(hour, minute, second, usecond) < 0)
4229 return NULL;
4230 if (check_tzinfo_subclass(tzinfo) < 0)
4231 return NULL;
4232 self = new_datetimetz(year, month, day,
4233 hour, minute, second, usecond,
4234 tzinfo);
4235 }
4236 return self;
4237}
4238
4239/* Return best possible local time -- this isn't constrained by the
4240 * precision of a timestamp.
4241 */
4242static PyObject *
4243datetimetz_now(PyObject *cls, PyObject *args, PyObject *kw)
4244{
4245 PyObject *self = NULL;
4246 PyObject *tzinfo = Py_None;
4247 static char *keywords[] = {"tzinfo", NULL};
4248
4249 if (PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
4250 &tzinfo)) {
4251 if (check_tzinfo_subclass(tzinfo) < 0)
4252 return NULL;
4253 self = datetime_best_possible(cls, localtime);
4254 if (self != NULL)
4255 replace_tzinfo(self, tzinfo);
4256 }
4257 return self;
4258}
4259
4260/* Return new local datetime from timestamp (Python timestamp -- a double). */
4261static PyObject *
4262datetimetz_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
4263{
4264 PyObject *self = NULL;
4265 double timestamp;
4266 PyObject *tzinfo = Py_None;
4267 static char *keywords[] = {"timestamp", "tzinfo", NULL};
4268
4269 if (PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
4270 keywords, &timestamp, &tzinfo)) {
4271 if (check_tzinfo_subclass(tzinfo) < 0)
4272 return NULL;
4273 self = datetime_from_timestamp(cls, localtime, timestamp);
4274 if (self != NULL)
4275 replace_tzinfo(self, tzinfo);
4276 }
4277 return self;
4278}
4279
4280/* Note: utcnow() is inherited, and doesn't accept tzinfo.
4281 * Ditto utcfromtimestamp(). Ditto combine().
4282 */
4283
4284
4285/*
4286 * Destructor.
4287 */
4288
4289static void
4290datetimetz_dealloc(PyDateTime_DateTimeTZ *self)
4291{
4292 Py_XDECREF(self->tzinfo);
4293 self->ob_type->tp_free((PyObject *)self);
4294}
4295
4296/*
4297 * Indirect access to tzinfo methods.
4298 */
4299
4300/* Internal helper.
4301 * Call a tzinfo object's method, or return None if tzinfo is None.
4302 */
4303static PyObject *
4304datetimetz_convienience(PyDateTime_DateTimeTZ *self, char *name)
4305{
4306 PyObject *result;
4307
4308 if (self->tzinfo == Py_None) {
4309 result = Py_None;
4310 Py_INCREF(result);
4311 }
4312 else
4313 result = PyObject_CallMethod(self->tzinfo, name, "O", self);
4314 return result;
4315}
4316
4317/* These are all METH_NOARGS, so don't need to check the arglist. */
4318static PyObject *
4319datetimetz_utcoffset(PyDateTime_DateTimeTZ *self, PyObject *unused) {
4320 return datetimetz_convienience(self, "utcoffset");
4321}
4322
4323static PyObject *
4324datetimetz_tzname(PyDateTime_DateTimeTZ *self, PyObject *unused) {
4325 return datetimetz_convienience(self, "tzname");
4326}
4327
4328static PyObject *
4329datetimetz_dst(PyDateTime_DateTimeTZ *self, PyObject *unused) {
4330 return datetimetz_convienience(self, "dst");
4331}
4332
4333/*
4334 * datetimetz arithmetic.
4335 */
4336
4337/* If base is Py_NotImplemented or NULL, just return it.
4338 * Else base is a datetime, exactly one of {left, right} is a datetimetz,
4339 * and we want to create a datetimetz with the same date and time fields
4340 * as base, and with the tzinfo field from left or right. Do that,
4341 * return it, and decref base. This is used to transform the result of
4342 * a binary datetime operation (base) into a datetimetz result.
4343 */
4344static PyObject *
4345attach_tzinfo(PyObject *base, PyObject *left, PyObject *right)
4346{
4347 PyDateTime_DateTimeTZ *self;
4348 PyDateTime_DateTimeTZ *result;
4349
4350 if (base == NULL || base == Py_NotImplemented)
4351 return base;
4352
4353 assert(PyDateTime_CheckExact(base));
4354
4355 if (PyDateTimeTZ_Check(left)) {
4356 assert(! PyDateTimeTZ_Check(right));
4357 self = (PyDateTime_DateTimeTZ *)left;
4358 }
4359 else {
4360 assert(PyDateTimeTZ_Check(right));
4361 self = (PyDateTime_DateTimeTZ *)right;
4362 }
4363 result = PyObject_New(PyDateTime_DateTimeTZ,
4364 &PyDateTime_DateTimeTZType);
4365 if (result != NULL) {
4366 memcpy(result->data, ((PyDateTime_DateTime *)base)->data,
4367 _PyDateTime_DATETIME_DATASIZE);
4368 Py_INCREF(self->tzinfo);
4369 result->tzinfo = self->tzinfo;
4370 }
4371 Py_DECREF(base);
4372 return (PyObject *)result;
4373}
4374
4375static PyObject *
4376datetimetz_add(PyObject *left, PyObject *right)
4377{
4378 return attach_tzinfo(datetime_add(left, right), left, right);
4379}
4380
4381static PyObject *
4382datetimetz_subtract(PyObject *left, PyObject *right)
4383{
4384 PyObject *result = Py_NotImplemented;
4385
4386 if (PyDateTime_Check(left)) {
4387 /* datetime - ??? */
4388 if (PyDateTime_Check(right)) {
4389 /* datetime - datetime */
4390 naivety n1, n2;
4391 int offset1, offset2;
4392 PyDateTime_Delta *delta;
4393
4394 n1 = classify_object(left, &offset1);
4395 assert(n1 != OFFSET_UNKNOWN);
4396 if (n1 == OFFSET_ERROR)
4397 return NULL;
4398
4399 n2 = classify_object(right, &offset2);
4400 assert(n2 != OFFSET_UNKNOWN);
4401 if (n2 == OFFSET_ERROR)
4402 return NULL;
4403
4404 if (n1 != n2) {
4405 PyErr_SetString(PyExc_TypeError,
4406 "can't subtract offset-naive and "
4407 "offset-aware datetimes");
4408 return NULL;
4409 }
4410 delta = (PyDateTime_Delta *)sub_datetime_datetime(
4411 (PyDateTime_DateTime *)left,
4412 (PyDateTime_DateTime *)right);
4413 if (delta == NULL || offset1 == offset2)
4414 return (PyObject *)delta;
4415 /* (left - offset1) - (right - offset2) =
4416 * (left - right) + (offset2 - offset1)
4417 */
4418 result = new_delta(delta->days,
4419 delta->seconds +
4420 (offset2 - offset1) * 60,
4421 delta->microseconds,
4422 1);
4423 Py_DECREF(delta);
4424 }
4425 else if (PyDelta_Check(right)) {
4426 /* datetimetz - delta */
4427 result = sub_datetime_timedelta(
4428 (PyDateTime_DateTime *)left,
4429 (PyDateTime_Delta *)right);
4430 result = attach_tzinfo(result, left, right);
4431 }
4432 }
4433
4434 if (result == Py_NotImplemented)
4435 Py_INCREF(result);
4436 return result;
4437}
4438
4439/* Various ways to turn a datetime into a string. */
4440
4441static PyObject *
4442datetimetz_repr(PyDateTime_DateTimeTZ *self)
4443{
4444 PyObject *baserepr = datetime_repr((PyDateTime_DateTime *)self);
4445
4446 if (baserepr == NULL)
4447 return NULL;
4448 return append_keyword_tzinfo(baserepr, self->tzinfo);
4449}
4450
4451/* Note: tp_str is inherited from datetime. */
4452
4453static PyObject *
4454datetimetz_isoformat(PyDateTime_DateTimeTZ *self,
4455 PyObject *args, PyObject *kw)
4456{
4457 char buf[100];
4458 PyObject *result = datetime_isoformat((PyDateTime_DateTime *)self,
4459 args, kw);
4460
4461 if (result == NULL || self->tzinfo == Py_None)
4462 return result;
4463
4464 /* We need to append the UTC offset. */
4465 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4466 (PyObject *)self) < 0) {
4467 Py_DECREF(result);
4468 return NULL;
4469 }
4470 PyString_ConcatAndDel(&result, PyString_FromString(buf));
4471 return result;
4472}
4473
4474/* Miscellaneous methods. */
4475
4476/* Note: tp_richcompare and tp_hash are inherited from datetime. */
4477
4478static PyObject *
4479datetimetz_timetuple(PyDateTime_DateTimeTZ *self)
4480{
4481 int dstflag = -1;
4482
4483 if (self->tzinfo != Py_None) {
4484 int none;
4485
4486 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4487 if (dstflag == -1 && PyErr_Occurred())
4488 return NULL;
4489
4490 if (none)
4491 dstflag = -1;
4492 else if (dstflag != 0)
4493 dstflag = 1;
4494
4495 }
4496 return build_struct_time(GET_YEAR(self),
4497 GET_MONTH(self),
4498 GET_DAY(self),
4499 DATE_GET_HOUR(self),
4500 DATE_GET_MINUTE(self),
4501 DATE_GET_SECOND(self),
4502 dstflag);
4503}
4504
4505static PyObject *
4506datetimetz_utctimetuple(PyDateTime_DateTimeTZ *self)
4507{
4508 int y = GET_YEAR(self);
4509 int m = GET_MONTH(self);
4510 int d = GET_DAY(self);
4511 int hh = DATE_GET_HOUR(self);
4512 int mm = DATE_GET_MINUTE(self);
4513 int ss = DATE_GET_SECOND(self);
4514 int us = 0; /* microseconds are ignored in a timetuple */
4515 int offset = 0;
4516
4517 if (self->tzinfo != Py_None) {
4518 int none;
4519
4520 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4521 if (offset == -1 && PyErr_Occurred())
4522 return NULL;
4523 }
4524 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4525 * 0 in a UTC timetuple regardless of what dst() says.
4526 */
4527 if (offset) {
4528 /* Subtract offset minutes & normalize. */
4529 int stat;
4530
4531 mm -= offset;
4532 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4533 if (stat < 0) {
4534 /* At the edges, it's possible we overflowed
4535 * beyond MINYEAR or MAXYEAR.
4536 */
4537 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4538 PyErr_Clear();
4539 else
4540 return NULL;
4541 }
4542 }
4543 return build_struct_time(y, m, d, hh, mm, ss, 0);
4544}
4545
4546static PyObject *
4547datetimetz_gettimetz(PyDateTime_DateTimeTZ *self)
4548{
4549 return new_timetz(DATE_GET_HOUR(self),
4550 DATE_GET_MINUTE(self),
4551 DATE_GET_SECOND(self),
4552 DATE_GET_MICROSECOND(self),
4553 self->tzinfo);
4554}
4555
4556/*
4557 * Pickle support. Quite a maze!
4558 */
4559
4560/* Let basestate be the state string returned by datetime_getstate.
4561 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4562 * So it's a tuple in any (non-error) case.
4563 */
4564static PyObject *
4565datetimetz_getstate(PyDateTime_DateTimeTZ *self)
4566{
4567 PyObject *basestate;
4568 PyObject *result = NULL;
4569
4570 basestate = datetime_getstate((PyDateTime_DateTime *)self);
4571 if (basestate != NULL) {
4572 if (self->tzinfo == Py_None)
4573 result = Py_BuildValue("(O)", basestate);
4574 else
4575 result = Py_BuildValue("OO", basestate, self->tzinfo);
4576 Py_DECREF(basestate);
4577 }
4578 return result;
4579}
4580
4581static PyObject *
4582datetimetz_setstate(PyDateTime_DateTimeTZ *self, PyObject *state)
4583{
4584 PyObject *temp;
4585 PyObject *basestate;
4586 PyObject *tzinfo = Py_None;
4587
4588 if (! PyArg_ParseTuple(state, "O!|O:__setstate__",
4589 &PyString_Type, &basestate,
4590 &tzinfo))
4591 return NULL;
4592 temp = datetime_setstate((PyDateTime_DateTime *)self, basestate);
4593 if (temp == NULL)
4594 return NULL;
4595 Py_DECREF(temp);
4596
4597 Py_INCREF(tzinfo);
4598 Py_XDECREF(self->tzinfo);
4599 self->tzinfo = tzinfo;
4600
4601 Py_INCREF(Py_None);
4602 return Py_None;
4603}
4604
4605static PyObject *
4606datetimetz_pickler(PyObject *module, PyDateTime_DateTimeTZ *datetimetz)
4607{
4608 PyObject *state;
4609 PyObject *result = NULL;
4610
4611 if (! PyDateTimeTZ_CheckExact(datetimetz)) {
4612 PyErr_Format(PyExc_TypeError,
4613 "bad type passed to datetimetz pickler: %s",
4614 datetimetz->ob_type->tp_name);
4615 return NULL;
4616 }
4617 state = datetimetz_getstate(datetimetz);
4618 if (state) {
4619 result = Py_BuildValue("O(O)",
4620 datetimetz_unpickler_object,
4621 state);
4622 Py_DECREF(state);
4623 }
4624 return result;
4625}
4626
4627static PyObject *
4628datetimetz_unpickler(PyObject *module, PyObject *arg)
4629{
4630 PyDateTime_DateTimeTZ *self;
4631
4632 self = PyObject_New(PyDateTime_DateTimeTZ, &PyDateTime_DateTimeTZType);
4633 if (self != NULL) {
4634 PyObject *res;
4635
4636 self->tzinfo = NULL;
4637 res = datetimetz_setstate(self, arg);
4638 if (res == NULL) {
4639 Py_DECREF(self);
4640 return NULL;
4641 }
4642 Py_DECREF(res);
4643 }
4644 return (PyObject *)self;
4645}
4646
4647
4648static PyMethodDef datetimetz_methods[] = {
4649 /* Class methods: */
4650 /* Inherited: combine(), utcnow(), utcfromtimestamp() */
4651
4652 {"now", (PyCFunction)datetimetz_now,
4653 METH_KEYWORDS | METH_CLASS,
4654 PyDoc_STR("[tzinfo] -> new datetimetz with local day and time.")},
4655
4656 {"fromtimestamp", (PyCFunction)datetimetz_fromtimestamp,
4657 METH_KEYWORDS | METH_CLASS,
4658 PyDoc_STR("timestamp[, tzinfo] -> local time from POSIX timestamp.")},
4659
4660 /* Instance methods: */
4661 /* Inherited: date(), time(), ctime(). */
4662 {"timetuple", (PyCFunction)datetimetz_timetuple, METH_NOARGS,
4663 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4664
4665 {"utctimetuple", (PyCFunction)datetimetz_utctimetuple, METH_NOARGS,
4666 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4667
4668 {"timetz", (PyCFunction)datetimetz_gettimetz, METH_NOARGS,
4669 PyDoc_STR("Return timetz object with same hour, minute, second, "
4670 "microsecond, and tzinfo.")},
4671
4672 {"isoformat", (PyCFunction)datetimetz_isoformat, METH_KEYWORDS,
4673 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4674 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4675 "sep is used to separate the year from the time, and "
4676 "defaults to 'T'.")},
4677
4678 {"utcoffset", (PyCFunction)datetimetz_utcoffset, METH_NOARGS,
4679 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4680
4681 {"tzname", (PyCFunction)datetimetz_tzname, METH_NOARGS,
4682 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4683
4684 {"dst", (PyCFunction)datetimetz_dst, METH_NOARGS,
4685 PyDoc_STR("Return self.tzinfo.dst(self).")},
4686
4687 {"__setstate__", (PyCFunction)datetimetz_setstate, METH_O,
4688 PyDoc_STR("__setstate__(state)")},
4689
4690 {"__getstate__", (PyCFunction)datetimetz_getstate, METH_NOARGS,
4691 PyDoc_STR("__getstate__() -> state")},
4692 {NULL, NULL}
4693};
4694
4695static char datetimetz_doc[] =
4696PyDoc_STR("date/time type.");
4697
4698static PyNumberMethods datetimetz_as_number = {
4699 datetimetz_add, /* nb_add */
4700 datetimetz_subtract, /* nb_subtract */
4701 0, /* nb_multiply */
4702 0, /* nb_divide */
4703 0, /* nb_remainder */
4704 0, /* nb_divmod */
4705 0, /* nb_power */
4706 0, /* nb_negative */
4707 0, /* nb_positive */
4708 0, /* nb_absolute */
4709 0, /* nb_nonzero */
4710};
4711
4712statichere PyTypeObject PyDateTime_DateTimeTZType = {
4713 PyObject_HEAD_INIT(NULL)
4714 0, /* ob_size */
4715 "datetime.datetimetz", /* tp_name */
4716 sizeof(PyDateTime_DateTimeTZ), /* tp_basicsize */
4717 0, /* tp_itemsize */
4718 (destructor)datetimetz_dealloc, /* tp_dealloc */
4719 0, /* tp_print */
4720 0, /* tp_getattr */
4721 0, /* tp_setattr */
4722 0, /* tp_compare */
4723 (reprfunc)datetimetz_repr, /* tp_repr */
4724 &datetimetz_as_number, /* tp_as_number */
4725 0, /* tp_as_sequence */
4726 0, /* tp_as_mapping */
4727 0, /* tp_hash */
4728 0, /* tp_call */
4729 0, /* tp_str */
4730 PyObject_GenericGetAttr, /* tp_getattro */
4731 0, /* tp_setattro */
4732 0, /* tp_as_buffer */
4733 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4734 Py_TPFLAGS_BASETYPE, /* tp_flags */
4735 datetimetz_doc, /* tp_doc */
4736 0, /* tp_traverse */
4737 0, /* tp_clear */
4738 0, /* tp_richcompare */
4739 0, /* tp_weaklistoffset */
4740 0, /* tp_iter */
4741 0, /* tp_iternext */
4742 datetimetz_methods, /* tp_methods */
4743 0, /* tp_members */
4744 datetimetz_getset, /* tp_getset */
4745 &PyDateTime_DateTimeType, /* tp_base */
4746 0, /* tp_dict */
4747 0, /* tp_descr_get */
4748 0, /* tp_descr_set */
4749 0, /* tp_dictoffset */
4750 0, /* tp_init */
4751 0, /* tp_alloc */
4752 datetimetz_new, /* tp_new */
4753 _PyObject_Del, /* tp_free */
4754};
4755
4756/* ---------------------------------------------------------------------------
4757 * Module methods and initialization.
4758 */
4759
4760static PyMethodDef module_methods[] = {
4761 /* Private functions for pickling support, registered with the
4762 * copy_reg module by the module init function.
4763 */
4764 {"_date_pickler", (PyCFunction)date_pickler, METH_O, NULL},
4765 {"_date_unpickler", (PyCFunction)date_unpickler, METH_O, NULL},
4766 {"_datetime_pickler", (PyCFunction)datetime_pickler, METH_O, NULL},
4767 {"_datetime_unpickler", (PyCFunction)datetime_unpickler,METH_O, NULL},
4768 {"_datetimetz_pickler", (PyCFunction)datetimetz_pickler,METH_O, NULL},
4769 {"_datetimetz_unpickler",(PyCFunction)datetimetz_unpickler,METH_O, NULL},
4770 {"_time_pickler", (PyCFunction)time_pickler, METH_O, NULL},
4771 {"_time_unpickler", (PyCFunction)time_unpickler, METH_O, NULL},
4772 {"_timetz_pickler", (PyCFunction)timetz_pickler, METH_O, NULL},
4773 {"_timetz_unpickler", (PyCFunction)timetz_unpickler, METH_O, NULL},
4774 {"_tzinfo_pickler", (PyCFunction)tzinfo_pickler, METH_O, NULL},
4775 {"_tzinfo_unpickler", (PyCFunction)tzinfo_unpickler, METH_NOARGS,
4776 NULL},
4777 {NULL, NULL}
4778};
4779
4780PyMODINIT_FUNC
4781initdatetime(void)
4782{
4783 PyObject *m; /* a module object */
4784 PyObject *d; /* its dict */
4785 PyObject *x;
4786
4787 /* Types that use __reduce__ for pickling need to set the following
4788 * magical attr in the type dict, with a true value.
4789 */
4790 PyObject *safepickle = PyString_FromString("__safe_for_unpickling__");
4791 if (safepickle == NULL)
4792 return;
4793
4794 m = Py_InitModule3("datetime", module_methods,
4795 "Fast implementation of the datetime type.");
4796
4797 if (PyType_Ready(&PyDateTime_DateType) < 0)
4798 return;
4799 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4800 return;
4801 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4802 return;
4803 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4804 return;
4805 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4806 return;
4807 if (PyType_Ready(&PyDateTime_TimeTZType) < 0)
4808 return;
4809 if (PyType_Ready(&PyDateTime_DateTimeTZType) < 0)
4810 return;
4811
4812 /* Pickling support, via registering functions with copy_reg. */
4813 {
4814 PyObject *pickler;
4815 PyObject *copyreg = PyImport_ImportModule("copy_reg");
4816
4817 if (copyreg == NULL) return;
4818
4819 pickler = PyObject_GetAttrString(m, "_date_pickler");
4820 if (pickler == NULL) return;
4821 date_unpickler_object = PyObject_GetAttrString(m,
4822 "_date_unpickler");
4823 if (date_unpickler_object == NULL) return;
4824 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4825 &PyDateTime_DateType,
4826 pickler,
4827 date_unpickler_object);
4828 if (x == NULL) return;
4829 Py_DECREF(x);
4830 Py_DECREF(pickler);
4831
4832 pickler = PyObject_GetAttrString(m, "_datetime_pickler");
4833 if (pickler == NULL) return;
4834 datetime_unpickler_object = PyObject_GetAttrString(m,
4835 "_datetime_unpickler");
4836 if (datetime_unpickler_object == NULL) return;
4837 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4838 &PyDateTime_DateTimeType,
4839 pickler,
4840 datetime_unpickler_object);
4841 if (x == NULL) return;
4842 Py_DECREF(x);
4843 Py_DECREF(pickler);
4844
4845 pickler = PyObject_GetAttrString(m, "_time_pickler");
4846 if (pickler == NULL) return;
4847 time_unpickler_object = PyObject_GetAttrString(m,
4848 "_time_unpickler");
4849 if (time_unpickler_object == NULL) return;
4850 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4851 &PyDateTime_TimeType,
4852 pickler,
4853 time_unpickler_object);
4854 if (x == NULL) return;
4855 Py_DECREF(x);
4856 Py_DECREF(pickler);
4857
4858 pickler = PyObject_GetAttrString(m, "_timetz_pickler");
4859 if (pickler == NULL) return;
4860 timetz_unpickler_object = PyObject_GetAttrString(m,
4861 "_timetz_unpickler");
4862 if (timetz_unpickler_object == NULL) return;
4863 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4864 &PyDateTime_TimeTZType,
4865 pickler,
4866 timetz_unpickler_object);
4867 if (x == NULL) return;
4868 Py_DECREF(x);
4869 Py_DECREF(pickler);
4870
4871 pickler = PyObject_GetAttrString(m, "_tzinfo_pickler");
4872 if (pickler == NULL) return;
4873 tzinfo_unpickler_object = PyObject_GetAttrString(m,
4874 "_tzinfo_unpickler");
4875 if (tzinfo_unpickler_object == NULL) return;
4876 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4877 &PyDateTime_TZInfoType,
4878 pickler,
4879 tzinfo_unpickler_object);
4880 if (x== NULL) return;
4881 Py_DECREF(x);
4882 Py_DECREF(pickler);
4883
4884 pickler = PyObject_GetAttrString(m, "_datetimetz_pickler");
4885 if (pickler == NULL) return;
4886 datetimetz_unpickler_object = PyObject_GetAttrString(m,
4887 "_datetimetz_unpickler");
4888 if (datetimetz_unpickler_object == NULL) return;
4889 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4890 &PyDateTime_DateTimeTZType,
4891 pickler,
4892 datetimetz_unpickler_object);
4893 if (x== NULL) return;
4894 Py_DECREF(x);
4895 Py_DECREF(pickler);
4896
4897 Py_DECREF(copyreg);
4898 }
4899
4900 /* timedelta values */
4901 d = PyDateTime_DeltaType.tp_dict;
4902
4903 if (PyDict_SetItem(d, safepickle, Py_True) < 0)
4904 return;
4905
4906 x = new_delta(0, 0, 1, 0);
4907 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4908 return;
4909 Py_DECREF(x);
4910
4911 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4912 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4913 return;
4914 Py_DECREF(x);
4915
4916 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4917 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4918 return;
4919 Py_DECREF(x);
4920
4921 /* date values */
4922 d = PyDateTime_DateType.tp_dict;
4923
4924 x = new_date(1, 1, 1);
4925 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4926 return;
4927 Py_DECREF(x);
4928
4929 x = new_date(MAXYEAR, 12, 31);
4930 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4931 return;
4932 Py_DECREF(x);
4933
4934 x = new_delta(1, 0, 0, 0);
4935 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4936 return;
4937 Py_DECREF(x);
4938
4939 /* datetime values */
4940 d = PyDateTime_DateTimeType.tp_dict;
4941
4942 x = new_datetime(1, 1, 1, 0, 0, 0, 0);
4943 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4944 return;
4945 Py_DECREF(x);
4946
4947 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999);
4948 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4949 return;
4950 Py_DECREF(x);
4951
4952 x = new_delta(0, 0, 1, 0);
4953 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4954 return;
4955 Py_DECREF(x);
4956
4957 /* time values */
4958 d = PyDateTime_TimeType.tp_dict;
4959
4960 x = new_time(0, 0, 0, 0);
4961 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4962 return;
4963 Py_DECREF(x);
4964
4965 x = new_time(23, 59, 59, 999999);
4966 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4967 return;
4968 Py_DECREF(x);
4969
4970 x = new_delta(0, 0, 1, 0);
4971 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4972 return;
4973 Py_DECREF(x);
4974
4975 /* timetz values */
4976 d = PyDateTime_TimeTZType.tp_dict;
4977
4978 x = new_timetz(0, 0, 0, 0, Py_None);
4979 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4980 return;
4981 Py_DECREF(x);
4982
4983 x = new_timetz(23, 59, 59, 999999, Py_None);
4984 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4985 return;
4986 Py_DECREF(x);
4987
4988 x = new_delta(0, 0, 1, 0);
4989 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4990 return;
4991 Py_DECREF(x);
4992
4993 /* datetimetz values */
4994 d = PyDateTime_DateTimeTZType.tp_dict;
4995
4996 x = new_datetimetz(1, 1, 1, 0, 0, 0, 0, Py_None);
4997 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4998 return;
4999 Py_DECREF(x);
5000
5001 x = new_datetimetz(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5002 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5003 return;
5004 Py_DECREF(x);
5005
5006 x = new_delta(0, 0, 1, 0);
5007 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5008 return;
5009 Py_DECREF(x);
5010
5011 Py_DECREF(safepickle);
5012
5013 /* module initialization */
5014 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
5015 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
5016
5017 Py_INCREF(&PyDateTime_DateType);
5018 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
5019
5020 Py_INCREF(&PyDateTime_DateTimeType);
5021 PyModule_AddObject(m, "datetime",
5022 (PyObject *) &PyDateTime_DateTimeType);
5023
5024 Py_INCREF(&PyDateTime_DeltaType);
5025 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
5026
5027 Py_INCREF(&PyDateTime_TimeType);
5028 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
5029
5030 Py_INCREF(&PyDateTime_TZInfoType);
5031 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
5032
5033 Py_INCREF(&PyDateTime_TimeTZType);
5034 PyModule_AddObject(m, "timetz", (PyObject *) &PyDateTime_TimeTZType);
5035
5036 Py_INCREF(&PyDateTime_DateTimeTZType);
5037 PyModule_AddObject(m, "datetimetz",
5038 (PyObject *)&PyDateTime_DateTimeTZType);
5039
5040 /* A 4-year cycle has an extra leap day over what we'd get from
5041 * pasting together 4 single years.
5042 */
5043 assert(DI4Y == 4 * 365 + 1);
5044 assert(DI4Y == days_before_year(4+1));
5045
5046 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5047 * get from pasting together 4 100-year cycles.
5048 */
5049 assert(DI400Y == 4 * DI100Y + 1);
5050 assert(DI400Y == days_before_year(400+1));
5051
5052 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5053 * pasting together 25 4-year cycles.
5054 */
5055 assert(DI100Y == 25 * DI4Y - 1);
5056 assert(DI100Y == days_before_year(100+1));
5057
5058 us_per_us = PyInt_FromLong(1);
5059 us_per_ms = PyInt_FromLong(1000);
5060 us_per_second = PyInt_FromLong(1000000);
5061 us_per_minute = PyInt_FromLong(60000000);
5062 seconds_per_day = PyInt_FromLong(24 * 3600);
5063 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5064 us_per_minute == NULL || seconds_per_day == NULL)
5065 return;
5066
5067 /* The rest are too big for 32-bit ints, but even
5068 * us_per_week fits in 40 bits, so doubles should be exact.
5069 */
5070 us_per_hour = PyLong_FromDouble(3600000000.0);
5071 us_per_day = PyLong_FromDouble(86400000000.0);
5072 us_per_week = PyLong_FromDouble(604800000000.0);
5073 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5074 return;
5075}