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