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