blob: 3aab3adf1152a73b84438d2c3db2938225799b88 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
11#include "datetime.h"
12
13/* We require that C int be at least 32 bits, and use int virtually
14 * everywhere. In just a few cases we use a temp long, where a Python
15 * API returns a C long. In such cases, we have to ensure that the
16 * final result fits in a C int (this can be an issue on 64-bit boxes).
17 */
18#if SIZEOF_INT < 4
19# error "datetime.c requires that C int have at least 32 bits"
20#endif
21
22#define MINYEAR 1
23#define MAXYEAR 9999
24
25/* Nine decimal digits is easy to communicate, and leaves enough room
26 * so that two delta days can be added w/o fear of overflowing a signed
27 * 32-bit int, and with plenty of room left over to absorb any possible
28 * carries from adding seconds.
29 */
30#define MAX_DELTA_DAYS 999999999
31
32/* Rename the long macros in datetime.h to more reasonable short names. */
33#define GET_YEAR PyDateTime_GET_YEAR
34#define GET_MONTH PyDateTime_GET_MONTH
35#define GET_DAY PyDateTime_GET_DAY
36#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
37#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
38#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
39#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
40
41/* Date accessors for date and datetime. */
42#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
43 ((o)->data[1] = ((v) & 0x00ff)))
44#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
45#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
46
47/* Date/Time accessors for datetime. */
48#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
49#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
50#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
51#define DATE_SET_MICROSECOND(o, v) \
52 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
53 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
54 ((o)->data[9] = ((v) & 0x0000ff)))
55
56/* Time accessors for time. */
57#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
58#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
59#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
60#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
61#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
62#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
63#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
64#define TIME_SET_MICROSECOND(o, v) \
65 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
66 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
67 ((o)->data[5] = ((v) & 0x0000ff)))
68
69/* Delta accessors for timedelta. */
70#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
71#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
72#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
73
74#define SET_TD_DAYS(o, v) ((o)->days = (v))
75#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
76#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
77
78/* Forward declarations. */
79static PyTypeObject PyDateTime_DateType;
80static PyTypeObject PyDateTime_DateTimeType;
81static PyTypeObject PyDateTime_DateTimeTZType;
82static PyTypeObject PyDateTime_DeltaType;
83static PyTypeObject PyDateTime_TimeType;
84static PyTypeObject PyDateTime_TZInfoType;
85static PyTypeObject PyDateTime_TimeTZType;
86
87/* ---------------------------------------------------------------------------
88 * Math utilities.
89 */
90
91/* k = i+j overflows iff k differs in sign from both inputs,
92 * iff k^i has sign bit set and k^j has sign bit set,
93 * iff (k^i)&(k^j) has sign bit set.
94 */
95#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
96 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
97
98/* Compute Python divmod(x, y), returning the quotient and storing the
99 * remainder into *r. The quotient is the floor of x/y, and that's
100 * the real point of this. C will probably truncate instead (C99
101 * requires truncation; C89 left it implementation-defined).
102 * Simplification: we *require* that y > 0 here. That's appropriate
103 * for all the uses made of it. This simplifies the code and makes
104 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
105 * overflow case).
106 */
107static int
108divmod(int x, int y, int *r)
109{
110 int quo;
111
112 assert(y > 0);
113 quo = x / y;
114 *r = x - quo * y;
115 if (*r < 0) {
116 --quo;
117 *r += y;
118 }
119 assert(0 <= *r && *r < y);
120 return quo;
121}
122
123/* ---------------------------------------------------------------------------
124 * General calendrical helper functions
125 */
126
127/* For each month ordinal in 1..12, the number of days in that month,
128 * and the number of days before that month in the same year. These
129 * are correct for non-leap years only.
130 */
131static int _days_in_month[] = {
132 0, /* unused; this vector uses 1-based indexing */
133 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
134};
135
136static int _days_before_month[] = {
137 0, /* unused; this vector uses 1-based indexing */
138 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
139};
140
141/* year -> 1 if leap year, else 0. */
142static int
143is_leap(int year)
144{
145 /* Cast year to unsigned. The result is the same either way, but
146 * C can generate faster code for unsigned mod than for signed
147 * mod (especially for % 4 -- a good compiler should just grab
148 * the last 2 bits when the LHS is unsigned).
149 */
150 const unsigned int ayear = (unsigned int)year;
151 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
152}
153
154/* year, month -> number of days in that month in that year */
155static int
156days_in_month(int year, int month)
157{
158 assert(month >= 1);
159 assert(month <= 12);
160 if (month == 2 && is_leap(year))
161 return 29;
162 else
163 return _days_in_month[month];
164}
165
166/* year, month -> number of days in year preceeding first day of month */
167static int
168days_before_month(int year, int month)
169{
170 int days;
171
172 assert(month >= 1);
173 assert(month <= 12);
174 days = _days_before_month[month];
175 if (month > 2 && is_leap(year))
176 ++days;
177 return days;
178}
179
180/* year -> number of days before January 1st of year. Remember that we
181 * start with year 1, so days_before_year(1) == 0.
182 */
183static int
184days_before_year(int year)
185{
186 int y = year - 1;
187 /* This is incorrect if year <= 0; we really want the floor
188 * here. But so long as MINYEAR is 1, the smallest year this
189 * can see is 0 (this can happen in some normalization endcases),
190 * so we'll just special-case that.
191 */
192 assert (year >= 0);
193 if (y >= 0)
194 return y*365 + y/4 - y/100 + y/400;
195 else {
196 assert(y == -1);
197 return -366;
198 }
199}
200
201/* Number of days in 4, 100, and 400 year cycles. That these have
202 * the correct values is asserted in the module init function.
203 */
204#define DI4Y 1461 /* days_before_year(5); days in 4 years */
205#define DI100Y 36524 /* days_before_year(101); days in 100 years */
206#define DI400Y 146097 /* days_before_year(401); days in 400 years */
207
208/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
209static void
210ord_to_ymd(int ordinal, int *year, int *month, int *day)
211{
212 int n, n1, n4, n100, n400, leapyear, preceding;
213
214 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
215 * leap years repeats exactly every 400 years. The basic strategy is
216 * to find the closest 400-year boundary at or before ordinal, then
217 * work with the offset from that boundary to ordinal. Life is much
218 * clearer if we subtract 1 from ordinal first -- then the values
219 * of ordinal at 400-year boundaries are exactly those divisible
220 * by DI400Y:
221 *
222 * D M Y n n-1
223 * -- --- ---- ---------- ----------------
224 * 31 Dec -400 -DI400Y -DI400Y -1
225 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
226 * ...
227 * 30 Dec 000 -1 -2
228 * 31 Dec 000 0 -1
229 * 1 Jan 001 1 0 400-year boundary
230 * 2 Jan 001 2 1
231 * 3 Jan 001 3 2
232 * ...
233 * 31 Dec 400 DI400Y DI400Y -1
234 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
235 */
236 assert(ordinal >= 1);
237 --ordinal;
238 n400 = ordinal / DI400Y;
239 n = ordinal % DI400Y;
240 *year = n400 * 400 + 1;
241
242 /* Now n is the (non-negative) offset, in days, from January 1 of
243 * year, to the desired date. Now compute how many 100-year cycles
244 * precede n.
245 * Note that it's possible for n100 to equal 4! In that case 4 full
246 * 100-year cycles precede the desired day, which implies the
247 * desired day is December 31 at the end of a 400-year cycle.
248 */
249 n100 = n / DI100Y;
250 n = n % DI100Y;
251
252 /* Now compute how many 4-year cycles precede it. */
253 n4 = n / DI4Y;
254 n = n % DI4Y;
255
256 /* And now how many single years. Again n1 can be 4, and again
257 * meaning that the desired day is December 31 at the end of the
258 * 4-year cycle.
259 */
260 n1 = n / 365;
261 n = n % 365;
262
263 *year += n100 * 100 + n4 * 4 + n1;
264 if (n1 == 4 || n100 == 4) {
265 assert(n == 0);
266 *year -= 1;
267 *month = 12;
268 *day = 31;
269 return;
270 }
271
272 /* Now the year is correct, and n is the offset from January 1. We
273 * find the month via an estimate that's either exact or one too
274 * large.
275 */
276 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
277 assert(leapyear == is_leap(*year));
278 *month = (n + 50) >> 5;
279 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
280 if (preceding > n) {
281 /* estimate is too large */
282 *month -= 1;
283 preceding -= days_in_month(*year, *month);
284 }
285 n -= preceding;
286 assert(0 <= n);
287 assert(n < days_in_month(*year, *month));
288
289 *day = n + 1;
290}
291
292/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
293static int
294ymd_to_ord(int year, int month, int day)
295{
296 return days_before_year(year) + days_before_month(year, month) + day;
297}
298
299/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
300static int
301weekday(int year, int month, int day)
302{
303 return (ymd_to_ord(year, month, day) + 6) % 7;
304}
305
306/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
307 * first calendar week containing a Thursday.
308 */
309static int
310iso_week1_monday(int year)
311{
312 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
313 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
314 int first_weekday = (first_day + 6) % 7;
315 /* ordinal of closest Monday at or before 1/1 */
316 int week1_monday = first_day - first_weekday;
317
318 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
319 week1_monday += 7;
320 return week1_monday;
321}
322
323/* ---------------------------------------------------------------------------
324 * Range checkers.
325 */
326
327/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
328 * If not, raise OverflowError and return -1.
329 */
330static int
331check_delta_day_range(int days)
332{
333 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
334 return 0;
335 PyErr_Format(PyExc_OverflowError,
336 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000337 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000338 return -1;
339}
340
341/* Check that date arguments are in range. Return 0 if they are. If they
342 * aren't, raise ValueError and return -1.
343 */
344static int
345check_date_args(int year, int month, int day)
346{
347
348 if (year < MINYEAR || year > MAXYEAR) {
349 PyErr_SetString(PyExc_ValueError,
350 "year is out of range");
351 return -1;
352 }
353 if (month < 1 || month > 12) {
354 PyErr_SetString(PyExc_ValueError,
355 "month must be in 1..12");
356 return -1;
357 }
358 if (day < 1 || day > days_in_month(year, month)) {
359 PyErr_SetString(PyExc_ValueError,
360 "day is out of range for month");
361 return -1;
362 }
363 return 0;
364}
365
366/* Check that time arguments are in range. Return 0 if they are. If they
367 * aren't, raise ValueError and return -1.
368 */
369static int
370check_time_args(int h, int m, int s, int us)
371{
372 if (h < 0 || h > 23) {
373 PyErr_SetString(PyExc_ValueError,
374 "hour must be in 0..23");
375 return -1;
376 }
377 if (m < 0 || m > 59) {
378 PyErr_SetString(PyExc_ValueError,
379 "minute must be in 0..59");
380 return -1;
381 }
382 if (s < 0 || s > 59) {
383 PyErr_SetString(PyExc_ValueError,
384 "second must be in 0..59");
385 return -1;
386 }
387 if (us < 0 || us > 999999) {
388 PyErr_SetString(PyExc_ValueError,
389 "microsecond must be in 0..999999");
390 return -1;
391 }
392 return 0;
393}
394
395/* ---------------------------------------------------------------------------
396 * Normalization utilities.
397 */
398
399/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
400 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
401 * at least factor, enough of *lo is converted into "hi" units so that
402 * 0 <= *lo < factor. The input values must be such that int overflow
403 * is impossible.
404 */
405static void
406normalize_pair(int *hi, int *lo, int factor)
407{
408 assert(factor > 0);
409 assert(lo != hi);
410 if (*lo < 0 || *lo >= factor) {
411 const int num_hi = divmod(*lo, factor, lo);
412 const int new_hi = *hi + num_hi;
413 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
414 *hi = new_hi;
415 }
416 assert(0 <= *lo && *lo < factor);
417}
418
419/* Fiddle days (d), seconds (s), and microseconds (us) so that
420 * 0 <= *s < 24*3600
421 * 0 <= *us < 1000000
422 * The input values must be such that the internals don't overflow.
423 * The way this routine is used, we don't get close.
424 */
425static void
426normalize_d_s_us(int *d, int *s, int *us)
427{
428 if (*us < 0 || *us >= 1000000) {
429 normalize_pair(s, us, 1000000);
430 /* |s| can't be bigger than about
431 * |original s| + |original us|/1000000 now.
432 */
433
434 }
435 if (*s < 0 || *s >= 24*3600) {
436 normalize_pair(d, s, 24*3600);
437 /* |d| can't be bigger than about
438 * |original d| +
439 * (|original s| + |original us|/1000000) / (24*3600) now.
440 */
441 }
442 assert(0 <= *s && *s < 24*3600);
443 assert(0 <= *us && *us < 1000000);
444}
445
446/* Fiddle years (y), months (m), and days (d) so that
447 * 1 <= *m <= 12
448 * 1 <= *d <= days_in_month(*y, *m)
449 * The input values must be such that the internals don't overflow.
450 * The way this routine is used, we don't get close.
451 */
452static void
453normalize_y_m_d(int *y, int *m, int *d)
454{
455 int dim; /* # of days in month */
456
457 /* This gets muddy: the proper range for day can't be determined
458 * without knowing the correct month and year, but if day is, e.g.,
459 * plus or minus a million, the current month and year values make
460 * no sense (and may also be out of bounds themselves).
461 * Saying 12 months == 1 year should be non-controversial.
462 */
463 if (*m < 1 || *m > 12) {
464 --*m;
465 normalize_pair(y, m, 12);
466 ++*m;
467 /* |y| can't be bigger than about
468 * |original y| + |original m|/12 now.
469 */
470 }
471 assert(1 <= *m && *m <= 12);
472
473 /* Now only day can be out of bounds (year may also be out of bounds
474 * for a datetime object, but we don't care about that here).
475 * If day is out of bounds, what to do is arguable, but at least the
476 * method here is principled and explainable.
477 */
478 dim = days_in_month(*y, *m);
479 if (*d < 1 || *d > dim) {
480 /* Move day-1 days from the first of the month. First try to
481 * get off cheap if we're only one day out of range
482 * (adjustments for timezone alone can't be worse than that).
483 */
484 if (*d == 0) {
485 --*m;
486 if (*m > 0)
487 *d = days_in_month(*y, *m);
488 else {
489 --*y;
490 *m = 12;
491 *d = 31;
492 }
493 }
494 else if (*d == dim + 1) {
495 /* move forward a day */
496 ++*m;
497 *d = 1;
498 if (*m > 12) {
499 *m = 1;
500 ++*y;
501 }
502 }
503 else {
504 int ordinal = ymd_to_ord(*y, *m, 1) +
505 *d - 1;
506 ord_to_ymd(ordinal, y, m, d);
507 }
508 }
509 assert(*m > 0);
510 assert(*d > 0);
511}
512
513/* Fiddle out-of-bounds months and days so that the result makes some kind
514 * of sense. The parameters are both inputs and outputs. Returns < 0 on
515 * failure, where failure means the adjusted year is out of bounds.
516 */
517static int
518normalize_date(int *year, int *month, int *day)
519{
520 int result;
521
522 normalize_y_m_d(year, month, day);
523 if (MINYEAR <= *year && *year <= MAXYEAR)
524 result = 0;
525 else {
526 PyErr_SetString(PyExc_OverflowError,
527 "date value out of range");
528 result = -1;
529 }
530 return result;
531}
532
533/* Force all the datetime fields into range. The parameters are both
534 * inputs and outputs. Returns < 0 on error.
535 */
536static int
537normalize_datetime(int *year, int *month, int *day,
538 int *hour, int *minute, int *second,
539 int *microsecond)
540{
541 normalize_pair(second, microsecond, 1000000);
542 normalize_pair(minute, second, 60);
543 normalize_pair(hour, minute, 60);
544 normalize_pair(day, hour, 24);
545 return normalize_date(year, month, day);
546}
547
548/* ---------------------------------------------------------------------------
549 * tzinfo helpers.
550 */
551
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 *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001028time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001029{
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;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001329 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001330
1331 PyObject *tuple = NULL;
1332 PyObject *num = NULL;
1333 PyObject *result = NULL;
1334
1335 tuple = PyNumber_Divmod(pyus, us_per_second);
1336 if (tuple == NULL)
1337 goto Done;
1338
1339 num = PyTuple_GetItem(tuple, 1); /* us */
1340 if (num == NULL)
1341 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001342 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001343 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001344 if (temp == -1 && PyErr_Occurred())
1345 goto Done;
1346 assert(0 <= temp && temp < 1000000);
1347 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001348 if (us < 0) {
1349 /* The divisor was positive, so this must be an error. */
1350 assert(PyErr_Occurred());
1351 goto Done;
1352 }
1353
1354 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1355 if (num == NULL)
1356 goto Done;
1357 Py_INCREF(num);
1358 Py_DECREF(tuple);
1359
1360 tuple = PyNumber_Divmod(num, seconds_per_day);
1361 if (tuple == NULL)
1362 goto Done;
1363 Py_DECREF(num);
1364
1365 num = PyTuple_GetItem(tuple, 1); /* seconds */
1366 if (num == NULL)
1367 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001368 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001369 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001370 if (temp == -1 && PyErr_Occurred())
1371 goto Done;
1372 assert(0 <= temp && temp < 24*3600);
1373 s = (int)temp;
1374
Tim Peters2a799bf2002-12-16 20:18:38 +00001375 if (s < 0) {
1376 /* The divisor was positive, so this must be an error. */
1377 assert(PyErr_Occurred());
1378 goto Done;
1379 }
1380
1381 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1382 if (num == NULL)
1383 goto Done;
1384 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001385 temp = PyLong_AsLong(num);
1386 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001387 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001388 d = (int)temp;
1389 if ((long)d != temp) {
1390 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1391 "large to fit in a C int");
1392 goto Done;
1393 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001394 result = new_delta(d, s, us, 0);
1395
1396Done:
1397 Py_XDECREF(tuple);
1398 Py_XDECREF(num);
1399 return result;
1400}
1401
1402static PyObject *
1403multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1404{
1405 PyObject *pyus_in;
1406 PyObject *pyus_out;
1407 PyObject *result;
1408
1409 pyus_in = delta_to_microseconds(delta);
1410 if (pyus_in == NULL)
1411 return NULL;
1412
1413 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1414 Py_DECREF(pyus_in);
1415 if (pyus_out == NULL)
1416 return NULL;
1417
1418 result = microseconds_to_delta(pyus_out);
1419 Py_DECREF(pyus_out);
1420 return result;
1421}
1422
1423static PyObject *
1424divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1425{
1426 PyObject *pyus_in;
1427 PyObject *pyus_out;
1428 PyObject *result;
1429
1430 pyus_in = delta_to_microseconds(delta);
1431 if (pyus_in == NULL)
1432 return NULL;
1433
1434 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1435 Py_DECREF(pyus_in);
1436 if (pyus_out == NULL)
1437 return NULL;
1438
1439 result = microseconds_to_delta(pyus_out);
1440 Py_DECREF(pyus_out);
1441 return result;
1442}
1443
1444static PyObject *
1445delta_add(PyObject *left, PyObject *right)
1446{
1447 PyObject *result = Py_NotImplemented;
1448
1449 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1450 /* delta + delta */
1451 /* The C-level additions can't overflow because of the
1452 * invariant bounds.
1453 */
1454 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1455 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1456 int microseconds = GET_TD_MICROSECONDS(left) +
1457 GET_TD_MICROSECONDS(right);
1458 result = new_delta(days, seconds, microseconds, 1);
1459 }
1460
1461 if (result == Py_NotImplemented)
1462 Py_INCREF(result);
1463 return result;
1464}
1465
1466static PyObject *
1467delta_negative(PyDateTime_Delta *self)
1468{
1469 return new_delta(-GET_TD_DAYS(self),
1470 -GET_TD_SECONDS(self),
1471 -GET_TD_MICROSECONDS(self),
1472 1);
1473}
1474
1475static PyObject *
1476delta_positive(PyDateTime_Delta *self)
1477{
1478 /* Could optimize this (by returning self) if this isn't a
1479 * subclass -- but who uses unary + ? Approximately nobody.
1480 */
1481 return new_delta(GET_TD_DAYS(self),
1482 GET_TD_SECONDS(self),
1483 GET_TD_MICROSECONDS(self),
1484 0);
1485}
1486
1487static PyObject *
1488delta_abs(PyDateTime_Delta *self)
1489{
1490 PyObject *result;
1491
1492 assert(GET_TD_MICROSECONDS(self) >= 0);
1493 assert(GET_TD_SECONDS(self) >= 0);
1494
1495 if (GET_TD_DAYS(self) < 0)
1496 result = delta_negative(self);
1497 else
1498 result = delta_positive(self);
1499
1500 return result;
1501}
1502
1503static PyObject *
1504delta_subtract(PyObject *left, PyObject *right)
1505{
1506 PyObject *result = Py_NotImplemented;
1507
1508 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1509 /* delta - delta */
1510 PyObject *minus_right = PyNumber_Negative(right);
1511 if (minus_right) {
1512 result = delta_add(left, minus_right);
1513 Py_DECREF(minus_right);
1514 }
1515 else
1516 result = NULL;
1517 }
1518
1519 if (result == Py_NotImplemented)
1520 Py_INCREF(result);
1521 return result;
1522}
1523
1524/* This is more natural as a tp_compare, but doesn't work then: for whatever
1525 * reason, Python's try_3way_compare ignores tp_compare unless
1526 * PyInstance_Check returns true, but these aren't old-style classes.
1527 */
1528static PyObject *
1529delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1530{
1531 int diff;
1532
1533 if (! PyDelta_CheckExact(other)) {
1534 PyErr_Format(PyExc_TypeError,
1535 "can't compare %s to %s instance",
1536 self->ob_type->tp_name, other->ob_type->tp_name);
1537 return NULL;
1538 }
1539 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1540 if (diff == 0) {
1541 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1542 if (diff == 0)
1543 diff = GET_TD_MICROSECONDS(self) -
1544 GET_TD_MICROSECONDS(other);
1545 }
1546 return diff_to_bool(diff, op);
1547}
1548
1549static PyObject *delta_getstate(PyDateTime_Delta *self);
1550
1551static long
1552delta_hash(PyDateTime_Delta *self)
1553{
1554 if (self->hashcode == -1) {
1555 PyObject *temp = delta_getstate(self);
1556 if (temp != NULL) {
1557 self->hashcode = PyObject_Hash(temp);
1558 Py_DECREF(temp);
1559 }
1560 }
1561 return self->hashcode;
1562}
1563
1564static PyObject *
1565delta_multiply(PyObject *left, PyObject *right)
1566{
1567 PyObject *result = Py_NotImplemented;
1568
1569 if (PyDelta_Check(left)) {
1570 /* delta * ??? */
1571 if (PyInt_Check(right) || PyLong_Check(right))
1572 result = multiply_int_timedelta(right,
1573 (PyDateTime_Delta *) left);
1574 }
1575 else if (PyInt_Check(left) || PyLong_Check(left))
1576 result = multiply_int_timedelta(left,
1577 (PyDateTime_Delta *) right);
1578
1579 if (result == Py_NotImplemented)
1580 Py_INCREF(result);
1581 return result;
1582}
1583
1584static PyObject *
1585delta_divide(PyObject *left, PyObject *right)
1586{
1587 PyObject *result = Py_NotImplemented;
1588
1589 if (PyDelta_Check(left)) {
1590 /* delta * ??? */
1591 if (PyInt_Check(right) || PyLong_Check(right))
1592 result = divide_timedelta_int(
1593 (PyDateTime_Delta *)left,
1594 right);
1595 }
1596
1597 if (result == Py_NotImplemented)
1598 Py_INCREF(result);
1599 return result;
1600}
1601
1602/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1603 * timedelta constructor. sofar is the # of microseconds accounted for
1604 * so far, and there are factor microseconds per current unit, the number
1605 * of which is given by num. num * factor is added to sofar in a
1606 * numerically careful way, and that's the result. Any fractional
1607 * microseconds left over (this can happen if num is a float type) are
1608 * added into *leftover.
1609 * Note that there are many ways this can give an error (NULL) return.
1610 */
1611static PyObject *
1612accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1613 double *leftover)
1614{
1615 PyObject *prod;
1616 PyObject *sum;
1617
1618 assert(num != NULL);
1619
1620 if (PyInt_Check(num) || PyLong_Check(num)) {
1621 prod = PyNumber_Multiply(num, factor);
1622 if (prod == NULL)
1623 return NULL;
1624 sum = PyNumber_Add(sofar, prod);
1625 Py_DECREF(prod);
1626 return sum;
1627 }
1628
1629 if (PyFloat_Check(num)) {
1630 double dnum;
1631 double fracpart;
1632 double intpart;
1633 PyObject *x;
1634 PyObject *y;
1635
1636 /* The Plan: decompose num into an integer part and a
1637 * fractional part, num = intpart + fracpart.
1638 * Then num * factor ==
1639 * intpart * factor + fracpart * factor
1640 * and the LHS can be computed exactly in long arithmetic.
1641 * The RHS is again broken into an int part and frac part.
1642 * and the frac part is added into *leftover.
1643 */
1644 dnum = PyFloat_AsDouble(num);
1645 if (dnum == -1.0 && PyErr_Occurred())
1646 return NULL;
1647 fracpart = modf(dnum, &intpart);
1648 x = PyLong_FromDouble(intpart);
1649 if (x == NULL)
1650 return NULL;
1651
1652 prod = PyNumber_Multiply(x, factor);
1653 Py_DECREF(x);
1654 if (prod == NULL)
1655 return NULL;
1656
1657 sum = PyNumber_Add(sofar, prod);
1658 Py_DECREF(prod);
1659 if (sum == NULL)
1660 return NULL;
1661
1662 if (fracpart == 0.0)
1663 return sum;
1664 /* So far we've lost no information. Dealing with the
1665 * fractional part requires float arithmetic, and may
1666 * lose a little info.
1667 */
1668 assert(PyInt_Check(factor) || PyLong_Check(factor));
1669 if (PyInt_Check(factor))
1670 dnum = (double)PyInt_AsLong(factor);
1671 else
1672 dnum = PyLong_AsDouble(factor);
1673
1674 dnum *= fracpart;
1675 fracpart = modf(dnum, &intpart);
1676 x = PyLong_FromDouble(intpart);
1677 if (x == NULL) {
1678 Py_DECREF(sum);
1679 return NULL;
1680 }
1681
1682 y = PyNumber_Add(sum, x);
1683 Py_DECREF(sum);
1684 Py_DECREF(x);
1685 *leftover += fracpart;
1686 return y;
1687 }
1688
1689 PyErr_Format(PyExc_TypeError,
1690 "unsupported type for timedelta %s component: %s",
1691 tag, num->ob_type->tp_name);
1692 return NULL;
1693}
1694
1695static PyObject *
1696delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1697{
1698 PyObject *self = NULL;
1699
1700 /* Argument objects. */
1701 PyObject *day = NULL;
1702 PyObject *second = NULL;
1703 PyObject *us = NULL;
1704 PyObject *ms = NULL;
1705 PyObject *minute = NULL;
1706 PyObject *hour = NULL;
1707 PyObject *week = NULL;
1708
1709 PyObject *x = NULL; /* running sum of microseconds */
1710 PyObject *y = NULL; /* temp sum of microseconds */
1711 double leftover_us = 0.0;
1712
1713 static char *keywords[] = {
1714 "days", "seconds", "microseconds", "milliseconds",
1715 "minutes", "hours", "weeks", NULL
1716 };
1717
1718 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1719 keywords,
1720 &day, &second, &us,
1721 &ms, &minute, &hour, &week) == 0)
1722 goto Done;
1723
1724 x = PyInt_FromLong(0);
1725 if (x == NULL)
1726 goto Done;
1727
1728#define CLEANUP \
1729 Py_DECREF(x); \
1730 x = y; \
1731 if (x == NULL) \
1732 goto Done
1733
1734 if (us) {
1735 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1736 CLEANUP;
1737 }
1738 if (ms) {
1739 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1740 CLEANUP;
1741 }
1742 if (second) {
1743 y = accum("seconds", x, second, us_per_second, &leftover_us);
1744 CLEANUP;
1745 }
1746 if (minute) {
1747 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1748 CLEANUP;
1749 }
1750 if (hour) {
1751 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1752 CLEANUP;
1753 }
1754 if (day) {
1755 y = accum("days", x, day, us_per_day, &leftover_us);
1756 CLEANUP;
1757 }
1758 if (week) {
1759 y = accum("weeks", x, week, us_per_week, &leftover_us);
1760 CLEANUP;
1761 }
1762 if (leftover_us) {
1763 /* Round to nearest whole # of us, and add into x. */
1764 PyObject *temp;
1765 if (leftover_us >= 0.0)
1766 leftover_us = floor(leftover_us + 0.5);
1767 else
1768 leftover_us = ceil(leftover_us - 0.5);
1769 temp = PyLong_FromDouble(leftover_us);
1770 if (temp == NULL) {
1771 Py_DECREF(x);
1772 goto Done;
1773 }
1774 y = PyNumber_Add(x, temp);
1775 Py_DECREF(temp);
1776 CLEANUP;
1777 }
1778
1779 self = microseconds_to_delta(x);
1780 Py_DECREF(x);
1781Done:
1782 return self;
1783
1784#undef CLEANUP
1785}
1786
1787static int
1788delta_nonzero(PyDateTime_Delta *self)
1789{
1790 return (GET_TD_DAYS(self) != 0
1791 || GET_TD_SECONDS(self) != 0
1792 || GET_TD_MICROSECONDS(self) != 0);
1793}
1794
1795static PyObject *
1796delta_repr(PyDateTime_Delta *self)
1797{
1798 if (GET_TD_MICROSECONDS(self) != 0)
1799 return PyString_FromFormat("%s(%d, %d, %d)",
1800 self->ob_type->tp_name,
1801 GET_TD_DAYS(self),
1802 GET_TD_SECONDS(self),
1803 GET_TD_MICROSECONDS(self));
1804 if (GET_TD_SECONDS(self) != 0)
1805 return PyString_FromFormat("%s(%d, %d)",
1806 self->ob_type->tp_name,
1807 GET_TD_DAYS(self),
1808 GET_TD_SECONDS(self));
1809
1810 return PyString_FromFormat("%s(%d)",
1811 self->ob_type->tp_name,
1812 GET_TD_DAYS(self));
1813}
1814
1815static PyObject *
1816delta_str(PyDateTime_Delta *self)
1817{
1818 int days = GET_TD_DAYS(self);
1819 int seconds = GET_TD_SECONDS(self);
1820 int us = GET_TD_MICROSECONDS(self);
1821 int hours;
1822 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00001823 char buf[100];
1824 char *pbuf = buf;
1825 size_t buflen = sizeof(buf);
1826 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001827
1828 minutes = divmod(seconds, 60, &seconds);
1829 hours = divmod(minutes, 60, &minutes);
1830
1831 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00001832 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
1833 (days == 1 || days == -1) ? "" : "s");
1834 if (n < 0 || (size_t)n >= buflen)
1835 goto Fail;
1836 pbuf += n;
1837 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001838 }
1839
Tim Petersba873472002-12-18 20:19:21 +00001840 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
1841 hours, minutes, seconds);
1842 if (n < 0 || (size_t)n >= buflen)
1843 goto Fail;
1844 pbuf += n;
1845 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001846
1847 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00001848 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
1849 if (n < 0 || (size_t)n >= buflen)
1850 goto Fail;
1851 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001852 }
1853
Tim Petersba873472002-12-18 20:19:21 +00001854 return PyString_FromStringAndSize(buf, pbuf - buf);
1855
1856 Fail:
1857 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
1858 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001859}
1860
1861/* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed
1862 * in the Python implementation, the C implementation also requires
1863 * __reduce__, and a __safe_for_unpickling__ attr in the type object.
1864 */
1865static PyObject *
1866delta_getstate(PyDateTime_Delta *self)
1867{
1868 return Py_BuildValue("iii", GET_TD_DAYS(self),
1869 GET_TD_SECONDS(self),
1870 GET_TD_MICROSECONDS(self));
1871}
1872
1873static PyObject *
1874delta_setstate(PyDateTime_Delta *self, PyObject *state)
1875{
1876 int day;
1877 int second;
1878 int us;
1879
1880 if (!PyArg_ParseTuple(state, "iii:__setstate__", &day, &second, &us))
1881 return NULL;
1882
1883 self->hashcode = -1;
1884 SET_TD_DAYS(self, day);
1885 SET_TD_SECONDS(self, second);
1886 SET_TD_MICROSECONDS(self, us);
1887
1888 Py_INCREF(Py_None);
1889 return Py_None;
1890}
1891
1892static PyObject *
1893delta_reduce(PyDateTime_Delta* self)
1894{
1895 PyObject* result = NULL;
1896 PyObject* state = delta_getstate(self);
1897
1898 if (state != NULL) {
1899 /* The funky "()" in the format string creates an empty
1900 * tuple as the 2nd component of the result 3-tuple.
1901 */
1902 result = Py_BuildValue("O()O", self->ob_type, state);
1903 Py_DECREF(state);
1904 }
1905 return result;
1906}
1907
1908#define OFFSET(field) offsetof(PyDateTime_Delta, field)
1909
1910static PyMemberDef delta_members[] = {
Neal Norwitzdfb80862002-12-19 02:30:56 +00001911 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00001912 PyDoc_STR("Number of days.")},
1913
Neal Norwitzdfb80862002-12-19 02:30:56 +00001914 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00001915 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
1916
Neal Norwitzdfb80862002-12-19 02:30:56 +00001917 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00001918 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
1919 {NULL}
1920};
1921
1922static PyMethodDef delta_methods[] = {
1923 {"__setstate__", (PyCFunction)delta_setstate, METH_O,
1924 PyDoc_STR("__setstate__(state)")},
1925
1926 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
1927 PyDoc_STR("__setstate__(state)")},
1928
1929 {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS,
1930 PyDoc_STR("__getstate__() -> state")},
1931 {NULL, NULL},
1932};
1933
1934static char delta_doc[] =
1935PyDoc_STR("Difference between two datetime values.");
1936
1937static PyNumberMethods delta_as_number = {
1938 delta_add, /* nb_add */
1939 delta_subtract, /* nb_subtract */
1940 delta_multiply, /* nb_multiply */
1941 delta_divide, /* nb_divide */
1942 0, /* nb_remainder */
1943 0, /* nb_divmod */
1944 0, /* nb_power */
1945 (unaryfunc)delta_negative, /* nb_negative */
1946 (unaryfunc)delta_positive, /* nb_positive */
1947 (unaryfunc)delta_abs, /* nb_absolute */
1948 (inquiry)delta_nonzero, /* nb_nonzero */
1949 0, /*nb_invert*/
1950 0, /*nb_lshift*/
1951 0, /*nb_rshift*/
1952 0, /*nb_and*/
1953 0, /*nb_xor*/
1954 0, /*nb_or*/
1955 0, /*nb_coerce*/
1956 0, /*nb_int*/
1957 0, /*nb_long*/
1958 0, /*nb_float*/
1959 0, /*nb_oct*/
1960 0, /*nb_hex*/
1961 0, /*nb_inplace_add*/
1962 0, /*nb_inplace_subtract*/
1963 0, /*nb_inplace_multiply*/
1964 0, /*nb_inplace_divide*/
1965 0, /*nb_inplace_remainder*/
1966 0, /*nb_inplace_power*/
1967 0, /*nb_inplace_lshift*/
1968 0, /*nb_inplace_rshift*/
1969 0, /*nb_inplace_and*/
1970 0, /*nb_inplace_xor*/
1971 0, /*nb_inplace_or*/
1972 delta_divide, /* nb_floor_divide */
1973 0, /* nb_true_divide */
1974 0, /* nb_inplace_floor_divide */
1975 0, /* nb_inplace_true_divide */
1976};
1977
1978static PyTypeObject PyDateTime_DeltaType = {
1979 PyObject_HEAD_INIT(NULL)
1980 0, /* ob_size */
1981 "datetime.timedelta", /* tp_name */
1982 sizeof(PyDateTime_Delta), /* tp_basicsize */
1983 0, /* tp_itemsize */
1984 0, /* tp_dealloc */
1985 0, /* tp_print */
1986 0, /* tp_getattr */
1987 0, /* tp_setattr */
1988 0, /* tp_compare */
1989 (reprfunc)delta_repr, /* tp_repr */
1990 &delta_as_number, /* tp_as_number */
1991 0, /* tp_as_sequence */
1992 0, /* tp_as_mapping */
1993 (hashfunc)delta_hash, /* tp_hash */
1994 0, /* tp_call */
1995 (reprfunc)delta_str, /* tp_str */
1996 PyObject_GenericGetAttr, /* tp_getattro */
1997 0, /* tp_setattro */
1998 0, /* tp_as_buffer */
1999 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
2000 delta_doc, /* tp_doc */
2001 0, /* tp_traverse */
2002 0, /* tp_clear */
2003 (richcmpfunc)delta_richcompare, /* tp_richcompare */
2004 0, /* tp_weaklistoffset */
2005 0, /* tp_iter */
2006 0, /* tp_iternext */
2007 delta_methods, /* tp_methods */
2008 delta_members, /* tp_members */
2009 0, /* tp_getset */
2010 0, /* tp_base */
2011 0, /* tp_dict */
2012 0, /* tp_descr_get */
2013 0, /* tp_descr_set */
2014 0, /* tp_dictoffset */
2015 0, /* tp_init */
2016 0, /* tp_alloc */
2017 delta_new, /* tp_new */
2018 _PyObject_Del, /* tp_free */
2019};
2020
2021/*
2022 * PyDateTime_Date implementation.
2023 */
2024
2025/* Accessor properties. */
2026
2027static PyObject *
2028date_year(PyDateTime_Date *self, void *unused)
2029{
2030 return PyInt_FromLong(GET_YEAR(self));
2031}
2032
2033static PyObject *
2034date_month(PyDateTime_Date *self, void *unused)
2035{
2036 return PyInt_FromLong(GET_MONTH(self));
2037}
2038
2039static PyObject *
2040date_day(PyDateTime_Date *self, void *unused)
2041{
2042 return PyInt_FromLong(GET_DAY(self));
2043}
2044
2045static PyGetSetDef date_getset[] = {
2046 {"year", (getter)date_year},
2047 {"month", (getter)date_month},
2048 {"day", (getter)date_day},
2049 {NULL}
2050};
2051
2052/* Constructors. */
2053
2054static PyObject *
2055date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2056{
2057 PyObject *self = NULL;
2058 int year;
2059 int month;
2060 int day;
2061
2062 static char *keywords[] = {
2063 "year", "month", "day", NULL
2064 };
2065
2066 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", keywords,
2067 &year, &month, &day)) {
2068 if (check_date_args(year, month, day) < 0)
2069 return NULL;
2070 self = new_date(year, month, day);
2071 }
2072 return self;
2073}
2074
2075/* Return new date from localtime(t). */
2076static PyObject *
2077date_local_from_time_t(PyObject *cls, time_t t)
2078{
2079 struct tm *tm;
2080 PyObject *result = NULL;
2081
2082 tm = localtime(&t);
2083 if (tm)
2084 result = PyObject_CallFunction(cls, "iii",
2085 tm->tm_year + 1900,
2086 tm->tm_mon + 1,
2087 tm->tm_mday);
2088 else
2089 PyErr_SetString(PyExc_ValueError,
2090 "timestamp out of range for "
2091 "platform localtime() function");
2092 return result;
2093}
2094
2095/* Return new date from current time.
2096 * We say this is equivalent to fromtimestamp(time.time()), and the
2097 * only way to be sure of that is to *call* time.time(). That's not
2098 * generally the same as calling C's time.
2099 */
2100static PyObject *
2101date_today(PyObject *cls, PyObject *dummy)
2102{
2103 PyObject *time;
2104 PyObject *result;
2105
2106 time = time_time();
2107 if (time == NULL)
2108 return NULL;
2109
2110 /* Note well: today() is a class method, so this may not call
2111 * date.fromtimestamp. For example, it may call
2112 * datetime.fromtimestamp. That's why we need all the accuracy
2113 * time.time() delivers; if someone were gonzo about optimization,
2114 * date.today() could get away with plain C time().
2115 */
2116 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2117 Py_DECREF(time);
2118 return result;
2119}
2120
2121/* Return new date from given timestamp (Python timestamp -- a double). */
2122static PyObject *
2123date_fromtimestamp(PyObject *cls, PyObject *args)
2124{
2125 double timestamp;
2126 PyObject *result = NULL;
2127
2128 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2129 result = date_local_from_time_t(cls, (time_t)timestamp);
2130 return result;
2131}
2132
2133/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2134 * the ordinal is out of range.
2135 */
2136static PyObject *
2137date_fromordinal(PyObject *cls, PyObject *args)
2138{
2139 PyObject *result = NULL;
2140 int ordinal;
2141
2142 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2143 int year;
2144 int month;
2145 int day;
2146
2147 if (ordinal < 1)
2148 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2149 ">= 1");
2150 else {
2151 ord_to_ymd(ordinal, &year, &month, &day);
2152 result = PyObject_CallFunction(cls, "iii",
2153 year, month, day);
2154 }
2155 }
2156 return result;
2157}
2158
2159/*
2160 * Date arithmetic.
2161 */
2162
2163/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2164 * instead.
2165 */
2166static PyObject *
2167add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2168{
2169 PyObject *result = NULL;
2170 int year = GET_YEAR(date);
2171 int month = GET_MONTH(date);
2172 int deltadays = GET_TD_DAYS(delta);
2173 /* C-level overflow is impossible because |deltadays| < 1e9. */
2174 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2175
2176 if (normalize_date(&year, &month, &day) >= 0)
2177 result = new_date(year, month, day);
2178 return result;
2179}
2180
2181static PyObject *
2182date_add(PyObject *left, PyObject *right)
2183{
2184 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2185 Py_INCREF(Py_NotImplemented);
2186 return Py_NotImplemented;
2187 }
2188 if (PyDate_CheckExact(left)) {
2189 /* date + ??? */
2190 if (PyDelta_Check(right))
2191 /* date + delta */
2192 return add_date_timedelta((PyDateTime_Date *) left,
2193 (PyDateTime_Delta *) right,
2194 0);
2195 }
2196 else {
2197 /* ??? + date
2198 * 'right' must be one of us, or we wouldn't have been called
2199 */
2200 if (PyDelta_Check(left))
2201 /* delta + date */
2202 return add_date_timedelta((PyDateTime_Date *) right,
2203 (PyDateTime_Delta *) left,
2204 0);
2205 }
2206 Py_INCREF(Py_NotImplemented);
2207 return Py_NotImplemented;
2208}
2209
2210static PyObject *
2211date_subtract(PyObject *left, PyObject *right)
2212{
2213 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2214 Py_INCREF(Py_NotImplemented);
2215 return Py_NotImplemented;
2216 }
2217 if (PyDate_CheckExact(left)) {
2218 if (PyDate_CheckExact(right)) {
2219 /* date - date */
2220 int left_ord = ymd_to_ord(GET_YEAR(left),
2221 GET_MONTH(left),
2222 GET_DAY(left));
2223 int right_ord = ymd_to_ord(GET_YEAR(right),
2224 GET_MONTH(right),
2225 GET_DAY(right));
2226 return new_delta(left_ord - right_ord, 0, 0, 0);
2227 }
2228 if (PyDelta_Check(right)) {
2229 /* date - delta */
2230 return add_date_timedelta((PyDateTime_Date *) left,
2231 (PyDateTime_Delta *) right,
2232 1);
2233 }
2234 }
2235 Py_INCREF(Py_NotImplemented);
2236 return Py_NotImplemented;
2237}
2238
2239
2240/* Various ways to turn a date into a string. */
2241
2242static PyObject *
2243date_repr(PyDateTime_Date *self)
2244{
2245 char buffer[1028];
2246 char *typename;
2247
2248 typename = self->ob_type->tp_name;
2249 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
2250 typename,
2251 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2252
2253 return PyString_FromString(buffer);
2254}
2255
2256static PyObject *
2257date_isoformat(PyDateTime_Date *self)
2258{
2259 char buffer[128];
2260
2261 isoformat_date(self, buffer, sizeof(buffer));
2262 return PyString_FromString(buffer);
2263}
2264
2265/* str() calls the appropriate isofomat() method. */
2266static PyObject *
2267date_str(PyDateTime_Date *self)
2268{
2269 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2270}
2271
2272
2273static PyObject *
2274date_ctime(PyDateTime_Date *self)
2275{
2276 return format_ctime(self, 0, 0, 0);
2277}
2278
2279static PyObject *
2280date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2281{
2282 /* This method can be inherited, and needs to call the
2283 * timetuple() method appropriate to self's class.
2284 */
2285 PyObject *result;
2286 PyObject *format;
2287 PyObject *tuple;
2288 static char *keywords[] = {"format", NULL};
2289
2290 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2291 &PyString_Type, &format))
2292 return NULL;
2293
2294 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2295 if (tuple == NULL)
2296 return NULL;
2297 result = wrap_strftime((PyObject *)self, format, tuple);
2298 Py_DECREF(tuple);
2299 return result;
2300}
2301
2302/* ISO methods. */
2303
2304static PyObject *
2305date_isoweekday(PyDateTime_Date *self)
2306{
2307 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2308
2309 return PyInt_FromLong(dow + 1);
2310}
2311
2312static PyObject *
2313date_isocalendar(PyDateTime_Date *self)
2314{
2315 int year = GET_YEAR(self);
2316 int week1_monday = iso_week1_monday(year);
2317 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2318 int week;
2319 int day;
2320
2321 week = divmod(today - week1_monday, 7, &day);
2322 if (week < 0) {
2323 --year;
2324 week1_monday = iso_week1_monday(year);
2325 week = divmod(today - week1_monday, 7, &day);
2326 }
2327 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2328 ++year;
2329 week = 0;
2330 }
2331 return Py_BuildValue("iii", year, week + 1, day + 1);
2332}
2333
2334/* Miscellaneous methods. */
2335
2336/* This is more natural as a tp_compare, but doesn't work then: for whatever
2337 * reason, Python's try_3way_compare ignores tp_compare unless
2338 * PyInstance_Check returns true, but these aren't old-style classes.
2339 */
2340static PyObject *
2341date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2342{
2343 int diff;
2344
2345 if (! PyDate_Check(other)) {
2346 PyErr_Format(PyExc_TypeError,
2347 "can't compare date to %s instance",
2348 other->ob_type->tp_name);
2349 return NULL;
2350 }
2351 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2352 _PyDateTime_DATE_DATASIZE);
2353 return diff_to_bool(diff, op);
2354}
2355
2356static PyObject *
2357date_timetuple(PyDateTime_Date *self)
2358{
2359 return build_struct_time(GET_YEAR(self),
2360 GET_MONTH(self),
2361 GET_DAY(self),
2362 0, 0, 0, -1);
2363}
2364
2365static PyObject *date_getstate(PyDateTime_Date *self);
2366
2367static long
2368date_hash(PyDateTime_Date *self)
2369{
2370 if (self->hashcode == -1) {
2371 PyObject *temp = date_getstate(self);
2372 if (temp != NULL) {
2373 self->hashcode = PyObject_Hash(temp);
2374 Py_DECREF(temp);
2375 }
2376 }
2377 return self->hashcode;
2378}
2379
2380static PyObject *
2381date_toordinal(PyDateTime_Date *self)
2382{
2383 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2384 GET_DAY(self)));
2385}
2386
2387static PyObject *
2388date_weekday(PyDateTime_Date *self)
2389{
2390 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2391
2392 return PyInt_FromLong(dow);
2393}
2394
2395/* Pickle support. Quite a maze! */
2396
2397static PyObject *
2398date_getstate(PyDateTime_Date *self)
2399{
2400 return PyString_FromStringAndSize(self->data,
2401 _PyDateTime_DATE_DATASIZE);
2402}
2403
2404static PyObject *
2405date_setstate(PyDateTime_Date *self, PyObject *state)
2406{
2407 const int len = PyString_Size(state);
2408 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
2409
2410 if (! PyString_Check(state) ||
2411 len != _PyDateTime_DATE_DATASIZE) {
2412 PyErr_SetString(PyExc_TypeError,
2413 "bad argument to date.__setstate__");
2414 return NULL;
2415 }
2416 memcpy(self->data, pdata, _PyDateTime_DATE_DATASIZE);
2417 self->hashcode = -1;
2418
2419 Py_INCREF(Py_None);
2420 return Py_None;
2421}
2422
2423/* XXX This seems a ridiculously inefficient way to pickle a short string. */
2424static PyObject *
2425date_pickler(PyObject *module, PyDateTime_Date *date)
2426{
2427 PyObject *state;
2428 PyObject *result = NULL;
2429
2430 if (! PyDate_CheckExact(date)) {
2431 PyErr_Format(PyExc_TypeError,
2432 "bad type passed to date pickler: %s",
2433 date->ob_type->tp_name);
2434 return NULL;
2435 }
2436 state = date_getstate(date);
2437 if (state) {
2438 result = Py_BuildValue("O(O)", date_unpickler_object, state);
2439 Py_DECREF(state);
2440 }
2441 return result;
2442}
2443
2444static PyObject *
2445date_unpickler(PyObject *module, PyObject *arg)
2446{
2447 PyDateTime_Date *self;
2448
2449 if (! PyString_CheckExact(arg)) {
2450 PyErr_Format(PyExc_TypeError,
2451 "bad type passed to date unpickler: %s",
2452 arg->ob_type->tp_name);
2453 return NULL;
2454 }
2455 self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType);
2456 if (self != NULL) {
2457 PyObject *res = date_setstate(self, arg);
2458 if (res == NULL) {
2459 Py_DECREF(self);
2460 return NULL;
2461 }
2462 Py_DECREF(res);
2463 }
2464 return (PyObject *)self;
2465}
2466
2467static PyMethodDef date_methods[] = {
2468 /* Class methods: */
2469 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2470 METH_CLASS,
2471 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2472 "time.time()).")},
2473
2474 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2475 METH_CLASS,
2476 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2477 "ordinal.")},
2478
2479 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2480 PyDoc_STR("Current date or datetime: same as "
2481 "self.__class__.fromtimestamp(time.time()).")},
2482
2483 /* Instance methods: */
2484
2485 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2486 PyDoc_STR("Return ctime() style string.")},
2487
2488 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2489 PyDoc_STR("format -> strftime() style string.")},
2490
2491 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2492 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2493
2494 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2495 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2496 "weekday.")},
2497
2498 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2499 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2500
2501 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2502 PyDoc_STR("Return the day of the week represented by the date.\n"
2503 "Monday == 1 ... Sunday == 7")},
2504
2505 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2506 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2507 "1 is day 1.")},
2508
2509 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2510 PyDoc_STR("Return the day of the week represented by the date.\n"
2511 "Monday == 0 ... Sunday == 6")},
2512
2513 {"__setstate__", (PyCFunction)date_setstate, METH_O,
2514 PyDoc_STR("__setstate__(state)")},
2515
2516 {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS,
2517 PyDoc_STR("__getstate__() -> state")},
2518
2519 {NULL, NULL}
2520};
2521
2522static char date_doc[] =
2523PyDoc_STR("Basic date type.");
2524
2525static PyNumberMethods date_as_number = {
2526 date_add, /* nb_add */
2527 date_subtract, /* nb_subtract */
2528 0, /* nb_multiply */
2529 0, /* nb_divide */
2530 0, /* nb_remainder */
2531 0, /* nb_divmod */
2532 0, /* nb_power */
2533 0, /* nb_negative */
2534 0, /* nb_positive */
2535 0, /* nb_absolute */
2536 0, /* nb_nonzero */
2537};
2538
2539static PyTypeObject PyDateTime_DateType = {
2540 PyObject_HEAD_INIT(NULL)
2541 0, /* ob_size */
2542 "datetime.date", /* tp_name */
2543 sizeof(PyDateTime_Date), /* tp_basicsize */
2544 0, /* tp_itemsize */
2545 (destructor)PyObject_Del, /* tp_dealloc */
2546 0, /* tp_print */
2547 0, /* tp_getattr */
2548 0, /* tp_setattr */
2549 0, /* tp_compare */
2550 (reprfunc)date_repr, /* tp_repr */
2551 &date_as_number, /* tp_as_number */
2552 0, /* tp_as_sequence */
2553 0, /* tp_as_mapping */
2554 (hashfunc)date_hash, /* tp_hash */
2555 0, /* tp_call */
2556 (reprfunc)date_str, /* tp_str */
2557 PyObject_GenericGetAttr, /* tp_getattro */
2558 0, /* tp_setattro */
2559 0, /* tp_as_buffer */
2560 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2561 Py_TPFLAGS_BASETYPE, /* tp_flags */
2562 date_doc, /* tp_doc */
2563 0, /* tp_traverse */
2564 0, /* tp_clear */
2565 (richcmpfunc)date_richcompare, /* tp_richcompare */
2566 0, /* tp_weaklistoffset */
2567 0, /* tp_iter */
2568 0, /* tp_iternext */
2569 date_methods, /* tp_methods */
2570 0, /* tp_members */
2571 date_getset, /* tp_getset */
2572 0, /* tp_base */
2573 0, /* tp_dict */
2574 0, /* tp_descr_get */
2575 0, /* tp_descr_set */
2576 0, /* tp_dictoffset */
2577 0, /* tp_init */
2578 0, /* tp_alloc */
2579 date_new, /* tp_new */
2580 _PyObject_Del, /* tp_free */
2581};
2582
2583/*
2584 * PyDateTime_DateTime implementation.
2585 */
2586
2587/* Accessor properties. */
2588
2589static PyObject *
2590datetime_hour(PyDateTime_DateTime *self, void *unused)
2591{
2592 return PyInt_FromLong(DATE_GET_HOUR(self));
2593}
2594
2595static PyObject *
2596datetime_minute(PyDateTime_DateTime *self, void *unused)
2597{
2598 return PyInt_FromLong(DATE_GET_MINUTE(self));
2599}
2600
2601static PyObject *
2602datetime_second(PyDateTime_DateTime *self, void *unused)
2603{
2604 return PyInt_FromLong(DATE_GET_SECOND(self));
2605}
2606
2607static PyObject *
2608datetime_microsecond(PyDateTime_DateTime *self, void *unused)
2609{
2610 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
2611}
2612
2613static PyGetSetDef datetime_getset[] = {
2614 {"hour", (getter)datetime_hour},
2615 {"minute", (getter)datetime_minute},
2616 {"second", (getter)datetime_second},
2617 {"microsecond", (getter)datetime_microsecond},
2618 {NULL}
2619};
2620
2621/* Constructors. */
2622
2623static PyObject *
2624datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2625{
2626 PyObject *self = NULL;
2627 int year;
2628 int month;
2629 int day;
2630 int hour = 0;
2631 int minute = 0;
2632 int second = 0;
2633 int usecond = 0;
2634
2635 static char *keywords[] = {
2636 "year", "month", "day", "hour", "minute", "second",
2637 "microsecond", NULL
2638 };
2639
2640 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiii", keywords,
2641 &year, &month, &day, &hour, &minute,
2642 &second, &usecond)) {
2643 if (check_date_args(year, month, day) < 0)
2644 return NULL;
2645 if (check_time_args(hour, minute, second, usecond) < 0)
2646 return NULL;
2647 self = new_datetime(year, month, day,
2648 hour, minute, second, usecond);
2649 }
2650 return self;
2651}
2652
2653
2654/* TM_FUNC is the shared type of localtime() and gmtime(). */
2655typedef struct tm *(*TM_FUNC)(const time_t *timer);
2656
2657/* Internal helper.
2658 * Build datetime from a time_t and a distinct count of microseconds.
2659 * Pass localtime or gmtime for f, to control the interpretation of timet.
2660 */
2661static PyObject *
2662datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us)
2663{
2664 struct tm *tm;
2665 PyObject *result = NULL;
2666
2667 tm = f(&timet);
2668 if (tm)
2669 result = PyObject_CallFunction(cls, "iiiiiii",
2670 tm->tm_year + 1900,
2671 tm->tm_mon + 1,
2672 tm->tm_mday,
2673 tm->tm_hour,
2674 tm->tm_min,
2675 tm->tm_sec,
2676 us);
2677 else
2678 PyErr_SetString(PyExc_ValueError,
2679 "timestamp out of range for "
2680 "platform localtime()/gmtime() function");
2681 return result;
2682}
2683
2684/* Internal helper.
2685 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
2686 * to control the interpretation of the timestamp. Since a double doesn't
2687 * have enough bits to cover a datetime's full range of precision, it's
2688 * better to call datetime_from_timet_and_us provided you have a way
2689 * to get that much precision (e.g., C time() isn't good enough).
2690 */
2691static PyObject *
2692datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp)
2693{
2694 time_t timet = (time_t)timestamp;
2695 int us = (int)((timestamp - (double)timet) * 1e6);
2696
2697 return datetime_from_timet_and_us(cls, f, timet, us);
2698}
2699
2700/* Internal helper.
2701 * Build most accurate possible datetime for current time. Pass localtime or
2702 * gmtime for f as appropriate.
2703 */
2704static PyObject *
2705datetime_best_possible(PyObject *cls, TM_FUNC f)
2706{
2707#ifdef HAVE_GETTIMEOFDAY
2708 struct timeval t;
2709
2710#ifdef GETTIMEOFDAY_NO_TZ
2711 gettimeofday(&t);
2712#else
2713 gettimeofday(&t, (struct timezone *)NULL);
2714#endif
2715 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec);
2716
2717#else /* ! HAVE_GETTIMEOFDAY */
2718 /* No flavor of gettimeofday exists on this platform. Python's
2719 * time.time() does a lot of other platform tricks to get the
2720 * best time it can on the platform, and we're not going to do
2721 * better than that (if we could, the better code would belong
2722 * in time.time()!) We're limited by the precision of a double,
2723 * though.
2724 */
2725 PyObject *time;
2726 double dtime;
2727
2728 time = time_time();
2729 if (time == NULL)
2730 return NULL;
2731 dtime = PyFloat_AsDouble(time);
2732 Py_DECREF(time);
2733 if (dtime == -1.0 && PyErr_Occurred())
2734 return NULL;
2735 return datetime_from_timestamp(cls, f, dtime);
2736#endif /* ! HAVE_GETTIMEOFDAY */
2737}
2738
2739/* Return new local datetime from timestamp (Python timestamp -- a double). */
2740static PyObject *
2741datetime_fromtimestamp(PyObject *cls, PyObject *args)
2742{
2743 double timestamp;
2744 PyObject *result = NULL;
2745
2746 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2747 result = datetime_from_timestamp(cls, localtime, timestamp);
2748 return result;
2749}
2750
2751/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
2752static PyObject *
2753datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
2754{
2755 double timestamp;
2756 PyObject *result = NULL;
2757
2758 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
2759 result = datetime_from_timestamp(cls, gmtime, timestamp);
2760 return result;
2761}
2762
2763/* Return best possible local time -- this isn't constrained by the
2764 * precision of a timestamp.
2765 */
2766static PyObject *
2767datetime_now(PyObject *cls, PyObject *dummy)
2768{
2769 return datetime_best_possible(cls, localtime);
2770}
2771
2772/* Return best possible UTC time -- this isn't constrained by the
2773 * precision of a timestamp.
2774 */
2775static PyObject *
2776datetime_utcnow(PyObject *cls, PyObject *dummy)
2777{
2778 return datetime_best_possible(cls, gmtime);
2779}
2780
2781/* Return new datetime or datetimetz from date/datetime/datetimetz and
2782 * time/timetz arguments.
2783 */
2784static PyObject *
2785datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
2786{
2787 static char *keywords[] = {"date", "time", NULL};
2788 PyObject *date;
2789 PyObject *time;
2790 PyObject *result = NULL;
2791
2792 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
2793 &PyDateTime_DateType, &date,
2794 &PyDateTime_TimeType, &time))
2795 result = PyObject_CallFunction(cls, "iiiiiii",
2796 GET_YEAR(date),
2797 GET_MONTH(date),
2798 GET_DAY(date),
2799 TIME_GET_HOUR(time),
2800 TIME_GET_MINUTE(time),
2801 TIME_GET_SECOND(time),
2802 TIME_GET_MICROSECOND(time));
2803 if (result && PyTimeTZ_Check(time) && PyDateTimeTZ_Check(result)) {
2804 /* Copy the tzinfo field. */
2805 PyObject *tzinfo = ((PyDateTime_TimeTZ *)time)->tzinfo;
2806 Py_INCREF(tzinfo);
2807 Py_DECREF(((PyDateTime_DateTimeTZ *)result)->tzinfo);
2808 ((PyDateTime_DateTimeTZ *)result)->tzinfo = tzinfo;
2809 }
2810 return result;
2811}
2812
2813/* datetime arithmetic. */
2814
2815static PyObject *
2816add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta)
2817{
2818 /* Note that the C-level additions can't overflow, because of
2819 * invariant bounds on the member values.
2820 */
2821 int year = GET_YEAR(date);
2822 int month = GET_MONTH(date);
2823 int day = GET_DAY(date) + GET_TD_DAYS(delta);
2824 int hour = DATE_GET_HOUR(date);
2825 int minute = DATE_GET_MINUTE(date);
2826 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta);
2827 int microsecond = DATE_GET_MICROSECOND(date) +
2828 GET_TD_MICROSECONDS(delta);
2829
2830 if (normalize_datetime(&year, &month, &day,
2831 &hour, &minute, &second, &microsecond) < 0)
2832 return NULL;
2833 else
2834 return new_datetime(year, month, day,
2835 hour, minute, second, microsecond);
2836}
2837
2838static PyObject *
2839sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta)
2840{
2841 /* Note that the C-level subtractions can't overflow, because of
2842 * invariant bounds on the member values.
2843 */
2844 int year = GET_YEAR(date);
2845 int month = GET_MONTH(date);
2846 int day = GET_DAY(date) - GET_TD_DAYS(delta);
2847 int hour = DATE_GET_HOUR(date);
2848 int minute = DATE_GET_MINUTE(date);
2849 int second = DATE_GET_SECOND(date) - GET_TD_SECONDS(delta);
2850 int microsecond = DATE_GET_MICROSECOND(date) -
2851 GET_TD_MICROSECONDS(delta);
2852
2853 if (normalize_datetime(&year, &month, &day,
2854 &hour, &minute, &second, &microsecond) < 0)
2855 return NULL;
2856 else
2857 return new_datetime(year, month, day,
2858 hour, minute, second, microsecond);
2859}
2860
2861static PyObject *
2862sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right)
2863{
2864 int days1 = ymd_to_ord(GET_YEAR(left), GET_MONTH(left), GET_DAY(left));
2865 int days2 = ymd_to_ord(GET_YEAR(right),
2866 GET_MONTH(right),
2867 GET_DAY(right));
2868 /* These can't overflow, since the values are normalized. At most
2869 * this gives the number of seconds in one day.
2870 */
2871 int delta_s = (DATE_GET_HOUR(left) - DATE_GET_HOUR(right)) * 3600 +
2872 (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 +
2873 DATE_GET_SECOND(left) - DATE_GET_SECOND(right);
2874 int delta_us = DATE_GET_MICROSECOND(left) -
2875 DATE_GET_MICROSECOND(right);
2876
2877 return new_delta(days1 - days2, delta_s, delta_us, 1);
2878}
2879
2880static PyObject *
2881datetime_add(PyObject *left, PyObject *right)
2882{
2883 if (PyDateTime_Check(left)) {
2884 /* datetime + ??? */
2885 if (PyDelta_Check(right))
2886 /* datetime + delta */
2887 return add_datetime_timedelta(
2888 (PyDateTime_DateTime *)left,
2889 (PyDateTime_Delta *)right);
2890 }
2891 else if (PyDelta_Check(left)) {
2892 /* delta + datetime */
2893 return add_datetime_timedelta((PyDateTime_DateTime *) right,
2894 (PyDateTime_Delta *) left);
2895 }
2896 Py_INCREF(Py_NotImplemented);
2897 return Py_NotImplemented;
2898}
2899
2900static PyObject *
2901datetime_subtract(PyObject *left, PyObject *right)
2902{
2903 PyObject *result = Py_NotImplemented;
2904
2905 if (PyDateTime_Check(left)) {
2906 /* datetime - ??? */
2907 if (PyDateTime_Check(right)) {
2908 /* datetime - datetime */
2909 result = sub_datetime_datetime(
2910 (PyDateTime_DateTime *)left,
2911 (PyDateTime_DateTime *)right);
2912 }
2913 else if (PyDelta_Check(right)) {
2914 /* datetime - delta */
2915 result = sub_datetime_timedelta(
2916 (PyDateTime_DateTime *)left,
2917 (PyDateTime_Delta *)right);
2918 }
2919 }
2920
2921 if (result == Py_NotImplemented)
2922 Py_INCREF(result);
2923 return result;
2924}
2925
2926/* Various ways to turn a datetime into a string. */
2927
2928static PyObject *
2929datetime_repr(PyDateTime_DateTime *self)
2930{
2931 char buffer[1000];
2932 char *typename = self->ob_type->tp_name;
2933
2934 if (DATE_GET_MICROSECOND(self)) {
2935 PyOS_snprintf(buffer, sizeof(buffer),
2936 "%s(%d, %d, %d, %d, %d, %d, %d)",
2937 typename,
2938 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
2939 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
2940 DATE_GET_SECOND(self),
2941 DATE_GET_MICROSECOND(self));
2942 }
2943 else if (DATE_GET_SECOND(self)) {
2944 PyOS_snprintf(buffer, sizeof(buffer),
2945 "%s(%d, %d, %d, %d, %d, %d)",
2946 typename,
2947 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
2948 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
2949 DATE_GET_SECOND(self));
2950 }
2951 else {
2952 PyOS_snprintf(buffer, sizeof(buffer),
2953 "%s(%d, %d, %d, %d, %d)",
2954 typename,
2955 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
2956 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
2957 }
2958 return PyString_FromString(buffer);
2959}
2960
2961static PyObject *
2962datetime_str(PyDateTime_DateTime *self)
2963{
2964 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
2965}
2966
2967static PyObject *
2968datetime_isoformat(PyDateTime_DateTime *self,
2969 PyObject *args, PyObject *kw)
2970{
2971 char sep = 'T';
2972 static char *keywords[] = {"sep", NULL};
2973 char buffer[100];
2974 char *cp;
2975
2976 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
2977 &sep))
2978 return NULL;
2979 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
2980 assert(cp != NULL);
2981 *cp++ = sep;
2982 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
2983 return PyString_FromString(buffer);
2984}
2985
2986static PyObject *
2987datetime_ctime(PyDateTime_DateTime *self)
2988{
2989 return format_ctime((PyDateTime_Date *)self,
2990 DATE_GET_HOUR(self),
2991 DATE_GET_MINUTE(self),
2992 DATE_GET_SECOND(self));
2993}
2994
2995/* Miscellaneous methods. */
2996
2997/* This is more natural as a tp_compare, but doesn't work then: for whatever
2998 * reason, Python's try_3way_compare ignores tp_compare unless
2999 * PyInstance_Check returns true, but these aren't old-style classes.
3000 * Note that this routine handles all comparisons for datetime and datetimetz.
3001 */
3002static PyObject *
3003datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
3004{
3005 int diff;
3006 naivety n1, n2;
3007 int offset1, offset2;
3008
3009 if (! PyDateTime_Check(other)) {
3010 /* Stop this from falling back to address comparison. */
3011 PyErr_Format(PyExc_TypeError,
3012 "can't compare '%s' to '%s'",
3013 self->ob_type->tp_name,
3014 other->ob_type->tp_name);
3015 return NULL;
3016 }
3017 n1 = classify_object((PyObject *)self, &offset1);
3018 assert(n1 != OFFSET_UNKNOWN);
3019 if (n1 == OFFSET_ERROR)
3020 return NULL;
3021
3022 n2 = classify_object(other, &offset2);
3023 assert(n2 != OFFSET_UNKNOWN);
3024 if (n2 == OFFSET_ERROR)
3025 return NULL;
3026
3027 /* If they're both naive, or both aware and have the same offsets,
3028 * we get off cheap. Note that if they're both naive, offset1 ==
3029 * offset2 == 0 at this point.
3030 */
3031 if (n1 == n2 && offset1 == offset2) {
3032 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
3033 _PyDateTime_DATETIME_DATASIZE);
3034 return diff_to_bool(diff, op);
3035 }
3036
3037 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3038 /* We want the sign of
3039 * (self - offset1 minutes) - (other - offset2 minutes) =
3040 * (self - other) + (offset2 - offset1) minutes.
3041 */
3042 PyDateTime_Delta *delta;
3043 int days, seconds, us;
3044
3045 assert(offset1 != offset2); /* else last "if" handled it */
3046 delta = (PyDateTime_Delta *)sub_datetime_datetime(self,
3047 (PyDateTime_DateTime *)other);
3048 if (delta == NULL)
3049 return NULL;
3050 days = delta->days;
3051 seconds = delta->seconds + (offset2 - offset1) * 60;
3052 us = delta->microseconds;
3053 Py_DECREF(delta);
3054 normalize_d_s_us(&days, &seconds, &us);
3055 diff = days;
3056 if (diff == 0)
3057 diff = seconds | us;
3058 return diff_to_bool(diff, op);
3059 }
3060
3061 assert(n1 != n2);
3062 PyErr_SetString(PyExc_TypeError,
3063 "can't compare offset-naive and "
3064 "offset-aware datetimes");
3065 return NULL;
3066}
3067
3068static PyObject *datetime_getstate(PyDateTime_DateTime *self);
3069
3070static long
3071datetime_hash(PyDateTime_DateTime *self)
3072{
3073 if (self->hashcode == -1) {
3074 naivety n;
3075 int offset;
3076 PyObject *temp;
3077
3078 n = classify_object((PyObject *)self, &offset);
3079 assert(n != OFFSET_UNKNOWN);
3080 if (n == OFFSET_ERROR)
3081 return -1;
3082
3083 /* Reduce this to a hash of another object. */
3084 if (n == OFFSET_NAIVE)
3085 temp = datetime_getstate(self);
3086 else {
3087 int days;
3088 int seconds;
3089
3090 assert(n == OFFSET_AWARE);
3091 assert(PyDateTimeTZ_Check(self));
3092 days = ymd_to_ord(GET_YEAR(self),
3093 GET_MONTH(self),
3094 GET_DAY(self));
3095 seconds = DATE_GET_HOUR(self) * 3600 +
3096 (DATE_GET_MINUTE(self) - offset) * 60 +
3097 DATE_GET_SECOND(self);
3098 temp = new_delta(days,
3099 seconds,
3100 DATE_GET_MICROSECOND(self),
3101 1);
3102 }
3103 if (temp != NULL) {
3104 self->hashcode = PyObject_Hash(temp);
3105 Py_DECREF(temp);
3106 }
3107 }
3108 return self->hashcode;
3109}
3110
3111static PyObject *
3112datetime_timetuple(PyDateTime_DateTime *self)
3113{
3114 return build_struct_time(GET_YEAR(self),
3115 GET_MONTH(self),
3116 GET_DAY(self),
3117 DATE_GET_HOUR(self),
3118 DATE_GET_MINUTE(self),
3119 DATE_GET_SECOND(self),
3120 -1);
3121}
3122
3123static PyObject *
3124datetime_getdate(PyDateTime_DateTime *self)
3125{
3126 return new_date(GET_YEAR(self),
3127 GET_MONTH(self),
3128 GET_DAY(self));
3129}
3130
3131static PyObject *
3132datetime_gettime(PyDateTime_DateTime *self)
3133{
3134 return new_time(DATE_GET_HOUR(self),
3135 DATE_GET_MINUTE(self),
3136 DATE_GET_SECOND(self),
3137 DATE_GET_MICROSECOND(self));
3138}
3139
3140/* Pickle support. Quite a maze! */
3141
3142static PyObject *
3143datetime_getstate(PyDateTime_DateTime *self)
3144{
3145 return PyString_FromStringAndSize(self->data,
3146 _PyDateTime_DATETIME_DATASIZE);
3147}
3148
3149static PyObject *
3150datetime_setstate(PyDateTime_DateTime *self, PyObject *state)
3151{
3152 const int len = PyString_Size(state);
3153 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
3154
3155 if (! PyString_Check(state) ||
3156 len != _PyDateTime_DATETIME_DATASIZE) {
3157 PyErr_SetString(PyExc_TypeError,
3158 "bad argument to datetime.__setstate__");
3159 return NULL;
3160 }
3161 memcpy(self->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3162 self->hashcode = -1;
3163
3164 Py_INCREF(Py_None);
3165 return Py_None;
3166}
3167
3168/* XXX This seems a ridiculously inefficient way to pickle a short string. */
3169static PyObject *
3170datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime)
3171{
3172 PyObject *state;
3173 PyObject *result = NULL;
3174
3175 if (! PyDateTime_CheckExact(datetime)) {
3176 PyErr_Format(PyExc_TypeError,
3177 "bad type passed to datetime pickler: %s",
3178 datetime->ob_type->tp_name);
3179 return NULL;
3180 }
3181 state = datetime_getstate(datetime);
3182 if (state) {
3183 result = Py_BuildValue("O(O)",
3184 datetime_unpickler_object,
3185 state);
3186 Py_DECREF(state);
3187 }
3188 return result;
3189}
3190
3191static PyObject *
3192datetime_unpickler(PyObject *module, PyObject *arg)
3193{
3194 PyDateTime_DateTime *self;
3195
3196 if (! PyString_CheckExact(arg)) {
3197 PyErr_Format(PyExc_TypeError,
3198 "bad type passed to datetime unpickler: %s",
3199 arg->ob_type->tp_name);
3200 return NULL;
3201 }
3202 self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType);
3203 if (self != NULL) {
3204 PyObject *res = datetime_setstate(self, arg);
3205 if (res == NULL) {
3206 Py_DECREF(self);
3207 return NULL;
3208 }
3209 Py_DECREF(res);
3210 }
3211 return (PyObject *)self;
3212}
3213
3214static PyMethodDef datetime_methods[] = {
3215 /* Class methods: */
3216 {"now", (PyCFunction)datetime_now,
3217 METH_NOARGS | METH_CLASS,
3218 PyDoc_STR("Return a new datetime representing local day and time.")},
3219
3220 {"utcnow", (PyCFunction)datetime_utcnow,
3221 METH_NOARGS | METH_CLASS,
3222 PyDoc_STR("Return a new datetime representing UTC day and time.")},
3223
3224 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
3225 METH_VARARGS | METH_CLASS,
3226 PyDoc_STR("timestamp -> local datetime from a POSIX timestamp "
3227 "(like time.time()).")},
3228
3229 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
3230 METH_VARARGS | METH_CLASS,
3231 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
3232 "(like time.time()).")},
3233
3234 {"combine", (PyCFunction)datetime_combine,
3235 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3236 PyDoc_STR("date, time -> datetime with same date and time fields")},
3237
3238 /* Instance methods: */
3239 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
3240 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
3241
3242 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
3243 PyDoc_STR("Return date object with same year, month and day.")},
3244
3245 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
3246 PyDoc_STR("Return time object with same hour, minute, second and "
3247 "microsecond.")},
3248
3249 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
3250 PyDoc_STR("Return ctime() style string.")},
3251
3252 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
3253 PyDoc_STR("[sep] -> string in ISO 8601 format, "
3254 "YYYY-MM-DDTHH:MM:SS[.mmmmmm].\n\n"
3255 "sep is used to separate the year from the time, and "
3256 "defaults\n"
3257 "to 'T'.")},
3258
3259 {"__setstate__", (PyCFunction)datetime_setstate, METH_O,
3260 PyDoc_STR("__setstate__(state)")},
3261
3262 {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS,
3263 PyDoc_STR("__getstate__() -> state")},
3264 {NULL, NULL}
3265};
3266
3267static char datetime_doc[] =
3268PyDoc_STR("Basic date/time type.");
3269
3270static PyNumberMethods datetime_as_number = {
3271 datetime_add, /* nb_add */
3272 datetime_subtract, /* nb_subtract */
3273 0, /* nb_multiply */
3274 0, /* nb_divide */
3275 0, /* nb_remainder */
3276 0, /* nb_divmod */
3277 0, /* nb_power */
3278 0, /* nb_negative */
3279 0, /* nb_positive */
3280 0, /* nb_absolute */
3281 0, /* nb_nonzero */
3282};
3283
3284statichere PyTypeObject PyDateTime_DateTimeType = {
3285 PyObject_HEAD_INIT(NULL)
3286 0, /* ob_size */
3287 "datetime.datetime", /* tp_name */
3288 sizeof(PyDateTime_DateTime), /* tp_basicsize */
3289 0, /* tp_itemsize */
3290 (destructor)PyObject_Del, /* tp_dealloc */
3291 0, /* tp_print */
3292 0, /* tp_getattr */
3293 0, /* tp_setattr */
3294 0, /* tp_compare */
3295 (reprfunc)datetime_repr, /* tp_repr */
3296 &datetime_as_number, /* tp_as_number */
3297 0, /* tp_as_sequence */
3298 0, /* tp_as_mapping */
3299 (hashfunc)datetime_hash, /* tp_hash */
3300 0, /* tp_call */
3301 (reprfunc)datetime_str, /* tp_str */
3302 PyObject_GenericGetAttr, /* tp_getattro */
3303 0, /* tp_setattro */
3304 0, /* tp_as_buffer */
3305 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3306 Py_TPFLAGS_BASETYPE, /* tp_flags */
3307 datetime_doc, /* tp_doc */
3308 0, /* tp_traverse */
3309 0, /* tp_clear */
3310 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
3311 0, /* tp_weaklistoffset */
3312 0, /* tp_iter */
3313 0, /* tp_iternext */
3314 datetime_methods, /* tp_methods */
3315 0, /* tp_members */
3316 datetime_getset, /* tp_getset */
3317 &PyDateTime_DateType, /* tp_base */
3318 0, /* tp_dict */
3319 0, /* tp_descr_get */
3320 0, /* tp_descr_set */
3321 0, /* tp_dictoffset */
3322 0, /* tp_init */
3323 0, /* tp_alloc */
3324 datetime_new, /* tp_new */
3325 _PyObject_Del, /* tp_free */
3326};
3327
3328/*
3329 * PyDateTime_Time implementation.
3330 */
3331
3332/* Accessor properties. */
3333
3334static PyObject *
3335time_hour(PyDateTime_Time *self, void *unused)
3336{
3337 return PyInt_FromLong(TIME_GET_HOUR(self));
3338}
3339
3340static PyObject *
3341time_minute(PyDateTime_Time *self, void *unused)
3342{
3343 return PyInt_FromLong(TIME_GET_MINUTE(self));
3344}
3345
3346static PyObject *
Jack Jansen51cd8a22002-12-17 20:57:24 +00003347py_time_second(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003348{
3349 return PyInt_FromLong(TIME_GET_SECOND(self));
3350}
3351
3352static PyObject *
3353time_microsecond(PyDateTime_Time *self, void *unused)
3354{
3355 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3356}
3357
3358static PyGetSetDef time_getset[] = {
3359 {"hour", (getter)time_hour},
3360 {"minute", (getter)time_minute},
Jack Jansen51cd8a22002-12-17 20:57:24 +00003361 {"second", (getter)py_time_second},
Tim Peters2a799bf2002-12-16 20:18:38 +00003362 {"microsecond", (getter)time_microsecond},
3363 {NULL}
3364};
3365
3366/* Constructors. */
3367
3368static PyObject *
3369time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3370{
3371 PyObject *self = NULL;
3372 int hour = 0;
3373 int minute = 0;
3374 int second = 0;
3375 int usecond = 0;
3376
3377 static char *keywords[] = {
3378 "hour", "minute", "second", "microsecond", NULL
3379 };
3380
3381 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiii", keywords,
3382 &hour, &minute, &second, &usecond)) {
3383 if (check_time_args(hour, minute, second, usecond) < 0)
3384 return NULL;
3385 self = new_time(hour, minute, second, usecond);
3386 }
3387 return self;
3388}
3389
3390/* Various ways to turn a time into a string. */
3391
3392static PyObject *
3393time_repr(PyDateTime_Time *self)
3394{
3395 char buffer[100];
3396 char *typename = self->ob_type->tp_name;
3397 int h = TIME_GET_HOUR(self);
3398 int m = TIME_GET_MINUTE(self);
3399 int s = TIME_GET_SECOND(self);
3400 int us = TIME_GET_MICROSECOND(self);
3401
3402 if (us)
3403 PyOS_snprintf(buffer, sizeof(buffer),
3404 "%s(%d, %d, %d, %d)", typename, h, m, s, us);
3405 else if (s)
3406 PyOS_snprintf(buffer, sizeof(buffer),
3407 "%s(%d, %d, %d)", typename, h, m, s);
3408 else
3409 PyOS_snprintf(buffer, sizeof(buffer),
3410 "%s(%d, %d)", typename, h, m);
3411 return PyString_FromString(buffer);
3412}
3413
3414static PyObject *
3415time_str(PyDateTime_Time *self)
3416{
3417 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3418}
3419
3420static PyObject *
3421time_isoformat(PyDateTime_Time *self)
3422{
3423 char buffer[100];
3424 /* Reuse the time format code from the datetime type. */
3425 PyDateTime_DateTime datetime;
3426 PyDateTime_DateTime *pdatetime = &datetime;
3427
3428 /* Copy over just the time bytes. */
3429 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3430 self->data,
3431 _PyDateTime_TIME_DATASIZE);
3432
3433 isoformat_time(pdatetime, buffer, sizeof(buffer));
3434 return PyString_FromString(buffer);
3435}
3436
3437static PyObject *
3438time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3439{
3440 PyObject *result;
3441 PyObject *format;
3442 PyObject *tuple;
3443 static char *keywords[] = {"format", NULL};
3444
3445 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3446 &PyString_Type, &format))
3447 return NULL;
3448
3449 tuple = Py_BuildValue("iiiiiiiii",
3450 0, 0, 0, /* year, month, day */
3451 TIME_GET_HOUR(self),
3452 TIME_GET_MINUTE(self),
3453 TIME_GET_SECOND(self),
3454 0, 0, -1); /* weekday, daynum, dst */
3455 if (tuple == NULL)
3456 return NULL;
3457 assert(PyTuple_Size(tuple) == 9);
3458 result = wrap_strftime((PyObject *)self, format, tuple);
3459 Py_DECREF(tuple);
3460 return result;
3461}
3462
3463/* Miscellaneous methods. */
3464
3465/* This is more natural as a tp_compare, but doesn't work then: for whatever
3466 * reason, Python's try_3way_compare ignores tp_compare unless
3467 * PyInstance_Check returns true, but these aren't old-style classes.
3468 * Note that this routine handles all comparisons for time and timetz.
3469 */
3470static PyObject *
3471time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3472{
3473 int diff;
3474 naivety n1, n2;
3475 int offset1, offset2;
3476
3477 if (! PyTime_Check(other)) {
3478 /* Stop this from falling back to address comparison. */
3479 PyErr_Format(PyExc_TypeError,
3480 "can't compare '%s' to '%s'",
3481 self->ob_type->tp_name,
3482 other->ob_type->tp_name);
3483 return NULL;
3484 }
3485 n1 = classify_object((PyObject *)self, &offset1);
3486 assert(n1 != OFFSET_UNKNOWN);
3487 if (n1 == OFFSET_ERROR)
3488 return NULL;
3489
3490 n2 = classify_object(other, &offset2);
3491 assert(n2 != OFFSET_UNKNOWN);
3492 if (n2 == OFFSET_ERROR)
3493 return NULL;
3494
3495 /* If they're both naive, or both aware and have the same offsets,
3496 * we get off cheap. Note that if they're both naive, offset1 ==
3497 * offset2 == 0 at this point.
3498 */
3499 if (n1 == n2 && offset1 == offset2) {
3500 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3501 _PyDateTime_TIME_DATASIZE);
3502 return diff_to_bool(diff, op);
3503 }
3504
3505 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3506 assert(offset1 != offset2); /* else last "if" handled it */
3507 /* Convert everything except microseconds to seconds. These
3508 * can't overflow (no more than the # of seconds in 2 days).
3509 */
3510 offset1 = TIME_GET_HOUR(self) * 3600 +
3511 (TIME_GET_MINUTE(self) - offset1) * 60 +
3512 TIME_GET_SECOND(self);
3513 offset2 = TIME_GET_HOUR(other) * 3600 +
3514 (TIME_GET_MINUTE(other) - offset2) * 60 +
3515 TIME_GET_SECOND(other);
3516 diff = offset1 - offset2;
3517 if (diff == 0)
3518 diff = TIME_GET_MICROSECOND(self) -
3519 TIME_GET_MICROSECOND(other);
3520 return diff_to_bool(diff, op);
3521 }
3522
3523 assert(n1 != n2);
3524 PyErr_SetString(PyExc_TypeError,
3525 "can't compare offset-naive and "
3526 "offset-aware times");
3527 return NULL;
3528}
3529
3530static PyObject *time_getstate(PyDateTime_Time *self);
3531
3532static long
3533time_hash(PyDateTime_Time *self)
3534{
3535 if (self->hashcode == -1) {
3536 naivety n;
3537 int offset;
3538 PyObject *temp;
3539
3540 n = classify_object((PyObject *)self, &offset);
3541 assert(n != OFFSET_UNKNOWN);
3542 if (n == OFFSET_ERROR)
3543 return -1;
3544
3545 /* Reduce this to a hash of another object. */
3546 if (offset == 0)
3547 temp = time_getstate(self);
3548 else {
3549 int hour;
3550 int minute;
3551
3552 assert(n == OFFSET_AWARE);
3553 assert(PyTimeTZ_Check(self));
3554 hour = divmod(TIME_GET_HOUR(self) * 60 +
3555 TIME_GET_MINUTE(self) - offset,
3556 60,
3557 &minute);
3558 if (0 <= hour && hour < 24)
3559 temp = new_time(hour, minute,
3560 TIME_GET_SECOND(self),
3561 TIME_GET_MICROSECOND(self));
3562 else
3563 temp = Py_BuildValue("iiii",
3564 hour, minute,
3565 TIME_GET_SECOND(self),
3566 TIME_GET_MICROSECOND(self));
3567 }
3568 if (temp != NULL) {
3569 self->hashcode = PyObject_Hash(temp);
3570 Py_DECREF(temp);
3571 }
3572 }
3573 return self->hashcode;
3574}
3575
3576static int
3577time_nonzero(PyDateTime_Time *self)
3578{
3579 return TIME_GET_HOUR(self) ||
3580 TIME_GET_MINUTE(self) ||
3581 TIME_GET_SECOND(self) ||
3582 TIME_GET_MICROSECOND(self);
3583}
3584
3585/* Pickle support. Quite a maze! */
3586
3587static PyObject *
3588time_getstate(PyDateTime_Time *self)
3589{
3590 return PyString_FromStringAndSize(self->data,
3591 _PyDateTime_TIME_DATASIZE);
3592}
3593
3594static PyObject *
3595time_setstate(PyDateTime_Time *self, PyObject *state)
3596{
3597 const int len = PyString_Size(state);
3598 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
3599
3600 if (! PyString_Check(state) ||
3601 len != _PyDateTime_TIME_DATASIZE) {
3602 PyErr_SetString(PyExc_TypeError,
3603 "bad argument to time.__setstate__");
3604 return NULL;
3605 }
3606 memcpy(self->data, pdata, _PyDateTime_TIME_DATASIZE);
3607 self->hashcode = -1;
3608
3609 Py_INCREF(Py_None);
3610 return Py_None;
3611}
3612
3613/* XXX This seems a ridiculously inefficient way to pickle a short string. */
3614static PyObject *
3615time_pickler(PyObject *module, PyDateTime_Time *time)
3616{
3617 PyObject *state;
3618 PyObject *result = NULL;
3619
3620 if (! PyTime_CheckExact(time)) {
3621 PyErr_Format(PyExc_TypeError,
3622 "bad type passed to time pickler: %s",
3623 time->ob_type->tp_name);
3624 return NULL;
3625 }
3626 state = time_getstate(time);
3627 if (state) {
3628 result = Py_BuildValue("O(O)",
3629 time_unpickler_object,
3630 state);
3631 Py_DECREF(state);
3632 }
3633 return result;
3634}
3635
3636static PyObject *
3637time_unpickler(PyObject *module, PyObject *arg)
3638{
3639 PyDateTime_Time *self;
3640
3641 if (! PyString_CheckExact(arg)) {
3642 PyErr_Format(PyExc_TypeError,
3643 "bad type passed to time unpickler: %s",
3644 arg->ob_type->tp_name);
3645 return NULL;
3646 }
3647 self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType);
3648 if (self != NULL) {
3649 PyObject *res = time_setstate(self, arg);
3650 if (res == NULL) {
3651 Py_DECREF(self);
3652 return NULL;
3653 }
3654 Py_DECREF(res);
3655 }
3656 return (PyObject *)self;
3657}
3658
3659static PyMethodDef time_methods[] = {
3660 {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
3661 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm].")},
3662
3663 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3664 PyDoc_STR("format -> strftime() style string.")},
3665
3666 {"__setstate__", (PyCFunction)time_setstate, METH_O,
3667 PyDoc_STR("__setstate__(state)")},
3668
3669 {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS,
3670 PyDoc_STR("__getstate__() -> state")},
3671 {NULL, NULL}
3672};
3673
3674static char time_doc[] =
3675PyDoc_STR("Basic time type.");
3676
3677static PyNumberMethods time_as_number = {
3678 0, /* nb_add */
3679 0, /* nb_subtract */
3680 0, /* nb_multiply */
3681 0, /* nb_divide */
3682 0, /* nb_remainder */
3683 0, /* nb_divmod */
3684 0, /* nb_power */
3685 0, /* nb_negative */
3686 0, /* nb_positive */
3687 0, /* nb_absolute */
3688 (inquiry)time_nonzero, /* nb_nonzero */
3689};
3690
3691statichere PyTypeObject PyDateTime_TimeType = {
3692 PyObject_HEAD_INIT(NULL)
3693 0, /* ob_size */
3694 "datetime.time", /* tp_name */
3695 sizeof(PyDateTime_Time), /* tp_basicsize */
3696 0, /* tp_itemsize */
3697 (destructor)PyObject_Del, /* tp_dealloc */
3698 0, /* tp_print */
3699 0, /* tp_getattr */
3700 0, /* tp_setattr */
3701 0, /* tp_compare */
3702 (reprfunc)time_repr, /* tp_repr */
3703 &time_as_number, /* tp_as_number */
3704 0, /* tp_as_sequence */
3705 0, /* tp_as_mapping */
3706 (hashfunc)time_hash, /* tp_hash */
3707 0, /* tp_call */
3708 (reprfunc)time_str, /* tp_str */
3709 PyObject_GenericGetAttr, /* tp_getattro */
3710 0, /* tp_setattro */
3711 0, /* tp_as_buffer */
3712 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3713 Py_TPFLAGS_BASETYPE, /* tp_flags */
3714 time_doc, /* tp_doc */
3715 0, /* tp_traverse */
3716 0, /* tp_clear */
3717 (richcmpfunc)time_richcompare, /* tp_richcompare */
3718 0, /* tp_weaklistoffset */
3719 0, /* tp_iter */
3720 0, /* tp_iternext */
3721 time_methods, /* tp_methods */
3722 0, /* tp_members */
3723 time_getset, /* tp_getset */
3724 0, /* tp_base */
3725 0, /* tp_dict */
3726 0, /* tp_descr_get */
3727 0, /* tp_descr_set */
3728 0, /* tp_dictoffset */
3729 0, /* tp_init */
3730 0, /* tp_alloc */
3731 time_new, /* tp_new */
3732 _PyObject_Del, /* tp_free */
3733};
3734
3735/*
3736 * PyDateTime_TZInfo implementation.
3737 */
3738
3739/* This is a pure abstract base class, so doesn't do anything beyond
3740 * raising NotImplemented exceptions. Real tzinfo classes need
3741 * to derive from this. This is mostly for clarity, and for efficiency in
3742 * datetimetz and timetz constructors (their tzinfo arguments need to
3743 * be subclasses of this tzinfo class, which is easy and quick to check).
3744 *
3745 * Note: For reasons having to do with pickling of subclasses, we have
3746 * to allow tzinfo objects to be instantiated. This wasn't an issue
3747 * in the Python implementation (__init__() could raise NotImplementedError
3748 * there without ill effect), but doing so in the C implementation hit a
3749 * brick wall.
3750 */
3751
3752static PyObject *
3753tzinfo_nogo(const char* methodname)
3754{
3755 PyErr_Format(PyExc_NotImplementedError,
3756 "a tzinfo subclass must implement %s()",
3757 methodname);
3758 return NULL;
3759}
3760
3761/* Methods. A subclass must implement these. */
3762
3763static PyObject*
3764tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3765{
3766 return tzinfo_nogo("tzname");
3767}
3768
3769static PyObject*
3770tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3771{
3772 return tzinfo_nogo("utcoffset");
3773}
3774
3775static PyObject*
3776tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3777{
3778 return tzinfo_nogo("dst");
3779}
3780
3781/*
3782 * Pickle support. This is solely so that tzinfo subclasses can use
3783 * pickling -- tzinfo itself is supposed to be uninstantiable. The
3784 * pickler and unpickler functions are given module-level private
3785 * names, and registered with copy_reg, by the module init function.
3786 */
3787
3788static PyObject*
3789tzinfo_pickler(PyDateTime_TZInfo *self) {
3790 return Py_BuildValue("O()", tzinfo_unpickler_object);
3791}
3792
3793static PyObject*
3794tzinfo_unpickler(PyObject * unused) {
3795 return PyType_GenericNew(&PyDateTime_TZInfoType, NULL, NULL);
3796}
3797
3798
3799static PyMethodDef tzinfo_methods[] = {
3800 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3801 PyDoc_STR("datetime -> string name of time zone.")},
3802
3803 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
3804 PyDoc_STR("datetime -> minutes east of UTC (negative for "
3805 "west of UTC).")},
3806
3807 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3808 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
3809
3810 {NULL, NULL}
3811};
3812
3813static char tzinfo_doc[] =
3814PyDoc_STR("Abstract base class for time zone info objects.");
3815
3816 statichere PyTypeObject PyDateTime_TZInfoType = {
3817 PyObject_HEAD_INIT(NULL)
3818 0, /* ob_size */
3819 "datetime.tzinfo", /* tp_name */
3820 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3821 0, /* tp_itemsize */
3822 0, /* tp_dealloc */
3823 0, /* tp_print */
3824 0, /* tp_getattr */
3825 0, /* tp_setattr */
3826 0, /* tp_compare */
3827 0, /* tp_repr */
3828 0, /* tp_as_number */
3829 0, /* tp_as_sequence */
3830 0, /* tp_as_mapping */
3831 0, /* tp_hash */
3832 0, /* tp_call */
3833 0, /* tp_str */
3834 PyObject_GenericGetAttr, /* tp_getattro */
3835 0, /* tp_setattro */
3836 0, /* tp_as_buffer */
3837 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3838 Py_TPFLAGS_BASETYPE, /* tp_flags */
3839 tzinfo_doc, /* tp_doc */
3840 0, /* tp_traverse */
3841 0, /* tp_clear */
3842 0, /* tp_richcompare */
3843 0, /* tp_weaklistoffset */
3844 0, /* tp_iter */
3845 0, /* tp_iternext */
3846 tzinfo_methods, /* tp_methods */
3847 0, /* tp_members */
3848 0, /* tp_getset */
3849 0, /* tp_base */
3850 0, /* tp_dict */
3851 0, /* tp_descr_get */
3852 0, /* tp_descr_set */
3853 0, /* tp_dictoffset */
3854 0, /* tp_init */
3855 0, /* tp_alloc */
3856 PyType_GenericNew, /* tp_new */
3857 0, /* tp_free */
3858};
3859
3860/*
3861 * PyDateTime_TimeTZ implementation.
3862 */
3863
3864/* Accessor properties. Properties for hour, minute, second and microsecond
3865 * are inherited from time.
3866 */
3867
3868static PyObject *
3869timetz_tzinfo(PyDateTime_TimeTZ *self, void *unused)
3870{
3871 Py_INCREF(self->tzinfo);
3872 return self->tzinfo;
3873}
3874
3875static PyGetSetDef timetz_getset[] = {
3876 {"tzinfo", (getter)timetz_tzinfo},
3877 {NULL}
3878};
3879
3880/*
3881 * Constructors.
3882 */
3883
3884static PyObject *
3885timetz_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3886{
3887 PyObject *self = NULL;
3888 int hour = 0;
3889 int minute = 0;
3890 int second = 0;
3891 int usecond = 0;
3892 PyObject *tzinfo = Py_None;
3893
3894 static char *keywords[] = {
3895 "hour", "minute", "second", "microsecond", "tzinfo", NULL
3896 };
3897
Neal Norwitzc296c632002-12-19 00:42:03 +00003898 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", keywords,
Tim Peters2a799bf2002-12-16 20:18:38 +00003899 &hour, &minute, &second, &usecond,
3900 &tzinfo)) {
3901 if (check_time_args(hour, minute, second, usecond) < 0)
3902 return NULL;
3903 if (check_tzinfo_subclass(tzinfo) < 0)
3904 return NULL;
3905 self = new_timetz(hour, minute, second, usecond, tzinfo);
3906 }
3907 return self;
3908}
3909
3910/*
3911 * Destructor.
3912 */
3913
3914static void
3915timetz_dealloc(PyDateTime_TimeTZ *self)
3916{
3917 Py_XDECREF(self->tzinfo);
3918 self->ob_type->tp_free((PyObject *)self);
3919}
3920
3921/*
3922 * Indirect access to tzinfo methods. One more "convenience function" and
3923 * it won't be possible to find the useful methods anymore <0.5 wink>.
3924 */
3925
3926static PyObject *
3927timetz_convienience(PyDateTime_TimeTZ *self, char *name)
3928{
3929 PyObject *result;
3930
3931 if (self->tzinfo == Py_None) {
3932 result = Py_None;
3933 Py_INCREF(result);
3934 }
3935 else
3936 result = PyObject_CallMethod(self->tzinfo, name, "O", self);
3937 return result;
3938}
3939
3940/* These are all METH_NOARGS, so don't need to check the arglist. */
3941static PyObject *
3942timetz_utcoffset(PyDateTime_TimeTZ *self, PyObject *unused) {
3943 return timetz_convienience(self, "utcoffset");
3944}
3945
3946static PyObject *
3947timetz_tzname(PyDateTime_TimeTZ *self, PyObject *unused) {
3948 return timetz_convienience(self, "tzname");
3949}
3950
3951static PyObject *
3952timetz_dst(PyDateTime_TimeTZ *self, PyObject *unused) {
3953 return timetz_convienience(self, "dst");
3954}
3955
3956/*
3957 * Various ways to turn a timetz into a string.
3958 */
3959
3960static PyObject *
3961timetz_repr(PyDateTime_TimeTZ *self)
3962{
3963 PyObject *baserepr = time_repr((PyDateTime_Time *)self);
3964
3965 if (baserepr == NULL)
3966 return NULL;
3967 return append_keyword_tzinfo(baserepr, self->tzinfo);
3968}
3969
3970/* Note: tp_str is inherited from time. */
3971
3972static PyObject *
3973timetz_isoformat(PyDateTime_TimeTZ *self)
3974{
3975 char buf[100];
3976 PyObject *result = time_isoformat((PyDateTime_Time *)self);
3977
3978 if (result == NULL || self->tzinfo == Py_None)
3979 return result;
3980
3981 /* We need to append the UTC offset. */
3982 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3983 (PyObject *)self) < 0) {
3984 Py_DECREF(result);
3985 return NULL;
3986 }
3987 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3988 return result;
3989}
3990
3991/* Note: strftime() is inherited from time. */
3992
3993/*
3994 * Miscellaneous methods.
3995 */
3996
3997/* Note: tp_richcompare and tp_hash are inherited from time. */
3998
3999static int
4000timetz_nonzero(PyDateTime_TimeTZ *self)
4001{
4002 int offset;
4003 int none;
4004
4005 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
4006 /* Since utcoffset is in whole minutes, nothing can
4007 * alter the conclusion that this is nonzero.
4008 */
4009 return 1;
4010 }
4011 offset = 0;
4012 if (self->tzinfo != Py_None) {
4013 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4014 if (offset == -1 && PyErr_Occurred())
4015 return -1;
4016 }
4017 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
4018}
4019
4020/*
4021 * Pickle support. Quite a maze!
4022 */
4023
4024/* Let basestate be the state string returned by time_getstate.
4025 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4026 * So it's a tuple in any (non-error) case.
4027 */
4028static PyObject *
4029timetz_getstate(PyDateTime_TimeTZ *self)
4030{
4031 PyObject *basestate;
4032 PyObject *result = NULL;
4033
4034 basestate = time_getstate((PyDateTime_Time *)self);
4035 if (basestate != NULL) {
4036 if (self->tzinfo == Py_None)
4037 result = Py_BuildValue("(O)", basestate);
4038 else
4039 result = Py_BuildValue("OO", basestate, self->tzinfo);
4040 Py_DECREF(basestate);
4041 }
4042 return result;
4043}
4044
4045static PyObject *
4046timetz_setstate(PyDateTime_TimeTZ *self, PyObject *state)
4047{
4048 PyObject *temp;
4049 PyObject *basestate;
4050 PyObject *tzinfo = Py_None;
4051
4052 if (! PyArg_ParseTuple(state, "O!|O:__setstate__",
4053 &PyString_Type, &basestate,
4054 &tzinfo))
4055 return NULL;
4056 temp = time_setstate((PyDateTime_Time *)self, basestate);
4057 if (temp == NULL)
4058 return NULL;
4059 Py_DECREF(temp);
4060
4061 Py_INCREF(tzinfo);
4062 Py_XDECREF(self->tzinfo);
4063 self->tzinfo = tzinfo;
4064
4065 Py_INCREF(Py_None);
4066 return Py_None;
4067}
4068
4069static PyObject *
4070timetz_pickler(PyObject *module, PyDateTime_TimeTZ *timetz)
4071{
4072 PyObject *state;
4073 PyObject *result = NULL;
4074
4075 if (! PyTimeTZ_CheckExact(timetz)) {
4076 PyErr_Format(PyExc_TypeError,
4077 "bad type passed to timetz pickler: %s",
4078 timetz->ob_type->tp_name);
4079 return NULL;
4080 }
4081 state = timetz_getstate(timetz);
4082 if (state) {
4083 result = Py_BuildValue("O(O)",
4084 timetz_unpickler_object,
4085 state);
4086 Py_DECREF(state);
4087 }
4088 return result;
4089}
4090
4091static PyObject *
4092timetz_unpickler(PyObject *module, PyObject *arg)
4093{
4094 PyDateTime_TimeTZ *self;
4095
4096 self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType);
4097 if (self != NULL) {
4098 PyObject *res;
4099
4100 self->tzinfo = NULL;
4101 res = timetz_setstate(self, arg);
4102 if (res == NULL) {
4103 Py_DECREF(self);
4104 return NULL;
4105 }
4106 Py_DECREF(res);
4107 }
4108 return (PyObject *)self;
4109}
4110
4111static PyMethodDef timetz_methods[] = {
4112 {"isoformat", (PyCFunction)timetz_isoformat, METH_KEYWORDS,
4113 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
4114 "[+HH:MM].")},
4115
4116 {"utcoffset", (PyCFunction)timetz_utcoffset, METH_NOARGS,
4117 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4118
4119 {"tzname", (PyCFunction)timetz_tzname, METH_NOARGS,
4120 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4121
4122 {"dst", (PyCFunction)timetz_dst, METH_NOARGS,
4123 PyDoc_STR("Return self.tzinfo.dst(self).")},
4124
4125 {"__setstate__", (PyCFunction)timetz_setstate, METH_O,
4126 PyDoc_STR("__setstate__(state)")},
4127
4128 {"__getstate__", (PyCFunction)timetz_getstate, METH_NOARGS,
4129 PyDoc_STR("__getstate__() -> state")},
4130 {NULL, NULL}
4131
4132};
4133
4134static char timetz_doc[] =
4135PyDoc_STR("Time type.");
4136
4137static PyNumberMethods timetz_as_number = {
4138 0, /* nb_add */
4139 0, /* nb_subtract */
4140 0, /* nb_multiply */
4141 0, /* nb_divide */
4142 0, /* nb_remainder */
4143 0, /* nb_divmod */
4144 0, /* nb_power */
4145 0, /* nb_negative */
4146 0, /* nb_positive */
4147 0, /* nb_absolute */
4148 (inquiry)timetz_nonzero, /* nb_nonzero */
4149};
4150
4151statichere PyTypeObject PyDateTime_TimeTZType = {
4152 PyObject_HEAD_INIT(NULL)
4153 0, /* ob_size */
4154 "datetime.timetz", /* tp_name */
4155 sizeof(PyDateTime_TimeTZ), /* tp_basicsize */
4156 0, /* tp_itemsize */
4157 (destructor)timetz_dealloc, /* tp_dealloc */
4158 0, /* tp_print */
4159 0, /* tp_getattr */
4160 0, /* tp_setattr */
4161 0, /* tp_compare */
4162 (reprfunc)timetz_repr, /* tp_repr */
4163 &timetz_as_number, /* tp_as_number */
4164 0, /* tp_as_sequence */
4165 0, /* tp_as_mapping */
4166 0, /* tp_hash */
4167 0, /* tp_call */
4168 0, /* tp_str */
4169 PyObject_GenericGetAttr, /* tp_getattro */
4170 0, /* tp_setattro */
4171 0, /* tp_as_buffer */
4172 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4173 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumbd43e912002-12-16 20:34:55 +00004174 timetz_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004175 0, /* tp_traverse */
4176 0, /* tp_clear */
4177 0, /* tp_richcompare */
4178 0, /* tp_weaklistoffset */
4179 0, /* tp_iter */
4180 0, /* tp_iternext */
4181 timetz_methods, /* tp_methods */
4182 0, /* tp_members */
4183 timetz_getset, /* tp_getset */
4184 &PyDateTime_TimeType, /* tp_base */
4185 0, /* tp_dict */
4186 0, /* tp_descr_get */
4187 0, /* tp_descr_set */
4188 0, /* tp_dictoffset */
4189 0, /* tp_init */
4190 0, /* tp_alloc */
4191 timetz_new, /* tp_new */
4192 _PyObject_Del, /* tp_free */
4193};
4194
4195/*
4196 * PyDateTime_DateTimeTZ implementation.
4197 */
4198
4199/* Accessor properties. Properties for day, month, year, hour, minute,
4200 * second and microsecond are inherited from datetime.
4201 */
4202
4203static PyObject *
4204datetimetz_tzinfo(PyDateTime_DateTimeTZ *self, void *unused)
4205{
4206 Py_INCREF(self->tzinfo);
4207 return self->tzinfo;
4208}
4209
4210static PyGetSetDef datetimetz_getset[] = {
4211 {"tzinfo", (getter)datetimetz_tzinfo},
4212 {NULL}
4213};
4214
4215/*
4216 * Constructors.
4217 * These are like the datetime methods of the same names, but allow an
4218 * optional tzinfo argument.
4219 */
4220
4221/* Internal helper.
4222 * self is a datetimetz. Replace its tzinfo member.
4223 */
4224void
4225replace_tzinfo(PyObject *self, PyObject *newtzinfo)
4226{
4227 assert(self != NULL);
4228 assert(newtzinfo != NULL);
4229 assert(PyDateTimeTZ_Check(self));
4230 Py_INCREF(newtzinfo);
4231 Py_DECREF(((PyDateTime_DateTimeTZ *)self)->tzinfo);
4232 ((PyDateTime_DateTimeTZ *)self)->tzinfo = newtzinfo;
4233}
4234
4235static PyObject *
4236datetimetz_new(PyTypeObject *type, PyObject *args, PyObject *kw)
4237{
4238 PyObject *self = NULL;
4239 int year;
4240 int month;
4241 int day;
4242 int hour = 0;
4243 int minute = 0;
4244 int second = 0;
4245 int usecond = 0;
4246 PyObject *tzinfo = Py_None;
4247
4248 static char *keywords[] = {
4249 "year", "month", "day", "hour", "minute", "second",
4250 "microsecond", "tzinfo", NULL
4251 };
4252
4253 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", keywords,
4254 &year, &month, &day, &hour, &minute,
4255 &second, &usecond, &tzinfo)) {
4256 if (check_date_args(year, month, day) < 0)
4257 return NULL;
4258 if (check_time_args(hour, minute, second, usecond) < 0)
4259 return NULL;
4260 if (check_tzinfo_subclass(tzinfo) < 0)
4261 return NULL;
4262 self = new_datetimetz(year, month, day,
4263 hour, minute, second, usecond,
4264 tzinfo);
4265 }
4266 return self;
4267}
4268
4269/* Return best possible local time -- this isn't constrained by the
4270 * precision of a timestamp.
4271 */
4272static PyObject *
4273datetimetz_now(PyObject *cls, PyObject *args, PyObject *kw)
4274{
4275 PyObject *self = NULL;
4276 PyObject *tzinfo = Py_None;
4277 static char *keywords[] = {"tzinfo", NULL};
4278
4279 if (PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
4280 &tzinfo)) {
4281 if (check_tzinfo_subclass(tzinfo) < 0)
4282 return NULL;
4283 self = datetime_best_possible(cls, localtime);
4284 if (self != NULL)
4285 replace_tzinfo(self, tzinfo);
4286 }
4287 return self;
4288}
4289
4290/* Return new local datetime from timestamp (Python timestamp -- a double). */
4291static PyObject *
4292datetimetz_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
4293{
4294 PyObject *self = NULL;
4295 double timestamp;
4296 PyObject *tzinfo = Py_None;
4297 static char *keywords[] = {"timestamp", "tzinfo", NULL};
4298
4299 if (PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
4300 keywords, &timestamp, &tzinfo)) {
4301 if (check_tzinfo_subclass(tzinfo) < 0)
4302 return NULL;
4303 self = datetime_from_timestamp(cls, localtime, timestamp);
4304 if (self != NULL)
4305 replace_tzinfo(self, tzinfo);
4306 }
4307 return self;
4308}
4309
4310/* Note: utcnow() is inherited, and doesn't accept tzinfo.
4311 * Ditto utcfromtimestamp(). Ditto combine().
4312 */
4313
4314
4315/*
4316 * Destructor.
4317 */
4318
4319static void
4320datetimetz_dealloc(PyDateTime_DateTimeTZ *self)
4321{
4322 Py_XDECREF(self->tzinfo);
4323 self->ob_type->tp_free((PyObject *)self);
4324}
4325
4326/*
4327 * Indirect access to tzinfo methods.
4328 */
4329
4330/* Internal helper.
4331 * Call a tzinfo object's method, or return None if tzinfo is None.
4332 */
4333static PyObject *
4334datetimetz_convienience(PyDateTime_DateTimeTZ *self, char *name)
4335{
4336 PyObject *result;
4337
4338 if (self->tzinfo == Py_None) {
4339 result = Py_None;
4340 Py_INCREF(result);
4341 }
4342 else
4343 result = PyObject_CallMethod(self->tzinfo, name, "O", self);
4344 return result;
4345}
4346
4347/* These are all METH_NOARGS, so don't need to check the arglist. */
4348static PyObject *
4349datetimetz_utcoffset(PyDateTime_DateTimeTZ *self, PyObject *unused) {
4350 return datetimetz_convienience(self, "utcoffset");
4351}
4352
4353static PyObject *
4354datetimetz_tzname(PyDateTime_DateTimeTZ *self, PyObject *unused) {
4355 return datetimetz_convienience(self, "tzname");
4356}
4357
4358static PyObject *
4359datetimetz_dst(PyDateTime_DateTimeTZ *self, PyObject *unused) {
4360 return datetimetz_convienience(self, "dst");
4361}
4362
4363/*
4364 * datetimetz arithmetic.
4365 */
4366
4367/* If base is Py_NotImplemented or NULL, just return it.
4368 * Else base is a datetime, exactly one of {left, right} is a datetimetz,
4369 * and we want to create a datetimetz with the same date and time fields
4370 * as base, and with the tzinfo field from left or right. Do that,
4371 * return it, and decref base. This is used to transform the result of
4372 * a binary datetime operation (base) into a datetimetz result.
4373 */
4374static PyObject *
4375attach_tzinfo(PyObject *base, PyObject *left, PyObject *right)
4376{
4377 PyDateTime_DateTimeTZ *self;
4378 PyDateTime_DateTimeTZ *result;
4379
4380 if (base == NULL || base == Py_NotImplemented)
4381 return base;
4382
4383 assert(PyDateTime_CheckExact(base));
4384
4385 if (PyDateTimeTZ_Check(left)) {
4386 assert(! PyDateTimeTZ_Check(right));
4387 self = (PyDateTime_DateTimeTZ *)left;
4388 }
4389 else {
4390 assert(PyDateTimeTZ_Check(right));
4391 self = (PyDateTime_DateTimeTZ *)right;
4392 }
4393 result = PyObject_New(PyDateTime_DateTimeTZ,
4394 &PyDateTime_DateTimeTZType);
4395 if (result != NULL) {
4396 memcpy(result->data, ((PyDateTime_DateTime *)base)->data,
4397 _PyDateTime_DATETIME_DATASIZE);
4398 Py_INCREF(self->tzinfo);
4399 result->tzinfo = self->tzinfo;
4400 }
4401 Py_DECREF(base);
4402 return (PyObject *)result;
4403}
4404
4405static PyObject *
4406datetimetz_add(PyObject *left, PyObject *right)
4407{
4408 return attach_tzinfo(datetime_add(left, right), left, right);
4409}
4410
4411static PyObject *
4412datetimetz_subtract(PyObject *left, PyObject *right)
4413{
4414 PyObject *result = Py_NotImplemented;
4415
4416 if (PyDateTime_Check(left)) {
4417 /* datetime - ??? */
4418 if (PyDateTime_Check(right)) {
4419 /* datetime - datetime */
4420 naivety n1, n2;
4421 int offset1, offset2;
4422 PyDateTime_Delta *delta;
4423
4424 n1 = classify_object(left, &offset1);
4425 assert(n1 != OFFSET_UNKNOWN);
4426 if (n1 == OFFSET_ERROR)
4427 return NULL;
4428
4429 n2 = classify_object(right, &offset2);
4430 assert(n2 != OFFSET_UNKNOWN);
4431 if (n2 == OFFSET_ERROR)
4432 return NULL;
4433
4434 if (n1 != n2) {
4435 PyErr_SetString(PyExc_TypeError,
4436 "can't subtract offset-naive and "
4437 "offset-aware datetimes");
4438 return NULL;
4439 }
4440 delta = (PyDateTime_Delta *)sub_datetime_datetime(
4441 (PyDateTime_DateTime *)left,
4442 (PyDateTime_DateTime *)right);
4443 if (delta == NULL || offset1 == offset2)
4444 return (PyObject *)delta;
4445 /* (left - offset1) - (right - offset2) =
4446 * (left - right) + (offset2 - offset1)
4447 */
4448 result = new_delta(delta->days,
4449 delta->seconds +
4450 (offset2 - offset1) * 60,
4451 delta->microseconds,
4452 1);
4453 Py_DECREF(delta);
4454 }
4455 else if (PyDelta_Check(right)) {
4456 /* datetimetz - delta */
4457 result = sub_datetime_timedelta(
4458 (PyDateTime_DateTime *)left,
4459 (PyDateTime_Delta *)right);
4460 result = attach_tzinfo(result, left, right);
4461 }
4462 }
4463
4464 if (result == Py_NotImplemented)
4465 Py_INCREF(result);
4466 return result;
4467}
4468
4469/* Various ways to turn a datetime into a string. */
4470
4471static PyObject *
4472datetimetz_repr(PyDateTime_DateTimeTZ *self)
4473{
4474 PyObject *baserepr = datetime_repr((PyDateTime_DateTime *)self);
4475
4476 if (baserepr == NULL)
4477 return NULL;
4478 return append_keyword_tzinfo(baserepr, self->tzinfo);
4479}
4480
4481/* Note: tp_str is inherited from datetime. */
4482
4483static PyObject *
4484datetimetz_isoformat(PyDateTime_DateTimeTZ *self,
4485 PyObject *args, PyObject *kw)
4486{
4487 char buf[100];
4488 PyObject *result = datetime_isoformat((PyDateTime_DateTime *)self,
4489 args, kw);
4490
4491 if (result == NULL || self->tzinfo == Py_None)
4492 return result;
4493
4494 /* We need to append the UTC offset. */
4495 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4496 (PyObject *)self) < 0) {
4497 Py_DECREF(result);
4498 return NULL;
4499 }
4500 PyString_ConcatAndDel(&result, PyString_FromString(buf));
4501 return result;
4502}
4503
4504/* Miscellaneous methods. */
4505
4506/* Note: tp_richcompare and tp_hash are inherited from datetime. */
4507
4508static PyObject *
4509datetimetz_timetuple(PyDateTime_DateTimeTZ *self)
4510{
4511 int dstflag = -1;
4512
4513 if (self->tzinfo != Py_None) {
4514 int none;
4515
4516 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4517 if (dstflag == -1 && PyErr_Occurred())
4518 return NULL;
4519
4520 if (none)
4521 dstflag = -1;
4522 else if (dstflag != 0)
4523 dstflag = 1;
4524
4525 }
4526 return build_struct_time(GET_YEAR(self),
4527 GET_MONTH(self),
4528 GET_DAY(self),
4529 DATE_GET_HOUR(self),
4530 DATE_GET_MINUTE(self),
4531 DATE_GET_SECOND(self),
4532 dstflag);
4533}
4534
4535static PyObject *
4536datetimetz_utctimetuple(PyDateTime_DateTimeTZ *self)
4537{
4538 int y = GET_YEAR(self);
4539 int m = GET_MONTH(self);
4540 int d = GET_DAY(self);
4541 int hh = DATE_GET_HOUR(self);
4542 int mm = DATE_GET_MINUTE(self);
4543 int ss = DATE_GET_SECOND(self);
4544 int us = 0; /* microseconds are ignored in a timetuple */
4545 int offset = 0;
4546
4547 if (self->tzinfo != Py_None) {
4548 int none;
4549
4550 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4551 if (offset == -1 && PyErr_Occurred())
4552 return NULL;
4553 }
4554 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4555 * 0 in a UTC timetuple regardless of what dst() says.
4556 */
4557 if (offset) {
4558 /* Subtract offset minutes & normalize. */
4559 int stat;
4560
4561 mm -= offset;
4562 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4563 if (stat < 0) {
4564 /* At the edges, it's possible we overflowed
4565 * beyond MINYEAR or MAXYEAR.
4566 */
4567 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4568 PyErr_Clear();
4569 else
4570 return NULL;
4571 }
4572 }
4573 return build_struct_time(y, m, d, hh, mm, ss, 0);
4574}
4575
4576static PyObject *
4577datetimetz_gettimetz(PyDateTime_DateTimeTZ *self)
4578{
4579 return new_timetz(DATE_GET_HOUR(self),
4580 DATE_GET_MINUTE(self),
4581 DATE_GET_SECOND(self),
4582 DATE_GET_MICROSECOND(self),
4583 self->tzinfo);
4584}
4585
4586/*
4587 * Pickle support. Quite a maze!
4588 */
4589
4590/* Let basestate be the state string returned by datetime_getstate.
4591 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4592 * So it's a tuple in any (non-error) case.
4593 */
4594static PyObject *
4595datetimetz_getstate(PyDateTime_DateTimeTZ *self)
4596{
4597 PyObject *basestate;
4598 PyObject *result = NULL;
4599
4600 basestate = datetime_getstate((PyDateTime_DateTime *)self);
4601 if (basestate != NULL) {
4602 if (self->tzinfo == Py_None)
4603 result = Py_BuildValue("(O)", basestate);
4604 else
4605 result = Py_BuildValue("OO", basestate, self->tzinfo);
4606 Py_DECREF(basestate);
4607 }
4608 return result;
4609}
4610
4611static PyObject *
4612datetimetz_setstate(PyDateTime_DateTimeTZ *self, PyObject *state)
4613{
4614 PyObject *temp;
4615 PyObject *basestate;
4616 PyObject *tzinfo = Py_None;
4617
4618 if (! PyArg_ParseTuple(state, "O!|O:__setstate__",
4619 &PyString_Type, &basestate,
4620 &tzinfo))
4621 return NULL;
4622 temp = datetime_setstate((PyDateTime_DateTime *)self, basestate);
4623 if (temp == NULL)
4624 return NULL;
4625 Py_DECREF(temp);
4626
4627 Py_INCREF(tzinfo);
4628 Py_XDECREF(self->tzinfo);
4629 self->tzinfo = tzinfo;
4630
4631 Py_INCREF(Py_None);
4632 return Py_None;
4633}
4634
4635static PyObject *
4636datetimetz_pickler(PyObject *module, PyDateTime_DateTimeTZ *datetimetz)
4637{
4638 PyObject *state;
4639 PyObject *result = NULL;
4640
4641 if (! PyDateTimeTZ_CheckExact(datetimetz)) {
4642 PyErr_Format(PyExc_TypeError,
4643 "bad type passed to datetimetz pickler: %s",
4644 datetimetz->ob_type->tp_name);
4645 return NULL;
4646 }
4647 state = datetimetz_getstate(datetimetz);
4648 if (state) {
4649 result = Py_BuildValue("O(O)",
4650 datetimetz_unpickler_object,
4651 state);
4652 Py_DECREF(state);
4653 }
4654 return result;
4655}
4656
4657static PyObject *
4658datetimetz_unpickler(PyObject *module, PyObject *arg)
4659{
4660 PyDateTime_DateTimeTZ *self;
4661
4662 self = PyObject_New(PyDateTime_DateTimeTZ, &PyDateTime_DateTimeTZType);
4663 if (self != NULL) {
4664 PyObject *res;
4665
4666 self->tzinfo = NULL;
4667 res = datetimetz_setstate(self, arg);
4668 if (res == NULL) {
4669 Py_DECREF(self);
4670 return NULL;
4671 }
4672 Py_DECREF(res);
4673 }
4674 return (PyObject *)self;
4675}
4676
4677
4678static PyMethodDef datetimetz_methods[] = {
4679 /* Class methods: */
4680 /* Inherited: combine(), utcnow(), utcfromtimestamp() */
4681
4682 {"now", (PyCFunction)datetimetz_now,
4683 METH_KEYWORDS | METH_CLASS,
4684 PyDoc_STR("[tzinfo] -> new datetimetz with local day and time.")},
4685
4686 {"fromtimestamp", (PyCFunction)datetimetz_fromtimestamp,
4687 METH_KEYWORDS | METH_CLASS,
4688 PyDoc_STR("timestamp[, tzinfo] -> local time from POSIX timestamp.")},
4689
4690 /* Instance methods: */
4691 /* Inherited: date(), time(), ctime(). */
4692 {"timetuple", (PyCFunction)datetimetz_timetuple, METH_NOARGS,
4693 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4694
4695 {"utctimetuple", (PyCFunction)datetimetz_utctimetuple, METH_NOARGS,
4696 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4697
4698 {"timetz", (PyCFunction)datetimetz_gettimetz, METH_NOARGS,
4699 PyDoc_STR("Return timetz object with same hour, minute, second, "
4700 "microsecond, and tzinfo.")},
4701
4702 {"isoformat", (PyCFunction)datetimetz_isoformat, METH_KEYWORDS,
4703 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4704 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4705 "sep is used to separate the year from the time, and "
4706 "defaults to 'T'.")},
4707
4708 {"utcoffset", (PyCFunction)datetimetz_utcoffset, METH_NOARGS,
4709 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4710
4711 {"tzname", (PyCFunction)datetimetz_tzname, METH_NOARGS,
4712 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4713
4714 {"dst", (PyCFunction)datetimetz_dst, METH_NOARGS,
4715 PyDoc_STR("Return self.tzinfo.dst(self).")},
4716
4717 {"__setstate__", (PyCFunction)datetimetz_setstate, METH_O,
4718 PyDoc_STR("__setstate__(state)")},
4719
4720 {"__getstate__", (PyCFunction)datetimetz_getstate, METH_NOARGS,
4721 PyDoc_STR("__getstate__() -> state")},
4722 {NULL, NULL}
4723};
4724
4725static char datetimetz_doc[] =
4726PyDoc_STR("date/time type.");
4727
4728static PyNumberMethods datetimetz_as_number = {
4729 datetimetz_add, /* nb_add */
4730 datetimetz_subtract, /* nb_subtract */
4731 0, /* nb_multiply */
4732 0, /* nb_divide */
4733 0, /* nb_remainder */
4734 0, /* nb_divmod */
4735 0, /* nb_power */
4736 0, /* nb_negative */
4737 0, /* nb_positive */
4738 0, /* nb_absolute */
4739 0, /* nb_nonzero */
4740};
4741
4742statichere PyTypeObject PyDateTime_DateTimeTZType = {
4743 PyObject_HEAD_INIT(NULL)
4744 0, /* ob_size */
4745 "datetime.datetimetz", /* tp_name */
4746 sizeof(PyDateTime_DateTimeTZ), /* tp_basicsize */
4747 0, /* tp_itemsize */
4748 (destructor)datetimetz_dealloc, /* tp_dealloc */
4749 0, /* tp_print */
4750 0, /* tp_getattr */
4751 0, /* tp_setattr */
4752 0, /* tp_compare */
4753 (reprfunc)datetimetz_repr, /* tp_repr */
4754 &datetimetz_as_number, /* tp_as_number */
4755 0, /* tp_as_sequence */
4756 0, /* tp_as_mapping */
4757 0, /* tp_hash */
4758 0, /* tp_call */
4759 0, /* tp_str */
4760 PyObject_GenericGetAttr, /* tp_getattro */
4761 0, /* tp_setattro */
4762 0, /* tp_as_buffer */
4763 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4764 Py_TPFLAGS_BASETYPE, /* tp_flags */
4765 datetimetz_doc, /* tp_doc */
4766 0, /* tp_traverse */
4767 0, /* tp_clear */
4768 0, /* tp_richcompare */
4769 0, /* tp_weaklistoffset */
4770 0, /* tp_iter */
4771 0, /* tp_iternext */
4772 datetimetz_methods, /* tp_methods */
4773 0, /* tp_members */
4774 datetimetz_getset, /* tp_getset */
4775 &PyDateTime_DateTimeType, /* tp_base */
4776 0, /* tp_dict */
4777 0, /* tp_descr_get */
4778 0, /* tp_descr_set */
4779 0, /* tp_dictoffset */
4780 0, /* tp_init */
4781 0, /* tp_alloc */
4782 datetimetz_new, /* tp_new */
4783 _PyObject_Del, /* tp_free */
4784};
4785
4786/* ---------------------------------------------------------------------------
4787 * Module methods and initialization.
4788 */
4789
4790static PyMethodDef module_methods[] = {
4791 /* Private functions for pickling support, registered with the
4792 * copy_reg module by the module init function.
4793 */
4794 {"_date_pickler", (PyCFunction)date_pickler, METH_O, NULL},
4795 {"_date_unpickler", (PyCFunction)date_unpickler, METH_O, NULL},
4796 {"_datetime_pickler", (PyCFunction)datetime_pickler, METH_O, NULL},
4797 {"_datetime_unpickler", (PyCFunction)datetime_unpickler,METH_O, NULL},
4798 {"_datetimetz_pickler", (PyCFunction)datetimetz_pickler,METH_O, NULL},
4799 {"_datetimetz_unpickler",(PyCFunction)datetimetz_unpickler,METH_O, NULL},
4800 {"_time_pickler", (PyCFunction)time_pickler, METH_O, NULL},
4801 {"_time_unpickler", (PyCFunction)time_unpickler, METH_O, NULL},
4802 {"_timetz_pickler", (PyCFunction)timetz_pickler, METH_O, NULL},
4803 {"_timetz_unpickler", (PyCFunction)timetz_unpickler, METH_O, NULL},
4804 {"_tzinfo_pickler", (PyCFunction)tzinfo_pickler, METH_O, NULL},
4805 {"_tzinfo_unpickler", (PyCFunction)tzinfo_unpickler, METH_NOARGS,
4806 NULL},
4807 {NULL, NULL}
4808};
4809
4810PyMODINIT_FUNC
4811initdatetime(void)
4812{
4813 PyObject *m; /* a module object */
4814 PyObject *d; /* its dict */
4815 PyObject *x;
4816
4817 /* Types that use __reduce__ for pickling need to set the following
4818 * magical attr in the type dict, with a true value.
4819 */
4820 PyObject *safepickle = PyString_FromString("__safe_for_unpickling__");
4821 if (safepickle == NULL)
4822 return;
4823
4824 m = Py_InitModule3("datetime", module_methods,
4825 "Fast implementation of the datetime type.");
4826
4827 if (PyType_Ready(&PyDateTime_DateType) < 0)
4828 return;
4829 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4830 return;
4831 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4832 return;
4833 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4834 return;
4835 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4836 return;
4837 if (PyType_Ready(&PyDateTime_TimeTZType) < 0)
4838 return;
4839 if (PyType_Ready(&PyDateTime_DateTimeTZType) < 0)
4840 return;
4841
4842 /* Pickling support, via registering functions with copy_reg. */
4843 {
4844 PyObject *pickler;
4845 PyObject *copyreg = PyImport_ImportModule("copy_reg");
4846
4847 if (copyreg == NULL) return;
4848
4849 pickler = PyObject_GetAttrString(m, "_date_pickler");
4850 if (pickler == NULL) return;
4851 date_unpickler_object = PyObject_GetAttrString(m,
4852 "_date_unpickler");
4853 if (date_unpickler_object == NULL) return;
4854 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4855 &PyDateTime_DateType,
4856 pickler,
4857 date_unpickler_object);
4858 if (x == NULL) return;
4859 Py_DECREF(x);
4860 Py_DECREF(pickler);
4861
4862 pickler = PyObject_GetAttrString(m, "_datetime_pickler");
4863 if (pickler == NULL) return;
4864 datetime_unpickler_object = PyObject_GetAttrString(m,
4865 "_datetime_unpickler");
4866 if (datetime_unpickler_object == NULL) return;
4867 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4868 &PyDateTime_DateTimeType,
4869 pickler,
4870 datetime_unpickler_object);
4871 if (x == NULL) return;
4872 Py_DECREF(x);
4873 Py_DECREF(pickler);
4874
4875 pickler = PyObject_GetAttrString(m, "_time_pickler");
4876 if (pickler == NULL) return;
4877 time_unpickler_object = PyObject_GetAttrString(m,
4878 "_time_unpickler");
4879 if (time_unpickler_object == NULL) return;
4880 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4881 &PyDateTime_TimeType,
4882 pickler,
4883 time_unpickler_object);
4884 if (x == NULL) return;
4885 Py_DECREF(x);
4886 Py_DECREF(pickler);
4887
4888 pickler = PyObject_GetAttrString(m, "_timetz_pickler");
4889 if (pickler == NULL) return;
4890 timetz_unpickler_object = PyObject_GetAttrString(m,
4891 "_timetz_unpickler");
4892 if (timetz_unpickler_object == NULL) return;
4893 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4894 &PyDateTime_TimeTZType,
4895 pickler,
4896 timetz_unpickler_object);
4897 if (x == NULL) return;
4898 Py_DECREF(x);
4899 Py_DECREF(pickler);
4900
4901 pickler = PyObject_GetAttrString(m, "_tzinfo_pickler");
4902 if (pickler == NULL) return;
4903 tzinfo_unpickler_object = PyObject_GetAttrString(m,
4904 "_tzinfo_unpickler");
4905 if (tzinfo_unpickler_object == NULL) return;
4906 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4907 &PyDateTime_TZInfoType,
4908 pickler,
4909 tzinfo_unpickler_object);
4910 if (x== NULL) return;
4911 Py_DECREF(x);
4912 Py_DECREF(pickler);
4913
4914 pickler = PyObject_GetAttrString(m, "_datetimetz_pickler");
4915 if (pickler == NULL) return;
4916 datetimetz_unpickler_object = PyObject_GetAttrString(m,
4917 "_datetimetz_unpickler");
4918 if (datetimetz_unpickler_object == NULL) return;
4919 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4920 &PyDateTime_DateTimeTZType,
4921 pickler,
4922 datetimetz_unpickler_object);
4923 if (x== NULL) return;
4924 Py_DECREF(x);
4925 Py_DECREF(pickler);
4926
4927 Py_DECREF(copyreg);
4928 }
4929
4930 /* timedelta values */
4931 d = PyDateTime_DeltaType.tp_dict;
4932
4933 if (PyDict_SetItem(d, safepickle, Py_True) < 0)
4934 return;
4935
4936 x = new_delta(0, 0, 1, 0);
4937 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4938 return;
4939 Py_DECREF(x);
4940
4941 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4942 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4943 return;
4944 Py_DECREF(x);
4945
4946 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4947 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4948 return;
4949 Py_DECREF(x);
4950
4951 /* date values */
4952 d = PyDateTime_DateType.tp_dict;
4953
4954 x = new_date(1, 1, 1);
4955 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4956 return;
4957 Py_DECREF(x);
4958
4959 x = new_date(MAXYEAR, 12, 31);
4960 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4961 return;
4962 Py_DECREF(x);
4963
4964 x = new_delta(1, 0, 0, 0);
4965 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4966 return;
4967 Py_DECREF(x);
4968
4969 /* datetime values */
4970 d = PyDateTime_DateTimeType.tp_dict;
4971
4972 x = new_datetime(1, 1, 1, 0, 0, 0, 0);
4973 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4974 return;
4975 Py_DECREF(x);
4976
4977 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999);
4978 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4979 return;
4980 Py_DECREF(x);
4981
4982 x = new_delta(0, 0, 1, 0);
4983 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4984 return;
4985 Py_DECREF(x);
4986
4987 /* time values */
4988 d = PyDateTime_TimeType.tp_dict;
4989
4990 x = new_time(0, 0, 0, 0);
4991 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4992 return;
4993 Py_DECREF(x);
4994
4995 x = new_time(23, 59, 59, 999999);
4996 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4997 return;
4998 Py_DECREF(x);
4999
5000 x = new_delta(0, 0, 1, 0);
5001 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5002 return;
5003 Py_DECREF(x);
5004
5005 /* timetz values */
5006 d = PyDateTime_TimeTZType.tp_dict;
5007
5008 x = new_timetz(0, 0, 0, 0, Py_None);
5009 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5010 return;
5011 Py_DECREF(x);
5012
5013 x = new_timetz(23, 59, 59, 999999, Py_None);
5014 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5015 return;
5016 Py_DECREF(x);
5017
5018 x = new_delta(0, 0, 1, 0);
5019 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5020 return;
5021 Py_DECREF(x);
5022
5023 /* datetimetz values */
5024 d = PyDateTime_DateTimeTZType.tp_dict;
5025
5026 x = new_datetimetz(1, 1, 1, 0, 0, 0, 0, Py_None);
5027 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5028 return;
5029 Py_DECREF(x);
5030
5031 x = new_datetimetz(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5032 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5033 return;
5034 Py_DECREF(x);
5035
5036 x = new_delta(0, 0, 1, 0);
5037 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5038 return;
5039 Py_DECREF(x);
5040
5041 Py_DECREF(safepickle);
5042
5043 /* module initialization */
5044 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
5045 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
5046
5047 Py_INCREF(&PyDateTime_DateType);
5048 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
5049
5050 Py_INCREF(&PyDateTime_DateTimeType);
5051 PyModule_AddObject(m, "datetime",
5052 (PyObject *) &PyDateTime_DateTimeType);
5053
5054 Py_INCREF(&PyDateTime_DeltaType);
5055 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
5056
5057 Py_INCREF(&PyDateTime_TimeType);
5058 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
5059
5060 Py_INCREF(&PyDateTime_TZInfoType);
5061 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
5062
5063 Py_INCREF(&PyDateTime_TimeTZType);
5064 PyModule_AddObject(m, "timetz", (PyObject *) &PyDateTime_TimeTZType);
5065
5066 Py_INCREF(&PyDateTime_DateTimeTZType);
5067 PyModule_AddObject(m, "datetimetz",
5068 (PyObject *)&PyDateTime_DateTimeTZType);
5069
5070 /* A 4-year cycle has an extra leap day over what we'd get from
5071 * pasting together 4 single years.
5072 */
5073 assert(DI4Y == 4 * 365 + 1);
5074 assert(DI4Y == days_before_year(4+1));
5075
5076 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5077 * get from pasting together 4 100-year cycles.
5078 */
5079 assert(DI400Y == 4 * DI100Y + 1);
5080 assert(DI400Y == days_before_year(400+1));
5081
5082 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5083 * pasting together 25 4-year cycles.
5084 */
5085 assert(DI100Y == 25 * DI4Y - 1);
5086 assert(DI100Y == days_before_year(100+1));
5087
5088 us_per_us = PyInt_FromLong(1);
5089 us_per_ms = PyInt_FromLong(1000);
5090 us_per_second = PyInt_FromLong(1000000);
5091 us_per_minute = PyInt_FromLong(60000000);
5092 seconds_per_day = PyInt_FromLong(24 * 3600);
5093 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5094 us_per_minute == NULL || seconds_per_day == NULL)
5095 return;
5096
5097 /* The rest are too big for 32-bit ints, but even
5098 * us_per_week fits in 40 bits, so doubles should be exact.
5099 */
5100 us_per_hour = PyLong_FromDouble(3600000000.0);
5101 us_per_day = PyLong_FromDouble(86400000000.0);
5102 us_per_week = PyLong_FromDouble(604800000000.0);
5103 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5104 return;
5105}