blob: 7ffa316013c83df561c0fed2479d0f247b1ddbe2 [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
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
16#define Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000017#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000018#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000019
20/* We require that C int be at least 32 bits, and use int virtually
21 * everywhere. In just a few cases we use a temp long, where a Python
22 * API returns a C long. In such cases, we have to ensure that the
23 * final result fits in a C int (this can be an issue on 64-bit boxes).
24 */
25#if SIZEOF_INT < 4
26# error "datetime.c requires that C int have at least 32 bits"
27#endif
28
29#define MINYEAR 1
30#define MAXYEAR 9999
31
32/* Nine decimal digits is easy to communicate, and leaves enough room
33 * so that two delta days can be added w/o fear of overflowing a signed
34 * 32-bit int, and with plenty of room left over to absorb any possible
35 * carries from adding seconds.
36 */
37#define MAX_DELTA_DAYS 999999999
38
39/* Rename the long macros in datetime.h to more reasonable short names. */
40#define GET_YEAR PyDateTime_GET_YEAR
41#define GET_MONTH PyDateTime_GET_MONTH
42#define GET_DAY PyDateTime_GET_DAY
43#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
44#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
45#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
46#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
47
48/* Date accessors for date and datetime. */
49#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
50 ((o)->data[1] = ((v) & 0x00ff)))
51#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
52#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
53
54/* Date/Time accessors for datetime. */
55#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
56#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
57#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
58#define DATE_SET_MICROSECOND(o, v) \
59 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
60 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
61 ((o)->data[9] = ((v) & 0x0000ff)))
62
63/* Time accessors for time. */
64#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
65#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
66#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
67#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
68#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
69#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
70#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
71#define TIME_SET_MICROSECOND(o, v) \
72 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
73 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
74 ((o)->data[5] = ((v) & 0x0000ff)))
75
76/* Delta accessors for timedelta. */
77#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
78#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
79#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
80
81#define SET_TD_DAYS(o, v) ((o)->days = (v))
82#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
83#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
84
Tim Petersa032d2e2003-01-11 00:15:54 +000085/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
86 * p->hastzinfo.
87 */
88#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
89
Tim Peters3f606292004-03-21 23:38:41 +000090/* M is a char or int claiming to be a valid month. The macro is equivalent
91 * to the two-sided Python test
92 * 1 <= M <= 12
93 */
94#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
95
Tim Peters2a799bf2002-12-16 20:18:38 +000096/* Forward declarations. */
97static PyTypeObject PyDateTime_DateType;
98static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +000099static PyTypeObject PyDateTime_DeltaType;
100static PyTypeObject PyDateTime_TimeType;
101static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000102
103/* ---------------------------------------------------------------------------
104 * Math utilities.
105 */
106
107/* k = i+j overflows iff k differs in sign from both inputs,
108 * iff k^i has sign bit set and k^j has sign bit set,
109 * iff (k^i)&(k^j) has sign bit set.
110 */
111#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
112 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
113
114/* Compute Python divmod(x, y), returning the quotient and storing the
115 * remainder into *r. The quotient is the floor of x/y, and that's
116 * the real point of this. C will probably truncate instead (C99
117 * requires truncation; C89 left it implementation-defined).
118 * Simplification: we *require* that y > 0 here. That's appropriate
119 * for all the uses made of it. This simplifies the code and makes
120 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
121 * overflow case).
122 */
123static int
124divmod(int x, int y, int *r)
125{
126 int quo;
127
128 assert(y > 0);
129 quo = x / y;
130 *r = x - quo * y;
131 if (*r < 0) {
132 --quo;
133 *r += y;
134 }
135 assert(0 <= *r && *r < y);
136 return quo;
137}
138
Tim Peters5d644dd2003-01-02 16:32:54 +0000139/* Round a double to the nearest long. |x| must be small enough to fit
140 * in a C long; this is not checked.
141 */
142static long
143round_to_long(double x)
144{
145 if (x >= 0.0)
146 x = floor(x + 0.5);
147 else
148 x = ceil(x - 0.5);
149 return (long)x;
150}
151
Tim Peters2a799bf2002-12-16 20:18:38 +0000152/* ---------------------------------------------------------------------------
153 * General calendrical helper functions
154 */
155
156/* For each month ordinal in 1..12, the number of days in that month,
157 * and the number of days before that month in the same year. These
158 * are correct for non-leap years only.
159 */
160static int _days_in_month[] = {
161 0, /* unused; this vector uses 1-based indexing */
162 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
163};
164
165static int _days_before_month[] = {
166 0, /* unused; this vector uses 1-based indexing */
167 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
168};
169
170/* year -> 1 if leap year, else 0. */
171static int
172is_leap(int year)
173{
174 /* Cast year to unsigned. The result is the same either way, but
175 * C can generate faster code for unsigned mod than for signed
176 * mod (especially for % 4 -- a good compiler should just grab
177 * the last 2 bits when the LHS is unsigned).
178 */
179 const unsigned int ayear = (unsigned int)year;
180 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
181}
182
183/* year, month -> number of days in that month in that year */
184static int
185days_in_month(int year, int month)
186{
187 assert(month >= 1);
188 assert(month <= 12);
189 if (month == 2 && is_leap(year))
190 return 29;
191 else
192 return _days_in_month[month];
193}
194
195/* year, month -> number of days in year preceeding first day of month */
196static int
197days_before_month(int year, int month)
198{
199 int days;
200
201 assert(month >= 1);
202 assert(month <= 12);
203 days = _days_before_month[month];
204 if (month > 2 && is_leap(year))
205 ++days;
206 return days;
207}
208
209/* year -> number of days before January 1st of year. Remember that we
210 * start with year 1, so days_before_year(1) == 0.
211 */
212static int
213days_before_year(int year)
214{
215 int y = year - 1;
216 /* This is incorrect if year <= 0; we really want the floor
217 * here. But so long as MINYEAR is 1, the smallest year this
218 * can see is 0 (this can happen in some normalization endcases),
219 * so we'll just special-case that.
220 */
221 assert (year >= 0);
222 if (y >= 0)
223 return y*365 + y/4 - y/100 + y/400;
224 else {
225 assert(y == -1);
226 return -366;
227 }
228}
229
230/* Number of days in 4, 100, and 400 year cycles. That these have
231 * the correct values is asserted in the module init function.
232 */
233#define DI4Y 1461 /* days_before_year(5); days in 4 years */
234#define DI100Y 36524 /* days_before_year(101); days in 100 years */
235#define DI400Y 146097 /* days_before_year(401); days in 400 years */
236
237/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
238static void
239ord_to_ymd(int ordinal, int *year, int *month, int *day)
240{
241 int n, n1, n4, n100, n400, leapyear, preceding;
242
243 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
244 * leap years repeats exactly every 400 years. The basic strategy is
245 * to find the closest 400-year boundary at or before ordinal, then
246 * work with the offset from that boundary to ordinal. Life is much
247 * clearer if we subtract 1 from ordinal first -- then the values
248 * of ordinal at 400-year boundaries are exactly those divisible
249 * by DI400Y:
250 *
251 * D M Y n n-1
252 * -- --- ---- ---------- ----------------
253 * 31 Dec -400 -DI400Y -DI400Y -1
254 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
255 * ...
256 * 30 Dec 000 -1 -2
257 * 31 Dec 000 0 -1
258 * 1 Jan 001 1 0 400-year boundary
259 * 2 Jan 001 2 1
260 * 3 Jan 001 3 2
261 * ...
262 * 31 Dec 400 DI400Y DI400Y -1
263 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
264 */
265 assert(ordinal >= 1);
266 --ordinal;
267 n400 = ordinal / DI400Y;
268 n = ordinal % DI400Y;
269 *year = n400 * 400 + 1;
270
271 /* Now n is the (non-negative) offset, in days, from January 1 of
272 * year, to the desired date. Now compute how many 100-year cycles
273 * precede n.
274 * Note that it's possible for n100 to equal 4! In that case 4 full
275 * 100-year cycles precede the desired day, which implies the
276 * desired day is December 31 at the end of a 400-year cycle.
277 */
278 n100 = n / DI100Y;
279 n = n % DI100Y;
280
281 /* Now compute how many 4-year cycles precede it. */
282 n4 = n / DI4Y;
283 n = n % DI4Y;
284
285 /* And now how many single years. Again n1 can be 4, and again
286 * meaning that the desired day is December 31 at the end of the
287 * 4-year cycle.
288 */
289 n1 = n / 365;
290 n = n % 365;
291
292 *year += n100 * 100 + n4 * 4 + n1;
293 if (n1 == 4 || n100 == 4) {
294 assert(n == 0);
295 *year -= 1;
296 *month = 12;
297 *day = 31;
298 return;
299 }
300
301 /* Now the year is correct, and n is the offset from January 1. We
302 * find the month via an estimate that's either exact or one too
303 * large.
304 */
305 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
306 assert(leapyear == is_leap(*year));
307 *month = (n + 50) >> 5;
308 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
309 if (preceding > n) {
310 /* estimate is too large */
311 *month -= 1;
312 preceding -= days_in_month(*year, *month);
313 }
314 n -= preceding;
315 assert(0 <= n);
316 assert(n < days_in_month(*year, *month));
317
318 *day = n + 1;
319}
320
321/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
322static int
323ymd_to_ord(int year, int month, int day)
324{
325 return days_before_year(year) + days_before_month(year, month) + day;
326}
327
328/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
329static int
330weekday(int year, int month, int day)
331{
332 return (ymd_to_ord(year, month, day) + 6) % 7;
333}
334
335/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
336 * first calendar week containing a Thursday.
337 */
338static int
339iso_week1_monday(int year)
340{
341 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
342 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
343 int first_weekday = (first_day + 6) % 7;
344 /* ordinal of closest Monday at or before 1/1 */
345 int week1_monday = first_day - first_weekday;
346
347 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
348 week1_monday += 7;
349 return week1_monday;
350}
351
352/* ---------------------------------------------------------------------------
353 * Range checkers.
354 */
355
356/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
357 * If not, raise OverflowError and return -1.
358 */
359static int
360check_delta_day_range(int days)
361{
362 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
363 return 0;
364 PyErr_Format(PyExc_OverflowError,
365 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000366 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000367 return -1;
368}
369
370/* Check that date arguments are in range. Return 0 if they are. If they
371 * aren't, raise ValueError and return -1.
372 */
373static int
374check_date_args(int year, int month, int day)
375{
376
377 if (year < MINYEAR || year > MAXYEAR) {
378 PyErr_SetString(PyExc_ValueError,
379 "year is out of range");
380 return -1;
381 }
382 if (month < 1 || month > 12) {
383 PyErr_SetString(PyExc_ValueError,
384 "month must be in 1..12");
385 return -1;
386 }
387 if (day < 1 || day > days_in_month(year, month)) {
388 PyErr_SetString(PyExc_ValueError,
389 "day is out of range for month");
390 return -1;
391 }
392 return 0;
393}
394
395/* Check that time arguments are in range. Return 0 if they are. If they
396 * aren't, raise ValueError and return -1.
397 */
398static int
399check_time_args(int h, int m, int s, int us)
400{
401 if (h < 0 || h > 23) {
402 PyErr_SetString(PyExc_ValueError,
403 "hour must be in 0..23");
404 return -1;
405 }
406 if (m < 0 || m > 59) {
407 PyErr_SetString(PyExc_ValueError,
408 "minute must be in 0..59");
409 return -1;
410 }
411 if (s < 0 || s > 59) {
412 PyErr_SetString(PyExc_ValueError,
413 "second must be in 0..59");
414 return -1;
415 }
416 if (us < 0 || us > 999999) {
417 PyErr_SetString(PyExc_ValueError,
418 "microsecond must be in 0..999999");
419 return -1;
420 }
421 return 0;
422}
423
424/* ---------------------------------------------------------------------------
425 * Normalization utilities.
426 */
427
428/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
429 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
430 * at least factor, enough of *lo is converted into "hi" units so that
431 * 0 <= *lo < factor. The input values must be such that int overflow
432 * is impossible.
433 */
434static void
435normalize_pair(int *hi, int *lo, int factor)
436{
437 assert(factor > 0);
438 assert(lo != hi);
439 if (*lo < 0 || *lo >= factor) {
440 const int num_hi = divmod(*lo, factor, lo);
441 const int new_hi = *hi + num_hi;
442 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
443 *hi = new_hi;
444 }
445 assert(0 <= *lo && *lo < factor);
446}
447
448/* Fiddle days (d), seconds (s), and microseconds (us) so that
449 * 0 <= *s < 24*3600
450 * 0 <= *us < 1000000
451 * The input values must be such that the internals don't overflow.
452 * The way this routine is used, we don't get close.
453 */
454static void
455normalize_d_s_us(int *d, int *s, int *us)
456{
457 if (*us < 0 || *us >= 1000000) {
458 normalize_pair(s, us, 1000000);
459 /* |s| can't be bigger than about
460 * |original s| + |original us|/1000000 now.
461 */
462
463 }
464 if (*s < 0 || *s >= 24*3600) {
465 normalize_pair(d, s, 24*3600);
466 /* |d| can't be bigger than about
467 * |original d| +
468 * (|original s| + |original us|/1000000) / (24*3600) now.
469 */
470 }
471 assert(0 <= *s && *s < 24*3600);
472 assert(0 <= *us && *us < 1000000);
473}
474
475/* Fiddle years (y), months (m), and days (d) so that
476 * 1 <= *m <= 12
477 * 1 <= *d <= days_in_month(*y, *m)
478 * The input values must be such that the internals don't overflow.
479 * The way this routine is used, we don't get close.
480 */
481static void
482normalize_y_m_d(int *y, int *m, int *d)
483{
484 int dim; /* # of days in month */
485
486 /* This gets muddy: the proper range for day can't be determined
487 * without knowing the correct month and year, but if day is, e.g.,
488 * plus or minus a million, the current month and year values make
489 * no sense (and may also be out of bounds themselves).
490 * Saying 12 months == 1 year should be non-controversial.
491 */
492 if (*m < 1 || *m > 12) {
493 --*m;
494 normalize_pair(y, m, 12);
495 ++*m;
496 /* |y| can't be bigger than about
497 * |original y| + |original m|/12 now.
498 */
499 }
500 assert(1 <= *m && *m <= 12);
501
502 /* Now only day can be out of bounds (year may also be out of bounds
503 * for a datetime object, but we don't care about that here).
504 * If day is out of bounds, what to do is arguable, but at least the
505 * method here is principled and explainable.
506 */
507 dim = days_in_month(*y, *m);
508 if (*d < 1 || *d > dim) {
509 /* Move day-1 days from the first of the month. First try to
510 * get off cheap if we're only one day out of range
511 * (adjustments for timezone alone can't be worse than that).
512 */
513 if (*d == 0) {
514 --*m;
515 if (*m > 0)
516 *d = days_in_month(*y, *m);
517 else {
518 --*y;
519 *m = 12;
520 *d = 31;
521 }
522 }
523 else if (*d == dim + 1) {
524 /* move forward a day */
525 ++*m;
526 *d = 1;
527 if (*m > 12) {
528 *m = 1;
529 ++*y;
530 }
531 }
532 else {
533 int ordinal = ymd_to_ord(*y, *m, 1) +
534 *d - 1;
535 ord_to_ymd(ordinal, y, m, d);
536 }
537 }
538 assert(*m > 0);
539 assert(*d > 0);
540}
541
542/* Fiddle out-of-bounds months and days so that the result makes some kind
543 * of sense. The parameters are both inputs and outputs. Returns < 0 on
544 * failure, where failure means the adjusted year is out of bounds.
545 */
546static int
547normalize_date(int *year, int *month, int *day)
548{
549 int result;
550
551 normalize_y_m_d(year, month, day);
552 if (MINYEAR <= *year && *year <= MAXYEAR)
553 result = 0;
554 else {
555 PyErr_SetString(PyExc_OverflowError,
556 "date value out of range");
557 result = -1;
558 }
559 return result;
560}
561
562/* Force all the datetime fields into range. The parameters are both
563 * inputs and outputs. Returns < 0 on error.
564 */
565static int
566normalize_datetime(int *year, int *month, int *day,
567 int *hour, int *minute, int *second,
568 int *microsecond)
569{
570 normalize_pair(second, microsecond, 1000000);
571 normalize_pair(minute, second, 60);
572 normalize_pair(hour, minute, 60);
573 normalize_pair(day, hour, 24);
574 return normalize_date(year, month, day);
575}
576
577/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000578 * Basic object allocation: tp_alloc implementations. These allocate
579 * Python objects of the right size and type, and do the Python object-
580 * initialization bit. If there's not enough memory, they return NULL after
581 * setting MemoryError. All data members remain uninitialized trash.
582 *
583 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000584 * member is needed. This is ugly, imprecise, and possibly insecure.
585 * tp_basicsize for the time and datetime types is set to the size of the
586 * struct that has room for the tzinfo member, so subclasses in Python will
587 * allocate enough space for a tzinfo member whether or not one is actually
588 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
589 * part is that PyType_GenericAlloc() (which subclasses in Python end up
590 * using) just happens today to effectively ignore the nitems argument
591 * when tp_itemsize is 0, which it is for these type objects. If that
592 * changes, perhaps the callers of tp_alloc slots in this file should
593 * be changed to force a 0 nitems argument unless the type being allocated
594 * is a base type implemented in this file (so that tp_alloc is time_alloc
595 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000596 */
597
598static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000599time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000600{
601 PyObject *self;
602
603 self = (PyObject *)
604 PyObject_MALLOC(aware ?
605 sizeof(PyDateTime_Time) :
606 sizeof(_PyDateTime_BaseTime));
607 if (self == NULL)
608 return (PyObject *)PyErr_NoMemory();
609 PyObject_INIT(self, type);
610 return self;
611}
612
613static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000614datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000615{
616 PyObject *self;
617
618 self = (PyObject *)
619 PyObject_MALLOC(aware ?
620 sizeof(PyDateTime_DateTime) :
621 sizeof(_PyDateTime_BaseDateTime));
622 if (self == NULL)
623 return (PyObject *)PyErr_NoMemory();
624 PyObject_INIT(self, type);
625 return self;
626}
627
628/* ---------------------------------------------------------------------------
629 * Helpers for setting object fields. These work on pointers to the
630 * appropriate base class.
631 */
632
633/* For date and datetime. */
634static void
635set_date_fields(PyDateTime_Date *self, int y, int m, int d)
636{
637 self->hashcode = -1;
638 SET_YEAR(self, y);
639 SET_MONTH(self, m);
640 SET_DAY(self, d);
641}
642
643/* ---------------------------------------------------------------------------
644 * Create various objects, mostly without range checking.
645 */
646
647/* Create a date instance with no range checking. */
648static PyObject *
649new_date_ex(int year, int month, int day, PyTypeObject *type)
650{
651 PyDateTime_Date *self;
652
653 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
654 if (self != NULL)
655 set_date_fields(self, year, month, day);
656 return (PyObject *) self;
657}
658
659#define new_date(year, month, day) \
660 new_date_ex(year, month, day, &PyDateTime_DateType)
661
662/* Create a datetime instance with no range checking. */
663static PyObject *
664new_datetime_ex(int year, int month, int day, int hour, int minute,
665 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
666{
667 PyDateTime_DateTime *self;
668 char aware = tzinfo != Py_None;
669
670 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
671 if (self != NULL) {
672 self->hastzinfo = aware;
673 set_date_fields((PyDateTime_Date *)self, year, month, day);
674 DATE_SET_HOUR(self, hour);
675 DATE_SET_MINUTE(self, minute);
676 DATE_SET_SECOND(self, second);
677 DATE_SET_MICROSECOND(self, usecond);
678 if (aware) {
679 Py_INCREF(tzinfo);
680 self->tzinfo = tzinfo;
681 }
682 }
683 return (PyObject *)self;
684}
685
686#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
687 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
688 &PyDateTime_DateTimeType)
689
690/* Create a time instance with no range checking. */
691static PyObject *
692new_time_ex(int hour, int minute, int second, int usecond,
693 PyObject *tzinfo, PyTypeObject *type)
694{
695 PyDateTime_Time *self;
696 char aware = tzinfo != Py_None;
697
698 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
699 if (self != NULL) {
700 self->hastzinfo = aware;
701 self->hashcode = -1;
702 TIME_SET_HOUR(self, hour);
703 TIME_SET_MINUTE(self, minute);
704 TIME_SET_SECOND(self, second);
705 TIME_SET_MICROSECOND(self, usecond);
706 if (aware) {
707 Py_INCREF(tzinfo);
708 self->tzinfo = tzinfo;
709 }
710 }
711 return (PyObject *)self;
712}
713
714#define new_time(hh, mm, ss, us, tzinfo) \
715 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
716
717/* Create a timedelta instance. Normalize the members iff normalize is
718 * true. Passing false is a speed optimization, if you know for sure
719 * that seconds and microseconds are already in their proper ranges. In any
720 * case, raises OverflowError and returns NULL if the normalized days is out
721 * of range).
722 */
723static PyObject *
724new_delta_ex(int days, int seconds, int microseconds, int normalize,
725 PyTypeObject *type)
726{
727 PyDateTime_Delta *self;
728
729 if (normalize)
730 normalize_d_s_us(&days, &seconds, &microseconds);
731 assert(0 <= seconds && seconds < 24*3600);
732 assert(0 <= microseconds && microseconds < 1000000);
733
734 if (check_delta_day_range(days) < 0)
735 return NULL;
736
737 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
738 if (self != NULL) {
739 self->hashcode = -1;
740 SET_TD_DAYS(self, days);
741 SET_TD_SECONDS(self, seconds);
742 SET_TD_MICROSECONDS(self, microseconds);
743 }
744 return (PyObject *) self;
745}
746
747#define new_delta(d, s, us, normalize) \
748 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
749
750/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000751 * tzinfo helpers.
752 */
753
Tim Peters855fe882002-12-22 03:43:39 +0000754/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
755 * raise TypeError and return -1.
756 */
757static int
758check_tzinfo_subclass(PyObject *p)
759{
760 if (p == Py_None || PyTZInfo_Check(p))
761 return 0;
762 PyErr_Format(PyExc_TypeError,
763 "tzinfo argument must be None or of a tzinfo subclass, "
764 "not type '%s'",
765 p->ob_type->tp_name);
766 return -1;
767}
768
Tim Petersbad8ff02002-12-30 20:52:32 +0000769/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000770 * If tzinfo is None, returns None.
771 */
772static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000773call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000774{
775 PyObject *result;
776
Tim Petersbad8ff02002-12-30 20:52:32 +0000777 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000778 assert(check_tzinfo_subclass(tzinfo) >= 0);
779 if (tzinfo == Py_None) {
780 result = Py_None;
781 Py_INCREF(result);
782 }
783 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000784 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000785 return result;
786}
787
Tim Peters2a799bf2002-12-16 20:18:38 +0000788/* If self has a tzinfo member, return a BORROWED reference to it. Else
789 * return NULL, which is NOT AN ERROR. There are no error returns here,
790 * and the caller must not decref the result.
791 */
792static PyObject *
793get_tzinfo_member(PyObject *self)
794{
795 PyObject *tzinfo = NULL;
796
Tim Petersa9bc1682003-01-11 03:39:11 +0000797 if (PyDateTime_Check(self) && HASTZINFO(self))
798 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000799 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000800 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000801
802 return tzinfo;
803}
804
Tim Petersbad8ff02002-12-30 20:52:32 +0000805/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000806 * result. tzinfo must be an instance of the tzinfo class. If the method
807 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000808 * return None or timedelta, TypeError is raised and this returns -1. If it
809 * returnsa timedelta and the value is out of range or isn't a whole number
810 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000811 * Else *none is set to 0 and the integer method result is returned.
812 */
813static int
814call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
815 int *none)
816{
817 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000818 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000819
820 assert(tzinfo != NULL);
821 assert(PyTZInfo_Check(tzinfo));
822 assert(tzinfoarg != NULL);
823
824 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000825 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000826 if (u == NULL)
827 return -1;
828
Tim Peters27362852002-12-23 16:17:39 +0000829 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000830 result = 0;
831 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 }
Tim Peters855fe882002-12-22 03:43:39 +0000833 else if (PyDelta_Check(u)) {
834 const int days = GET_TD_DAYS(u);
835 if (days < -1 || days > 0)
836 result = 24*60; /* trigger ValueError below */
837 else {
838 /* next line can't overflow because we know days
839 * is -1 or 0 now
840 */
841 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
842 result = divmod(ss, 60, &ss);
843 if (ss || GET_TD_MICROSECONDS(u)) {
844 PyErr_Format(PyExc_ValueError,
845 "tzinfo.%s() must return a "
846 "whole number of minutes",
847 name);
848 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000849 }
850 }
851 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000852 else {
853 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000854 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000855 "timedelta, not '%s'",
856 name, u->ob_type->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000857 }
858
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 Py_DECREF(u);
860 if (result < -1439 || result > 1439) {
861 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000862 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000863 "-1439 .. 1439",
864 name, result);
865 result = -1;
866 }
Tim Peters397301e2003-01-02 21:28:08 +0000867 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000868}
869
870/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
871 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
872 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000873 * doesn't return None or timedelta, TypeError is raised and this returns -1.
874 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
875 * # of minutes), ValueError is raised and this returns -1. Else *none is
876 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000877 */
878static int
879call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
880{
881 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
882}
883
Tim Petersbad8ff02002-12-30 20:52:32 +0000884/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
885 */
Tim Peters855fe882002-12-22 03:43:39 +0000886static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000887offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000888 PyObject *result;
889
Tim Petersbad8ff02002-12-30 20:52:32 +0000890 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000891 if (tzinfo == Py_None) {
892 result = Py_None;
893 Py_INCREF(result);
894 }
895 else {
896 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000897 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
898 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000899 if (offset < 0 && PyErr_Occurred())
900 return NULL;
901 if (none) {
902 result = Py_None;
903 Py_INCREF(result);
904 }
905 else
906 result = new_delta(0, offset * 60, 0, 1);
907 }
908 return result;
909}
910
Tim Peters2a799bf2002-12-16 20:18:38 +0000911/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
912 * result. tzinfo must be an instance of the tzinfo class. If dst()
913 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000914 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000915 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000916 * ValueError is raised and this returns -1. Else *none is set to 0 and
917 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000918 */
919static int
920call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
921{
922 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
923}
924
Tim Petersbad8ff02002-12-30 20:52:32 +0000925/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000926 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000927 * tzname() doesn't return None or a string, TypeError is raised and this
Tim Peters855fe882002-12-22 03:43:39 +0000928 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000929 */
930static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000931call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000932{
933 PyObject *result;
934
935 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000936 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000937 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000938
Tim Peters855fe882002-12-22 03:43:39 +0000939 if (tzinfo == Py_None) {
940 result = Py_None;
941 Py_INCREF(result);
942 }
943 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000944 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000945
946 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
947 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
Tim Peters2a799bf2002-12-16 20:18:38 +0000948 "return None or a string, not '%s'",
949 result->ob_type->tp_name);
950 Py_DECREF(result);
951 result = NULL;
952 }
953 return result;
954}
955
956typedef enum {
957 /* an exception has been set; the caller should pass it on */
958 OFFSET_ERROR,
959
Tim Petersa9bc1682003-01-11 03:39:11 +0000960 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000961 OFFSET_UNKNOWN,
962
963 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000964 * datetime with !hastzinfo
965 * datetime with None tzinfo,
966 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000967 * time with !hastzinfo
968 * time with None tzinfo,
969 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000970 */
971 OFFSET_NAIVE,
972
Tim Petersa9bc1682003-01-11 03:39:11 +0000973 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000974 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000975} naivety;
976
Tim Peters14b69412002-12-22 18:10:22 +0000977/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000978 * the "naivety" typedef for details. If the type is aware, *offset is set
979 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000980 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000981 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000982 */
983static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000984classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000985{
986 int none;
987 PyObject *tzinfo;
988
Tim Peterse39a80c2002-12-30 21:28:52 +0000989 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000990 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +0000991 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 if (tzinfo == Py_None)
993 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +0000994 if (tzinfo == NULL) {
995 /* note that a datetime passes the PyDate_Check test */
996 return (PyTime_Check(op) || PyDate_Check(op)) ?
997 OFFSET_NAIVE : OFFSET_UNKNOWN;
998 }
Tim Peterse39a80c2002-12-30 21:28:52 +0000999 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001000 if (*offset == -1 && PyErr_Occurred())
1001 return OFFSET_ERROR;
1002 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1003}
1004
Tim Peters00237032002-12-27 02:21:51 +00001005/* Classify two objects as to whether they're naive or offset-aware.
1006 * This isn't quite the same as calling classify_utcoffset() twice: for
1007 * binary operations (comparison and subtraction), we generally want to
1008 * ignore the tzinfo members if they're identical. This is by design,
1009 * so that results match "naive" expectations when mixing objects from a
1010 * single timezone. So in that case, this sets both offsets to 0 and
1011 * both naiveties to OFFSET_NAIVE.
1012 * The function returns 0 if everything's OK, and -1 on error.
1013 */
1014static int
1015classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001016 PyObject *tzinfoarg1,
1017 PyObject *o2, int *offset2, naivety *n2,
1018 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001019{
1020 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1021 *offset1 = *offset2 = 0;
1022 *n1 = *n2 = OFFSET_NAIVE;
1023 }
1024 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001025 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001026 if (*n1 == OFFSET_ERROR)
1027 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001028 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001029 if (*n2 == OFFSET_ERROR)
1030 return -1;
1031 }
1032 return 0;
1033}
1034
Tim Peters2a799bf2002-12-16 20:18:38 +00001035/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1036 * stuff
1037 * ", tzinfo=" + repr(tzinfo)
1038 * before the closing ")".
1039 */
1040static PyObject *
1041append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1042{
1043 PyObject *temp;
1044
1045 assert(PyString_Check(repr));
1046 assert(tzinfo);
1047 if (tzinfo == Py_None)
1048 return repr;
1049 /* Get rid of the trailing ')'. */
1050 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1051 temp = PyString_FromStringAndSize(PyString_AsString(repr),
1052 PyString_Size(repr) - 1);
1053 Py_DECREF(repr);
1054 if (temp == NULL)
1055 return NULL;
1056 repr = temp;
1057
1058 /* Append ", tzinfo=". */
1059 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
1060
1061 /* Append repr(tzinfo). */
1062 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
1063
1064 /* Add a closing paren. */
1065 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1066 return repr;
1067}
1068
1069/* ---------------------------------------------------------------------------
1070 * String format helpers.
1071 */
1072
1073static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001074format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001075{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001076 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001077 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1078 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001079 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001080 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1081 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1082 };
1083
1084 char buffer[128];
1085 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1086
1087 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1088 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1089 GET_DAY(date), hours, minutes, seconds,
1090 GET_YEAR(date));
1091 return PyString_FromString(buffer);
1092}
1093
1094/* Add an hours & minutes UTC offset string to buf. buf has no more than
1095 * buflen bytes remaining. The UTC offset is gotten by calling
1096 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1097 * *buf, and that's all. Else the returned value is checked for sanity (an
1098 * integer in range), and if that's OK it's converted to an hours & minutes
1099 * string of the form
1100 * sign HH sep MM
1101 * Returns 0 if everything is OK. If the return value from utcoffset() is
1102 * bogus, an appropriate exception is set and -1 is returned.
1103 */
1104static int
Tim Peters328fff72002-12-20 01:31:27 +00001105format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001106 PyObject *tzinfo, PyObject *tzinfoarg)
1107{
1108 int offset;
1109 int hours;
1110 int minutes;
1111 char sign;
1112 int none;
1113
1114 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1115 if (offset == -1 && PyErr_Occurred())
1116 return -1;
1117 if (none) {
1118 *buf = '\0';
1119 return 0;
1120 }
1121 sign = '+';
1122 if (offset < 0) {
1123 sign = '-';
1124 offset = - offset;
1125 }
1126 hours = divmod(offset, 60, &minutes);
1127 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1128 return 0;
1129}
1130
1131/* I sure don't want to reproduce the strftime code from the time module,
1132 * so this imports the module and calls it. All the hair is due to
1133 * giving special meanings to the %z and %Z format codes via a preprocessing
1134 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001135 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1136 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001137 */
1138static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001139wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1140 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001141{
1142 PyObject *result = NULL; /* guilty until proved innocent */
1143
1144 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1145 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1146
1147 char *pin; /* pointer to next char in input format */
1148 char ch; /* next char in input format */
1149
1150 PyObject *newfmt = NULL; /* py string, the output format */
1151 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001152 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001153 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001154 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001155
1156 char *ptoappend; /* pointer to string to append to output buffer */
1157 int ntoappend; /* # of bytes to append to output buffer */
1158
Tim Peters2a799bf2002-12-16 20:18:38 +00001159 assert(object && format && timetuple);
1160 assert(PyString_Check(format));
1161
Tim Petersd6844152002-12-22 20:58:42 +00001162 /* Give up if the year is before 1900.
1163 * Python strftime() plays games with the year, and different
1164 * games depending on whether envar PYTHON2K is set. This makes
1165 * years before 1900 a nightmare, even if the platform strftime
1166 * supports them (and not all do).
1167 * We could get a lot farther here by avoiding Python's strftime
1168 * wrapper and calling the C strftime() directly, but that isn't
1169 * an option in the Python implementation of this module.
1170 */
1171 {
1172 long year;
1173 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1174 if (pyyear == NULL) return NULL;
1175 assert(PyInt_Check(pyyear));
1176 year = PyInt_AsLong(pyyear);
1177 Py_DECREF(pyyear);
1178 if (year < 1900) {
1179 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1180 "1900; the datetime strftime() "
1181 "methods require year >= 1900",
1182 year);
1183 return NULL;
1184 }
1185 }
1186
Tim Peters2a799bf2002-12-16 20:18:38 +00001187 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001188 * a new format. Since computing the replacements for those codes
1189 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001190 */
Raymond Hettingerf69d9f62003-06-27 08:14:17 +00001191 totalnew = PyString_Size(format) + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001192 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1193 if (newfmt == NULL) goto Done;
1194 pnew = PyString_AsString(newfmt);
1195 usednew = 0;
1196
1197 pin = PyString_AsString(format);
1198 while ((ch = *pin++) != '\0') {
1199 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001200 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001201 ntoappend = 1;
1202 }
1203 else if ((ch = *pin++) == '\0') {
1204 /* There's a lone trailing %; doesn't make sense. */
1205 PyErr_SetString(PyExc_ValueError, "strftime format "
1206 "ends with raw %");
1207 goto Done;
1208 }
1209 /* A % has been seen and ch is the character after it. */
1210 else if (ch == 'z') {
1211 if (zreplacement == NULL) {
1212 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001213 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001214 PyObject *tzinfo = get_tzinfo_member(object);
1215 zreplacement = PyString_FromString("");
1216 if (zreplacement == NULL) goto Done;
1217 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001218 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001219 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001220 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001221 "",
1222 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001223 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001224 goto Done;
1225 Py_DECREF(zreplacement);
1226 zreplacement = PyString_FromString(buf);
1227 if (zreplacement == NULL) goto Done;
1228 }
1229 }
1230 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001231 ptoappend = PyString_AS_STRING(zreplacement);
1232 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001233 }
1234 else if (ch == 'Z') {
1235 /* format tzname */
1236 if (Zreplacement == NULL) {
1237 PyObject *tzinfo = get_tzinfo_member(object);
1238 Zreplacement = PyString_FromString("");
1239 if (Zreplacement == NULL) goto Done;
1240 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001241 PyObject *temp;
1242 assert(tzinfoarg != NULL);
1243 temp = call_tzname(tzinfo, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001244 if (temp == NULL) goto Done;
1245 if (temp != Py_None) {
1246 assert(PyString_Check(temp));
1247 /* Since the tzname is getting
1248 * stuffed into the format, we
1249 * have to double any % signs
1250 * so that strftime doesn't
1251 * treat them as format codes.
1252 */
1253 Py_DECREF(Zreplacement);
1254 Zreplacement = PyObject_CallMethod(
1255 temp, "replace",
1256 "ss", "%", "%%");
1257 Py_DECREF(temp);
1258 if (Zreplacement == NULL)
1259 goto Done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001260 if (!PyString_Check(Zreplacement)) {
1261 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1262 goto Done;
1263 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001264 }
1265 else
1266 Py_DECREF(temp);
1267 }
1268 }
1269 assert(Zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001270 ptoappend = PyString_AS_STRING(Zreplacement);
1271 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001272 }
1273 else {
Tim Peters328fff72002-12-20 01:31:27 +00001274 /* percent followed by neither z nor Z */
1275 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001276 ntoappend = 2;
1277 }
1278
1279 /* Append the ntoappend chars starting at ptoappend to
1280 * the new format.
1281 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001282 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001283 assert(ntoappend >= 0);
1284 if (ntoappend == 0)
1285 continue;
1286 while (usednew + ntoappend > totalnew) {
1287 int bigger = totalnew << 1;
1288 if ((bigger >> 1) != totalnew) { /* overflow */
1289 PyErr_NoMemory();
1290 goto Done;
1291 }
1292 if (_PyString_Resize(&newfmt, bigger) < 0)
1293 goto Done;
1294 totalnew = bigger;
1295 pnew = PyString_AsString(newfmt) + usednew;
1296 }
1297 memcpy(pnew, ptoappend, ntoappend);
1298 pnew += ntoappend;
1299 usednew += ntoappend;
1300 assert(usednew <= totalnew);
1301 } /* end while() */
1302
1303 if (_PyString_Resize(&newfmt, usednew) < 0)
1304 goto Done;
1305 {
1306 PyObject *time = PyImport_ImportModule("time");
1307 if (time == NULL)
1308 goto Done;
1309 result = PyObject_CallMethod(time, "strftime", "OO",
1310 newfmt, timetuple);
1311 Py_DECREF(time);
1312 }
1313 Done:
1314 Py_XDECREF(zreplacement);
1315 Py_XDECREF(Zreplacement);
1316 Py_XDECREF(newfmt);
1317 return result;
1318}
1319
1320static char *
1321isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1322{
1323 int x;
1324 x = PyOS_snprintf(buffer, bufflen,
1325 "%04d-%02d-%02d",
1326 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1327 return buffer + x;
1328}
1329
1330static void
1331isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1332{
1333 int us = DATE_GET_MICROSECOND(dt);
1334
1335 PyOS_snprintf(buffer, bufflen,
1336 "%02d:%02d:%02d", /* 8 characters */
1337 DATE_GET_HOUR(dt),
1338 DATE_GET_MINUTE(dt),
1339 DATE_GET_SECOND(dt));
1340 if (us)
1341 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1342}
1343
1344/* ---------------------------------------------------------------------------
1345 * Wrap functions from the time module. These aren't directly available
1346 * from C. Perhaps they should be.
1347 */
1348
1349/* Call time.time() and return its result (a Python float). */
1350static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001351time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001352{
1353 PyObject *result = NULL;
1354 PyObject *time = PyImport_ImportModule("time");
1355
1356 if (time != NULL) {
1357 result = PyObject_CallMethod(time, "time", "()");
1358 Py_DECREF(time);
1359 }
1360 return result;
1361}
1362
1363/* Build a time.struct_time. The weekday and day number are automatically
1364 * computed from the y,m,d args.
1365 */
1366static PyObject *
1367build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1368{
1369 PyObject *time;
1370 PyObject *result = NULL;
1371
1372 time = PyImport_ImportModule("time");
1373 if (time != NULL) {
1374 result = PyObject_CallMethod(time, "struct_time",
1375 "((iiiiiiiii))",
1376 y, m, d,
1377 hh, mm, ss,
1378 weekday(y, m, d),
1379 days_before_month(y, m) + d,
1380 dstflag);
1381 Py_DECREF(time);
1382 }
1383 return result;
1384}
1385
1386/* ---------------------------------------------------------------------------
1387 * Miscellaneous helpers.
1388 */
1389
Guido van Rossum19960592006-08-24 17:29:38 +00001390/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001391 * The comparisons here all most naturally compute a cmp()-like result.
1392 * This little helper turns that into a bool result for rich comparisons.
1393 */
1394static PyObject *
1395diff_to_bool(int diff, int op)
1396{
1397 PyObject *result;
1398 int istrue;
1399
1400 switch (op) {
1401 case Py_EQ: istrue = diff == 0; break;
1402 case Py_NE: istrue = diff != 0; break;
1403 case Py_LE: istrue = diff <= 0; break;
1404 case Py_GE: istrue = diff >= 0; break;
1405 case Py_LT: istrue = diff < 0; break;
1406 case Py_GT: istrue = diff > 0; break;
1407 default:
1408 assert(! "op unknown");
1409 istrue = 0; /* To shut up compiler */
1410 }
1411 result = istrue ? Py_True : Py_False;
1412 Py_INCREF(result);
1413 return result;
1414}
1415
Tim Peters07534a62003-02-07 22:50:28 +00001416/* Raises a "can't compare" TypeError and returns NULL. */
1417static PyObject *
1418cmperror(PyObject *a, PyObject *b)
1419{
1420 PyErr_Format(PyExc_TypeError,
1421 "can't compare %s to %s",
1422 a->ob_type->tp_name, b->ob_type->tp_name);
1423 return NULL;
1424}
1425
Tim Peters2a799bf2002-12-16 20:18:38 +00001426/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001427 * Cached Python objects; these are set by the module init function.
1428 */
1429
1430/* Conversion factors. */
1431static PyObject *us_per_us = NULL; /* 1 */
1432static PyObject *us_per_ms = NULL; /* 1000 */
1433static PyObject *us_per_second = NULL; /* 1000000 */
1434static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1435static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1436static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1437static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1438static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1439
Tim Peters2a799bf2002-12-16 20:18:38 +00001440/* ---------------------------------------------------------------------------
1441 * Class implementations.
1442 */
1443
1444/*
1445 * PyDateTime_Delta implementation.
1446 */
1447
1448/* Convert a timedelta to a number of us,
1449 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1450 * as a Python int or long.
1451 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1452 * due to ubiquitous overflow possibilities.
1453 */
1454static PyObject *
1455delta_to_microseconds(PyDateTime_Delta *self)
1456{
1457 PyObject *x1 = NULL;
1458 PyObject *x2 = NULL;
1459 PyObject *x3 = NULL;
1460 PyObject *result = NULL;
1461
1462 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1463 if (x1 == NULL)
1464 goto Done;
1465 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1466 if (x2 == NULL)
1467 goto Done;
1468 Py_DECREF(x1);
1469 x1 = NULL;
1470
1471 /* x2 has days in seconds */
1472 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1473 if (x1 == NULL)
1474 goto Done;
1475 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1476 if (x3 == NULL)
1477 goto Done;
1478 Py_DECREF(x1);
1479 Py_DECREF(x2);
1480 x1 = x2 = NULL;
1481
1482 /* x3 has days+seconds in seconds */
1483 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1484 if (x1 == NULL)
1485 goto Done;
1486 Py_DECREF(x3);
1487 x3 = NULL;
1488
1489 /* x1 has days+seconds in us */
1490 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1491 if (x2 == NULL)
1492 goto Done;
1493 result = PyNumber_Add(x1, x2);
1494
1495Done:
1496 Py_XDECREF(x1);
1497 Py_XDECREF(x2);
1498 Py_XDECREF(x3);
1499 return result;
1500}
1501
1502/* Convert a number of us (as a Python int or long) to a timedelta.
1503 */
1504static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001505microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001506{
1507 int us;
1508 int s;
1509 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001510 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001511
1512 PyObject *tuple = NULL;
1513 PyObject *num = NULL;
1514 PyObject *result = NULL;
1515
1516 tuple = PyNumber_Divmod(pyus, us_per_second);
1517 if (tuple == NULL)
1518 goto Done;
1519
1520 num = PyTuple_GetItem(tuple, 1); /* us */
1521 if (num == NULL)
1522 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001523 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001524 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001525 if (temp == -1 && PyErr_Occurred())
1526 goto Done;
1527 assert(0 <= temp && temp < 1000000);
1528 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001529 if (us < 0) {
1530 /* The divisor was positive, so this must be an error. */
1531 assert(PyErr_Occurred());
1532 goto Done;
1533 }
1534
1535 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1536 if (num == NULL)
1537 goto Done;
1538 Py_INCREF(num);
1539 Py_DECREF(tuple);
1540
1541 tuple = PyNumber_Divmod(num, seconds_per_day);
1542 if (tuple == NULL)
1543 goto Done;
1544 Py_DECREF(num);
1545
1546 num = PyTuple_GetItem(tuple, 1); /* seconds */
1547 if (num == NULL)
1548 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001549 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001550 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001551 if (temp == -1 && PyErr_Occurred())
1552 goto Done;
1553 assert(0 <= temp && temp < 24*3600);
1554 s = (int)temp;
1555
Tim Peters2a799bf2002-12-16 20:18:38 +00001556 if (s < 0) {
1557 /* The divisor was positive, so this must be an error. */
1558 assert(PyErr_Occurred());
1559 goto Done;
1560 }
1561
1562 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1563 if (num == NULL)
1564 goto Done;
1565 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001566 temp = PyLong_AsLong(num);
1567 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001568 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001569 d = (int)temp;
1570 if ((long)d != temp) {
1571 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1572 "large to fit in a C int");
1573 goto Done;
1574 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001575 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001576
1577Done:
1578 Py_XDECREF(tuple);
1579 Py_XDECREF(num);
1580 return result;
1581}
1582
Tim Petersb0c854d2003-05-17 15:57:00 +00001583#define microseconds_to_delta(pymicros) \
1584 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1585
Tim Peters2a799bf2002-12-16 20:18:38 +00001586static PyObject *
1587multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1588{
1589 PyObject *pyus_in;
1590 PyObject *pyus_out;
1591 PyObject *result;
1592
1593 pyus_in = delta_to_microseconds(delta);
1594 if (pyus_in == NULL)
1595 return NULL;
1596
1597 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1598 Py_DECREF(pyus_in);
1599 if (pyus_out == NULL)
1600 return NULL;
1601
1602 result = microseconds_to_delta(pyus_out);
1603 Py_DECREF(pyus_out);
1604 return result;
1605}
1606
1607static PyObject *
1608divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1609{
1610 PyObject *pyus_in;
1611 PyObject *pyus_out;
1612 PyObject *result;
1613
1614 pyus_in = delta_to_microseconds(delta);
1615 if (pyus_in == NULL)
1616 return NULL;
1617
1618 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1619 Py_DECREF(pyus_in);
1620 if (pyus_out == NULL)
1621 return NULL;
1622
1623 result = microseconds_to_delta(pyus_out);
1624 Py_DECREF(pyus_out);
1625 return result;
1626}
1627
1628static PyObject *
1629delta_add(PyObject *left, PyObject *right)
1630{
1631 PyObject *result = Py_NotImplemented;
1632
1633 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1634 /* delta + delta */
1635 /* The C-level additions can't overflow because of the
1636 * invariant bounds.
1637 */
1638 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1639 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1640 int microseconds = GET_TD_MICROSECONDS(left) +
1641 GET_TD_MICROSECONDS(right);
1642 result = new_delta(days, seconds, microseconds, 1);
1643 }
1644
1645 if (result == Py_NotImplemented)
1646 Py_INCREF(result);
1647 return result;
1648}
1649
1650static PyObject *
1651delta_negative(PyDateTime_Delta *self)
1652{
1653 return new_delta(-GET_TD_DAYS(self),
1654 -GET_TD_SECONDS(self),
1655 -GET_TD_MICROSECONDS(self),
1656 1);
1657}
1658
1659static PyObject *
1660delta_positive(PyDateTime_Delta *self)
1661{
1662 /* Could optimize this (by returning self) if this isn't a
1663 * subclass -- but who uses unary + ? Approximately nobody.
1664 */
1665 return new_delta(GET_TD_DAYS(self),
1666 GET_TD_SECONDS(self),
1667 GET_TD_MICROSECONDS(self),
1668 0);
1669}
1670
1671static PyObject *
1672delta_abs(PyDateTime_Delta *self)
1673{
1674 PyObject *result;
1675
1676 assert(GET_TD_MICROSECONDS(self) >= 0);
1677 assert(GET_TD_SECONDS(self) >= 0);
1678
1679 if (GET_TD_DAYS(self) < 0)
1680 result = delta_negative(self);
1681 else
1682 result = delta_positive(self);
1683
1684 return result;
1685}
1686
1687static PyObject *
1688delta_subtract(PyObject *left, PyObject *right)
1689{
1690 PyObject *result = Py_NotImplemented;
1691
1692 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1693 /* delta - delta */
1694 PyObject *minus_right = PyNumber_Negative(right);
1695 if (minus_right) {
1696 result = delta_add(left, minus_right);
1697 Py_DECREF(minus_right);
1698 }
1699 else
1700 result = NULL;
1701 }
1702
1703 if (result == Py_NotImplemented)
1704 Py_INCREF(result);
1705 return result;
1706}
1707
Tim Peters2a799bf2002-12-16 20:18:38 +00001708static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001709delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001710{
Tim Petersaa7d8492003-02-08 03:28:59 +00001711 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001712 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001713 if (diff == 0) {
1714 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1715 if (diff == 0)
1716 diff = GET_TD_MICROSECONDS(self) -
1717 GET_TD_MICROSECONDS(other);
1718 }
Guido van Rossum19960592006-08-24 17:29:38 +00001719 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001720 }
Guido van Rossum19960592006-08-24 17:29:38 +00001721 else {
1722 Py_INCREF(Py_NotImplemented);
1723 return Py_NotImplemented;
1724 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001725}
1726
1727static PyObject *delta_getstate(PyDateTime_Delta *self);
1728
1729static long
1730delta_hash(PyDateTime_Delta *self)
1731{
1732 if (self->hashcode == -1) {
1733 PyObject *temp = delta_getstate(self);
1734 if (temp != NULL) {
1735 self->hashcode = PyObject_Hash(temp);
1736 Py_DECREF(temp);
1737 }
1738 }
1739 return self->hashcode;
1740}
1741
1742static PyObject *
1743delta_multiply(PyObject *left, PyObject *right)
1744{
1745 PyObject *result = Py_NotImplemented;
1746
1747 if (PyDelta_Check(left)) {
1748 /* delta * ??? */
1749 if (PyInt_Check(right) || PyLong_Check(right))
1750 result = multiply_int_timedelta(right,
1751 (PyDateTime_Delta *) left);
1752 }
1753 else if (PyInt_Check(left) || PyLong_Check(left))
1754 result = multiply_int_timedelta(left,
1755 (PyDateTime_Delta *) right);
1756
1757 if (result == Py_NotImplemented)
1758 Py_INCREF(result);
1759 return result;
1760}
1761
1762static PyObject *
1763delta_divide(PyObject *left, PyObject *right)
1764{
1765 PyObject *result = Py_NotImplemented;
1766
1767 if (PyDelta_Check(left)) {
1768 /* delta * ??? */
1769 if (PyInt_Check(right) || PyLong_Check(right))
1770 result = divide_timedelta_int(
1771 (PyDateTime_Delta *)left,
1772 right);
1773 }
1774
1775 if (result == Py_NotImplemented)
1776 Py_INCREF(result);
1777 return result;
1778}
1779
1780/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1781 * timedelta constructor. sofar is the # of microseconds accounted for
1782 * so far, and there are factor microseconds per current unit, the number
1783 * of which is given by num. num * factor is added to sofar in a
1784 * numerically careful way, and that's the result. Any fractional
1785 * microseconds left over (this can happen if num is a float type) are
1786 * added into *leftover.
1787 * Note that there are many ways this can give an error (NULL) return.
1788 */
1789static PyObject *
1790accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1791 double *leftover)
1792{
1793 PyObject *prod;
1794 PyObject *sum;
1795
1796 assert(num != NULL);
1797
1798 if (PyInt_Check(num) || PyLong_Check(num)) {
1799 prod = PyNumber_Multiply(num, factor);
1800 if (prod == NULL)
1801 return NULL;
1802 sum = PyNumber_Add(sofar, prod);
1803 Py_DECREF(prod);
1804 return sum;
1805 }
1806
1807 if (PyFloat_Check(num)) {
1808 double dnum;
1809 double fracpart;
1810 double intpart;
1811 PyObject *x;
1812 PyObject *y;
1813
1814 /* The Plan: decompose num into an integer part and a
1815 * fractional part, num = intpart + fracpart.
1816 * Then num * factor ==
1817 * intpart * factor + fracpart * factor
1818 * and the LHS can be computed exactly in long arithmetic.
1819 * The RHS is again broken into an int part and frac part.
1820 * and the frac part is added into *leftover.
1821 */
1822 dnum = PyFloat_AsDouble(num);
1823 if (dnum == -1.0 && PyErr_Occurred())
1824 return NULL;
1825 fracpart = modf(dnum, &intpart);
1826 x = PyLong_FromDouble(intpart);
1827 if (x == NULL)
1828 return NULL;
1829
1830 prod = PyNumber_Multiply(x, factor);
1831 Py_DECREF(x);
1832 if (prod == NULL)
1833 return NULL;
1834
1835 sum = PyNumber_Add(sofar, prod);
1836 Py_DECREF(prod);
1837 if (sum == NULL)
1838 return NULL;
1839
1840 if (fracpart == 0.0)
1841 return sum;
1842 /* So far we've lost no information. Dealing with the
1843 * fractional part requires float arithmetic, and may
1844 * lose a little info.
1845 */
1846 assert(PyInt_Check(factor) || PyLong_Check(factor));
1847 if (PyInt_Check(factor))
1848 dnum = (double)PyInt_AsLong(factor);
1849 else
1850 dnum = PyLong_AsDouble(factor);
1851
1852 dnum *= fracpart;
1853 fracpart = modf(dnum, &intpart);
1854 x = PyLong_FromDouble(intpart);
1855 if (x == NULL) {
1856 Py_DECREF(sum);
1857 return NULL;
1858 }
1859
1860 y = PyNumber_Add(sum, x);
1861 Py_DECREF(sum);
1862 Py_DECREF(x);
1863 *leftover += fracpart;
1864 return y;
1865 }
1866
1867 PyErr_Format(PyExc_TypeError,
1868 "unsupported type for timedelta %s component: %s",
1869 tag, num->ob_type->tp_name);
1870 return NULL;
1871}
1872
1873static PyObject *
1874delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1875{
1876 PyObject *self = NULL;
1877
1878 /* Argument objects. */
1879 PyObject *day = NULL;
1880 PyObject *second = NULL;
1881 PyObject *us = NULL;
1882 PyObject *ms = NULL;
1883 PyObject *minute = NULL;
1884 PyObject *hour = NULL;
1885 PyObject *week = NULL;
1886
1887 PyObject *x = NULL; /* running sum of microseconds */
1888 PyObject *y = NULL; /* temp sum of microseconds */
1889 double leftover_us = 0.0;
1890
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001891 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001892 "days", "seconds", "microseconds", "milliseconds",
1893 "minutes", "hours", "weeks", NULL
1894 };
1895
1896 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1897 keywords,
1898 &day, &second, &us,
1899 &ms, &minute, &hour, &week) == 0)
1900 goto Done;
1901
1902 x = PyInt_FromLong(0);
1903 if (x == NULL)
1904 goto Done;
1905
1906#define CLEANUP \
1907 Py_DECREF(x); \
1908 x = y; \
1909 if (x == NULL) \
1910 goto Done
1911
1912 if (us) {
1913 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1914 CLEANUP;
1915 }
1916 if (ms) {
1917 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1918 CLEANUP;
1919 }
1920 if (second) {
1921 y = accum("seconds", x, second, us_per_second, &leftover_us);
1922 CLEANUP;
1923 }
1924 if (minute) {
1925 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1926 CLEANUP;
1927 }
1928 if (hour) {
1929 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1930 CLEANUP;
1931 }
1932 if (day) {
1933 y = accum("days", x, day, us_per_day, &leftover_us);
1934 CLEANUP;
1935 }
1936 if (week) {
1937 y = accum("weeks", x, week, us_per_week, &leftover_us);
1938 CLEANUP;
1939 }
1940 if (leftover_us) {
1941 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001942 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001943 if (temp == NULL) {
1944 Py_DECREF(x);
1945 goto Done;
1946 }
1947 y = PyNumber_Add(x, temp);
1948 Py_DECREF(temp);
1949 CLEANUP;
1950 }
1951
Tim Petersb0c854d2003-05-17 15:57:00 +00001952 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001953 Py_DECREF(x);
1954Done:
1955 return self;
1956
1957#undef CLEANUP
1958}
1959
1960static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001961delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001962{
1963 return (GET_TD_DAYS(self) != 0
1964 || GET_TD_SECONDS(self) != 0
1965 || GET_TD_MICROSECONDS(self) != 0);
1966}
1967
1968static PyObject *
1969delta_repr(PyDateTime_Delta *self)
1970{
1971 if (GET_TD_MICROSECONDS(self) != 0)
1972 return PyString_FromFormat("%s(%d, %d, %d)",
1973 self->ob_type->tp_name,
1974 GET_TD_DAYS(self),
1975 GET_TD_SECONDS(self),
1976 GET_TD_MICROSECONDS(self));
1977 if (GET_TD_SECONDS(self) != 0)
1978 return PyString_FromFormat("%s(%d, %d)",
1979 self->ob_type->tp_name,
1980 GET_TD_DAYS(self),
1981 GET_TD_SECONDS(self));
1982
1983 return PyString_FromFormat("%s(%d)",
1984 self->ob_type->tp_name,
1985 GET_TD_DAYS(self));
1986}
1987
1988static PyObject *
1989delta_str(PyDateTime_Delta *self)
1990{
1991 int days = GET_TD_DAYS(self);
1992 int seconds = GET_TD_SECONDS(self);
1993 int us = GET_TD_MICROSECONDS(self);
1994 int hours;
1995 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00001996 char buf[100];
1997 char *pbuf = buf;
1998 size_t buflen = sizeof(buf);
1999 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002000
2001 minutes = divmod(seconds, 60, &seconds);
2002 hours = divmod(minutes, 60, &minutes);
2003
2004 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002005 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2006 (days == 1 || days == -1) ? "" : "s");
2007 if (n < 0 || (size_t)n >= buflen)
2008 goto Fail;
2009 pbuf += n;
2010 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002011 }
2012
Tim Petersba873472002-12-18 20:19:21 +00002013 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2014 hours, minutes, seconds);
2015 if (n < 0 || (size_t)n >= buflen)
2016 goto Fail;
2017 pbuf += n;
2018 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002019
2020 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002021 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2022 if (n < 0 || (size_t)n >= buflen)
2023 goto Fail;
2024 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002025 }
2026
Tim Petersba873472002-12-18 20:19:21 +00002027 return PyString_FromStringAndSize(buf, pbuf - buf);
2028
2029 Fail:
2030 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2031 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002032}
2033
Tim Peters371935f2003-02-01 01:52:50 +00002034/* Pickle support, a simple use of __reduce__. */
2035
Tim Petersb57f8f02003-02-01 02:54:15 +00002036/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002037static PyObject *
2038delta_getstate(PyDateTime_Delta *self)
2039{
2040 return Py_BuildValue("iii", GET_TD_DAYS(self),
2041 GET_TD_SECONDS(self),
2042 GET_TD_MICROSECONDS(self));
2043}
2044
Tim Peters2a799bf2002-12-16 20:18:38 +00002045static PyObject *
2046delta_reduce(PyDateTime_Delta* self)
2047{
Tim Peters8a60c222003-02-01 01:47:29 +00002048 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002049}
2050
2051#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2052
2053static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002054
Neal Norwitzdfb80862002-12-19 02:30:56 +00002055 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002056 PyDoc_STR("Number of days.")},
2057
Neal Norwitzdfb80862002-12-19 02:30:56 +00002058 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002059 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2060
Neal Norwitzdfb80862002-12-19 02:30:56 +00002061 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002062 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2063 {NULL}
2064};
2065
2066static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002067 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2068 PyDoc_STR("__reduce__() -> (cls, state)")},
2069
Tim Peters2a799bf2002-12-16 20:18:38 +00002070 {NULL, NULL},
2071};
2072
2073static char delta_doc[] =
2074PyDoc_STR("Difference between two datetime values.");
2075
2076static PyNumberMethods delta_as_number = {
2077 delta_add, /* nb_add */
2078 delta_subtract, /* nb_subtract */
2079 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002080 0, /* nb_remainder */
2081 0, /* nb_divmod */
2082 0, /* nb_power */
2083 (unaryfunc)delta_negative, /* nb_negative */
2084 (unaryfunc)delta_positive, /* nb_positive */
2085 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002086 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002087 0, /*nb_invert*/
2088 0, /*nb_lshift*/
2089 0, /*nb_rshift*/
2090 0, /*nb_and*/
2091 0, /*nb_xor*/
2092 0, /*nb_or*/
2093 0, /*nb_coerce*/
2094 0, /*nb_int*/
2095 0, /*nb_long*/
2096 0, /*nb_float*/
2097 0, /*nb_oct*/
2098 0, /*nb_hex*/
2099 0, /*nb_inplace_add*/
2100 0, /*nb_inplace_subtract*/
2101 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002102 0, /*nb_inplace_remainder*/
2103 0, /*nb_inplace_power*/
2104 0, /*nb_inplace_lshift*/
2105 0, /*nb_inplace_rshift*/
2106 0, /*nb_inplace_and*/
2107 0, /*nb_inplace_xor*/
2108 0, /*nb_inplace_or*/
2109 delta_divide, /* nb_floor_divide */
2110 0, /* nb_true_divide */
2111 0, /* nb_inplace_floor_divide */
2112 0, /* nb_inplace_true_divide */
2113};
2114
2115static PyTypeObject PyDateTime_DeltaType = {
2116 PyObject_HEAD_INIT(NULL)
2117 0, /* ob_size */
2118 "datetime.timedelta", /* tp_name */
2119 sizeof(PyDateTime_Delta), /* tp_basicsize */
2120 0, /* tp_itemsize */
2121 0, /* tp_dealloc */
2122 0, /* tp_print */
2123 0, /* tp_getattr */
2124 0, /* tp_setattr */
2125 0, /* tp_compare */
2126 (reprfunc)delta_repr, /* tp_repr */
2127 &delta_as_number, /* tp_as_number */
2128 0, /* tp_as_sequence */
2129 0, /* tp_as_mapping */
2130 (hashfunc)delta_hash, /* tp_hash */
2131 0, /* tp_call */
2132 (reprfunc)delta_str, /* tp_str */
2133 PyObject_GenericGetAttr, /* tp_getattro */
2134 0, /* tp_setattro */
2135 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002136 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002137 delta_doc, /* tp_doc */
2138 0, /* tp_traverse */
2139 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002140 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002141 0, /* tp_weaklistoffset */
2142 0, /* tp_iter */
2143 0, /* tp_iternext */
2144 delta_methods, /* tp_methods */
2145 delta_members, /* tp_members */
2146 0, /* tp_getset */
2147 0, /* tp_base */
2148 0, /* tp_dict */
2149 0, /* tp_descr_get */
2150 0, /* tp_descr_set */
2151 0, /* tp_dictoffset */
2152 0, /* tp_init */
2153 0, /* tp_alloc */
2154 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002155 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002156};
2157
2158/*
2159 * PyDateTime_Date implementation.
2160 */
2161
2162/* Accessor properties. */
2163
2164static PyObject *
2165date_year(PyDateTime_Date *self, void *unused)
2166{
2167 return PyInt_FromLong(GET_YEAR(self));
2168}
2169
2170static PyObject *
2171date_month(PyDateTime_Date *self, void *unused)
2172{
2173 return PyInt_FromLong(GET_MONTH(self));
2174}
2175
2176static PyObject *
2177date_day(PyDateTime_Date *self, void *unused)
2178{
2179 return PyInt_FromLong(GET_DAY(self));
2180}
2181
2182static PyGetSetDef date_getset[] = {
2183 {"year", (getter)date_year},
2184 {"month", (getter)date_month},
2185 {"day", (getter)date_day},
2186 {NULL}
2187};
2188
2189/* Constructors. */
2190
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002191static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002192
Tim Peters2a799bf2002-12-16 20:18:38 +00002193static PyObject *
2194date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2195{
2196 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002197 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002198 int year;
2199 int month;
2200 int day;
2201
Guido van Rossum177e41a2003-01-30 22:06:23 +00002202 /* Check for invocation from pickle with __getstate__ state */
2203 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002204 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002205 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2206 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002207 {
Tim Peters70533e22003-02-01 04:40:04 +00002208 PyDateTime_Date *me;
2209
Tim Peters604c0132004-06-07 23:04:33 +00002210 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002211 if (me != NULL) {
2212 char *pdata = PyString_AS_STRING(state);
2213 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2214 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002215 }
Tim Peters70533e22003-02-01 04:40:04 +00002216 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002217 }
2218
Tim Peters12bf3392002-12-24 05:41:27 +00002219 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002220 &year, &month, &day)) {
2221 if (check_date_args(year, month, day) < 0)
2222 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002223 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002224 }
2225 return self;
2226}
2227
2228/* Return new date from localtime(t). */
2229static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002230date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002231{
2232 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002233 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002234 PyObject *result = NULL;
2235
Tim Peters1b6f7a92004-06-20 02:50:16 +00002236 t = _PyTime_DoubleToTimet(ts);
2237 if (t == (time_t)-1 && PyErr_Occurred())
2238 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002239 tm = localtime(&t);
2240 if (tm)
2241 result = PyObject_CallFunction(cls, "iii",
2242 tm->tm_year + 1900,
2243 tm->tm_mon + 1,
2244 tm->tm_mday);
2245 else
2246 PyErr_SetString(PyExc_ValueError,
2247 "timestamp out of range for "
2248 "platform localtime() function");
2249 return result;
2250}
2251
2252/* Return new date from current time.
2253 * We say this is equivalent to fromtimestamp(time.time()), and the
2254 * only way to be sure of that is to *call* time.time(). That's not
2255 * generally the same as calling C's time.
2256 */
2257static PyObject *
2258date_today(PyObject *cls, PyObject *dummy)
2259{
2260 PyObject *time;
2261 PyObject *result;
2262
2263 time = time_time();
2264 if (time == NULL)
2265 return NULL;
2266
2267 /* Note well: today() is a class method, so this may not call
2268 * date.fromtimestamp. For example, it may call
2269 * datetime.fromtimestamp. That's why we need all the accuracy
2270 * time.time() delivers; if someone were gonzo about optimization,
2271 * date.today() could get away with plain C time().
2272 */
2273 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2274 Py_DECREF(time);
2275 return result;
2276}
2277
2278/* Return new date from given timestamp (Python timestamp -- a double). */
2279static PyObject *
2280date_fromtimestamp(PyObject *cls, PyObject *args)
2281{
2282 double timestamp;
2283 PyObject *result = NULL;
2284
2285 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002286 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002287 return result;
2288}
2289
2290/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2291 * the ordinal is out of range.
2292 */
2293static PyObject *
2294date_fromordinal(PyObject *cls, PyObject *args)
2295{
2296 PyObject *result = NULL;
2297 int ordinal;
2298
2299 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2300 int year;
2301 int month;
2302 int day;
2303
2304 if (ordinal < 1)
2305 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2306 ">= 1");
2307 else {
2308 ord_to_ymd(ordinal, &year, &month, &day);
2309 result = PyObject_CallFunction(cls, "iii",
2310 year, month, day);
2311 }
2312 }
2313 return result;
2314}
2315
2316/*
2317 * Date arithmetic.
2318 */
2319
2320/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2321 * instead.
2322 */
2323static PyObject *
2324add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2325{
2326 PyObject *result = NULL;
2327 int year = GET_YEAR(date);
2328 int month = GET_MONTH(date);
2329 int deltadays = GET_TD_DAYS(delta);
2330 /* C-level overflow is impossible because |deltadays| < 1e9. */
2331 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2332
2333 if (normalize_date(&year, &month, &day) >= 0)
2334 result = new_date(year, month, day);
2335 return result;
2336}
2337
2338static PyObject *
2339date_add(PyObject *left, PyObject *right)
2340{
2341 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2342 Py_INCREF(Py_NotImplemented);
2343 return Py_NotImplemented;
2344 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002345 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002346 /* date + ??? */
2347 if (PyDelta_Check(right))
2348 /* date + delta */
2349 return add_date_timedelta((PyDateTime_Date *) left,
2350 (PyDateTime_Delta *) right,
2351 0);
2352 }
2353 else {
2354 /* ??? + date
2355 * 'right' must be one of us, or we wouldn't have been called
2356 */
2357 if (PyDelta_Check(left))
2358 /* delta + date */
2359 return add_date_timedelta((PyDateTime_Date *) right,
2360 (PyDateTime_Delta *) left,
2361 0);
2362 }
2363 Py_INCREF(Py_NotImplemented);
2364 return Py_NotImplemented;
2365}
2366
2367static PyObject *
2368date_subtract(PyObject *left, PyObject *right)
2369{
2370 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2371 Py_INCREF(Py_NotImplemented);
2372 return Py_NotImplemented;
2373 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002374 if (PyDate_Check(left)) {
2375 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002376 /* date - date */
2377 int left_ord = ymd_to_ord(GET_YEAR(left),
2378 GET_MONTH(left),
2379 GET_DAY(left));
2380 int right_ord = ymd_to_ord(GET_YEAR(right),
2381 GET_MONTH(right),
2382 GET_DAY(right));
2383 return new_delta(left_ord - right_ord, 0, 0, 0);
2384 }
2385 if (PyDelta_Check(right)) {
2386 /* date - delta */
2387 return add_date_timedelta((PyDateTime_Date *) left,
2388 (PyDateTime_Delta *) right,
2389 1);
2390 }
2391 }
2392 Py_INCREF(Py_NotImplemented);
2393 return Py_NotImplemented;
2394}
2395
2396
2397/* Various ways to turn a date into a string. */
2398
2399static PyObject *
2400date_repr(PyDateTime_Date *self)
2401{
2402 char buffer[1028];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002403 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002404
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002405 type_name = self->ob_type->tp_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002406 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002407 type_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002408 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2409
2410 return PyString_FromString(buffer);
2411}
2412
2413static PyObject *
2414date_isoformat(PyDateTime_Date *self)
2415{
2416 char buffer[128];
2417
2418 isoformat_date(self, buffer, sizeof(buffer));
2419 return PyString_FromString(buffer);
2420}
2421
Tim Peterse2df5ff2003-05-02 18:39:55 +00002422/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002423static PyObject *
2424date_str(PyDateTime_Date *self)
2425{
2426 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2427}
2428
2429
2430static PyObject *
2431date_ctime(PyDateTime_Date *self)
2432{
2433 return format_ctime(self, 0, 0, 0);
2434}
2435
2436static PyObject *
2437date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2438{
2439 /* This method can be inherited, and needs to call the
2440 * timetuple() method appropriate to self's class.
2441 */
2442 PyObject *result;
2443 PyObject *format;
2444 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002445 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002446
2447 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2448 &PyString_Type, &format))
2449 return NULL;
2450
2451 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2452 if (tuple == NULL)
2453 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002454 result = wrap_strftime((PyObject *)self, format, tuple,
2455 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002456 Py_DECREF(tuple);
2457 return result;
2458}
2459
2460/* ISO methods. */
2461
2462static PyObject *
2463date_isoweekday(PyDateTime_Date *self)
2464{
2465 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2466
2467 return PyInt_FromLong(dow + 1);
2468}
2469
2470static PyObject *
2471date_isocalendar(PyDateTime_Date *self)
2472{
2473 int year = GET_YEAR(self);
2474 int week1_monday = iso_week1_monday(year);
2475 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2476 int week;
2477 int day;
2478
2479 week = divmod(today - week1_monday, 7, &day);
2480 if (week < 0) {
2481 --year;
2482 week1_monday = iso_week1_monday(year);
2483 week = divmod(today - week1_monday, 7, &day);
2484 }
2485 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2486 ++year;
2487 week = 0;
2488 }
2489 return Py_BuildValue("iii", year, week + 1, day + 1);
2490}
2491
2492/* Miscellaneous methods. */
2493
Tim Peters2a799bf2002-12-16 20:18:38 +00002494static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002495date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002496{
Guido van Rossum19960592006-08-24 17:29:38 +00002497 if (PyDate_Check(other)) {
2498 int diff = memcmp(((PyDateTime_Date *)self)->data,
2499 ((PyDateTime_Date *)other)->data,
2500 _PyDateTime_DATE_DATASIZE);
2501 return diff_to_bool(diff, op);
2502 }
2503 else {
Tim Peters07534a62003-02-07 22:50:28 +00002504 Py_INCREF(Py_NotImplemented);
2505 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002506 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002507}
2508
2509static PyObject *
2510date_timetuple(PyDateTime_Date *self)
2511{
2512 return build_struct_time(GET_YEAR(self),
2513 GET_MONTH(self),
2514 GET_DAY(self),
2515 0, 0, 0, -1);
2516}
2517
Tim Peters12bf3392002-12-24 05:41:27 +00002518static PyObject *
2519date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2520{
2521 PyObject *clone;
2522 PyObject *tuple;
2523 int year = GET_YEAR(self);
2524 int month = GET_MONTH(self);
2525 int day = GET_DAY(self);
2526
2527 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2528 &year, &month, &day))
2529 return NULL;
2530 tuple = Py_BuildValue("iii", year, month, day);
2531 if (tuple == NULL)
2532 return NULL;
2533 clone = date_new(self->ob_type, tuple, NULL);
2534 Py_DECREF(tuple);
2535 return clone;
2536}
2537
Tim Peters2a799bf2002-12-16 20:18:38 +00002538static PyObject *date_getstate(PyDateTime_Date *self);
2539
2540static long
2541date_hash(PyDateTime_Date *self)
2542{
2543 if (self->hashcode == -1) {
2544 PyObject *temp = date_getstate(self);
2545 if (temp != NULL) {
2546 self->hashcode = PyObject_Hash(temp);
2547 Py_DECREF(temp);
2548 }
2549 }
2550 return self->hashcode;
2551}
2552
2553static PyObject *
2554date_toordinal(PyDateTime_Date *self)
2555{
2556 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2557 GET_DAY(self)));
2558}
2559
2560static PyObject *
2561date_weekday(PyDateTime_Date *self)
2562{
2563 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2564
2565 return PyInt_FromLong(dow);
2566}
2567
Tim Peters371935f2003-02-01 01:52:50 +00002568/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002569
Tim Petersb57f8f02003-02-01 02:54:15 +00002570/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002571static PyObject *
2572date_getstate(PyDateTime_Date *self)
2573{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002574 return Py_BuildValue(
2575 "(N)",
2576 PyString_FromStringAndSize((char *)self->data,
2577 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002578}
2579
2580static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002581date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002582{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002583 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002584}
2585
2586static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002587
Tim Peters2a799bf2002-12-16 20:18:38 +00002588 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002589
Tim Peters2a799bf2002-12-16 20:18:38 +00002590 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2591 METH_CLASS,
2592 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2593 "time.time()).")},
2594
2595 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2596 METH_CLASS,
2597 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2598 "ordinal.")},
2599
2600 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2601 PyDoc_STR("Current date or datetime: same as "
2602 "self.__class__.fromtimestamp(time.time()).")},
2603
2604 /* Instance methods: */
2605
2606 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2607 PyDoc_STR("Return ctime() style string.")},
2608
2609 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2610 PyDoc_STR("format -> strftime() style string.")},
2611
2612 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2613 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2614
2615 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2616 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2617 "weekday.")},
2618
2619 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2620 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2621
2622 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2623 PyDoc_STR("Return the day of the week represented by the date.\n"
2624 "Monday == 1 ... Sunday == 7")},
2625
2626 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2627 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2628 "1 is day 1.")},
2629
2630 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2631 PyDoc_STR("Return the day of the week represented by the date.\n"
2632 "Monday == 0 ... Sunday == 6")},
2633
Tim Peters12bf3392002-12-24 05:41:27 +00002634 {"replace", (PyCFunction)date_replace, METH_KEYWORDS,
2635 PyDoc_STR("Return date with new specified fields.")},
2636
Guido van Rossum177e41a2003-01-30 22:06:23 +00002637 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2638 PyDoc_STR("__reduce__() -> (cls, state)")},
2639
Tim Peters2a799bf2002-12-16 20:18:38 +00002640 {NULL, NULL}
2641};
2642
2643static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002644PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002645
2646static PyNumberMethods date_as_number = {
2647 date_add, /* nb_add */
2648 date_subtract, /* nb_subtract */
2649 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002650 0, /* nb_remainder */
2651 0, /* nb_divmod */
2652 0, /* nb_power */
2653 0, /* nb_negative */
2654 0, /* nb_positive */
2655 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002656 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002657};
2658
2659static PyTypeObject PyDateTime_DateType = {
2660 PyObject_HEAD_INIT(NULL)
2661 0, /* ob_size */
2662 "datetime.date", /* tp_name */
2663 sizeof(PyDateTime_Date), /* tp_basicsize */
2664 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002665 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002666 0, /* tp_print */
2667 0, /* tp_getattr */
2668 0, /* tp_setattr */
2669 0, /* tp_compare */
2670 (reprfunc)date_repr, /* tp_repr */
2671 &date_as_number, /* tp_as_number */
2672 0, /* tp_as_sequence */
2673 0, /* tp_as_mapping */
2674 (hashfunc)date_hash, /* tp_hash */
2675 0, /* tp_call */
2676 (reprfunc)date_str, /* tp_str */
2677 PyObject_GenericGetAttr, /* tp_getattro */
2678 0, /* tp_setattro */
2679 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002680 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002681 date_doc, /* tp_doc */
2682 0, /* tp_traverse */
2683 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002684 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002685 0, /* tp_weaklistoffset */
2686 0, /* tp_iter */
2687 0, /* tp_iternext */
2688 date_methods, /* tp_methods */
2689 0, /* tp_members */
2690 date_getset, /* tp_getset */
2691 0, /* tp_base */
2692 0, /* tp_dict */
2693 0, /* tp_descr_get */
2694 0, /* tp_descr_set */
2695 0, /* tp_dictoffset */
2696 0, /* tp_init */
2697 0, /* tp_alloc */
2698 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002699 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002700};
2701
2702/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002703 * PyDateTime_TZInfo implementation.
2704 */
2705
2706/* This is a pure abstract base class, so doesn't do anything beyond
2707 * raising NotImplemented exceptions. Real tzinfo classes need
2708 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002709 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002710 * be subclasses of this tzinfo class, which is easy and quick to check).
2711 *
2712 * Note: For reasons having to do with pickling of subclasses, we have
2713 * to allow tzinfo objects to be instantiated. This wasn't an issue
2714 * in the Python implementation (__init__() could raise NotImplementedError
2715 * there without ill effect), but doing so in the C implementation hit a
2716 * brick wall.
2717 */
2718
2719static PyObject *
2720tzinfo_nogo(const char* methodname)
2721{
2722 PyErr_Format(PyExc_NotImplementedError,
2723 "a tzinfo subclass must implement %s()",
2724 methodname);
2725 return NULL;
2726}
2727
2728/* Methods. A subclass must implement these. */
2729
Tim Peters52dcce22003-01-23 16:36:11 +00002730static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002731tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2732{
2733 return tzinfo_nogo("tzname");
2734}
2735
Tim Peters52dcce22003-01-23 16:36:11 +00002736static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002737tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2738{
2739 return tzinfo_nogo("utcoffset");
2740}
2741
Tim Peters52dcce22003-01-23 16:36:11 +00002742static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002743tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2744{
2745 return tzinfo_nogo("dst");
2746}
2747
Tim Peters52dcce22003-01-23 16:36:11 +00002748static PyObject *
2749tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2750{
2751 int y, m, d, hh, mm, ss, us;
2752
2753 PyObject *result;
2754 int off, dst;
2755 int none;
2756 int delta;
2757
2758 if (! PyDateTime_Check(dt)) {
2759 PyErr_SetString(PyExc_TypeError,
2760 "fromutc: argument must be a datetime");
2761 return NULL;
2762 }
2763 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2764 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2765 "is not self");
2766 return NULL;
2767 }
2768
2769 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2770 if (off == -1 && PyErr_Occurred())
2771 return NULL;
2772 if (none) {
2773 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2774 "utcoffset() result required");
2775 return NULL;
2776 }
2777
2778 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2779 if (dst == -1 && PyErr_Occurred())
2780 return NULL;
2781 if (none) {
2782 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2783 "dst() result required");
2784 return NULL;
2785 }
2786
2787 y = GET_YEAR(dt);
2788 m = GET_MONTH(dt);
2789 d = GET_DAY(dt);
2790 hh = DATE_GET_HOUR(dt);
2791 mm = DATE_GET_MINUTE(dt);
2792 ss = DATE_GET_SECOND(dt);
2793 us = DATE_GET_MICROSECOND(dt);
2794
2795 delta = off - dst;
2796 mm += delta;
2797 if ((mm < 0 || mm >= 60) &&
2798 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002799 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002800 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2801 if (result == NULL)
2802 return result;
2803
2804 dst = call_dst(dt->tzinfo, result, &none);
2805 if (dst == -1 && PyErr_Occurred())
2806 goto Fail;
2807 if (none)
2808 goto Inconsistent;
2809 if (dst == 0)
2810 return result;
2811
2812 mm += dst;
2813 if ((mm < 0 || mm >= 60) &&
2814 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2815 goto Fail;
2816 Py_DECREF(result);
2817 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2818 return result;
2819
2820Inconsistent:
2821 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2822 "inconsistent results; cannot convert");
2823
2824 /* fall thru to failure */
2825Fail:
2826 Py_DECREF(result);
2827 return NULL;
2828}
2829
Tim Peters2a799bf2002-12-16 20:18:38 +00002830/*
2831 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002832 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002833 */
2834
Guido van Rossum177e41a2003-01-30 22:06:23 +00002835static PyObject *
2836tzinfo_reduce(PyObject *self)
2837{
2838 PyObject *args, *state, *tmp;
2839 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002840
Guido van Rossum177e41a2003-01-30 22:06:23 +00002841 tmp = PyTuple_New(0);
2842 if (tmp == NULL)
2843 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002844
Guido van Rossum177e41a2003-01-30 22:06:23 +00002845 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2846 if (getinitargs != NULL) {
2847 args = PyObject_CallObject(getinitargs, tmp);
2848 Py_DECREF(getinitargs);
2849 if (args == NULL) {
2850 Py_DECREF(tmp);
2851 return NULL;
2852 }
2853 }
2854 else {
2855 PyErr_Clear();
2856 args = tmp;
2857 Py_INCREF(args);
2858 }
2859
2860 getstate = PyObject_GetAttrString(self, "__getstate__");
2861 if (getstate != NULL) {
2862 state = PyObject_CallObject(getstate, tmp);
2863 Py_DECREF(getstate);
2864 if (state == NULL) {
2865 Py_DECREF(args);
2866 Py_DECREF(tmp);
2867 return NULL;
2868 }
2869 }
2870 else {
2871 PyObject **dictptr;
2872 PyErr_Clear();
2873 state = Py_None;
2874 dictptr = _PyObject_GetDictPtr(self);
2875 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2876 state = *dictptr;
2877 Py_INCREF(state);
2878 }
2879
2880 Py_DECREF(tmp);
2881
2882 if (state == Py_None) {
2883 Py_DECREF(state);
2884 return Py_BuildValue("(ON)", self->ob_type, args);
2885 }
2886 else
2887 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2888}
Tim Peters2a799bf2002-12-16 20:18:38 +00002889
2890static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002891
Tim Peters2a799bf2002-12-16 20:18:38 +00002892 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2893 PyDoc_STR("datetime -> string name of time zone.")},
2894
2895 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2896 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2897 "west of UTC).")},
2898
2899 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2900 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2901
Tim Peters52dcce22003-01-23 16:36:11 +00002902 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2903 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2904
Guido van Rossum177e41a2003-01-30 22:06:23 +00002905 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2906 PyDoc_STR("-> (cls, state)")},
2907
Tim Peters2a799bf2002-12-16 20:18:38 +00002908 {NULL, NULL}
2909};
2910
2911static char tzinfo_doc[] =
2912PyDoc_STR("Abstract base class for time zone info objects.");
2913
Neal Norwitz227b5332006-03-22 09:28:35 +00002914static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002915 PyObject_HEAD_INIT(NULL)
2916 0, /* ob_size */
2917 "datetime.tzinfo", /* tp_name */
2918 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2919 0, /* tp_itemsize */
2920 0, /* tp_dealloc */
2921 0, /* tp_print */
2922 0, /* tp_getattr */
2923 0, /* tp_setattr */
2924 0, /* tp_compare */
2925 0, /* tp_repr */
2926 0, /* tp_as_number */
2927 0, /* tp_as_sequence */
2928 0, /* tp_as_mapping */
2929 0, /* tp_hash */
2930 0, /* tp_call */
2931 0, /* tp_str */
2932 PyObject_GenericGetAttr, /* tp_getattro */
2933 0, /* tp_setattro */
2934 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002935 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002936 tzinfo_doc, /* tp_doc */
2937 0, /* tp_traverse */
2938 0, /* tp_clear */
2939 0, /* tp_richcompare */
2940 0, /* tp_weaklistoffset */
2941 0, /* tp_iter */
2942 0, /* tp_iternext */
2943 tzinfo_methods, /* tp_methods */
2944 0, /* tp_members */
2945 0, /* tp_getset */
2946 0, /* tp_base */
2947 0, /* tp_dict */
2948 0, /* tp_descr_get */
2949 0, /* tp_descr_set */
2950 0, /* tp_dictoffset */
2951 0, /* tp_init */
2952 0, /* tp_alloc */
2953 PyType_GenericNew, /* tp_new */
2954 0, /* tp_free */
2955};
2956
2957/*
Tim Peters37f39822003-01-10 03:49:02 +00002958 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002959 */
2960
Tim Peters37f39822003-01-10 03:49:02 +00002961/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002962 */
2963
2964static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002965time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002966{
Tim Peters37f39822003-01-10 03:49:02 +00002967 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002968}
2969
Tim Peters37f39822003-01-10 03:49:02 +00002970static PyObject *
2971time_minute(PyDateTime_Time *self, void *unused)
2972{
2973 return PyInt_FromLong(TIME_GET_MINUTE(self));
2974}
2975
2976/* The name time_second conflicted with some platform header file. */
2977static PyObject *
2978py_time_second(PyDateTime_Time *self, void *unused)
2979{
2980 return PyInt_FromLong(TIME_GET_SECOND(self));
2981}
2982
2983static PyObject *
2984time_microsecond(PyDateTime_Time *self, void *unused)
2985{
2986 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2987}
2988
2989static PyObject *
2990time_tzinfo(PyDateTime_Time *self, void *unused)
2991{
Tim Petersa032d2e2003-01-11 00:15:54 +00002992 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002993 Py_INCREF(result);
2994 return result;
2995}
2996
2997static PyGetSetDef time_getset[] = {
2998 {"hour", (getter)time_hour},
2999 {"minute", (getter)time_minute},
3000 {"second", (getter)py_time_second},
3001 {"microsecond", (getter)time_microsecond},
3002 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003003 {NULL}
3004};
3005
3006/*
3007 * Constructors.
3008 */
3009
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003010static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003011 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003012
Tim Peters2a799bf2002-12-16 20:18:38 +00003013static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003014time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003015{
3016 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003017 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003018 int hour = 0;
3019 int minute = 0;
3020 int second = 0;
3021 int usecond = 0;
3022 PyObject *tzinfo = Py_None;
3023
Guido van Rossum177e41a2003-01-30 22:06:23 +00003024 /* Check for invocation from pickle with __getstate__ state */
3025 if (PyTuple_GET_SIZE(args) >= 1 &&
3026 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003027 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003028 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3029 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003030 {
Tim Peters70533e22003-02-01 04:40:04 +00003031 PyDateTime_Time *me;
3032 char aware;
3033
3034 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003035 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003036 if (check_tzinfo_subclass(tzinfo) < 0) {
3037 PyErr_SetString(PyExc_TypeError, "bad "
3038 "tzinfo state arg");
3039 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003040 }
3041 }
Tim Peters70533e22003-02-01 04:40:04 +00003042 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003043 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003044 if (me != NULL) {
3045 char *pdata = PyString_AS_STRING(state);
3046
3047 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3048 me->hashcode = -1;
3049 me->hastzinfo = aware;
3050 if (aware) {
3051 Py_INCREF(tzinfo);
3052 me->tzinfo = tzinfo;
3053 }
3054 }
3055 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003056 }
3057
Tim Peters37f39822003-01-10 03:49:02 +00003058 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003059 &hour, &minute, &second, &usecond,
3060 &tzinfo)) {
3061 if (check_time_args(hour, minute, second, usecond) < 0)
3062 return NULL;
3063 if (check_tzinfo_subclass(tzinfo) < 0)
3064 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003065 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3066 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003067 }
3068 return self;
3069}
3070
3071/*
3072 * Destructor.
3073 */
3074
3075static void
Tim Peters37f39822003-01-10 03:49:02 +00003076time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003077{
Tim Petersa032d2e2003-01-11 00:15:54 +00003078 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003079 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003080 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003081 self->ob_type->tp_free((PyObject *)self);
3082}
3083
3084/*
Tim Peters855fe882002-12-22 03:43:39 +00003085 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003086 */
3087
Tim Peters2a799bf2002-12-16 20:18:38 +00003088/* These are all METH_NOARGS, so don't need to check the arglist. */
3089static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003090time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003091 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003092 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003093}
3094
3095static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003096time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003097 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003098 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003099}
3100
3101static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003102time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003103 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003104 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003105}
3106
3107/*
Tim Peters37f39822003-01-10 03:49:02 +00003108 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003109 */
3110
3111static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003112time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003113{
Tim Peters37f39822003-01-10 03:49:02 +00003114 char buffer[100];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003115 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003116 int h = TIME_GET_HOUR(self);
3117 int m = TIME_GET_MINUTE(self);
3118 int s = TIME_GET_SECOND(self);
3119 int us = TIME_GET_MICROSECOND(self);
3120 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003121
Tim Peters37f39822003-01-10 03:49:02 +00003122 if (us)
3123 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003124 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003125 else if (s)
3126 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003127 "%s(%d, %d, %d)", type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003128 else
3129 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003130 "%s(%d, %d)", type_name, h, m);
Tim Peters37f39822003-01-10 03:49:02 +00003131 result = PyString_FromString(buffer);
Tim Petersa032d2e2003-01-11 00:15:54 +00003132 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003133 result = append_keyword_tzinfo(result, self->tzinfo);
3134 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003135}
3136
Tim Peters37f39822003-01-10 03:49:02 +00003137static PyObject *
3138time_str(PyDateTime_Time *self)
3139{
3140 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3141}
Tim Peters2a799bf2002-12-16 20:18:38 +00003142
3143static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003144time_isoformat(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003145{
3146 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003147 PyObject *result;
3148 /* Reuse the time format code from the datetime type. */
3149 PyDateTime_DateTime datetime;
3150 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003151
Tim Peters37f39822003-01-10 03:49:02 +00003152 /* Copy over just the time bytes. */
3153 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3154 self->data,
3155 _PyDateTime_TIME_DATASIZE);
3156
3157 isoformat_time(pdatetime, buf, sizeof(buf));
3158 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003159 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003160 return result;
3161
3162 /* We need to append the UTC offset. */
3163 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003164 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003165 Py_DECREF(result);
3166 return NULL;
3167 }
3168 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3169 return result;
3170}
3171
Tim Peters37f39822003-01-10 03:49:02 +00003172static PyObject *
3173time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3174{
3175 PyObject *result;
3176 PyObject *format;
3177 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003178 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003179
3180 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3181 &PyString_Type, &format))
3182 return NULL;
3183
3184 /* Python's strftime does insane things with the year part of the
3185 * timetuple. The year is forced to (the otherwise nonsensical)
3186 * 1900 to worm around that.
3187 */
3188 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003189 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003190 TIME_GET_HOUR(self),
3191 TIME_GET_MINUTE(self),
3192 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003193 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003194 if (tuple == NULL)
3195 return NULL;
3196 assert(PyTuple_Size(tuple) == 9);
3197 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3198 Py_DECREF(tuple);
3199 return result;
3200}
Tim Peters2a799bf2002-12-16 20:18:38 +00003201
3202/*
3203 * Miscellaneous methods.
3204 */
3205
Tim Peters37f39822003-01-10 03:49:02 +00003206static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003207time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003208{
3209 int diff;
3210 naivety n1, n2;
3211 int offset1, offset2;
3212
3213 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003214 Py_INCREF(Py_NotImplemented);
3215 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003216 }
Guido van Rossum19960592006-08-24 17:29:38 +00003217 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3218 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003219 return NULL;
3220 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3221 /* If they're both naive, or both aware and have the same offsets,
3222 * we get off cheap. Note that if they're both naive, offset1 ==
3223 * offset2 == 0 at this point.
3224 */
3225 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003226 diff = memcmp(((PyDateTime_Time *)self)->data,
3227 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003228 _PyDateTime_TIME_DATASIZE);
3229 return diff_to_bool(diff, op);
3230 }
3231
3232 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3233 assert(offset1 != offset2); /* else last "if" handled it */
3234 /* Convert everything except microseconds to seconds. These
3235 * can't overflow (no more than the # of seconds in 2 days).
3236 */
3237 offset1 = TIME_GET_HOUR(self) * 3600 +
3238 (TIME_GET_MINUTE(self) - offset1) * 60 +
3239 TIME_GET_SECOND(self);
3240 offset2 = TIME_GET_HOUR(other) * 3600 +
3241 (TIME_GET_MINUTE(other) - offset2) * 60 +
3242 TIME_GET_SECOND(other);
3243 diff = offset1 - offset2;
3244 if (diff == 0)
3245 diff = TIME_GET_MICROSECOND(self) -
3246 TIME_GET_MICROSECOND(other);
3247 return diff_to_bool(diff, op);
3248 }
3249
3250 assert(n1 != n2);
3251 PyErr_SetString(PyExc_TypeError,
3252 "can't compare offset-naive and "
3253 "offset-aware times");
3254 return NULL;
3255}
3256
3257static long
3258time_hash(PyDateTime_Time *self)
3259{
3260 if (self->hashcode == -1) {
3261 naivety n;
3262 int offset;
3263 PyObject *temp;
3264
3265 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3266 assert(n != OFFSET_UNKNOWN);
3267 if (n == OFFSET_ERROR)
3268 return -1;
3269
3270 /* Reduce this to a hash of another object. */
3271 if (offset == 0)
3272 temp = PyString_FromStringAndSize((char *)self->data,
3273 _PyDateTime_TIME_DATASIZE);
3274 else {
3275 int hour;
3276 int minute;
3277
3278 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003279 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003280 hour = divmod(TIME_GET_HOUR(self) * 60 +
3281 TIME_GET_MINUTE(self) - offset,
3282 60,
3283 &minute);
3284 if (0 <= hour && hour < 24)
3285 temp = new_time(hour, minute,
3286 TIME_GET_SECOND(self),
3287 TIME_GET_MICROSECOND(self),
3288 Py_None);
3289 else
3290 temp = Py_BuildValue("iiii",
3291 hour, minute,
3292 TIME_GET_SECOND(self),
3293 TIME_GET_MICROSECOND(self));
3294 }
3295 if (temp != NULL) {
3296 self->hashcode = PyObject_Hash(temp);
3297 Py_DECREF(temp);
3298 }
3299 }
3300 return self->hashcode;
3301}
Tim Peters2a799bf2002-12-16 20:18:38 +00003302
Tim Peters12bf3392002-12-24 05:41:27 +00003303static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003304time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003305{
3306 PyObject *clone;
3307 PyObject *tuple;
3308 int hh = TIME_GET_HOUR(self);
3309 int mm = TIME_GET_MINUTE(self);
3310 int ss = TIME_GET_SECOND(self);
3311 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003312 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003313
3314 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003315 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003316 &hh, &mm, &ss, &us, &tzinfo))
3317 return NULL;
3318 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3319 if (tuple == NULL)
3320 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003321 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003322 Py_DECREF(tuple);
3323 return clone;
3324}
3325
Tim Peters2a799bf2002-12-16 20:18:38 +00003326static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003327time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003328{
3329 int offset;
3330 int none;
3331
3332 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3333 /* Since utcoffset is in whole minutes, nothing can
3334 * alter the conclusion that this is nonzero.
3335 */
3336 return 1;
3337 }
3338 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003339 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003340 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003341 if (offset == -1 && PyErr_Occurred())
3342 return -1;
3343 }
3344 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3345}
3346
Tim Peters371935f2003-02-01 01:52:50 +00003347/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003348
Tim Peters33e0f382003-01-10 02:05:14 +00003349/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003350 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3351 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003352 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003353 */
3354static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003355time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003356{
3357 PyObject *basestate;
3358 PyObject *result = NULL;
3359
Tim Peters33e0f382003-01-10 02:05:14 +00003360 basestate = PyString_FromStringAndSize((char *)self->data,
3361 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003362 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003363 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003364 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003365 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003366 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003367 Py_DECREF(basestate);
3368 }
3369 return result;
3370}
3371
3372static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003373time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003374{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003375 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003376}
3377
Tim Peters37f39822003-01-10 03:49:02 +00003378static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003379
Tim Peters37f39822003-01-10 03:49:02 +00003380 {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003381 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3382 "[+HH:MM].")},
3383
Tim Peters37f39822003-01-10 03:49:02 +00003384 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3385 PyDoc_STR("format -> strftime() style string.")},
3386
3387 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003388 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3389
Tim Peters37f39822003-01-10 03:49:02 +00003390 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003391 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3392
Tim Peters37f39822003-01-10 03:49:02 +00003393 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003394 PyDoc_STR("Return self.tzinfo.dst(self).")},
3395
Tim Peters37f39822003-01-10 03:49:02 +00003396 {"replace", (PyCFunction)time_replace, METH_KEYWORDS,
3397 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003398
Guido van Rossum177e41a2003-01-30 22:06:23 +00003399 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3400 PyDoc_STR("__reduce__() -> (cls, state)")},
3401
Tim Peters2a799bf2002-12-16 20:18:38 +00003402 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003403};
3404
Tim Peters37f39822003-01-10 03:49:02 +00003405static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003406PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3407\n\
3408All arguments are optional. tzinfo may be None, or an instance of\n\
3409a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003410
Tim Peters37f39822003-01-10 03:49:02 +00003411static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003412 0, /* nb_add */
3413 0, /* nb_subtract */
3414 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003415 0, /* nb_remainder */
3416 0, /* nb_divmod */
3417 0, /* nb_power */
3418 0, /* nb_negative */
3419 0, /* nb_positive */
3420 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003421 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003422};
3423
Neal Norwitz227b5332006-03-22 09:28:35 +00003424static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003425 PyObject_HEAD_INIT(NULL)
3426 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003427 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003428 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003429 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003430 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003431 0, /* tp_print */
3432 0, /* tp_getattr */
3433 0, /* tp_setattr */
3434 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003435 (reprfunc)time_repr, /* tp_repr */
3436 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003437 0, /* tp_as_sequence */
3438 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003439 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003440 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003441 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003442 PyObject_GenericGetAttr, /* tp_getattro */
3443 0, /* tp_setattro */
3444 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003445 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003446 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003447 0, /* tp_traverse */
3448 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003449 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003450 0, /* tp_weaklistoffset */
3451 0, /* tp_iter */
3452 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003453 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003454 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003455 time_getset, /* tp_getset */
3456 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003457 0, /* tp_dict */
3458 0, /* tp_descr_get */
3459 0, /* tp_descr_set */
3460 0, /* tp_dictoffset */
3461 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003462 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003463 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003464 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003465};
3466
3467/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003468 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003469 */
3470
Tim Petersa9bc1682003-01-11 03:39:11 +00003471/* Accessor properties. Properties for day, month, and year are inherited
3472 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003473 */
3474
3475static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003476datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003477{
Tim Petersa9bc1682003-01-11 03:39:11 +00003478 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003479}
3480
Tim Petersa9bc1682003-01-11 03:39:11 +00003481static PyObject *
3482datetime_minute(PyDateTime_DateTime *self, void *unused)
3483{
3484 return PyInt_FromLong(DATE_GET_MINUTE(self));
3485}
3486
3487static PyObject *
3488datetime_second(PyDateTime_DateTime *self, void *unused)
3489{
3490 return PyInt_FromLong(DATE_GET_SECOND(self));
3491}
3492
3493static PyObject *
3494datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3495{
3496 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3497}
3498
3499static PyObject *
3500datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3501{
3502 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3503 Py_INCREF(result);
3504 return result;
3505}
3506
3507static PyGetSetDef datetime_getset[] = {
3508 {"hour", (getter)datetime_hour},
3509 {"minute", (getter)datetime_minute},
3510 {"second", (getter)datetime_second},
3511 {"microsecond", (getter)datetime_microsecond},
3512 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003513 {NULL}
3514};
3515
3516/*
3517 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003518 */
3519
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003520static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003521 "year", "month", "day", "hour", "minute", "second",
3522 "microsecond", "tzinfo", NULL
3523};
3524
Tim Peters2a799bf2002-12-16 20:18:38 +00003525static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003526datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003527{
3528 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003529 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003530 int year;
3531 int month;
3532 int day;
3533 int hour = 0;
3534 int minute = 0;
3535 int second = 0;
3536 int usecond = 0;
3537 PyObject *tzinfo = Py_None;
3538
Guido van Rossum177e41a2003-01-30 22:06:23 +00003539 /* Check for invocation from pickle with __getstate__ state */
3540 if (PyTuple_GET_SIZE(args) >= 1 &&
3541 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003542 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003543 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3544 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003545 {
Tim Peters70533e22003-02-01 04:40:04 +00003546 PyDateTime_DateTime *me;
3547 char aware;
3548
3549 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003550 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003551 if (check_tzinfo_subclass(tzinfo) < 0) {
3552 PyErr_SetString(PyExc_TypeError, "bad "
3553 "tzinfo state arg");
3554 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003555 }
3556 }
Tim Peters70533e22003-02-01 04:40:04 +00003557 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003558 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003559 if (me != NULL) {
3560 char *pdata = PyString_AS_STRING(state);
3561
3562 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3563 me->hashcode = -1;
3564 me->hastzinfo = aware;
3565 if (aware) {
3566 Py_INCREF(tzinfo);
3567 me->tzinfo = tzinfo;
3568 }
3569 }
3570 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003571 }
3572
Tim Petersa9bc1682003-01-11 03:39:11 +00003573 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003574 &year, &month, &day, &hour, &minute,
3575 &second, &usecond, &tzinfo)) {
3576 if (check_date_args(year, month, day) < 0)
3577 return NULL;
3578 if (check_time_args(hour, minute, second, usecond) < 0)
3579 return NULL;
3580 if (check_tzinfo_subclass(tzinfo) < 0)
3581 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003582 self = new_datetime_ex(year, month, day,
3583 hour, minute, second, usecond,
3584 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003585 }
3586 return self;
3587}
3588
Tim Petersa9bc1682003-01-11 03:39:11 +00003589/* TM_FUNC is the shared type of localtime() and gmtime(). */
3590typedef struct tm *(*TM_FUNC)(const time_t *timer);
3591
3592/* Internal helper.
3593 * Build datetime from a time_t and a distinct count of microseconds.
3594 * Pass localtime or gmtime for f, to control the interpretation of timet.
3595 */
3596static PyObject *
3597datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3598 PyObject *tzinfo)
3599{
3600 struct tm *tm;
3601 PyObject *result = NULL;
3602
3603 tm = f(&timet);
3604 if (tm) {
3605 /* The platform localtime/gmtime may insert leap seconds,
3606 * indicated by tm->tm_sec > 59. We don't care about them,
3607 * except to the extent that passing them on to the datetime
3608 * constructor would raise ValueError for a reason that
3609 * made no sense to the user.
3610 */
3611 if (tm->tm_sec > 59)
3612 tm->tm_sec = 59;
3613 result = PyObject_CallFunction(cls, "iiiiiiiO",
3614 tm->tm_year + 1900,
3615 tm->tm_mon + 1,
3616 tm->tm_mday,
3617 tm->tm_hour,
3618 tm->tm_min,
3619 tm->tm_sec,
3620 us,
3621 tzinfo);
3622 }
3623 else
3624 PyErr_SetString(PyExc_ValueError,
3625 "timestamp out of range for "
3626 "platform localtime()/gmtime() function");
3627 return result;
3628}
3629
3630/* Internal helper.
3631 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3632 * to control the interpretation of the timestamp. Since a double doesn't
3633 * have enough bits to cover a datetime's full range of precision, it's
3634 * better to call datetime_from_timet_and_us provided you have a way
3635 * to get that much precision (e.g., C time() isn't good enough).
3636 */
3637static PyObject *
3638datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3639 PyObject *tzinfo)
3640{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003641 time_t timet;
3642 double fraction;
3643 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003644
Tim Peters1b6f7a92004-06-20 02:50:16 +00003645 timet = _PyTime_DoubleToTimet(timestamp);
3646 if (timet == (time_t)-1 && PyErr_Occurred())
3647 return NULL;
3648 fraction = timestamp - (double)timet;
3649 us = (int)round_to_long(fraction * 1e6);
Thomas Wouters477c8d52006-05-27 19:21:47 +00003650 /* If timestamp is less than one microsecond smaller than a
3651 * full second, round up. Otherwise, ValueErrors are raised
3652 * for some floats. */
3653 if (us == 1000000) {
3654 timet += 1;
3655 us = 0;
3656 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003657 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3658}
3659
3660/* Internal helper.
3661 * Build most accurate possible datetime for current time. Pass localtime or
3662 * gmtime for f as appropriate.
3663 */
3664static PyObject *
3665datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3666{
3667#ifdef HAVE_GETTIMEOFDAY
3668 struct timeval t;
3669
3670#ifdef GETTIMEOFDAY_NO_TZ
3671 gettimeofday(&t);
3672#else
3673 gettimeofday(&t, (struct timezone *)NULL);
3674#endif
3675 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3676 tzinfo);
3677
3678#else /* ! HAVE_GETTIMEOFDAY */
3679 /* No flavor of gettimeofday exists on this platform. Python's
3680 * time.time() does a lot of other platform tricks to get the
3681 * best time it can on the platform, and we're not going to do
3682 * better than that (if we could, the better code would belong
3683 * in time.time()!) We're limited by the precision of a double,
3684 * though.
3685 */
3686 PyObject *time;
3687 double dtime;
3688
3689 time = time_time();
3690 if (time == NULL)
3691 return NULL;
3692 dtime = PyFloat_AsDouble(time);
3693 Py_DECREF(time);
3694 if (dtime == -1.0 && PyErr_Occurred())
3695 return NULL;
3696 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3697#endif /* ! HAVE_GETTIMEOFDAY */
3698}
3699
Tim Peters2a799bf2002-12-16 20:18:38 +00003700/* Return best possible local time -- this isn't constrained by the
3701 * precision of a timestamp.
3702 */
3703static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003704datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003705{
Tim Peters10cadce2003-01-23 19:58:02 +00003706 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003707 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003708 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003709
Tim Peters10cadce2003-01-23 19:58:02 +00003710 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3711 &tzinfo))
3712 return NULL;
3713 if (check_tzinfo_subclass(tzinfo) < 0)
3714 return NULL;
3715
3716 self = datetime_best_possible(cls,
3717 tzinfo == Py_None ? localtime : gmtime,
3718 tzinfo);
3719 if (self != NULL && tzinfo != Py_None) {
3720 /* Convert UTC to tzinfo's zone. */
3721 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003722 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003723 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003724 }
3725 return self;
3726}
3727
Tim Petersa9bc1682003-01-11 03:39:11 +00003728/* Return best possible UTC time -- this isn't constrained by the
3729 * precision of a timestamp.
3730 */
3731static PyObject *
3732datetime_utcnow(PyObject *cls, PyObject *dummy)
3733{
3734 return datetime_best_possible(cls, gmtime, Py_None);
3735}
3736
Tim Peters2a799bf2002-12-16 20:18:38 +00003737/* Return new local datetime from timestamp (Python timestamp -- a double). */
3738static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003739datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003740{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003741 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003742 double timestamp;
3743 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003744 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003745
Tim Peters2a44a8d2003-01-23 20:53:10 +00003746 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3747 keywords, &timestamp, &tzinfo))
3748 return NULL;
3749 if (check_tzinfo_subclass(tzinfo) < 0)
3750 return NULL;
3751
3752 self = datetime_from_timestamp(cls,
3753 tzinfo == Py_None ? localtime : gmtime,
3754 timestamp,
3755 tzinfo);
3756 if (self != NULL && tzinfo != Py_None) {
3757 /* Convert UTC to tzinfo's zone. */
3758 PyObject *temp = self;
3759 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3760 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003761 }
3762 return self;
3763}
3764
Tim Petersa9bc1682003-01-11 03:39:11 +00003765/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3766static PyObject *
3767datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3768{
3769 double timestamp;
3770 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003771
Tim Petersa9bc1682003-01-11 03:39:11 +00003772 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3773 result = datetime_from_timestamp(cls, gmtime, timestamp,
3774 Py_None);
3775 return result;
3776}
3777
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003778/* Return new datetime from time.strptime(). */
3779static PyObject *
3780datetime_strptime(PyObject *cls, PyObject *args)
3781{
3782 PyObject *result = NULL, *obj, *module;
3783 const char *string, *format;
3784
3785 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3786 return NULL;
3787
3788 if ((module = PyImport_ImportModule("time")) == NULL)
3789 return NULL;
3790 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3791 Py_DECREF(module);
3792
3793 if (obj != NULL) {
3794 int i, good_timetuple = 1;
3795 long int ia[6];
3796 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3797 for (i=0; i < 6; i++) {
3798 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003799 if (p == NULL) {
3800 Py_DECREF(obj);
3801 return NULL;
3802 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003803 if (PyInt_Check(p))
3804 ia[i] = PyInt_AsLong(p);
3805 else
3806 good_timetuple = 0;
3807 Py_DECREF(p);
3808 }
3809 else
3810 good_timetuple = 0;
3811 if (good_timetuple)
3812 result = PyObject_CallFunction(cls, "iiiiii",
3813 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3814 else
3815 PyErr_SetString(PyExc_ValueError,
3816 "unexpected value from time.strptime");
3817 Py_DECREF(obj);
3818 }
3819 return result;
3820}
3821
Tim Petersa9bc1682003-01-11 03:39:11 +00003822/* Return new datetime from date/datetime and time arguments. */
3823static PyObject *
3824datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3825{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003826 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003827 PyObject *date;
3828 PyObject *time;
3829 PyObject *result = NULL;
3830
3831 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3832 &PyDateTime_DateType, &date,
3833 &PyDateTime_TimeType, &time)) {
3834 PyObject *tzinfo = Py_None;
3835
3836 if (HASTZINFO(time))
3837 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3838 result = PyObject_CallFunction(cls, "iiiiiiiO",
3839 GET_YEAR(date),
3840 GET_MONTH(date),
3841 GET_DAY(date),
3842 TIME_GET_HOUR(time),
3843 TIME_GET_MINUTE(time),
3844 TIME_GET_SECOND(time),
3845 TIME_GET_MICROSECOND(time),
3846 tzinfo);
3847 }
3848 return result;
3849}
Tim Peters2a799bf2002-12-16 20:18:38 +00003850
3851/*
3852 * Destructor.
3853 */
3854
3855static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003856datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003857{
Tim Petersa9bc1682003-01-11 03:39:11 +00003858 if (HASTZINFO(self)) {
3859 Py_XDECREF(self->tzinfo);
3860 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003861 self->ob_type->tp_free((PyObject *)self);
3862}
3863
3864/*
3865 * Indirect access to tzinfo methods.
3866 */
3867
Tim Peters2a799bf2002-12-16 20:18:38 +00003868/* These are all METH_NOARGS, so don't need to check the arglist. */
3869static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003870datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3871 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3872 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003873}
3874
3875static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003876datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3877 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3878 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003879}
3880
3881static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003882datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3883 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3884 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003885}
3886
3887/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003888 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003889 */
3890
Tim Petersa9bc1682003-01-11 03:39:11 +00003891/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3892 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003893 */
3894static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003895add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3896 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003897{
Tim Petersa9bc1682003-01-11 03:39:11 +00003898 /* Note that the C-level additions can't overflow, because of
3899 * invariant bounds on the member values.
3900 */
3901 int year = GET_YEAR(date);
3902 int month = GET_MONTH(date);
3903 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3904 int hour = DATE_GET_HOUR(date);
3905 int minute = DATE_GET_MINUTE(date);
3906 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3907 int microsecond = DATE_GET_MICROSECOND(date) +
3908 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003909
Tim Petersa9bc1682003-01-11 03:39:11 +00003910 assert(factor == 1 || factor == -1);
3911 if (normalize_datetime(&year, &month, &day,
3912 &hour, &minute, &second, &microsecond) < 0)
3913 return NULL;
3914 else
3915 return new_datetime(year, month, day,
3916 hour, minute, second, microsecond,
3917 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003918}
3919
3920static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003921datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003922{
Tim Petersa9bc1682003-01-11 03:39:11 +00003923 if (PyDateTime_Check(left)) {
3924 /* datetime + ??? */
3925 if (PyDelta_Check(right))
3926 /* datetime + delta */
3927 return add_datetime_timedelta(
3928 (PyDateTime_DateTime *)left,
3929 (PyDateTime_Delta *)right,
3930 1);
3931 }
3932 else if (PyDelta_Check(left)) {
3933 /* delta + datetime */
3934 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3935 (PyDateTime_Delta *) left,
3936 1);
3937 }
3938 Py_INCREF(Py_NotImplemented);
3939 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003940}
3941
3942static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003943datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003944{
3945 PyObject *result = Py_NotImplemented;
3946
3947 if (PyDateTime_Check(left)) {
3948 /* datetime - ??? */
3949 if (PyDateTime_Check(right)) {
3950 /* datetime - datetime */
3951 naivety n1, n2;
3952 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003953 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003954
Tim Peterse39a80c2002-12-30 21:28:52 +00003955 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3956 right, &offset2, &n2,
3957 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003958 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003959 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003960 if (n1 != n2) {
3961 PyErr_SetString(PyExc_TypeError,
3962 "can't subtract offset-naive and "
3963 "offset-aware datetimes");
3964 return NULL;
3965 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003966 delta_d = ymd_to_ord(GET_YEAR(left),
3967 GET_MONTH(left),
3968 GET_DAY(left)) -
3969 ymd_to_ord(GET_YEAR(right),
3970 GET_MONTH(right),
3971 GET_DAY(right));
3972 /* These can't overflow, since the values are
3973 * normalized. At most this gives the number of
3974 * seconds in one day.
3975 */
3976 delta_s = (DATE_GET_HOUR(left) -
3977 DATE_GET_HOUR(right)) * 3600 +
3978 (DATE_GET_MINUTE(left) -
3979 DATE_GET_MINUTE(right)) * 60 +
3980 (DATE_GET_SECOND(left) -
3981 DATE_GET_SECOND(right));
3982 delta_us = DATE_GET_MICROSECOND(left) -
3983 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003984 /* (left - offset1) - (right - offset2) =
3985 * (left - right) + (offset2 - offset1)
3986 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003987 delta_s += (offset2 - offset1) * 60;
3988 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003989 }
3990 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003991 /* datetime - delta */
3992 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003993 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00003994 (PyDateTime_Delta *)right,
3995 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003996 }
3997 }
3998
3999 if (result == Py_NotImplemented)
4000 Py_INCREF(result);
4001 return result;
4002}
4003
4004/* Various ways to turn a datetime into a string. */
4005
4006static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004007datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004008{
Tim Petersa9bc1682003-01-11 03:39:11 +00004009 char buffer[1000];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004010 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004011 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004012
Tim Petersa9bc1682003-01-11 03:39:11 +00004013 if (DATE_GET_MICROSECOND(self)) {
4014 PyOS_snprintf(buffer, sizeof(buffer),
4015 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004016 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004017 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4018 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4019 DATE_GET_SECOND(self),
4020 DATE_GET_MICROSECOND(self));
4021 }
4022 else if (DATE_GET_SECOND(self)) {
4023 PyOS_snprintf(buffer, sizeof(buffer),
4024 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004025 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004026 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4027 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4028 DATE_GET_SECOND(self));
4029 }
4030 else {
4031 PyOS_snprintf(buffer, sizeof(buffer),
4032 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004033 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004034 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4035 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4036 }
4037 baserepr = PyString_FromString(buffer);
4038 if (baserepr == NULL || ! HASTZINFO(self))
4039 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004040 return append_keyword_tzinfo(baserepr, self->tzinfo);
4041}
4042
Tim Petersa9bc1682003-01-11 03:39:11 +00004043static PyObject *
4044datetime_str(PyDateTime_DateTime *self)
4045{
4046 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4047}
Tim Peters2a799bf2002-12-16 20:18:38 +00004048
4049static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004050datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004051{
Tim Petersa9bc1682003-01-11 03:39:11 +00004052 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004053 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004054 char buffer[100];
4055 char *cp;
4056 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004057
Tim Petersa9bc1682003-01-11 03:39:11 +00004058 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4059 &sep))
4060 return NULL;
4061 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4062 assert(cp != NULL);
4063 *cp++ = sep;
4064 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4065 result = PyString_FromString(buffer);
4066 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004067 return result;
4068
4069 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004070 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004071 (PyObject *)self) < 0) {
4072 Py_DECREF(result);
4073 return NULL;
4074 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004075 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004076 return result;
4077}
4078
Tim Petersa9bc1682003-01-11 03:39:11 +00004079static PyObject *
4080datetime_ctime(PyDateTime_DateTime *self)
4081{
4082 return format_ctime((PyDateTime_Date *)self,
4083 DATE_GET_HOUR(self),
4084 DATE_GET_MINUTE(self),
4085 DATE_GET_SECOND(self));
4086}
4087
Tim Peters2a799bf2002-12-16 20:18:38 +00004088/* Miscellaneous methods. */
4089
Tim Petersa9bc1682003-01-11 03:39:11 +00004090static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004091datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004092{
4093 int diff;
4094 naivety n1, n2;
4095 int offset1, offset2;
4096
4097 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004098 if (PyDate_Check(other)) {
4099 /* Prevent invocation of date_richcompare. We want to
4100 return NotImplemented here to give the other object
4101 a chance. But since DateTime is a subclass of
4102 Date, if the other object is a Date, it would
4103 compute an ordering based on the date part alone,
4104 and we don't want that. So force unequal or
4105 uncomparable here in that case. */
4106 if (op == Py_EQ)
4107 Py_RETURN_FALSE;
4108 if (op == Py_NE)
4109 Py_RETURN_TRUE;
4110 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004111 }
Guido van Rossum19960592006-08-24 17:29:38 +00004112 Py_INCREF(Py_NotImplemented);
4113 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004114 }
4115
Guido van Rossum19960592006-08-24 17:29:38 +00004116 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4117 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004118 return NULL;
4119 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4120 /* If they're both naive, or both aware and have the same offsets,
4121 * we get off cheap. Note that if they're both naive, offset1 ==
4122 * offset2 == 0 at this point.
4123 */
4124 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004125 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4126 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004127 _PyDateTime_DATETIME_DATASIZE);
4128 return diff_to_bool(diff, op);
4129 }
4130
4131 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4132 PyDateTime_Delta *delta;
4133
4134 assert(offset1 != offset2); /* else last "if" handled it */
4135 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4136 other);
4137 if (delta == NULL)
4138 return NULL;
4139 diff = GET_TD_DAYS(delta);
4140 if (diff == 0)
4141 diff = GET_TD_SECONDS(delta) |
4142 GET_TD_MICROSECONDS(delta);
4143 Py_DECREF(delta);
4144 return diff_to_bool(diff, op);
4145 }
4146
4147 assert(n1 != n2);
4148 PyErr_SetString(PyExc_TypeError,
4149 "can't compare offset-naive and "
4150 "offset-aware datetimes");
4151 return NULL;
4152}
4153
4154static long
4155datetime_hash(PyDateTime_DateTime *self)
4156{
4157 if (self->hashcode == -1) {
4158 naivety n;
4159 int offset;
4160 PyObject *temp;
4161
4162 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4163 &offset);
4164 assert(n != OFFSET_UNKNOWN);
4165 if (n == OFFSET_ERROR)
4166 return -1;
4167
4168 /* Reduce this to a hash of another object. */
4169 if (n == OFFSET_NAIVE)
4170 temp = PyString_FromStringAndSize(
4171 (char *)self->data,
4172 _PyDateTime_DATETIME_DATASIZE);
4173 else {
4174 int days;
4175 int seconds;
4176
4177 assert(n == OFFSET_AWARE);
4178 assert(HASTZINFO(self));
4179 days = ymd_to_ord(GET_YEAR(self),
4180 GET_MONTH(self),
4181 GET_DAY(self));
4182 seconds = DATE_GET_HOUR(self) * 3600 +
4183 (DATE_GET_MINUTE(self) - offset) * 60 +
4184 DATE_GET_SECOND(self);
4185 temp = new_delta(days,
4186 seconds,
4187 DATE_GET_MICROSECOND(self),
4188 1);
4189 }
4190 if (temp != NULL) {
4191 self->hashcode = PyObject_Hash(temp);
4192 Py_DECREF(temp);
4193 }
4194 }
4195 return self->hashcode;
4196}
Tim Peters2a799bf2002-12-16 20:18:38 +00004197
4198static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004199datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004200{
4201 PyObject *clone;
4202 PyObject *tuple;
4203 int y = GET_YEAR(self);
4204 int m = GET_MONTH(self);
4205 int d = GET_DAY(self);
4206 int hh = DATE_GET_HOUR(self);
4207 int mm = DATE_GET_MINUTE(self);
4208 int ss = DATE_GET_SECOND(self);
4209 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004210 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004211
4212 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004213 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004214 &y, &m, &d, &hh, &mm, &ss, &us,
4215 &tzinfo))
4216 return NULL;
4217 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4218 if (tuple == NULL)
4219 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004220 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004221 Py_DECREF(tuple);
4222 return clone;
4223}
4224
4225static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004226datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004227{
Tim Peters52dcce22003-01-23 16:36:11 +00004228 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004229 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004230 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004231
Tim Peters80475bb2002-12-25 07:40:55 +00004232 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004233 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004234
Tim Peters52dcce22003-01-23 16:36:11 +00004235 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4236 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004237 return NULL;
4238
Tim Peters52dcce22003-01-23 16:36:11 +00004239 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4240 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004241
Tim Peters52dcce22003-01-23 16:36:11 +00004242 /* Conversion to self's own time zone is a NOP. */
4243 if (self->tzinfo == tzinfo) {
4244 Py_INCREF(self);
4245 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004246 }
Tim Peters521fc152002-12-31 17:36:56 +00004247
Tim Peters52dcce22003-01-23 16:36:11 +00004248 /* Convert self to UTC. */
4249 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4250 if (offset == -1 && PyErr_Occurred())
4251 return NULL;
4252 if (none)
4253 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004254
Tim Peters52dcce22003-01-23 16:36:11 +00004255 y = GET_YEAR(self);
4256 m = GET_MONTH(self);
4257 d = GET_DAY(self);
4258 hh = DATE_GET_HOUR(self);
4259 mm = DATE_GET_MINUTE(self);
4260 ss = DATE_GET_SECOND(self);
4261 us = DATE_GET_MICROSECOND(self);
4262
4263 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004264 if ((mm < 0 || mm >= 60) &&
4265 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004266 return NULL;
4267
4268 /* Attach new tzinfo and let fromutc() do the rest. */
4269 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4270 if (result != NULL) {
4271 PyObject *temp = result;
4272
4273 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4274 Py_DECREF(temp);
4275 }
Tim Petersadf64202003-01-04 06:03:15 +00004276 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004277
Tim Peters52dcce22003-01-23 16:36:11 +00004278NeedAware:
4279 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4280 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004281 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004282}
4283
4284static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004285datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004286{
4287 int dstflag = -1;
4288
Tim Petersa9bc1682003-01-11 03:39:11 +00004289 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004290 int none;
4291
4292 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4293 if (dstflag == -1 && PyErr_Occurred())
4294 return NULL;
4295
4296 if (none)
4297 dstflag = -1;
4298 else if (dstflag != 0)
4299 dstflag = 1;
4300
4301 }
4302 return build_struct_time(GET_YEAR(self),
4303 GET_MONTH(self),
4304 GET_DAY(self),
4305 DATE_GET_HOUR(self),
4306 DATE_GET_MINUTE(self),
4307 DATE_GET_SECOND(self),
4308 dstflag);
4309}
4310
4311static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004312datetime_getdate(PyDateTime_DateTime *self)
4313{
4314 return new_date(GET_YEAR(self),
4315 GET_MONTH(self),
4316 GET_DAY(self));
4317}
4318
4319static PyObject *
4320datetime_gettime(PyDateTime_DateTime *self)
4321{
4322 return new_time(DATE_GET_HOUR(self),
4323 DATE_GET_MINUTE(self),
4324 DATE_GET_SECOND(self),
4325 DATE_GET_MICROSECOND(self),
4326 Py_None);
4327}
4328
4329static PyObject *
4330datetime_gettimetz(PyDateTime_DateTime *self)
4331{
4332 return new_time(DATE_GET_HOUR(self),
4333 DATE_GET_MINUTE(self),
4334 DATE_GET_SECOND(self),
4335 DATE_GET_MICROSECOND(self),
4336 HASTZINFO(self) ? self->tzinfo : Py_None);
4337}
4338
4339static PyObject *
4340datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004341{
4342 int y = GET_YEAR(self);
4343 int m = GET_MONTH(self);
4344 int d = GET_DAY(self);
4345 int hh = DATE_GET_HOUR(self);
4346 int mm = DATE_GET_MINUTE(self);
4347 int ss = DATE_GET_SECOND(self);
4348 int us = 0; /* microseconds are ignored in a timetuple */
4349 int offset = 0;
4350
Tim Petersa9bc1682003-01-11 03:39:11 +00004351 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004352 int none;
4353
4354 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4355 if (offset == -1 && PyErr_Occurred())
4356 return NULL;
4357 }
4358 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4359 * 0 in a UTC timetuple regardless of what dst() says.
4360 */
4361 if (offset) {
4362 /* Subtract offset minutes & normalize. */
4363 int stat;
4364
4365 mm -= offset;
4366 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4367 if (stat < 0) {
4368 /* At the edges, it's possible we overflowed
4369 * beyond MINYEAR or MAXYEAR.
4370 */
4371 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4372 PyErr_Clear();
4373 else
4374 return NULL;
4375 }
4376 }
4377 return build_struct_time(y, m, d, hh, mm, ss, 0);
4378}
4379
Tim Peters371935f2003-02-01 01:52:50 +00004380/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004381
Tim Petersa9bc1682003-01-11 03:39:11 +00004382/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004383 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4384 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004385 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004386 */
4387static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004388datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004389{
4390 PyObject *basestate;
4391 PyObject *result = NULL;
4392
Tim Peters33e0f382003-01-10 02:05:14 +00004393 basestate = PyString_FromStringAndSize((char *)self->data,
4394 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004395 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004396 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004397 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004398 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004399 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004400 Py_DECREF(basestate);
4401 }
4402 return result;
4403}
4404
4405static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004406datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004407{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004408 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004409}
4410
Tim Petersa9bc1682003-01-11 03:39:11 +00004411static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004412
Tim Peters2a799bf2002-12-16 20:18:38 +00004413 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004414
Tim Petersa9bc1682003-01-11 03:39:11 +00004415 {"now", (PyCFunction)datetime_now,
Tim Peters2a799bf2002-12-16 20:18:38 +00004416 METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004417 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004418
Tim Petersa9bc1682003-01-11 03:39:11 +00004419 {"utcnow", (PyCFunction)datetime_utcnow,
4420 METH_NOARGS | METH_CLASS,
4421 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4422
4423 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Tim Peters2a799bf2002-12-16 20:18:38 +00004424 METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004425 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004426
Tim Petersa9bc1682003-01-11 03:39:11 +00004427 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4428 METH_VARARGS | METH_CLASS,
4429 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4430 "(like time.time()).")},
4431
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004432 {"strptime", (PyCFunction)datetime_strptime,
4433 METH_VARARGS | METH_CLASS,
4434 PyDoc_STR("string, format -> new datetime parsed from a string "
4435 "(like time.strptime()).")},
4436
Tim Petersa9bc1682003-01-11 03:39:11 +00004437 {"combine", (PyCFunction)datetime_combine,
4438 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4439 PyDoc_STR("date, time -> datetime with same date and time fields")},
4440
Tim Peters2a799bf2002-12-16 20:18:38 +00004441 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004442
Tim Petersa9bc1682003-01-11 03:39:11 +00004443 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4444 PyDoc_STR("Return date object with same year, month and day.")},
4445
4446 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4447 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4448
4449 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4450 PyDoc_STR("Return time object with same time and tzinfo.")},
4451
4452 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4453 PyDoc_STR("Return ctime() style string.")},
4454
4455 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004456 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4457
Tim Petersa9bc1682003-01-11 03:39:11 +00004458 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004459 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4460
Tim Petersa9bc1682003-01-11 03:39:11 +00004461 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004462 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4463 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4464 "sep is used to separate the year from the time, and "
4465 "defaults to 'T'.")},
4466
Tim Petersa9bc1682003-01-11 03:39:11 +00004467 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004468 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4469
Tim Petersa9bc1682003-01-11 03:39:11 +00004470 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004471 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4472
Tim Petersa9bc1682003-01-11 03:39:11 +00004473 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004474 PyDoc_STR("Return self.tzinfo.dst(self).")},
4475
Tim Petersa9bc1682003-01-11 03:39:11 +00004476 {"replace", (PyCFunction)datetime_replace, METH_KEYWORDS,
4477 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004478
Tim Petersa9bc1682003-01-11 03:39:11 +00004479 {"astimezone", (PyCFunction)datetime_astimezone, METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004480 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4481
Guido van Rossum177e41a2003-01-30 22:06:23 +00004482 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4483 PyDoc_STR("__reduce__() -> (cls, state)")},
4484
Tim Peters2a799bf2002-12-16 20:18:38 +00004485 {NULL, NULL}
4486};
4487
Tim Petersa9bc1682003-01-11 03:39:11 +00004488static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004489PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4490\n\
4491The year, month and day arguments are required. tzinfo may be None, or an\n\
4492instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004493
Tim Petersa9bc1682003-01-11 03:39:11 +00004494static PyNumberMethods datetime_as_number = {
4495 datetime_add, /* nb_add */
4496 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004497 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004498 0, /* nb_remainder */
4499 0, /* nb_divmod */
4500 0, /* nb_power */
4501 0, /* nb_negative */
4502 0, /* nb_positive */
4503 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004504 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004505};
4506
Neal Norwitz227b5332006-03-22 09:28:35 +00004507static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004508 PyObject_HEAD_INIT(NULL)
4509 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004510 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004511 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004512 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004513 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004514 0, /* tp_print */
4515 0, /* tp_getattr */
4516 0, /* tp_setattr */
4517 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004518 (reprfunc)datetime_repr, /* tp_repr */
4519 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004520 0, /* tp_as_sequence */
4521 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004522 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004523 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004524 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004525 PyObject_GenericGetAttr, /* tp_getattro */
4526 0, /* tp_setattro */
4527 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004528 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004529 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004530 0, /* tp_traverse */
4531 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004532 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004533 0, /* tp_weaklistoffset */
4534 0, /* tp_iter */
4535 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004536 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004537 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004538 datetime_getset, /* tp_getset */
4539 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004540 0, /* tp_dict */
4541 0, /* tp_descr_get */
4542 0, /* tp_descr_set */
4543 0, /* tp_dictoffset */
4544 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004545 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004546 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004547 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004548};
4549
4550/* ---------------------------------------------------------------------------
4551 * Module methods and initialization.
4552 */
4553
4554static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004555 {NULL, NULL}
4556};
4557
Tim Peters9ddf40b2004-06-20 22:41:32 +00004558/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4559 * datetime.h.
4560 */
4561static PyDateTime_CAPI CAPI = {
4562 &PyDateTime_DateType,
4563 &PyDateTime_DateTimeType,
4564 &PyDateTime_TimeType,
4565 &PyDateTime_DeltaType,
4566 &PyDateTime_TZInfoType,
4567 new_date_ex,
4568 new_datetime_ex,
4569 new_time_ex,
4570 new_delta_ex,
4571 datetime_fromtimestamp,
4572 date_fromtimestamp
4573};
4574
4575
Tim Peters2a799bf2002-12-16 20:18:38 +00004576PyMODINIT_FUNC
4577initdatetime(void)
4578{
4579 PyObject *m; /* a module object */
4580 PyObject *d; /* its dict */
4581 PyObject *x;
4582
Tim Peters2a799bf2002-12-16 20:18:38 +00004583 m = Py_InitModule3("datetime", module_methods,
4584 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004585 if (m == NULL)
4586 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004587
4588 if (PyType_Ready(&PyDateTime_DateType) < 0)
4589 return;
4590 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4591 return;
4592 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4593 return;
4594 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4595 return;
4596 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4597 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004598
Tim Peters2a799bf2002-12-16 20:18:38 +00004599 /* timedelta values */
4600 d = PyDateTime_DeltaType.tp_dict;
4601
Tim Peters2a799bf2002-12-16 20:18:38 +00004602 x = new_delta(0, 0, 1, 0);
4603 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4604 return;
4605 Py_DECREF(x);
4606
4607 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4608 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4609 return;
4610 Py_DECREF(x);
4611
4612 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4613 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4614 return;
4615 Py_DECREF(x);
4616
4617 /* date values */
4618 d = PyDateTime_DateType.tp_dict;
4619
4620 x = new_date(1, 1, 1);
4621 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4622 return;
4623 Py_DECREF(x);
4624
4625 x = new_date(MAXYEAR, 12, 31);
4626 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4627 return;
4628 Py_DECREF(x);
4629
4630 x = new_delta(1, 0, 0, 0);
4631 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4632 return;
4633 Py_DECREF(x);
4634
Tim Peters37f39822003-01-10 03:49:02 +00004635 /* time values */
4636 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004637
Tim Peters37f39822003-01-10 03:49:02 +00004638 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004639 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4640 return;
4641 Py_DECREF(x);
4642
Tim Peters37f39822003-01-10 03:49:02 +00004643 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004644 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4645 return;
4646 Py_DECREF(x);
4647
4648 x = new_delta(0, 0, 1, 0);
4649 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4650 return;
4651 Py_DECREF(x);
4652
Tim Petersa9bc1682003-01-11 03:39:11 +00004653 /* datetime values */
4654 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004655
Tim Petersa9bc1682003-01-11 03:39:11 +00004656 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004657 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4658 return;
4659 Py_DECREF(x);
4660
Tim Petersa9bc1682003-01-11 03:39:11 +00004661 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004662 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4663 return;
4664 Py_DECREF(x);
4665
4666 x = new_delta(0, 0, 1, 0);
4667 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4668 return;
4669 Py_DECREF(x);
4670
Tim Peters2a799bf2002-12-16 20:18:38 +00004671 /* module initialization */
4672 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4673 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4674
4675 Py_INCREF(&PyDateTime_DateType);
4676 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4677
Tim Petersa9bc1682003-01-11 03:39:11 +00004678 Py_INCREF(&PyDateTime_DateTimeType);
4679 PyModule_AddObject(m, "datetime",
4680 (PyObject *)&PyDateTime_DateTimeType);
4681
4682 Py_INCREF(&PyDateTime_TimeType);
4683 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4684
Tim Peters2a799bf2002-12-16 20:18:38 +00004685 Py_INCREF(&PyDateTime_DeltaType);
4686 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4687
Tim Peters2a799bf2002-12-16 20:18:38 +00004688 Py_INCREF(&PyDateTime_TZInfoType);
4689 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4690
Tim Peters9ddf40b2004-06-20 22:41:32 +00004691 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4692 NULL);
4693 if (x == NULL)
4694 return;
4695 PyModule_AddObject(m, "datetime_CAPI", x);
4696
Tim Peters2a799bf2002-12-16 20:18:38 +00004697 /* A 4-year cycle has an extra leap day over what we'd get from
4698 * pasting together 4 single years.
4699 */
4700 assert(DI4Y == 4 * 365 + 1);
4701 assert(DI4Y == days_before_year(4+1));
4702
4703 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4704 * get from pasting together 4 100-year cycles.
4705 */
4706 assert(DI400Y == 4 * DI100Y + 1);
4707 assert(DI400Y == days_before_year(400+1));
4708
4709 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4710 * pasting together 25 4-year cycles.
4711 */
4712 assert(DI100Y == 25 * DI4Y - 1);
4713 assert(DI100Y == days_before_year(100+1));
4714
4715 us_per_us = PyInt_FromLong(1);
4716 us_per_ms = PyInt_FromLong(1000);
4717 us_per_second = PyInt_FromLong(1000000);
4718 us_per_minute = PyInt_FromLong(60000000);
4719 seconds_per_day = PyInt_FromLong(24 * 3600);
4720 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4721 us_per_minute == NULL || seconds_per_day == NULL)
4722 return;
4723
4724 /* The rest are too big for 32-bit ints, but even
4725 * us_per_week fits in 40 bits, so doubles should be exact.
4726 */
4727 us_per_hour = PyLong_FromDouble(3600000000.0);
4728 us_per_day = PyLong_FromDouble(86400000000.0);
4729 us_per_week = PyLong_FromDouble(604800000000.0);
4730 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4731 return;
4732}
Tim Petersf3615152003-01-01 21:51:37 +00004733
4734/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004735Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004736 x.n = x stripped of its timezone -- its naive time.
4737 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4738 return None
4739 x.d = x.dst(), and assuming that doesn't raise an exception or
4740 return None
4741 x.s = x's standard offset, x.o - x.d
4742
4743Now some derived rules, where k is a duration (timedelta).
4744
47451. x.o = x.s + x.d
4746 This follows from the definition of x.s.
4747
Tim Petersc5dc4da2003-01-02 17:55:03 +000047482. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004749 This is actually a requirement, an assumption we need to make about
4750 sane tzinfo classes.
4751
47523. The naive UTC time corresponding to x is x.n - x.o.
4753 This is again a requirement for a sane tzinfo class.
4754
47554. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004756 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004757
Tim Petersc5dc4da2003-01-02 17:55:03 +000047585. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004759 Again follows from how arithmetic is defined.
4760
Tim Peters8bb5ad22003-01-24 02:44:45 +00004761Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004762(meaning that the various tzinfo methods exist, and don't blow up or return
4763None when called).
4764
Tim Petersa9bc1682003-01-11 03:39:11 +00004765The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004766x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004767
4768By #3, we want
4769
Tim Peters8bb5ad22003-01-24 02:44:45 +00004770 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004771
4772The algorithm starts by attaching tz to x.n, and calling that y. So
4773x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4774becomes true; in effect, we want to solve [2] for k:
4775
Tim Peters8bb5ad22003-01-24 02:44:45 +00004776 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004777
4778By #1, this is the same as
4779
Tim Peters8bb5ad22003-01-24 02:44:45 +00004780 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004781
4782By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4783Substituting that into [3],
4784
Tim Peters8bb5ad22003-01-24 02:44:45 +00004785 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4786 k - (y+k).s - (y+k).d = 0; rearranging,
4787 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4788 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004789
Tim Peters8bb5ad22003-01-24 02:44:45 +00004790On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4791approximate k by ignoring the (y+k).d term at first. Note that k can't be
4792very large, since all offset-returning methods return a duration of magnitude
4793less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4794be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004795
4796In any case, the new value is
4797
Tim Peters8bb5ad22003-01-24 02:44:45 +00004798 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004799
Tim Peters8bb5ad22003-01-24 02:44:45 +00004800It's helpful to step back at look at [4] from a higher level: it's simply
4801mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004802
4803At this point, if
4804
Tim Peters8bb5ad22003-01-24 02:44:45 +00004805 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004806
4807we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004808at the start of daylight time. Picture US Eastern for concreteness. The wall
4809time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
Tim Peters8bb5ad22003-01-24 02:44:45 +00004810sense then. The docs ask that an Eastern tzinfo class consider such a time to
4811be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4812on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004813the only spelling that makes sense on the local wall clock.
4814
Tim Petersc5dc4da2003-01-02 17:55:03 +00004815In fact, if [5] holds at this point, we do have the standard-time spelling,
4816but that takes a bit of proof. We first prove a stronger result. What's the
4817difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004818
Tim Peters8bb5ad22003-01-24 02:44:45 +00004819 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004820
Tim Petersc5dc4da2003-01-02 17:55:03 +00004821Now
4822 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004823 (y + y.s).n = by #5
4824 y.n + y.s = since y.n = x.n
4825 x.n + y.s = since z and y are have the same tzinfo member,
4826 y.s = z.s by #2
4827 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004828
Tim Petersc5dc4da2003-01-02 17:55:03 +00004829Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004830
Tim Petersc5dc4da2003-01-02 17:55:03 +00004831 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004832 x.n - ((x.n + z.s) - z.o) = expanding
4833 x.n - x.n - z.s + z.o = cancelling
4834 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004835 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004836
Tim Petersc5dc4da2003-01-02 17:55:03 +00004837So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004838
Tim Petersc5dc4da2003-01-02 17:55:03 +00004839If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004840spelling we wanted in the endcase described above. We're done. Contrarily,
4841if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004842
Tim Petersc5dc4da2003-01-02 17:55:03 +00004843If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4844add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004845local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004846
Tim Petersc5dc4da2003-01-02 17:55:03 +00004847Let
Tim Petersf3615152003-01-01 21:51:37 +00004848
Tim Peters4fede1a2003-01-04 00:26:59 +00004849 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004850
Tim Peters4fede1a2003-01-04 00:26:59 +00004851and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004852
Tim Peters8bb5ad22003-01-24 02:44:45 +00004853 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004854
Tim Peters8bb5ad22003-01-24 02:44:45 +00004855If so, we're done. If not, the tzinfo class is insane, according to the
4856assumptions we've made. This also requires a bit of proof. As before, let's
4857compute the difference between the LHS and RHS of [8] (and skipping some of
4858the justifications for the kinds of substitutions we've done several times
4859already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004860
Tim Peters8bb5ad22003-01-24 02:44:45 +00004861 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4862 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4863 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4864 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4865 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004866 - z.o + z'.o = #1 twice
4867 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4868 z'.d - z.d
4869
4870So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
Tim Peters8bb5ad22003-01-24 02:44:45 +00004871we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4872return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004873
Tim Peters8bb5ad22003-01-24 02:44:45 +00004874How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4875a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4876would have to change the result dst() returns: we start in DST, and moving
4877a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004878
Tim Peters8bb5ad22003-01-24 02:44:45 +00004879There isn't a sane case where this can happen. The closest it gets is at
4880the end of DST, where there's an hour in UTC with no spelling in a hybrid
4881tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4882that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4883UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4884time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4885clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4886standard time. Since that's what the local clock *does*, we want to map both
4887UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004888in local time, but so it goes -- it's the way the local clock works.
4889
Tim Peters8bb5ad22003-01-24 02:44:45 +00004890When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4891so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4892z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
Tim Peters4fede1a2003-01-04 00:26:59 +00004893(correctly) concludes that z' is not UTC-equivalent to x.
4894
4895Because we know z.d said z was in daylight time (else [5] would have held and
4896we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004897and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004898return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4899but the reasoning doesn't depend on the example -- it depends on there being
4900two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004901z' must be in standard time, and is the spelling we want in this case.
4902
4903Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4904concerned (because it takes z' as being in standard time rather than the
4905daylight time we intend here), but returning it gives the real-life "local
4906clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4907tz.
4908
4909When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4910the 1:MM standard time spelling we want.
4911
4912So how can this break? One of the assumptions must be violated. Two
4913possibilities:
4914
49151) [2] effectively says that y.s is invariant across all y belong to a given
4916 time zone. This isn't true if, for political reasons or continental drift,
4917 a region decides to change its base offset from UTC.
4918
49192) There may be versions of "double daylight" time where the tail end of
4920 the analysis gives up a step too early. I haven't thought about that
4921 enough to say.
4922
4923In any case, it's clear that the default fromutc() is strong enough to handle
4924"almost all" time zones: so long as the standard offset is invariant, it
4925doesn't matter if daylight time transition points change from year to year, or
4926if daylight time is skipped in some years; it doesn't matter how large or
4927small dst() may get within its bounds; and it doesn't even matter if some
4928perverse time zone returns a negative dst()). So a breaking case must be
4929pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004930--------------------------------------------------------------------------- */