blob: 250ee236ac02edfcb4e4da24b5e9ba5be071efbb [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
2146static PyObject *
2147date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2148{
2149 PyObject *self = NULL;
2150 int year;
2151 int month;
2152 int day;
2153
2154 static char *keywords[] = {
2155 "year", "month", "day", NULL
2156 };
2157
2158 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", keywords,
2159 &year, &month, &day)) {
2160 if (check_date_args(year, month, day) < 0)
2161 return NULL;
2162 self = new_date(year, month, day);
2163 }
2164 return self;
2165}
2166
2167/* Return new date from localtime(t). */
2168static PyObject *
2169date_local_from_time_t(PyObject *cls, time_t t)
2170{
2171 struct tm *tm;
2172 PyObject *result = NULL;
2173
2174 tm = localtime(&t);
2175 if (tm)
2176 result = PyObject_CallFunction(cls, "iii",
2177 tm->tm_year + 1900,
2178 tm->tm_mon + 1,
2179 tm->tm_mday);
2180 else
2181 PyErr_SetString(PyExc_ValueError,
2182 "timestamp out of range for "
2183 "platform localtime() function");
2184 return result;
2185}
2186
2187/* Return new date from current time.
2188 * We say this is equivalent to fromtimestamp(time.time()), and the
2189 * only way to be sure of that is to *call* time.time(). That's not
2190 * generally the same as calling C's time.
2191 */
2192static PyObject *
2193date_today(PyObject *cls, PyObject *dummy)
2194{
2195 PyObject *time;
2196 PyObject *result;
2197
2198 time = time_time();
2199 if (time == NULL)
2200 return NULL;
2201
2202 /* Note well: today() is a class method, so this may not call
2203 * date.fromtimestamp. For example, it may call
2204 * datetime.fromtimestamp. That's why we need all the accuracy
2205 * time.time() delivers; if someone were gonzo about optimization,
2206 * date.today() could get away with plain C time().
2207 */
2208 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2209 Py_DECREF(time);
2210 return result;
2211}
2212
2213/* Return new date from given timestamp (Python timestamp -- a double). */
2214static PyObject *
2215date_fromtimestamp(PyObject *cls, PyObject *args)
2216{
2217 double timestamp;
2218 PyObject *result = NULL;
2219
2220 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2221 result = date_local_from_time_t(cls, (time_t)timestamp);
2222 return result;
2223}
2224
2225/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2226 * the ordinal is out of range.
2227 */
2228static PyObject *
2229date_fromordinal(PyObject *cls, PyObject *args)
2230{
2231 PyObject *result = NULL;
2232 int ordinal;
2233
2234 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2235 int year;
2236 int month;
2237 int day;
2238
2239 if (ordinal < 1)
2240 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2241 ">= 1");
2242 else {
2243 ord_to_ymd(ordinal, &year, &month, &day);
2244 result = PyObject_CallFunction(cls, "iii",
2245 year, month, day);
2246 }
2247 }
2248 return result;
2249}
2250
2251/*
2252 * Date arithmetic.
2253 */
2254
2255/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2256 * instead.
2257 */
2258static PyObject *
2259add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2260{
2261 PyObject *result = NULL;
2262 int year = GET_YEAR(date);
2263 int month = GET_MONTH(date);
2264 int deltadays = GET_TD_DAYS(delta);
2265 /* C-level overflow is impossible because |deltadays| < 1e9. */
2266 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2267
2268 if (normalize_date(&year, &month, &day) >= 0)
2269 result = new_date(year, month, day);
2270 return result;
2271}
2272
2273static PyObject *
2274date_add(PyObject *left, PyObject *right)
2275{
2276 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2277 Py_INCREF(Py_NotImplemented);
2278 return Py_NotImplemented;
2279 }
2280 if (PyDate_CheckExact(left)) {
2281 /* date + ??? */
2282 if (PyDelta_Check(right))
2283 /* date + delta */
2284 return add_date_timedelta((PyDateTime_Date *) left,
2285 (PyDateTime_Delta *) right,
2286 0);
2287 }
2288 else {
2289 /* ??? + date
2290 * 'right' must be one of us, or we wouldn't have been called
2291 */
2292 if (PyDelta_Check(left))
2293 /* delta + date */
2294 return add_date_timedelta((PyDateTime_Date *) right,
2295 (PyDateTime_Delta *) left,
2296 0);
2297 }
2298 Py_INCREF(Py_NotImplemented);
2299 return Py_NotImplemented;
2300}
2301
2302static PyObject *
2303date_subtract(PyObject *left, PyObject *right)
2304{
2305 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2306 Py_INCREF(Py_NotImplemented);
2307 return Py_NotImplemented;
2308 }
2309 if (PyDate_CheckExact(left)) {
2310 if (PyDate_CheckExact(right)) {
2311 /* date - date */
2312 int left_ord = ymd_to_ord(GET_YEAR(left),
2313 GET_MONTH(left),
2314 GET_DAY(left));
2315 int right_ord = ymd_to_ord(GET_YEAR(right),
2316 GET_MONTH(right),
2317 GET_DAY(right));
2318 return new_delta(left_ord - right_ord, 0, 0, 0);
2319 }
2320 if (PyDelta_Check(right)) {
2321 /* date - delta */
2322 return add_date_timedelta((PyDateTime_Date *) left,
2323 (PyDateTime_Delta *) right,
2324 1);
2325 }
2326 }
2327 Py_INCREF(Py_NotImplemented);
2328 return Py_NotImplemented;
2329}
2330
2331
2332/* Various ways to turn a date into a string. */
2333
2334static PyObject *
2335date_repr(PyDateTime_Date *self)
2336{
2337 char buffer[1028];
2338 char *typename;
2339
2340 typename = self->ob_type->tp_name;
2341 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
2342 typename,
2343 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2344
2345 return PyString_FromString(buffer);
2346}
2347
2348static PyObject *
2349date_isoformat(PyDateTime_Date *self)
2350{
2351 char buffer[128];
2352
2353 isoformat_date(self, buffer, sizeof(buffer));
2354 return PyString_FromString(buffer);
2355}
2356
2357/* str() calls the appropriate isofomat() method. */
2358static PyObject *
2359date_str(PyDateTime_Date *self)
2360{
2361 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2362}
2363
2364
2365static PyObject *
2366date_ctime(PyDateTime_Date *self)
2367{
2368 return format_ctime(self, 0, 0, 0);
2369}
2370
2371static PyObject *
2372date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2373{
2374 /* This method can be inherited, and needs to call the
2375 * timetuple() method appropriate to self's class.
2376 */
2377 PyObject *result;
2378 PyObject *format;
2379 PyObject *tuple;
2380 static char *keywords[] = {"format", NULL};
2381
2382 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2383 &PyString_Type, &format))
2384 return NULL;
2385
2386 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2387 if (tuple == NULL)
2388 return NULL;
2389 result = wrap_strftime((PyObject *)self, format, tuple);
2390 Py_DECREF(tuple);
2391 return result;
2392}
2393
2394/* ISO methods. */
2395
2396static PyObject *
2397date_isoweekday(PyDateTime_Date *self)
2398{
2399 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2400
2401 return PyInt_FromLong(dow + 1);
2402}
2403
2404static PyObject *
2405date_isocalendar(PyDateTime_Date *self)
2406{
2407 int year = GET_YEAR(self);
2408 int week1_monday = iso_week1_monday(year);
2409 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2410 int week;
2411 int day;
2412
2413 week = divmod(today - week1_monday, 7, &day);
2414 if (week < 0) {
2415 --year;
2416 week1_monday = iso_week1_monday(year);
2417 week = divmod(today - week1_monday, 7, &day);
2418 }
2419 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2420 ++year;
2421 week = 0;
2422 }
2423 return Py_BuildValue("iii", year, week + 1, day + 1);
2424}
2425
2426/* Miscellaneous methods. */
2427
2428/* This is more natural as a tp_compare, but doesn't work then: for whatever
2429 * reason, Python's try_3way_compare ignores tp_compare unless
2430 * PyInstance_Check returns true, but these aren't old-style classes.
2431 */
2432static PyObject *
2433date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2434{
2435 int diff;
2436
2437 if (! PyDate_Check(other)) {
2438 PyErr_Format(PyExc_TypeError,
2439 "can't compare date to %s instance",
2440 other->ob_type->tp_name);
2441 return NULL;
2442 }
2443 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2444 _PyDateTime_DATE_DATASIZE);
2445 return diff_to_bool(diff, op);
2446}
2447
2448static PyObject *
2449date_timetuple(PyDateTime_Date *self)
2450{
2451 return build_struct_time(GET_YEAR(self),
2452 GET_MONTH(self),
2453 GET_DAY(self),
2454 0, 0, 0, -1);
2455}
2456
2457static PyObject *date_getstate(PyDateTime_Date *self);
2458
2459static long
2460date_hash(PyDateTime_Date *self)
2461{
2462 if (self->hashcode == -1) {
2463 PyObject *temp = date_getstate(self);
2464 if (temp != NULL) {
2465 self->hashcode = PyObject_Hash(temp);
2466 Py_DECREF(temp);
2467 }
2468 }
2469 return self->hashcode;
2470}
2471
2472static PyObject *
2473date_toordinal(PyDateTime_Date *self)
2474{
2475 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2476 GET_DAY(self)));
2477}
2478
2479static PyObject *
2480date_weekday(PyDateTime_Date *self)
2481{
2482 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2483
2484 return PyInt_FromLong(dow);
2485}
2486
2487/* Pickle support. Quite a maze! */
2488
2489static PyObject *
2490date_getstate(PyDateTime_Date *self)
2491{
2492 return PyString_FromStringAndSize(self->data,
2493 _PyDateTime_DATE_DATASIZE);
2494}
2495
2496static PyObject *
2497date_setstate(PyDateTime_Date *self, PyObject *state)
2498{
2499 const int len = PyString_Size(state);
2500 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
2501
2502 if (! PyString_Check(state) ||
2503 len != _PyDateTime_DATE_DATASIZE) {
2504 PyErr_SetString(PyExc_TypeError,
2505 "bad argument to date.__setstate__");
2506 return NULL;
2507 }
2508 memcpy(self->data, pdata, _PyDateTime_DATE_DATASIZE);
2509 self->hashcode = -1;
2510
2511 Py_INCREF(Py_None);
2512 return Py_None;
2513}
2514
2515/* XXX This seems a ridiculously inefficient way to pickle a short string. */
2516static PyObject *
2517date_pickler(PyObject *module, PyDateTime_Date *date)
2518{
2519 PyObject *state;
2520 PyObject *result = NULL;
2521
2522 if (! PyDate_CheckExact(date)) {
2523 PyErr_Format(PyExc_TypeError,
2524 "bad type passed to date pickler: %s",
2525 date->ob_type->tp_name);
2526 return NULL;
2527 }
2528 state = date_getstate(date);
2529 if (state) {
2530 result = Py_BuildValue("O(O)", date_unpickler_object, state);
2531 Py_DECREF(state);
2532 }
2533 return result;
2534}
2535
2536static PyObject *
2537date_unpickler(PyObject *module, PyObject *arg)
2538{
2539 PyDateTime_Date *self;
2540
2541 if (! PyString_CheckExact(arg)) {
2542 PyErr_Format(PyExc_TypeError,
2543 "bad type passed to date unpickler: %s",
2544 arg->ob_type->tp_name);
2545 return NULL;
2546 }
2547 self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType);
2548 if (self != NULL) {
2549 PyObject *res = date_setstate(self, arg);
2550 if (res == NULL) {
2551 Py_DECREF(self);
2552 return NULL;
2553 }
2554 Py_DECREF(res);
2555 }
2556 return (PyObject *)self;
2557}
2558
2559static PyMethodDef date_methods[] = {
2560 /* Class methods: */
2561 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2562 METH_CLASS,
2563 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2564 "time.time()).")},
2565
2566 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2567 METH_CLASS,
2568 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2569 "ordinal.")},
2570
2571 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2572 PyDoc_STR("Current date or datetime: same as "
2573 "self.__class__.fromtimestamp(time.time()).")},
2574
2575 /* Instance methods: */
2576
2577 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2578 PyDoc_STR("Return ctime() style string.")},
2579
2580 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2581 PyDoc_STR("format -> strftime() style string.")},
2582
2583 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2584 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2585
2586 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2587 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2588 "weekday.")},
2589
2590 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2591 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2592
2593 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2594 PyDoc_STR("Return the day of the week represented by the date.\n"
2595 "Monday == 1 ... Sunday == 7")},
2596
2597 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2598 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2599 "1 is day 1.")},
2600
2601 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2602 PyDoc_STR("Return the day of the week represented by the date.\n"
2603 "Monday == 0 ... Sunday == 6")},
2604
2605 {"__setstate__", (PyCFunction)date_setstate, METH_O,
2606 PyDoc_STR("__setstate__(state)")},
2607
2608 {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS,
2609 PyDoc_STR("__getstate__() -> state")},
2610
2611 {NULL, NULL}
2612};
2613
2614static char date_doc[] =
2615PyDoc_STR("Basic date type.");
2616
2617static PyNumberMethods date_as_number = {
2618 date_add, /* nb_add */
2619 date_subtract, /* nb_subtract */
2620 0, /* nb_multiply */
2621 0, /* nb_divide */
2622 0, /* nb_remainder */
2623 0, /* nb_divmod */
2624 0, /* nb_power */
2625 0, /* nb_negative */
2626 0, /* nb_positive */
2627 0, /* nb_absolute */
2628 0, /* nb_nonzero */
2629};
2630
2631static PyTypeObject PyDateTime_DateType = {
2632 PyObject_HEAD_INIT(NULL)
2633 0, /* ob_size */
2634 "datetime.date", /* tp_name */
2635 sizeof(PyDateTime_Date), /* tp_basicsize */
2636 0, /* tp_itemsize */
2637 (destructor)PyObject_Del, /* tp_dealloc */
2638 0, /* tp_print */
2639 0, /* tp_getattr */
2640 0, /* tp_setattr */
2641 0, /* tp_compare */
2642 (reprfunc)date_repr, /* tp_repr */
2643 &date_as_number, /* tp_as_number */
2644 0, /* tp_as_sequence */
2645 0, /* tp_as_mapping */
2646 (hashfunc)date_hash, /* tp_hash */
2647 0, /* tp_call */
2648 (reprfunc)date_str, /* tp_str */
2649 PyObject_GenericGetAttr, /* tp_getattro */
2650 0, /* tp_setattro */
2651 0, /* tp_as_buffer */
2652 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2653 Py_TPFLAGS_BASETYPE, /* tp_flags */
2654 date_doc, /* tp_doc */
2655 0, /* tp_traverse */
2656 0, /* tp_clear */
2657 (richcmpfunc)date_richcompare, /* tp_richcompare */
2658 0, /* tp_weaklistoffset */
2659 0, /* tp_iter */
2660 0, /* tp_iternext */
2661 date_methods, /* tp_methods */
2662 0, /* tp_members */
2663 date_getset, /* tp_getset */
2664 0, /* tp_base */
2665 0, /* tp_dict */
2666 0, /* tp_descr_get */
2667 0, /* tp_descr_set */
2668 0, /* tp_dictoffset */
2669 0, /* tp_init */
2670 0, /* tp_alloc */
2671 date_new, /* tp_new */
2672 _PyObject_Del, /* tp_free */
2673};
2674
2675/*
2676 * PyDateTime_DateTime implementation.
2677 */
2678
2679/* Accessor properties. */
2680
2681static PyObject *
2682datetime_hour(PyDateTime_DateTime *self, void *unused)
2683{
2684 return PyInt_FromLong(DATE_GET_HOUR(self));
2685}
2686
2687static PyObject *
2688datetime_minute(PyDateTime_DateTime *self, void *unused)
2689{
2690 return PyInt_FromLong(DATE_GET_MINUTE(self));
2691}
2692
2693static PyObject *
2694datetime_second(PyDateTime_DateTime *self, void *unused)
2695{
2696 return PyInt_FromLong(DATE_GET_SECOND(self));
2697}
2698
2699static PyObject *
2700datetime_microsecond(PyDateTime_DateTime *self, void *unused)
2701{
2702 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
2703}
2704
2705static PyGetSetDef datetime_getset[] = {
2706 {"hour", (getter)datetime_hour},
2707 {"minute", (getter)datetime_minute},
2708 {"second", (getter)datetime_second},
2709 {"microsecond", (getter)datetime_microsecond},
2710 {NULL}
2711};
2712
2713/* Constructors. */
2714
2715static PyObject *
2716datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2717{
2718 PyObject *self = NULL;
2719 int year;
2720 int month;
2721 int day;
2722 int hour = 0;
2723 int minute = 0;
2724 int second = 0;
2725 int usecond = 0;
2726
2727 static char *keywords[] = {
2728 "year", "month", "day", "hour", "minute", "second",
2729 "microsecond", NULL
2730 };
2731
2732 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiii", keywords,
2733 &year, &month, &day, &hour, &minute,
2734 &second, &usecond)) {
2735 if (check_date_args(year, month, day) < 0)
2736 return NULL;
2737 if (check_time_args(hour, minute, second, usecond) < 0)
2738 return NULL;
2739 self = new_datetime(year, month, day,
2740 hour, minute, second, usecond);
2741 }
2742 return self;
2743}
2744
2745
2746/* TM_FUNC is the shared type of localtime() and gmtime(). */
2747typedef struct tm *(*TM_FUNC)(const time_t *timer);
2748
2749/* Internal helper.
2750 * Build datetime from a time_t and a distinct count of microseconds.
2751 * Pass localtime or gmtime for f, to control the interpretation of timet.
2752 */
2753static PyObject *
2754datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us)
2755{
2756 struct tm *tm;
2757 PyObject *result = NULL;
2758
2759 tm = f(&timet);
2760 if (tm)
2761 result = PyObject_CallFunction(cls, "iiiiiii",
2762 tm->tm_year + 1900,
2763 tm->tm_mon + 1,
2764 tm->tm_mday,
2765 tm->tm_hour,
2766 tm->tm_min,
2767 tm->tm_sec,
2768 us);
2769 else
2770 PyErr_SetString(PyExc_ValueError,
2771 "timestamp out of range for "
2772 "platform localtime()/gmtime() function");
2773 return result;
2774}
2775
2776/* Internal helper.
2777 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
2778 * to control the interpretation of the timestamp. Since a double doesn't
2779 * have enough bits to cover a datetime's full range of precision, it's
2780 * better to call datetime_from_timet_and_us provided you have a way
2781 * to get that much precision (e.g., C time() isn't good enough).
2782 */
2783static PyObject *
2784datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp)
2785{
2786 time_t timet = (time_t)timestamp;
2787 int us = (int)((timestamp - (double)timet) * 1e6);
2788
2789 return datetime_from_timet_and_us(cls, f, timet, us);
2790}
2791
2792/* Internal helper.
2793 * Build most accurate possible datetime for current time. Pass localtime or
2794 * gmtime for f as appropriate.
2795 */
2796static PyObject *
2797datetime_best_possible(PyObject *cls, TM_FUNC f)
2798{
2799#ifdef HAVE_GETTIMEOFDAY
2800 struct timeval t;
2801
2802#ifdef GETTIMEOFDAY_NO_TZ
2803 gettimeofday(&t);
2804#else
2805 gettimeofday(&t, (struct timezone *)NULL);
2806#endif
2807 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec);
2808
2809#else /* ! HAVE_GETTIMEOFDAY */
2810 /* No flavor of gettimeofday exists on this platform. Python's
2811 * time.time() does a lot of other platform tricks to get the
2812 * best time it can on the platform, and we're not going to do
2813 * better than that (if we could, the better code would belong
2814 * in time.time()!) We're limited by the precision of a double,
2815 * though.
2816 */
2817 PyObject *time;
2818 double dtime;
2819
2820 time = time_time();
2821 if (time == NULL)
2822 return NULL;
2823 dtime = PyFloat_AsDouble(time);
2824 Py_DECREF(time);
2825 if (dtime == -1.0 && PyErr_Occurred())
2826 return NULL;
2827 return datetime_from_timestamp(cls, f, dtime);
2828#endif /* ! HAVE_GETTIMEOFDAY */
2829}
2830
2831/* Return new local datetime from timestamp (Python timestamp -- a double). */
2832static PyObject *
2833datetime_fromtimestamp(PyObject *cls, PyObject *args)
2834{
2835 double timestamp;
2836 PyObject *result = NULL;
2837
2838 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2839 result = datetime_from_timestamp(cls, localtime, timestamp);
2840 return result;
2841}
2842
2843/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
2844static PyObject *
2845datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
2846{
2847 double timestamp;
2848 PyObject *result = NULL;
2849
2850 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
2851 result = datetime_from_timestamp(cls, gmtime, timestamp);
2852 return result;
2853}
2854
2855/* Return best possible local time -- this isn't constrained by the
2856 * precision of a timestamp.
2857 */
2858static PyObject *
2859datetime_now(PyObject *cls, PyObject *dummy)
2860{
2861 return datetime_best_possible(cls, localtime);
2862}
2863
2864/* Return best possible UTC time -- this isn't constrained by the
2865 * precision of a timestamp.
2866 */
2867static PyObject *
2868datetime_utcnow(PyObject *cls, PyObject *dummy)
2869{
2870 return datetime_best_possible(cls, gmtime);
2871}
2872
2873/* Return new datetime or datetimetz from date/datetime/datetimetz and
2874 * time/timetz arguments.
2875 */
2876static PyObject *
2877datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
2878{
2879 static char *keywords[] = {"date", "time", NULL};
2880 PyObject *date;
2881 PyObject *time;
2882 PyObject *result = NULL;
2883
2884 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
2885 &PyDateTime_DateType, &date,
2886 &PyDateTime_TimeType, &time))
2887 result = PyObject_CallFunction(cls, "iiiiiii",
2888 GET_YEAR(date),
2889 GET_MONTH(date),
2890 GET_DAY(date),
2891 TIME_GET_HOUR(time),
2892 TIME_GET_MINUTE(time),
2893 TIME_GET_SECOND(time),
2894 TIME_GET_MICROSECOND(time));
2895 if (result && PyTimeTZ_Check(time) && PyDateTimeTZ_Check(result)) {
2896 /* Copy the tzinfo field. */
2897 PyObject *tzinfo = ((PyDateTime_TimeTZ *)time)->tzinfo;
2898 Py_INCREF(tzinfo);
2899 Py_DECREF(((PyDateTime_DateTimeTZ *)result)->tzinfo);
2900 ((PyDateTime_DateTimeTZ *)result)->tzinfo = tzinfo;
2901 }
2902 return result;
2903}
2904
2905/* datetime arithmetic. */
2906
2907static PyObject *
2908add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta)
2909{
2910 /* Note that the C-level additions can't overflow, because of
2911 * invariant bounds on the member values.
2912 */
2913 int year = GET_YEAR(date);
2914 int month = GET_MONTH(date);
2915 int day = GET_DAY(date) + GET_TD_DAYS(delta);
2916 int hour = DATE_GET_HOUR(date);
2917 int minute = DATE_GET_MINUTE(date);
2918 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta);
2919 int microsecond = DATE_GET_MICROSECOND(date) +
2920 GET_TD_MICROSECONDS(delta);
2921
2922 if (normalize_datetime(&year, &month, &day,
2923 &hour, &minute, &second, &microsecond) < 0)
2924 return NULL;
2925 else
2926 return new_datetime(year, month, day,
2927 hour, minute, second, microsecond);
2928}
2929
2930static PyObject *
2931sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta)
2932{
2933 /* Note that the C-level subtractions can't overflow, because of
2934 * invariant bounds on the member values.
2935 */
2936 int year = GET_YEAR(date);
2937 int month = GET_MONTH(date);
2938 int day = GET_DAY(date) - GET_TD_DAYS(delta);
2939 int hour = DATE_GET_HOUR(date);
2940 int minute = DATE_GET_MINUTE(date);
2941 int second = DATE_GET_SECOND(date) - GET_TD_SECONDS(delta);
2942 int microsecond = DATE_GET_MICROSECOND(date) -
2943 GET_TD_MICROSECONDS(delta);
2944
2945 if (normalize_datetime(&year, &month, &day,
2946 &hour, &minute, &second, &microsecond) < 0)
2947 return NULL;
2948 else
2949 return new_datetime(year, month, day,
2950 hour, minute, second, microsecond);
2951}
2952
2953static PyObject *
2954sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right)
2955{
2956 int days1 = ymd_to_ord(GET_YEAR(left), GET_MONTH(left), GET_DAY(left));
2957 int days2 = ymd_to_ord(GET_YEAR(right),
2958 GET_MONTH(right),
2959 GET_DAY(right));
2960 /* These can't overflow, since the values are normalized. At most
2961 * this gives the number of seconds in one day.
2962 */
2963 int delta_s = (DATE_GET_HOUR(left) - DATE_GET_HOUR(right)) * 3600 +
2964 (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 +
2965 DATE_GET_SECOND(left) - DATE_GET_SECOND(right);
2966 int delta_us = DATE_GET_MICROSECOND(left) -
2967 DATE_GET_MICROSECOND(right);
2968
2969 return new_delta(days1 - days2, delta_s, delta_us, 1);
2970}
2971
2972static PyObject *
2973datetime_add(PyObject *left, PyObject *right)
2974{
2975 if (PyDateTime_Check(left)) {
2976 /* datetime + ??? */
2977 if (PyDelta_Check(right))
2978 /* datetime + delta */
2979 return add_datetime_timedelta(
2980 (PyDateTime_DateTime *)left,
2981 (PyDateTime_Delta *)right);
2982 }
2983 else if (PyDelta_Check(left)) {
2984 /* delta + datetime */
2985 return add_datetime_timedelta((PyDateTime_DateTime *) right,
2986 (PyDateTime_Delta *) left);
2987 }
2988 Py_INCREF(Py_NotImplemented);
2989 return Py_NotImplemented;
2990}
2991
2992static PyObject *
2993datetime_subtract(PyObject *left, PyObject *right)
2994{
2995 PyObject *result = Py_NotImplemented;
2996
2997 if (PyDateTime_Check(left)) {
2998 /* datetime - ??? */
2999 if (PyDateTime_Check(right)) {
3000 /* datetime - datetime */
3001 result = sub_datetime_datetime(
3002 (PyDateTime_DateTime *)left,
3003 (PyDateTime_DateTime *)right);
3004 }
3005 else if (PyDelta_Check(right)) {
3006 /* datetime - delta */
3007 result = sub_datetime_timedelta(
3008 (PyDateTime_DateTime *)left,
3009 (PyDateTime_Delta *)right);
3010 }
3011 }
3012
3013 if (result == Py_NotImplemented)
3014 Py_INCREF(result);
3015 return result;
3016}
3017
3018/* Various ways to turn a datetime into a string. */
3019
3020static PyObject *
3021datetime_repr(PyDateTime_DateTime *self)
3022{
3023 char buffer[1000];
3024 char *typename = self->ob_type->tp_name;
3025
3026 if (DATE_GET_MICROSECOND(self)) {
3027 PyOS_snprintf(buffer, sizeof(buffer),
3028 "%s(%d, %d, %d, %d, %d, %d, %d)",
3029 typename,
3030 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
3031 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
3032 DATE_GET_SECOND(self),
3033 DATE_GET_MICROSECOND(self));
3034 }
3035 else if (DATE_GET_SECOND(self)) {
3036 PyOS_snprintf(buffer, sizeof(buffer),
3037 "%s(%d, %d, %d, %d, %d, %d)",
3038 typename,
3039 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
3040 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
3041 DATE_GET_SECOND(self));
3042 }
3043 else {
3044 PyOS_snprintf(buffer, sizeof(buffer),
3045 "%s(%d, %d, %d, %d, %d)",
3046 typename,
3047 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
3048 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
3049 }
3050 return PyString_FromString(buffer);
3051}
3052
3053static PyObject *
3054datetime_str(PyDateTime_DateTime *self)
3055{
3056 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
3057}
3058
3059static PyObject *
3060datetime_isoformat(PyDateTime_DateTime *self,
3061 PyObject *args, PyObject *kw)
3062{
3063 char sep = 'T';
3064 static char *keywords[] = {"sep", NULL};
3065 char buffer[100];
3066 char *cp;
3067
3068 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
3069 &sep))
3070 return NULL;
3071 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
3072 assert(cp != NULL);
3073 *cp++ = sep;
3074 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
3075 return PyString_FromString(buffer);
3076}
3077
3078static PyObject *
3079datetime_ctime(PyDateTime_DateTime *self)
3080{
3081 return format_ctime((PyDateTime_Date *)self,
3082 DATE_GET_HOUR(self),
3083 DATE_GET_MINUTE(self),
3084 DATE_GET_SECOND(self));
3085}
3086
3087/* Miscellaneous methods. */
3088
3089/* This is more natural as a tp_compare, but doesn't work then: for whatever
3090 * reason, Python's try_3way_compare ignores tp_compare unless
3091 * PyInstance_Check returns true, but these aren't old-style classes.
3092 * Note that this routine handles all comparisons for datetime and datetimetz.
3093 */
3094static PyObject *
3095datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
3096{
3097 int diff;
3098 naivety n1, n2;
3099 int offset1, offset2;
3100
3101 if (! PyDateTime_Check(other)) {
3102 /* Stop this from falling back to address comparison. */
3103 PyErr_Format(PyExc_TypeError,
3104 "can't compare '%s' to '%s'",
3105 self->ob_type->tp_name,
3106 other->ob_type->tp_name);
3107 return NULL;
3108 }
Tim Peters14b69412002-12-22 18:10:22 +00003109 n1 = classify_utcoffset((PyObject *)self, &offset1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003110 assert(n1 != OFFSET_UNKNOWN);
3111 if (n1 == OFFSET_ERROR)
3112 return NULL;
3113
Tim Peters14b69412002-12-22 18:10:22 +00003114 n2 = classify_utcoffset(other, &offset2);
Tim Peters2a799bf2002-12-16 20:18:38 +00003115 assert(n2 != OFFSET_UNKNOWN);
3116 if (n2 == OFFSET_ERROR)
3117 return NULL;
3118
3119 /* If they're both naive, or both aware and have the same offsets,
3120 * we get off cheap. Note that if they're both naive, offset1 ==
3121 * offset2 == 0 at this point.
3122 */
3123 if (n1 == n2 && offset1 == offset2) {
3124 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
3125 _PyDateTime_DATETIME_DATASIZE);
3126 return diff_to_bool(diff, op);
3127 }
3128
3129 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3130 /* We want the sign of
3131 * (self - offset1 minutes) - (other - offset2 minutes) =
3132 * (self - other) + (offset2 - offset1) minutes.
3133 */
3134 PyDateTime_Delta *delta;
3135 int days, seconds, us;
3136
3137 assert(offset1 != offset2); /* else last "if" handled it */
3138 delta = (PyDateTime_Delta *)sub_datetime_datetime(self,
3139 (PyDateTime_DateTime *)other);
3140 if (delta == NULL)
3141 return NULL;
3142 days = delta->days;
3143 seconds = delta->seconds + (offset2 - offset1) * 60;
3144 us = delta->microseconds;
3145 Py_DECREF(delta);
3146 normalize_d_s_us(&days, &seconds, &us);
3147 diff = days;
3148 if (diff == 0)
3149 diff = seconds | us;
3150 return diff_to_bool(diff, op);
3151 }
3152
3153 assert(n1 != n2);
3154 PyErr_SetString(PyExc_TypeError,
3155 "can't compare offset-naive and "
3156 "offset-aware datetimes");
3157 return NULL;
3158}
3159
3160static PyObject *datetime_getstate(PyDateTime_DateTime *self);
3161
3162static long
3163datetime_hash(PyDateTime_DateTime *self)
3164{
3165 if (self->hashcode == -1) {
3166 naivety n;
3167 int offset;
3168 PyObject *temp;
3169
Tim Peters14b69412002-12-22 18:10:22 +00003170 n = classify_utcoffset((PyObject *)self, &offset);
Tim Peters2a799bf2002-12-16 20:18:38 +00003171 assert(n != OFFSET_UNKNOWN);
3172 if (n == OFFSET_ERROR)
3173 return -1;
3174
3175 /* Reduce this to a hash of another object. */
3176 if (n == OFFSET_NAIVE)
3177 temp = datetime_getstate(self);
3178 else {
3179 int days;
3180 int seconds;
3181
3182 assert(n == OFFSET_AWARE);
3183 assert(PyDateTimeTZ_Check(self));
3184 days = ymd_to_ord(GET_YEAR(self),
3185 GET_MONTH(self),
3186 GET_DAY(self));
3187 seconds = DATE_GET_HOUR(self) * 3600 +
3188 (DATE_GET_MINUTE(self) - offset) * 60 +
3189 DATE_GET_SECOND(self);
3190 temp = new_delta(days,
3191 seconds,
3192 DATE_GET_MICROSECOND(self),
3193 1);
3194 }
3195 if (temp != NULL) {
3196 self->hashcode = PyObject_Hash(temp);
3197 Py_DECREF(temp);
3198 }
3199 }
3200 return self->hashcode;
3201}
3202
3203static PyObject *
3204datetime_timetuple(PyDateTime_DateTime *self)
3205{
3206 return build_struct_time(GET_YEAR(self),
3207 GET_MONTH(self),
3208 GET_DAY(self),
3209 DATE_GET_HOUR(self),
3210 DATE_GET_MINUTE(self),
3211 DATE_GET_SECOND(self),
3212 -1);
3213}
3214
3215static PyObject *
3216datetime_getdate(PyDateTime_DateTime *self)
3217{
3218 return new_date(GET_YEAR(self),
3219 GET_MONTH(self),
3220 GET_DAY(self));
3221}
3222
3223static PyObject *
3224datetime_gettime(PyDateTime_DateTime *self)
3225{
3226 return new_time(DATE_GET_HOUR(self),
3227 DATE_GET_MINUTE(self),
3228 DATE_GET_SECOND(self),
3229 DATE_GET_MICROSECOND(self));
3230}
3231
3232/* Pickle support. Quite a maze! */
3233
3234static PyObject *
3235datetime_getstate(PyDateTime_DateTime *self)
3236{
3237 return PyString_FromStringAndSize(self->data,
3238 _PyDateTime_DATETIME_DATASIZE);
3239}
3240
3241static PyObject *
3242datetime_setstate(PyDateTime_DateTime *self, PyObject *state)
3243{
3244 const int len = PyString_Size(state);
3245 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
3246
3247 if (! PyString_Check(state) ||
3248 len != _PyDateTime_DATETIME_DATASIZE) {
3249 PyErr_SetString(PyExc_TypeError,
3250 "bad argument to datetime.__setstate__");
3251 return NULL;
3252 }
3253 memcpy(self->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3254 self->hashcode = -1;
3255
3256 Py_INCREF(Py_None);
3257 return Py_None;
3258}
3259
3260/* XXX This seems a ridiculously inefficient way to pickle a short string. */
3261static PyObject *
3262datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime)
3263{
3264 PyObject *state;
3265 PyObject *result = NULL;
3266
3267 if (! PyDateTime_CheckExact(datetime)) {
3268 PyErr_Format(PyExc_TypeError,
3269 "bad type passed to datetime pickler: %s",
3270 datetime->ob_type->tp_name);
3271 return NULL;
3272 }
3273 state = datetime_getstate(datetime);
3274 if (state) {
3275 result = Py_BuildValue("O(O)",
3276 datetime_unpickler_object,
3277 state);
3278 Py_DECREF(state);
3279 }
3280 return result;
3281}
3282
3283static PyObject *
3284datetime_unpickler(PyObject *module, PyObject *arg)
3285{
3286 PyDateTime_DateTime *self;
3287
3288 if (! PyString_CheckExact(arg)) {
3289 PyErr_Format(PyExc_TypeError,
3290 "bad type passed to datetime unpickler: %s",
3291 arg->ob_type->tp_name);
3292 return NULL;
3293 }
3294 self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType);
3295 if (self != NULL) {
3296 PyObject *res = datetime_setstate(self, arg);
3297 if (res == NULL) {
3298 Py_DECREF(self);
3299 return NULL;
3300 }
3301 Py_DECREF(res);
3302 }
3303 return (PyObject *)self;
3304}
3305
3306static PyMethodDef datetime_methods[] = {
3307 /* Class methods: */
3308 {"now", (PyCFunction)datetime_now,
3309 METH_NOARGS | METH_CLASS,
3310 PyDoc_STR("Return a new datetime representing local day and time.")},
3311
3312 {"utcnow", (PyCFunction)datetime_utcnow,
3313 METH_NOARGS | METH_CLASS,
3314 PyDoc_STR("Return a new datetime representing UTC day and time.")},
3315
3316 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
3317 METH_VARARGS | METH_CLASS,
3318 PyDoc_STR("timestamp -> local datetime from a POSIX timestamp "
3319 "(like time.time()).")},
3320
3321 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
3322 METH_VARARGS | METH_CLASS,
3323 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
3324 "(like time.time()).")},
3325
3326 {"combine", (PyCFunction)datetime_combine,
3327 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
3328 PyDoc_STR("date, time -> datetime with same date and time fields")},
3329
3330 /* Instance methods: */
3331 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
3332 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
3333
3334 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
3335 PyDoc_STR("Return date object with same year, month and day.")},
3336
3337 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
3338 PyDoc_STR("Return time object with same hour, minute, second and "
3339 "microsecond.")},
3340
3341 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
3342 PyDoc_STR("Return ctime() style string.")},
3343
3344 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
3345 PyDoc_STR("[sep] -> string in ISO 8601 format, "
3346 "YYYY-MM-DDTHH:MM:SS[.mmmmmm].\n\n"
3347 "sep is used to separate the year from the time, and "
3348 "defaults\n"
3349 "to 'T'.")},
3350
3351 {"__setstate__", (PyCFunction)datetime_setstate, METH_O,
3352 PyDoc_STR("__setstate__(state)")},
3353
3354 {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS,
3355 PyDoc_STR("__getstate__() -> state")},
3356 {NULL, NULL}
3357};
3358
3359static char datetime_doc[] =
3360PyDoc_STR("Basic date/time type.");
3361
3362static PyNumberMethods datetime_as_number = {
3363 datetime_add, /* nb_add */
3364 datetime_subtract, /* nb_subtract */
3365 0, /* nb_multiply */
3366 0, /* nb_divide */
3367 0, /* nb_remainder */
3368 0, /* nb_divmod */
3369 0, /* nb_power */
3370 0, /* nb_negative */
3371 0, /* nb_positive */
3372 0, /* nb_absolute */
3373 0, /* nb_nonzero */
3374};
3375
3376statichere PyTypeObject PyDateTime_DateTimeType = {
3377 PyObject_HEAD_INIT(NULL)
3378 0, /* ob_size */
3379 "datetime.datetime", /* tp_name */
3380 sizeof(PyDateTime_DateTime), /* tp_basicsize */
3381 0, /* tp_itemsize */
3382 (destructor)PyObject_Del, /* tp_dealloc */
3383 0, /* tp_print */
3384 0, /* tp_getattr */
3385 0, /* tp_setattr */
3386 0, /* tp_compare */
3387 (reprfunc)datetime_repr, /* tp_repr */
3388 &datetime_as_number, /* tp_as_number */
3389 0, /* tp_as_sequence */
3390 0, /* tp_as_mapping */
3391 (hashfunc)datetime_hash, /* tp_hash */
3392 0, /* tp_call */
3393 (reprfunc)datetime_str, /* tp_str */
3394 PyObject_GenericGetAttr, /* tp_getattro */
3395 0, /* tp_setattro */
3396 0, /* tp_as_buffer */
3397 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3398 Py_TPFLAGS_BASETYPE, /* tp_flags */
3399 datetime_doc, /* tp_doc */
3400 0, /* tp_traverse */
3401 0, /* tp_clear */
3402 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
3403 0, /* tp_weaklistoffset */
3404 0, /* tp_iter */
3405 0, /* tp_iternext */
3406 datetime_methods, /* tp_methods */
3407 0, /* tp_members */
3408 datetime_getset, /* tp_getset */
3409 &PyDateTime_DateType, /* tp_base */
3410 0, /* tp_dict */
3411 0, /* tp_descr_get */
3412 0, /* tp_descr_set */
3413 0, /* tp_dictoffset */
3414 0, /* tp_init */
3415 0, /* tp_alloc */
3416 datetime_new, /* tp_new */
3417 _PyObject_Del, /* tp_free */
3418};
3419
3420/*
3421 * PyDateTime_Time implementation.
3422 */
3423
3424/* Accessor properties. */
3425
3426static PyObject *
3427time_hour(PyDateTime_Time *self, void *unused)
3428{
3429 return PyInt_FromLong(TIME_GET_HOUR(self));
3430}
3431
3432static PyObject *
3433time_minute(PyDateTime_Time *self, void *unused)
3434{
3435 return PyInt_FromLong(TIME_GET_MINUTE(self));
3436}
3437
3438static PyObject *
Jack Jansen51cd8a22002-12-17 20:57:24 +00003439py_time_second(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003440{
3441 return PyInt_FromLong(TIME_GET_SECOND(self));
3442}
3443
3444static PyObject *
3445time_microsecond(PyDateTime_Time *self, void *unused)
3446{
3447 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3448}
3449
3450static PyGetSetDef time_getset[] = {
3451 {"hour", (getter)time_hour},
3452 {"minute", (getter)time_minute},
Jack Jansen51cd8a22002-12-17 20:57:24 +00003453 {"second", (getter)py_time_second},
Tim Peters2a799bf2002-12-16 20:18:38 +00003454 {"microsecond", (getter)time_microsecond},
3455 {NULL}
3456};
3457
3458/* Constructors. */
3459
3460static PyObject *
3461time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3462{
3463 PyObject *self = NULL;
3464 int hour = 0;
3465 int minute = 0;
3466 int second = 0;
3467 int usecond = 0;
3468
3469 static char *keywords[] = {
3470 "hour", "minute", "second", "microsecond", NULL
3471 };
3472
3473 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiii", keywords,
3474 &hour, &minute, &second, &usecond)) {
3475 if (check_time_args(hour, minute, second, usecond) < 0)
3476 return NULL;
3477 self = new_time(hour, minute, second, usecond);
3478 }
3479 return self;
3480}
3481
3482/* Various ways to turn a time into a string. */
3483
3484static PyObject *
3485time_repr(PyDateTime_Time *self)
3486{
3487 char buffer[100];
3488 char *typename = self->ob_type->tp_name;
3489 int h = TIME_GET_HOUR(self);
3490 int m = TIME_GET_MINUTE(self);
3491 int s = TIME_GET_SECOND(self);
3492 int us = TIME_GET_MICROSECOND(self);
3493
3494 if (us)
3495 PyOS_snprintf(buffer, sizeof(buffer),
3496 "%s(%d, %d, %d, %d)", typename, h, m, s, us);
3497 else if (s)
3498 PyOS_snprintf(buffer, sizeof(buffer),
3499 "%s(%d, %d, %d)", typename, h, m, s);
3500 else
3501 PyOS_snprintf(buffer, sizeof(buffer),
3502 "%s(%d, %d)", typename, h, m);
3503 return PyString_FromString(buffer);
3504}
3505
3506static PyObject *
3507time_str(PyDateTime_Time *self)
3508{
3509 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3510}
3511
3512static PyObject *
3513time_isoformat(PyDateTime_Time *self)
3514{
3515 char buffer[100];
3516 /* Reuse the time format code from the datetime type. */
3517 PyDateTime_DateTime datetime;
3518 PyDateTime_DateTime *pdatetime = &datetime;
3519
3520 /* Copy over just the time bytes. */
3521 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3522 self->data,
3523 _PyDateTime_TIME_DATASIZE);
3524
3525 isoformat_time(pdatetime, buffer, sizeof(buffer));
3526 return PyString_FromString(buffer);
3527}
3528
3529static PyObject *
3530time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3531{
3532 PyObject *result;
3533 PyObject *format;
3534 PyObject *tuple;
3535 static char *keywords[] = {"format", NULL};
3536
3537 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3538 &PyString_Type, &format))
3539 return NULL;
3540
Tim Peters83b85f12002-12-22 20:34:46 +00003541 /* Python's strftime does insane things with the year part of the
3542 * timetuple. The year is forced to (the otherwise nonsensical)
3543 * 1900 to worm around that.
3544 */
Tim Peters2a799bf2002-12-16 20:18:38 +00003545 tuple = Py_BuildValue("iiiiiiiii",
Tim Peters83b85f12002-12-22 20:34:46 +00003546 1900, 0, 0, /* year, month, day */
Tim Peters2a799bf2002-12-16 20:18:38 +00003547 TIME_GET_HOUR(self),
3548 TIME_GET_MINUTE(self),
3549 TIME_GET_SECOND(self),
3550 0, 0, -1); /* weekday, daynum, dst */
3551 if (tuple == NULL)
3552 return NULL;
3553 assert(PyTuple_Size(tuple) == 9);
3554 result = wrap_strftime((PyObject *)self, format, tuple);
3555 Py_DECREF(tuple);
3556 return result;
3557}
3558
3559/* Miscellaneous methods. */
3560
3561/* This is more natural as a tp_compare, but doesn't work then: for whatever
3562 * reason, Python's try_3way_compare ignores tp_compare unless
3563 * PyInstance_Check returns true, but these aren't old-style classes.
3564 * Note that this routine handles all comparisons for time and timetz.
3565 */
3566static PyObject *
3567time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3568{
3569 int diff;
3570 naivety n1, n2;
3571 int offset1, offset2;
3572
3573 if (! PyTime_Check(other)) {
3574 /* Stop this from falling back to address comparison. */
3575 PyErr_Format(PyExc_TypeError,
3576 "can't compare '%s' to '%s'",
3577 self->ob_type->tp_name,
3578 other->ob_type->tp_name);
3579 return NULL;
3580 }
Tim Peters14b69412002-12-22 18:10:22 +00003581 n1 = classify_utcoffset((PyObject *)self, &offset1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003582 assert(n1 != OFFSET_UNKNOWN);
3583 if (n1 == OFFSET_ERROR)
3584 return NULL;
3585
Tim Peters14b69412002-12-22 18:10:22 +00003586 n2 = classify_utcoffset(other, &offset2);
Tim Peters2a799bf2002-12-16 20:18:38 +00003587 assert(n2 != OFFSET_UNKNOWN);
3588 if (n2 == OFFSET_ERROR)
3589 return NULL;
3590
3591 /* If they're both naive, or both aware and have the same offsets,
3592 * we get off cheap. Note that if they're both naive, offset1 ==
3593 * offset2 == 0 at this point.
3594 */
3595 if (n1 == n2 && offset1 == offset2) {
3596 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3597 _PyDateTime_TIME_DATASIZE);
3598 return diff_to_bool(diff, op);
3599 }
3600
3601 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3602 assert(offset1 != offset2); /* else last "if" handled it */
3603 /* Convert everything except microseconds to seconds. These
3604 * can't overflow (no more than the # of seconds in 2 days).
3605 */
3606 offset1 = TIME_GET_HOUR(self) * 3600 +
3607 (TIME_GET_MINUTE(self) - offset1) * 60 +
3608 TIME_GET_SECOND(self);
3609 offset2 = TIME_GET_HOUR(other) * 3600 +
3610 (TIME_GET_MINUTE(other) - offset2) * 60 +
3611 TIME_GET_SECOND(other);
3612 diff = offset1 - offset2;
3613 if (diff == 0)
3614 diff = TIME_GET_MICROSECOND(self) -
3615 TIME_GET_MICROSECOND(other);
3616 return diff_to_bool(diff, op);
3617 }
3618
3619 assert(n1 != n2);
3620 PyErr_SetString(PyExc_TypeError,
3621 "can't compare offset-naive and "
3622 "offset-aware times");
3623 return NULL;
3624}
3625
3626static PyObject *time_getstate(PyDateTime_Time *self);
3627
3628static long
3629time_hash(PyDateTime_Time *self)
3630{
3631 if (self->hashcode == -1) {
3632 naivety n;
3633 int offset;
3634 PyObject *temp;
3635
Tim Peters14b69412002-12-22 18:10:22 +00003636 n = classify_utcoffset((PyObject *)self, &offset);
Tim Peters2a799bf2002-12-16 20:18:38 +00003637 assert(n != OFFSET_UNKNOWN);
3638 if (n == OFFSET_ERROR)
3639 return -1;
3640
3641 /* Reduce this to a hash of another object. */
3642 if (offset == 0)
3643 temp = time_getstate(self);
3644 else {
3645 int hour;
3646 int minute;
3647
3648 assert(n == OFFSET_AWARE);
3649 assert(PyTimeTZ_Check(self));
3650 hour = divmod(TIME_GET_HOUR(self) * 60 +
3651 TIME_GET_MINUTE(self) - offset,
3652 60,
3653 &minute);
3654 if (0 <= hour && hour < 24)
3655 temp = new_time(hour, minute,
3656 TIME_GET_SECOND(self),
3657 TIME_GET_MICROSECOND(self));
3658 else
3659 temp = Py_BuildValue("iiii",
3660 hour, minute,
3661 TIME_GET_SECOND(self),
3662 TIME_GET_MICROSECOND(self));
3663 }
3664 if (temp != NULL) {
3665 self->hashcode = PyObject_Hash(temp);
3666 Py_DECREF(temp);
3667 }
3668 }
3669 return self->hashcode;
3670}
3671
3672static int
3673time_nonzero(PyDateTime_Time *self)
3674{
3675 return TIME_GET_HOUR(self) ||
3676 TIME_GET_MINUTE(self) ||
3677 TIME_GET_SECOND(self) ||
3678 TIME_GET_MICROSECOND(self);
3679}
3680
3681/* Pickle support. Quite a maze! */
3682
3683static PyObject *
3684time_getstate(PyDateTime_Time *self)
3685{
3686 return PyString_FromStringAndSize(self->data,
3687 _PyDateTime_TIME_DATASIZE);
3688}
3689
3690static PyObject *
3691time_setstate(PyDateTime_Time *self, PyObject *state)
3692{
3693 const int len = PyString_Size(state);
3694 unsigned char *pdata = (unsigned char*)PyString_AsString(state);
3695
3696 if (! PyString_Check(state) ||
3697 len != _PyDateTime_TIME_DATASIZE) {
3698 PyErr_SetString(PyExc_TypeError,
3699 "bad argument to time.__setstate__");
3700 return NULL;
3701 }
3702 memcpy(self->data, pdata, _PyDateTime_TIME_DATASIZE);
3703 self->hashcode = -1;
3704
3705 Py_INCREF(Py_None);
3706 return Py_None;
3707}
3708
3709/* XXX This seems a ridiculously inefficient way to pickle a short string. */
3710static PyObject *
3711time_pickler(PyObject *module, PyDateTime_Time *time)
3712{
3713 PyObject *state;
3714 PyObject *result = NULL;
3715
3716 if (! PyTime_CheckExact(time)) {
3717 PyErr_Format(PyExc_TypeError,
3718 "bad type passed to time pickler: %s",
3719 time->ob_type->tp_name);
3720 return NULL;
3721 }
3722 state = time_getstate(time);
3723 if (state) {
3724 result = Py_BuildValue("O(O)",
3725 time_unpickler_object,
3726 state);
3727 Py_DECREF(state);
3728 }
3729 return result;
3730}
3731
3732static PyObject *
3733time_unpickler(PyObject *module, PyObject *arg)
3734{
3735 PyDateTime_Time *self;
3736
3737 if (! PyString_CheckExact(arg)) {
3738 PyErr_Format(PyExc_TypeError,
3739 "bad type passed to time unpickler: %s",
3740 arg->ob_type->tp_name);
3741 return NULL;
3742 }
3743 self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType);
3744 if (self != NULL) {
3745 PyObject *res = time_setstate(self, arg);
3746 if (res == NULL) {
3747 Py_DECREF(self);
3748 return NULL;
3749 }
3750 Py_DECREF(res);
3751 }
3752 return (PyObject *)self;
3753}
3754
3755static PyMethodDef time_methods[] = {
3756 {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
3757 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm].")},
3758
3759 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3760 PyDoc_STR("format -> strftime() style string.")},
3761
3762 {"__setstate__", (PyCFunction)time_setstate, METH_O,
3763 PyDoc_STR("__setstate__(state)")},
3764
3765 {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS,
3766 PyDoc_STR("__getstate__() -> state")},
3767 {NULL, NULL}
3768};
3769
3770static char time_doc[] =
3771PyDoc_STR("Basic time type.");
3772
3773static PyNumberMethods time_as_number = {
3774 0, /* nb_add */
3775 0, /* nb_subtract */
3776 0, /* nb_multiply */
3777 0, /* nb_divide */
3778 0, /* nb_remainder */
3779 0, /* nb_divmod */
3780 0, /* nb_power */
3781 0, /* nb_negative */
3782 0, /* nb_positive */
3783 0, /* nb_absolute */
3784 (inquiry)time_nonzero, /* nb_nonzero */
3785};
3786
3787statichere PyTypeObject PyDateTime_TimeType = {
3788 PyObject_HEAD_INIT(NULL)
3789 0, /* ob_size */
3790 "datetime.time", /* tp_name */
3791 sizeof(PyDateTime_Time), /* tp_basicsize */
3792 0, /* tp_itemsize */
3793 (destructor)PyObject_Del, /* tp_dealloc */
3794 0, /* tp_print */
3795 0, /* tp_getattr */
3796 0, /* tp_setattr */
3797 0, /* tp_compare */
3798 (reprfunc)time_repr, /* tp_repr */
3799 &time_as_number, /* tp_as_number */
3800 0, /* tp_as_sequence */
3801 0, /* tp_as_mapping */
3802 (hashfunc)time_hash, /* tp_hash */
3803 0, /* tp_call */
3804 (reprfunc)time_str, /* tp_str */
3805 PyObject_GenericGetAttr, /* tp_getattro */
3806 0, /* tp_setattro */
3807 0, /* tp_as_buffer */
3808 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3809 Py_TPFLAGS_BASETYPE, /* tp_flags */
3810 time_doc, /* tp_doc */
3811 0, /* tp_traverse */
3812 0, /* tp_clear */
3813 (richcmpfunc)time_richcompare, /* tp_richcompare */
3814 0, /* tp_weaklistoffset */
3815 0, /* tp_iter */
3816 0, /* tp_iternext */
3817 time_methods, /* tp_methods */
3818 0, /* tp_members */
3819 time_getset, /* tp_getset */
3820 0, /* tp_base */
3821 0, /* tp_dict */
3822 0, /* tp_descr_get */
3823 0, /* tp_descr_set */
3824 0, /* tp_dictoffset */
3825 0, /* tp_init */
3826 0, /* tp_alloc */
3827 time_new, /* tp_new */
3828 _PyObject_Del, /* tp_free */
3829};
3830
3831/*
3832 * PyDateTime_TZInfo implementation.
3833 */
3834
3835/* This is a pure abstract base class, so doesn't do anything beyond
3836 * raising NotImplemented exceptions. Real tzinfo classes need
3837 * to derive from this. This is mostly for clarity, and for efficiency in
3838 * datetimetz and timetz constructors (their tzinfo arguments need to
3839 * be subclasses of this tzinfo class, which is easy and quick to check).
3840 *
3841 * Note: For reasons having to do with pickling of subclasses, we have
3842 * to allow tzinfo objects to be instantiated. This wasn't an issue
3843 * in the Python implementation (__init__() could raise NotImplementedError
3844 * there without ill effect), but doing so in the C implementation hit a
3845 * brick wall.
3846 */
3847
3848static PyObject *
3849tzinfo_nogo(const char* methodname)
3850{
3851 PyErr_Format(PyExc_NotImplementedError,
3852 "a tzinfo subclass must implement %s()",
3853 methodname);
3854 return NULL;
3855}
3856
3857/* Methods. A subclass must implement these. */
3858
3859static PyObject*
3860tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
3861{
3862 return tzinfo_nogo("tzname");
3863}
3864
3865static PyObject*
3866tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
3867{
3868 return tzinfo_nogo("utcoffset");
3869}
3870
3871static PyObject*
3872tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
3873{
3874 return tzinfo_nogo("dst");
3875}
3876
3877/*
3878 * Pickle support. This is solely so that tzinfo subclasses can use
3879 * pickling -- tzinfo itself is supposed to be uninstantiable. The
3880 * pickler and unpickler functions are given module-level private
3881 * names, and registered with copy_reg, by the module init function.
3882 */
3883
3884static PyObject*
3885tzinfo_pickler(PyDateTime_TZInfo *self) {
3886 return Py_BuildValue("O()", tzinfo_unpickler_object);
3887}
3888
3889static PyObject*
3890tzinfo_unpickler(PyObject * unused) {
3891 return PyType_GenericNew(&PyDateTime_TZInfoType, NULL, NULL);
3892}
3893
3894
3895static PyMethodDef tzinfo_methods[] = {
3896 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3897 PyDoc_STR("datetime -> string name of time zone.")},
3898
3899 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
3900 PyDoc_STR("datetime -> minutes east of UTC (negative for "
3901 "west of UTC).")},
3902
3903 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3904 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
3905
3906 {NULL, NULL}
3907};
3908
3909static char tzinfo_doc[] =
3910PyDoc_STR("Abstract base class for time zone info objects.");
3911
3912 statichere PyTypeObject PyDateTime_TZInfoType = {
3913 PyObject_HEAD_INIT(NULL)
3914 0, /* ob_size */
3915 "datetime.tzinfo", /* tp_name */
3916 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3917 0, /* tp_itemsize */
3918 0, /* tp_dealloc */
3919 0, /* tp_print */
3920 0, /* tp_getattr */
3921 0, /* tp_setattr */
3922 0, /* tp_compare */
3923 0, /* tp_repr */
3924 0, /* tp_as_number */
3925 0, /* tp_as_sequence */
3926 0, /* tp_as_mapping */
3927 0, /* tp_hash */
3928 0, /* tp_call */
3929 0, /* tp_str */
3930 PyObject_GenericGetAttr, /* tp_getattro */
3931 0, /* tp_setattro */
3932 0, /* tp_as_buffer */
3933 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3934 Py_TPFLAGS_BASETYPE, /* tp_flags */
3935 tzinfo_doc, /* tp_doc */
3936 0, /* tp_traverse */
3937 0, /* tp_clear */
3938 0, /* tp_richcompare */
3939 0, /* tp_weaklistoffset */
3940 0, /* tp_iter */
3941 0, /* tp_iternext */
3942 tzinfo_methods, /* tp_methods */
3943 0, /* tp_members */
3944 0, /* tp_getset */
3945 0, /* tp_base */
3946 0, /* tp_dict */
3947 0, /* tp_descr_get */
3948 0, /* tp_descr_set */
3949 0, /* tp_dictoffset */
3950 0, /* tp_init */
3951 0, /* tp_alloc */
3952 PyType_GenericNew, /* tp_new */
3953 0, /* tp_free */
3954};
3955
3956/*
3957 * PyDateTime_TimeTZ implementation.
3958 */
3959
3960/* Accessor properties. Properties for hour, minute, second and microsecond
3961 * are inherited from time.
3962 */
3963
3964static PyObject *
3965timetz_tzinfo(PyDateTime_TimeTZ *self, void *unused)
3966{
3967 Py_INCREF(self->tzinfo);
3968 return self->tzinfo;
3969}
3970
3971static PyGetSetDef timetz_getset[] = {
3972 {"tzinfo", (getter)timetz_tzinfo},
3973 {NULL}
3974};
3975
3976/*
3977 * Constructors.
3978 */
3979
3980static PyObject *
3981timetz_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3982{
3983 PyObject *self = NULL;
3984 int hour = 0;
3985 int minute = 0;
3986 int second = 0;
3987 int usecond = 0;
3988 PyObject *tzinfo = Py_None;
3989
3990 static char *keywords[] = {
3991 "hour", "minute", "second", "microsecond", "tzinfo", NULL
3992 };
3993
Neal Norwitzc296c632002-12-19 00:42:03 +00003994 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", keywords,
Tim Peters2a799bf2002-12-16 20:18:38 +00003995 &hour, &minute, &second, &usecond,
3996 &tzinfo)) {
3997 if (check_time_args(hour, minute, second, usecond) < 0)
3998 return NULL;
3999 if (check_tzinfo_subclass(tzinfo) < 0)
4000 return NULL;
4001 self = new_timetz(hour, minute, second, usecond, tzinfo);
4002 }
4003 return self;
4004}
4005
4006/*
4007 * Destructor.
4008 */
4009
4010static void
4011timetz_dealloc(PyDateTime_TimeTZ *self)
4012{
4013 Py_XDECREF(self->tzinfo);
4014 self->ob_type->tp_free((PyObject *)self);
4015}
4016
4017/*
Tim Peters855fe882002-12-22 03:43:39 +00004018 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00004019 */
4020
Tim Peters2a799bf2002-12-16 20:18:38 +00004021/* These are all METH_NOARGS, so don't need to check the arglist. */
4022static PyObject *
4023timetz_utcoffset(PyDateTime_TimeTZ *self, PyObject *unused) {
Tim Peters855fe882002-12-22 03:43:39 +00004024 return offset_as_timedelta((PyObject *)self, self->tzinfo,
4025 "utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00004026}
4027
4028static PyObject *
4029timetz_dst(PyDateTime_TimeTZ *self, PyObject *unused) {
Tim Peters855fe882002-12-22 03:43:39 +00004030 return offset_as_timedelta((PyObject *)self, self->tzinfo, "dst");
4031}
4032
4033static PyObject *
4034timetz_tzname(PyDateTime_TimeTZ *self, PyObject *unused) {
4035 return call_tzname((PyObject *)self, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004036}
4037
4038/*
4039 * Various ways to turn a timetz into a string.
4040 */
4041
4042static PyObject *
4043timetz_repr(PyDateTime_TimeTZ *self)
4044{
4045 PyObject *baserepr = time_repr((PyDateTime_Time *)self);
4046
4047 if (baserepr == NULL)
4048 return NULL;
4049 return append_keyword_tzinfo(baserepr, self->tzinfo);
4050}
4051
4052/* Note: tp_str is inherited from time. */
4053
4054static PyObject *
4055timetz_isoformat(PyDateTime_TimeTZ *self)
4056{
4057 char buf[100];
4058 PyObject *result = time_isoformat((PyDateTime_Time *)self);
4059
4060 if (result == NULL || self->tzinfo == Py_None)
4061 return result;
4062
4063 /* We need to append the UTC offset. */
4064 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4065 (PyObject *)self) < 0) {
4066 Py_DECREF(result);
4067 return NULL;
4068 }
4069 PyString_ConcatAndDel(&result, PyString_FromString(buf));
4070 return result;
4071}
4072
4073/* Note: strftime() is inherited from time. */
4074
4075/*
4076 * Miscellaneous methods.
4077 */
4078
4079/* Note: tp_richcompare and tp_hash are inherited from time. */
4080
4081static int
4082timetz_nonzero(PyDateTime_TimeTZ *self)
4083{
4084 int offset;
4085 int none;
4086
4087 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
4088 /* Since utcoffset is in whole minutes, nothing can
4089 * alter the conclusion that this is nonzero.
4090 */
4091 return 1;
4092 }
4093 offset = 0;
4094 if (self->tzinfo != Py_None) {
4095 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4096 if (offset == -1 && PyErr_Occurred())
4097 return -1;
4098 }
4099 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
4100}
4101
4102/*
4103 * Pickle support. Quite a maze!
4104 */
4105
4106/* Let basestate be the state string returned by time_getstate.
4107 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4108 * So it's a tuple in any (non-error) case.
4109 */
4110static PyObject *
4111timetz_getstate(PyDateTime_TimeTZ *self)
4112{
4113 PyObject *basestate;
4114 PyObject *result = NULL;
4115
4116 basestate = time_getstate((PyDateTime_Time *)self);
4117 if (basestate != NULL) {
4118 if (self->tzinfo == Py_None)
4119 result = Py_BuildValue("(O)", basestate);
4120 else
4121 result = Py_BuildValue("OO", basestate, self->tzinfo);
4122 Py_DECREF(basestate);
4123 }
4124 return result;
4125}
4126
4127static PyObject *
4128timetz_setstate(PyDateTime_TimeTZ *self, PyObject *state)
4129{
4130 PyObject *temp;
4131 PyObject *basestate;
4132 PyObject *tzinfo = Py_None;
4133
4134 if (! PyArg_ParseTuple(state, "O!|O:__setstate__",
4135 &PyString_Type, &basestate,
4136 &tzinfo))
4137 return NULL;
4138 temp = time_setstate((PyDateTime_Time *)self, basestate);
4139 if (temp == NULL)
4140 return NULL;
4141 Py_DECREF(temp);
4142
4143 Py_INCREF(tzinfo);
4144 Py_XDECREF(self->tzinfo);
4145 self->tzinfo = tzinfo;
4146
4147 Py_INCREF(Py_None);
4148 return Py_None;
4149}
4150
4151static PyObject *
4152timetz_pickler(PyObject *module, PyDateTime_TimeTZ *timetz)
4153{
4154 PyObject *state;
4155 PyObject *result = NULL;
4156
4157 if (! PyTimeTZ_CheckExact(timetz)) {
4158 PyErr_Format(PyExc_TypeError,
4159 "bad type passed to timetz pickler: %s",
4160 timetz->ob_type->tp_name);
4161 return NULL;
4162 }
4163 state = timetz_getstate(timetz);
4164 if (state) {
4165 result = Py_BuildValue("O(O)",
4166 timetz_unpickler_object,
4167 state);
4168 Py_DECREF(state);
4169 }
4170 return result;
4171}
4172
4173static PyObject *
4174timetz_unpickler(PyObject *module, PyObject *arg)
4175{
4176 PyDateTime_TimeTZ *self;
4177
4178 self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType);
4179 if (self != NULL) {
4180 PyObject *res;
4181
4182 self->tzinfo = NULL;
4183 res = timetz_setstate(self, arg);
4184 if (res == NULL) {
4185 Py_DECREF(self);
4186 return NULL;
4187 }
4188 Py_DECREF(res);
4189 }
4190 return (PyObject *)self;
4191}
4192
4193static PyMethodDef timetz_methods[] = {
4194 {"isoformat", (PyCFunction)timetz_isoformat, METH_KEYWORDS,
4195 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
4196 "[+HH:MM].")},
4197
4198 {"utcoffset", (PyCFunction)timetz_utcoffset, METH_NOARGS,
4199 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4200
4201 {"tzname", (PyCFunction)timetz_tzname, METH_NOARGS,
4202 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4203
4204 {"dst", (PyCFunction)timetz_dst, METH_NOARGS,
4205 PyDoc_STR("Return self.tzinfo.dst(self).")},
4206
4207 {"__setstate__", (PyCFunction)timetz_setstate, METH_O,
4208 PyDoc_STR("__setstate__(state)")},
4209
4210 {"__getstate__", (PyCFunction)timetz_getstate, METH_NOARGS,
4211 PyDoc_STR("__getstate__() -> state")},
4212 {NULL, NULL}
4213
4214};
4215
4216static char timetz_doc[] =
4217PyDoc_STR("Time type.");
4218
4219static PyNumberMethods timetz_as_number = {
4220 0, /* nb_add */
4221 0, /* nb_subtract */
4222 0, /* nb_multiply */
4223 0, /* nb_divide */
4224 0, /* nb_remainder */
4225 0, /* nb_divmod */
4226 0, /* nb_power */
4227 0, /* nb_negative */
4228 0, /* nb_positive */
4229 0, /* nb_absolute */
4230 (inquiry)timetz_nonzero, /* nb_nonzero */
4231};
4232
4233statichere PyTypeObject PyDateTime_TimeTZType = {
4234 PyObject_HEAD_INIT(NULL)
4235 0, /* ob_size */
4236 "datetime.timetz", /* tp_name */
4237 sizeof(PyDateTime_TimeTZ), /* tp_basicsize */
4238 0, /* tp_itemsize */
4239 (destructor)timetz_dealloc, /* tp_dealloc */
4240 0, /* tp_print */
4241 0, /* tp_getattr */
4242 0, /* tp_setattr */
4243 0, /* tp_compare */
4244 (reprfunc)timetz_repr, /* tp_repr */
4245 &timetz_as_number, /* tp_as_number */
4246 0, /* tp_as_sequence */
4247 0, /* tp_as_mapping */
4248 0, /* tp_hash */
4249 0, /* tp_call */
4250 0, /* tp_str */
4251 PyObject_GenericGetAttr, /* tp_getattro */
4252 0, /* tp_setattro */
4253 0, /* tp_as_buffer */
4254 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4255 Py_TPFLAGS_BASETYPE, /* tp_flags */
Guido van Rossumbd43e912002-12-16 20:34:55 +00004256 timetz_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004257 0, /* tp_traverse */
4258 0, /* tp_clear */
4259 0, /* tp_richcompare */
4260 0, /* tp_weaklistoffset */
4261 0, /* tp_iter */
4262 0, /* tp_iternext */
4263 timetz_methods, /* tp_methods */
4264 0, /* tp_members */
4265 timetz_getset, /* tp_getset */
4266 &PyDateTime_TimeType, /* tp_base */
4267 0, /* tp_dict */
4268 0, /* tp_descr_get */
4269 0, /* tp_descr_set */
4270 0, /* tp_dictoffset */
4271 0, /* tp_init */
4272 0, /* tp_alloc */
4273 timetz_new, /* tp_new */
4274 _PyObject_Del, /* tp_free */
4275};
4276
4277/*
4278 * PyDateTime_DateTimeTZ implementation.
4279 */
4280
4281/* Accessor properties. Properties for day, month, year, hour, minute,
4282 * second and microsecond are inherited from datetime.
4283 */
4284
4285static PyObject *
4286datetimetz_tzinfo(PyDateTime_DateTimeTZ *self, void *unused)
4287{
4288 Py_INCREF(self->tzinfo);
4289 return self->tzinfo;
4290}
4291
4292static PyGetSetDef datetimetz_getset[] = {
4293 {"tzinfo", (getter)datetimetz_tzinfo},
4294 {NULL}
4295};
4296
4297/*
4298 * Constructors.
4299 * These are like the datetime methods of the same names, but allow an
4300 * optional tzinfo argument.
4301 */
4302
4303/* Internal helper.
4304 * self is a datetimetz. Replace its tzinfo member.
4305 */
4306void
4307replace_tzinfo(PyObject *self, PyObject *newtzinfo)
4308{
4309 assert(self != NULL);
4310 assert(newtzinfo != NULL);
4311 assert(PyDateTimeTZ_Check(self));
4312 Py_INCREF(newtzinfo);
4313 Py_DECREF(((PyDateTime_DateTimeTZ *)self)->tzinfo);
4314 ((PyDateTime_DateTimeTZ *)self)->tzinfo = newtzinfo;
4315}
4316
4317static PyObject *
4318datetimetz_new(PyTypeObject *type, PyObject *args, PyObject *kw)
4319{
4320 PyObject *self = NULL;
4321 int year;
4322 int month;
4323 int day;
4324 int hour = 0;
4325 int minute = 0;
4326 int second = 0;
4327 int usecond = 0;
4328 PyObject *tzinfo = Py_None;
4329
4330 static char *keywords[] = {
4331 "year", "month", "day", "hour", "minute", "second",
4332 "microsecond", "tzinfo", NULL
4333 };
4334
4335 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", keywords,
4336 &year, &month, &day, &hour, &minute,
4337 &second, &usecond, &tzinfo)) {
4338 if (check_date_args(year, month, day) < 0)
4339 return NULL;
4340 if (check_time_args(hour, minute, second, usecond) < 0)
4341 return NULL;
4342 if (check_tzinfo_subclass(tzinfo) < 0)
4343 return NULL;
4344 self = new_datetimetz(year, month, day,
4345 hour, minute, second, usecond,
4346 tzinfo);
4347 }
4348 return self;
4349}
4350
4351/* Return best possible local time -- this isn't constrained by the
4352 * precision of a timestamp.
4353 */
4354static PyObject *
4355datetimetz_now(PyObject *cls, PyObject *args, PyObject *kw)
4356{
4357 PyObject *self = NULL;
4358 PyObject *tzinfo = Py_None;
4359 static char *keywords[] = {"tzinfo", NULL};
4360
4361 if (PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
4362 &tzinfo)) {
4363 if (check_tzinfo_subclass(tzinfo) < 0)
4364 return NULL;
4365 self = datetime_best_possible(cls, localtime);
4366 if (self != NULL)
4367 replace_tzinfo(self, tzinfo);
4368 }
4369 return self;
4370}
4371
4372/* Return new local datetime from timestamp (Python timestamp -- a double). */
4373static PyObject *
4374datetimetz_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
4375{
4376 PyObject *self = NULL;
4377 double timestamp;
4378 PyObject *tzinfo = Py_None;
4379 static char *keywords[] = {"timestamp", "tzinfo", NULL};
4380
4381 if (PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
4382 keywords, &timestamp, &tzinfo)) {
4383 if (check_tzinfo_subclass(tzinfo) < 0)
4384 return NULL;
4385 self = datetime_from_timestamp(cls, localtime, timestamp);
4386 if (self != NULL)
4387 replace_tzinfo(self, tzinfo);
4388 }
4389 return self;
4390}
4391
4392/* Note: utcnow() is inherited, and doesn't accept tzinfo.
4393 * Ditto utcfromtimestamp(). Ditto combine().
4394 */
4395
4396
4397/*
4398 * Destructor.
4399 */
4400
4401static void
4402datetimetz_dealloc(PyDateTime_DateTimeTZ *self)
4403{
4404 Py_XDECREF(self->tzinfo);
4405 self->ob_type->tp_free((PyObject *)self);
4406}
4407
4408/*
4409 * Indirect access to tzinfo methods.
4410 */
4411
Tim Peters2a799bf2002-12-16 20:18:38 +00004412/* These are all METH_NOARGS, so don't need to check the arglist. */
4413static PyObject *
4414datetimetz_utcoffset(PyDateTime_DateTimeTZ *self, PyObject *unused) {
Tim Peters855fe882002-12-22 03:43:39 +00004415 return offset_as_timedelta((PyObject *)self, self->tzinfo,
4416 "utcoffset");
Tim Peters2a799bf2002-12-16 20:18:38 +00004417}
4418
4419static PyObject *
4420datetimetz_dst(PyDateTime_DateTimeTZ *self, PyObject *unused) {
Tim Peters855fe882002-12-22 03:43:39 +00004421 return offset_as_timedelta((PyObject *)self, self->tzinfo, "dst");
4422}
4423
4424static PyObject *
4425datetimetz_tzname(PyDateTime_DateTimeTZ *self, PyObject *unused) {
4426 return call_tzname((PyObject *)self, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004427}
4428
4429/*
4430 * datetimetz arithmetic.
4431 */
4432
4433/* If base is Py_NotImplemented or NULL, just return it.
4434 * Else base is a datetime, exactly one of {left, right} is a datetimetz,
4435 * and we want to create a datetimetz with the same date and time fields
4436 * as base, and with the tzinfo field from left or right. Do that,
4437 * return it, and decref base. This is used to transform the result of
4438 * a binary datetime operation (base) into a datetimetz result.
4439 */
4440static PyObject *
4441attach_tzinfo(PyObject *base, PyObject *left, PyObject *right)
4442{
4443 PyDateTime_DateTimeTZ *self;
4444 PyDateTime_DateTimeTZ *result;
4445
4446 if (base == NULL || base == Py_NotImplemented)
4447 return base;
4448
4449 assert(PyDateTime_CheckExact(base));
4450
4451 if (PyDateTimeTZ_Check(left)) {
4452 assert(! PyDateTimeTZ_Check(right));
4453 self = (PyDateTime_DateTimeTZ *)left;
4454 }
4455 else {
4456 assert(PyDateTimeTZ_Check(right));
4457 self = (PyDateTime_DateTimeTZ *)right;
4458 }
4459 result = PyObject_New(PyDateTime_DateTimeTZ,
4460 &PyDateTime_DateTimeTZType);
4461 if (result != NULL) {
4462 memcpy(result->data, ((PyDateTime_DateTime *)base)->data,
4463 _PyDateTime_DATETIME_DATASIZE);
4464 Py_INCREF(self->tzinfo);
4465 result->tzinfo = self->tzinfo;
4466 }
4467 Py_DECREF(base);
4468 return (PyObject *)result;
4469}
4470
4471static PyObject *
4472datetimetz_add(PyObject *left, PyObject *right)
4473{
4474 return attach_tzinfo(datetime_add(left, right), left, right);
4475}
4476
4477static PyObject *
4478datetimetz_subtract(PyObject *left, PyObject *right)
4479{
4480 PyObject *result = Py_NotImplemented;
4481
4482 if (PyDateTime_Check(left)) {
4483 /* datetime - ??? */
4484 if (PyDateTime_Check(right)) {
4485 /* datetime - datetime */
4486 naivety n1, n2;
4487 int offset1, offset2;
4488 PyDateTime_Delta *delta;
4489
Tim Peters14b69412002-12-22 18:10:22 +00004490 n1 = classify_utcoffset(left, &offset1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004491 assert(n1 != OFFSET_UNKNOWN);
4492 if (n1 == OFFSET_ERROR)
4493 return NULL;
4494
Tim Peters14b69412002-12-22 18:10:22 +00004495 n2 = classify_utcoffset(right, &offset2);
Tim Peters2a799bf2002-12-16 20:18:38 +00004496 assert(n2 != OFFSET_UNKNOWN);
4497 if (n2 == OFFSET_ERROR)
4498 return NULL;
4499
4500 if (n1 != n2) {
4501 PyErr_SetString(PyExc_TypeError,
4502 "can't subtract offset-naive and "
4503 "offset-aware datetimes");
4504 return NULL;
4505 }
4506 delta = (PyDateTime_Delta *)sub_datetime_datetime(
4507 (PyDateTime_DateTime *)left,
4508 (PyDateTime_DateTime *)right);
4509 if (delta == NULL || offset1 == offset2)
4510 return (PyObject *)delta;
4511 /* (left - offset1) - (right - offset2) =
4512 * (left - right) + (offset2 - offset1)
4513 */
4514 result = new_delta(delta->days,
4515 delta->seconds +
4516 (offset2 - offset1) * 60,
4517 delta->microseconds,
4518 1);
4519 Py_DECREF(delta);
4520 }
4521 else if (PyDelta_Check(right)) {
4522 /* datetimetz - delta */
4523 result = sub_datetime_timedelta(
4524 (PyDateTime_DateTime *)left,
4525 (PyDateTime_Delta *)right);
4526 result = attach_tzinfo(result, left, right);
4527 }
4528 }
4529
4530 if (result == Py_NotImplemented)
4531 Py_INCREF(result);
4532 return result;
4533}
4534
4535/* Various ways to turn a datetime into a string. */
4536
4537static PyObject *
4538datetimetz_repr(PyDateTime_DateTimeTZ *self)
4539{
4540 PyObject *baserepr = datetime_repr((PyDateTime_DateTime *)self);
4541
4542 if (baserepr == NULL)
4543 return NULL;
4544 return append_keyword_tzinfo(baserepr, self->tzinfo);
4545}
4546
4547/* Note: tp_str is inherited from datetime. */
4548
4549static PyObject *
4550datetimetz_isoformat(PyDateTime_DateTimeTZ *self,
4551 PyObject *args, PyObject *kw)
4552{
4553 char buf[100];
4554 PyObject *result = datetime_isoformat((PyDateTime_DateTime *)self,
4555 args, kw);
4556
4557 if (result == NULL || self->tzinfo == Py_None)
4558 return result;
4559
4560 /* We need to append the UTC offset. */
4561 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
4562 (PyObject *)self) < 0) {
4563 Py_DECREF(result);
4564 return NULL;
4565 }
4566 PyString_ConcatAndDel(&result, PyString_FromString(buf));
4567 return result;
4568}
4569
4570/* Miscellaneous methods. */
4571
4572/* Note: tp_richcompare and tp_hash are inherited from datetime. */
4573
4574static PyObject *
4575datetimetz_timetuple(PyDateTime_DateTimeTZ *self)
4576{
4577 int dstflag = -1;
4578
4579 if (self->tzinfo != Py_None) {
4580 int none;
4581
4582 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4583 if (dstflag == -1 && PyErr_Occurred())
4584 return NULL;
4585
4586 if (none)
4587 dstflag = -1;
4588 else if (dstflag != 0)
4589 dstflag = 1;
4590
4591 }
4592 return build_struct_time(GET_YEAR(self),
4593 GET_MONTH(self),
4594 GET_DAY(self),
4595 DATE_GET_HOUR(self),
4596 DATE_GET_MINUTE(self),
4597 DATE_GET_SECOND(self),
4598 dstflag);
4599}
4600
4601static PyObject *
4602datetimetz_utctimetuple(PyDateTime_DateTimeTZ *self)
4603{
4604 int y = GET_YEAR(self);
4605 int m = GET_MONTH(self);
4606 int d = GET_DAY(self);
4607 int hh = DATE_GET_HOUR(self);
4608 int mm = DATE_GET_MINUTE(self);
4609 int ss = DATE_GET_SECOND(self);
4610 int us = 0; /* microseconds are ignored in a timetuple */
4611 int offset = 0;
4612
4613 if (self->tzinfo != Py_None) {
4614 int none;
4615
4616 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4617 if (offset == -1 && PyErr_Occurred())
4618 return NULL;
4619 }
4620 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4621 * 0 in a UTC timetuple regardless of what dst() says.
4622 */
4623 if (offset) {
4624 /* Subtract offset minutes & normalize. */
4625 int stat;
4626
4627 mm -= offset;
4628 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4629 if (stat < 0) {
4630 /* At the edges, it's possible we overflowed
4631 * beyond MINYEAR or MAXYEAR.
4632 */
4633 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4634 PyErr_Clear();
4635 else
4636 return NULL;
4637 }
4638 }
4639 return build_struct_time(y, m, d, hh, mm, ss, 0);
4640}
4641
4642static PyObject *
4643datetimetz_gettimetz(PyDateTime_DateTimeTZ *self)
4644{
4645 return new_timetz(DATE_GET_HOUR(self),
4646 DATE_GET_MINUTE(self),
4647 DATE_GET_SECOND(self),
4648 DATE_GET_MICROSECOND(self),
4649 self->tzinfo);
4650}
4651
4652/*
4653 * Pickle support. Quite a maze!
4654 */
4655
4656/* Let basestate be the state string returned by datetime_getstate.
4657 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4658 * So it's a tuple in any (non-error) case.
4659 */
4660static PyObject *
4661datetimetz_getstate(PyDateTime_DateTimeTZ *self)
4662{
4663 PyObject *basestate;
4664 PyObject *result = NULL;
4665
4666 basestate = datetime_getstate((PyDateTime_DateTime *)self);
4667 if (basestate != NULL) {
4668 if (self->tzinfo == Py_None)
4669 result = Py_BuildValue("(O)", basestate);
4670 else
4671 result = Py_BuildValue("OO", basestate, self->tzinfo);
4672 Py_DECREF(basestate);
4673 }
4674 return result;
4675}
4676
4677static PyObject *
4678datetimetz_setstate(PyDateTime_DateTimeTZ *self, PyObject *state)
4679{
4680 PyObject *temp;
4681 PyObject *basestate;
4682 PyObject *tzinfo = Py_None;
4683
4684 if (! PyArg_ParseTuple(state, "O!|O:__setstate__",
4685 &PyString_Type, &basestate,
4686 &tzinfo))
4687 return NULL;
4688 temp = datetime_setstate((PyDateTime_DateTime *)self, basestate);
4689 if (temp == NULL)
4690 return NULL;
4691 Py_DECREF(temp);
4692
4693 Py_INCREF(tzinfo);
4694 Py_XDECREF(self->tzinfo);
4695 self->tzinfo = tzinfo;
4696
4697 Py_INCREF(Py_None);
4698 return Py_None;
4699}
4700
4701static PyObject *
4702datetimetz_pickler(PyObject *module, PyDateTime_DateTimeTZ *datetimetz)
4703{
4704 PyObject *state;
4705 PyObject *result = NULL;
4706
4707 if (! PyDateTimeTZ_CheckExact(datetimetz)) {
4708 PyErr_Format(PyExc_TypeError,
4709 "bad type passed to datetimetz pickler: %s",
4710 datetimetz->ob_type->tp_name);
4711 return NULL;
4712 }
4713 state = datetimetz_getstate(datetimetz);
4714 if (state) {
4715 result = Py_BuildValue("O(O)",
4716 datetimetz_unpickler_object,
4717 state);
4718 Py_DECREF(state);
4719 }
4720 return result;
4721}
4722
4723static PyObject *
4724datetimetz_unpickler(PyObject *module, PyObject *arg)
4725{
4726 PyDateTime_DateTimeTZ *self;
4727
4728 self = PyObject_New(PyDateTime_DateTimeTZ, &PyDateTime_DateTimeTZType);
4729 if (self != NULL) {
4730 PyObject *res;
4731
4732 self->tzinfo = NULL;
4733 res = datetimetz_setstate(self, arg);
4734 if (res == NULL) {
4735 Py_DECREF(self);
4736 return NULL;
4737 }
4738 Py_DECREF(res);
4739 }
4740 return (PyObject *)self;
4741}
4742
4743
4744static PyMethodDef datetimetz_methods[] = {
4745 /* Class methods: */
4746 /* Inherited: combine(), utcnow(), utcfromtimestamp() */
4747
4748 {"now", (PyCFunction)datetimetz_now,
4749 METH_KEYWORDS | METH_CLASS,
4750 PyDoc_STR("[tzinfo] -> new datetimetz with local day and time.")},
4751
4752 {"fromtimestamp", (PyCFunction)datetimetz_fromtimestamp,
4753 METH_KEYWORDS | METH_CLASS,
4754 PyDoc_STR("timestamp[, tzinfo] -> local time from POSIX timestamp.")},
4755
4756 /* Instance methods: */
4757 /* Inherited: date(), time(), ctime(). */
4758 {"timetuple", (PyCFunction)datetimetz_timetuple, METH_NOARGS,
4759 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4760
4761 {"utctimetuple", (PyCFunction)datetimetz_utctimetuple, METH_NOARGS,
4762 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4763
4764 {"timetz", (PyCFunction)datetimetz_gettimetz, METH_NOARGS,
4765 PyDoc_STR("Return timetz object with same hour, minute, second, "
4766 "microsecond, and tzinfo.")},
4767
4768 {"isoformat", (PyCFunction)datetimetz_isoformat, METH_KEYWORDS,
4769 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4770 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4771 "sep is used to separate the year from the time, and "
4772 "defaults to 'T'.")},
4773
4774 {"utcoffset", (PyCFunction)datetimetz_utcoffset, METH_NOARGS,
4775 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4776
4777 {"tzname", (PyCFunction)datetimetz_tzname, METH_NOARGS,
4778 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4779
4780 {"dst", (PyCFunction)datetimetz_dst, METH_NOARGS,
4781 PyDoc_STR("Return self.tzinfo.dst(self).")},
4782
4783 {"__setstate__", (PyCFunction)datetimetz_setstate, METH_O,
4784 PyDoc_STR("__setstate__(state)")},
4785
4786 {"__getstate__", (PyCFunction)datetimetz_getstate, METH_NOARGS,
4787 PyDoc_STR("__getstate__() -> state")},
4788 {NULL, NULL}
4789};
4790
4791static char datetimetz_doc[] =
4792PyDoc_STR("date/time type.");
4793
4794static PyNumberMethods datetimetz_as_number = {
4795 datetimetz_add, /* nb_add */
4796 datetimetz_subtract, /* nb_subtract */
4797 0, /* nb_multiply */
4798 0, /* nb_divide */
4799 0, /* nb_remainder */
4800 0, /* nb_divmod */
4801 0, /* nb_power */
4802 0, /* nb_negative */
4803 0, /* nb_positive */
4804 0, /* nb_absolute */
4805 0, /* nb_nonzero */
4806};
4807
4808statichere PyTypeObject PyDateTime_DateTimeTZType = {
4809 PyObject_HEAD_INIT(NULL)
4810 0, /* ob_size */
4811 "datetime.datetimetz", /* tp_name */
4812 sizeof(PyDateTime_DateTimeTZ), /* tp_basicsize */
4813 0, /* tp_itemsize */
4814 (destructor)datetimetz_dealloc, /* tp_dealloc */
4815 0, /* tp_print */
4816 0, /* tp_getattr */
4817 0, /* tp_setattr */
4818 0, /* tp_compare */
4819 (reprfunc)datetimetz_repr, /* tp_repr */
4820 &datetimetz_as_number, /* tp_as_number */
4821 0, /* tp_as_sequence */
4822 0, /* tp_as_mapping */
4823 0, /* tp_hash */
4824 0, /* tp_call */
4825 0, /* tp_str */
4826 PyObject_GenericGetAttr, /* tp_getattro */
4827 0, /* tp_setattro */
4828 0, /* tp_as_buffer */
4829 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4830 Py_TPFLAGS_BASETYPE, /* tp_flags */
4831 datetimetz_doc, /* tp_doc */
4832 0, /* tp_traverse */
4833 0, /* tp_clear */
4834 0, /* tp_richcompare */
4835 0, /* tp_weaklistoffset */
4836 0, /* tp_iter */
4837 0, /* tp_iternext */
4838 datetimetz_methods, /* tp_methods */
4839 0, /* tp_members */
4840 datetimetz_getset, /* tp_getset */
4841 &PyDateTime_DateTimeType, /* tp_base */
4842 0, /* tp_dict */
4843 0, /* tp_descr_get */
4844 0, /* tp_descr_set */
4845 0, /* tp_dictoffset */
4846 0, /* tp_init */
4847 0, /* tp_alloc */
4848 datetimetz_new, /* tp_new */
4849 _PyObject_Del, /* tp_free */
4850};
4851
4852/* ---------------------------------------------------------------------------
4853 * Module methods and initialization.
4854 */
4855
4856static PyMethodDef module_methods[] = {
4857 /* Private functions for pickling support, registered with the
4858 * copy_reg module by the module init function.
4859 */
4860 {"_date_pickler", (PyCFunction)date_pickler, METH_O, NULL},
4861 {"_date_unpickler", (PyCFunction)date_unpickler, METH_O, NULL},
4862 {"_datetime_pickler", (PyCFunction)datetime_pickler, METH_O, NULL},
4863 {"_datetime_unpickler", (PyCFunction)datetime_unpickler,METH_O, NULL},
4864 {"_datetimetz_pickler", (PyCFunction)datetimetz_pickler,METH_O, NULL},
4865 {"_datetimetz_unpickler",(PyCFunction)datetimetz_unpickler,METH_O, NULL},
4866 {"_time_pickler", (PyCFunction)time_pickler, METH_O, NULL},
4867 {"_time_unpickler", (PyCFunction)time_unpickler, METH_O, NULL},
4868 {"_timetz_pickler", (PyCFunction)timetz_pickler, METH_O, NULL},
4869 {"_timetz_unpickler", (PyCFunction)timetz_unpickler, METH_O, NULL},
4870 {"_tzinfo_pickler", (PyCFunction)tzinfo_pickler, METH_O, NULL},
4871 {"_tzinfo_unpickler", (PyCFunction)tzinfo_unpickler, METH_NOARGS,
4872 NULL},
4873 {NULL, NULL}
4874};
4875
4876PyMODINIT_FUNC
4877initdatetime(void)
4878{
4879 PyObject *m; /* a module object */
4880 PyObject *d; /* its dict */
4881 PyObject *x;
4882
4883 /* Types that use __reduce__ for pickling need to set the following
4884 * magical attr in the type dict, with a true value.
4885 */
4886 PyObject *safepickle = PyString_FromString("__safe_for_unpickling__");
4887 if (safepickle == NULL)
4888 return;
4889
4890 m = Py_InitModule3("datetime", module_methods,
4891 "Fast implementation of the datetime type.");
4892
4893 if (PyType_Ready(&PyDateTime_DateType) < 0)
4894 return;
4895 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4896 return;
4897 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4898 return;
4899 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4900 return;
4901 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4902 return;
4903 if (PyType_Ready(&PyDateTime_TimeTZType) < 0)
4904 return;
4905 if (PyType_Ready(&PyDateTime_DateTimeTZType) < 0)
4906 return;
4907
4908 /* Pickling support, via registering functions with copy_reg. */
4909 {
4910 PyObject *pickler;
4911 PyObject *copyreg = PyImport_ImportModule("copy_reg");
4912
4913 if (copyreg == NULL) return;
4914
4915 pickler = PyObject_GetAttrString(m, "_date_pickler");
4916 if (pickler == NULL) return;
4917 date_unpickler_object = PyObject_GetAttrString(m,
4918 "_date_unpickler");
4919 if (date_unpickler_object == NULL) return;
4920 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4921 &PyDateTime_DateType,
4922 pickler,
4923 date_unpickler_object);
4924 if (x == NULL) return;
4925 Py_DECREF(x);
4926 Py_DECREF(pickler);
4927
4928 pickler = PyObject_GetAttrString(m, "_datetime_pickler");
4929 if (pickler == NULL) return;
4930 datetime_unpickler_object = PyObject_GetAttrString(m,
4931 "_datetime_unpickler");
4932 if (datetime_unpickler_object == NULL) return;
4933 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4934 &PyDateTime_DateTimeType,
4935 pickler,
4936 datetime_unpickler_object);
4937 if (x == NULL) return;
4938 Py_DECREF(x);
4939 Py_DECREF(pickler);
4940
4941 pickler = PyObject_GetAttrString(m, "_time_pickler");
4942 if (pickler == NULL) return;
4943 time_unpickler_object = PyObject_GetAttrString(m,
4944 "_time_unpickler");
4945 if (time_unpickler_object == NULL) return;
4946 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4947 &PyDateTime_TimeType,
4948 pickler,
4949 time_unpickler_object);
4950 if (x == NULL) return;
4951 Py_DECREF(x);
4952 Py_DECREF(pickler);
4953
4954 pickler = PyObject_GetAttrString(m, "_timetz_pickler");
4955 if (pickler == NULL) return;
4956 timetz_unpickler_object = PyObject_GetAttrString(m,
4957 "_timetz_unpickler");
4958 if (timetz_unpickler_object == NULL) return;
4959 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4960 &PyDateTime_TimeTZType,
4961 pickler,
4962 timetz_unpickler_object);
4963 if (x == NULL) return;
4964 Py_DECREF(x);
4965 Py_DECREF(pickler);
4966
4967 pickler = PyObject_GetAttrString(m, "_tzinfo_pickler");
4968 if (pickler == NULL) return;
4969 tzinfo_unpickler_object = PyObject_GetAttrString(m,
4970 "_tzinfo_unpickler");
4971 if (tzinfo_unpickler_object == NULL) return;
4972 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4973 &PyDateTime_TZInfoType,
4974 pickler,
4975 tzinfo_unpickler_object);
4976 if (x== NULL) return;
4977 Py_DECREF(x);
4978 Py_DECREF(pickler);
4979
4980 pickler = PyObject_GetAttrString(m, "_datetimetz_pickler");
4981 if (pickler == NULL) return;
4982 datetimetz_unpickler_object = PyObject_GetAttrString(m,
4983 "_datetimetz_unpickler");
4984 if (datetimetz_unpickler_object == NULL) return;
4985 x = PyObject_CallMethod(copyreg, "pickle", "OOO",
4986 &PyDateTime_DateTimeTZType,
4987 pickler,
4988 datetimetz_unpickler_object);
4989 if (x== NULL) return;
4990 Py_DECREF(x);
4991 Py_DECREF(pickler);
4992
4993 Py_DECREF(copyreg);
4994 }
4995
4996 /* timedelta values */
4997 d = PyDateTime_DeltaType.tp_dict;
4998
4999 if (PyDict_SetItem(d, safepickle, Py_True) < 0)
5000 return;
5001
5002 x = new_delta(0, 0, 1, 0);
5003 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5004 return;
5005 Py_DECREF(x);
5006
5007 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
5008 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5009 return;
5010 Py_DECREF(x);
5011
5012 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
5013 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5014 return;
5015 Py_DECREF(x);
5016
5017 /* date values */
5018 d = PyDateTime_DateType.tp_dict;
5019
5020 x = new_date(1, 1, 1);
5021 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5022 return;
5023 Py_DECREF(x);
5024
5025 x = new_date(MAXYEAR, 12, 31);
5026 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5027 return;
5028 Py_DECREF(x);
5029
5030 x = new_delta(1, 0, 0, 0);
5031 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5032 return;
5033 Py_DECREF(x);
5034
5035 /* datetime values */
5036 d = PyDateTime_DateTimeType.tp_dict;
5037
5038 x = new_datetime(1, 1, 1, 0, 0, 0, 0);
5039 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5040 return;
5041 Py_DECREF(x);
5042
5043 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999);
5044 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5045 return;
5046 Py_DECREF(x);
5047
5048 x = new_delta(0, 0, 1, 0);
5049 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5050 return;
5051 Py_DECREF(x);
5052
5053 /* time values */
5054 d = PyDateTime_TimeType.tp_dict;
5055
5056 x = new_time(0, 0, 0, 0);
5057 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5058 return;
5059 Py_DECREF(x);
5060
5061 x = new_time(23, 59, 59, 999999);
5062 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5063 return;
5064 Py_DECREF(x);
5065
5066 x = new_delta(0, 0, 1, 0);
5067 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5068 return;
5069 Py_DECREF(x);
5070
5071 /* timetz values */
5072 d = PyDateTime_TimeTZType.tp_dict;
5073
5074 x = new_timetz(0, 0, 0, 0, Py_None);
5075 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5076 return;
5077 Py_DECREF(x);
5078
5079 x = new_timetz(23, 59, 59, 999999, Py_None);
5080 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5081 return;
5082 Py_DECREF(x);
5083
5084 x = new_delta(0, 0, 1, 0);
5085 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5086 return;
5087 Py_DECREF(x);
5088
5089 /* datetimetz values */
5090 d = PyDateTime_DateTimeTZType.tp_dict;
5091
5092 x = new_datetimetz(1, 1, 1, 0, 0, 0, 0, Py_None);
5093 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
5094 return;
5095 Py_DECREF(x);
5096
5097 x = new_datetimetz(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
5098 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
5099 return;
5100 Py_DECREF(x);
5101
5102 x = new_delta(0, 0, 1, 0);
5103 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
5104 return;
5105 Py_DECREF(x);
5106
5107 Py_DECREF(safepickle);
5108
5109 /* module initialization */
5110 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
5111 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
5112
5113 Py_INCREF(&PyDateTime_DateType);
5114 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
5115
5116 Py_INCREF(&PyDateTime_DateTimeType);
5117 PyModule_AddObject(m, "datetime",
5118 (PyObject *) &PyDateTime_DateTimeType);
5119
5120 Py_INCREF(&PyDateTime_DeltaType);
5121 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
5122
5123 Py_INCREF(&PyDateTime_TimeType);
5124 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
5125
5126 Py_INCREF(&PyDateTime_TZInfoType);
5127 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
5128
5129 Py_INCREF(&PyDateTime_TimeTZType);
5130 PyModule_AddObject(m, "timetz", (PyObject *) &PyDateTime_TimeTZType);
5131
5132 Py_INCREF(&PyDateTime_DateTimeTZType);
5133 PyModule_AddObject(m, "datetimetz",
5134 (PyObject *)&PyDateTime_DateTimeTZType);
5135
5136 /* A 4-year cycle has an extra leap day over what we'd get from
5137 * pasting together 4 single years.
5138 */
5139 assert(DI4Y == 4 * 365 + 1);
5140 assert(DI4Y == days_before_year(4+1));
5141
5142 /* Similarly, a 400-year cycle has an extra leap day over what we'd
5143 * get from pasting together 4 100-year cycles.
5144 */
5145 assert(DI400Y == 4 * DI100Y + 1);
5146 assert(DI400Y == days_before_year(400+1));
5147
5148 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
5149 * pasting together 25 4-year cycles.
5150 */
5151 assert(DI100Y == 25 * DI4Y - 1);
5152 assert(DI100Y == days_before_year(100+1));
5153
5154 us_per_us = PyInt_FromLong(1);
5155 us_per_ms = PyInt_FromLong(1000);
5156 us_per_second = PyInt_FromLong(1000000);
5157 us_per_minute = PyInt_FromLong(60000000);
5158 seconds_per_day = PyInt_FromLong(24 * 3600);
5159 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
5160 us_per_minute == NULL || seconds_per_day == NULL)
5161 return;
5162
5163 /* The rest are too big for 32-bit ints, but even
5164 * us_per_week fits in 40 bits, so doubles should be exact.
5165 */
5166 us_per_hour = PyLong_FromDouble(3600000000.0);
5167 us_per_day = PyLong_FromDouble(86400000000.0);
5168 us_per_week = PyLong_FromDouble(604800000000.0);
5169 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
5170 return;
5171}