blob: 3757513d186edf20617ed07580bfe8fbd7a83316 [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));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001847 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001848
1849 dnum *= fracpart;
1850 fracpart = modf(dnum, &intpart);
1851 x = PyLong_FromDouble(intpart);
1852 if (x == NULL) {
1853 Py_DECREF(sum);
1854 return NULL;
1855 }
1856
1857 y = PyNumber_Add(sum, x);
1858 Py_DECREF(sum);
1859 Py_DECREF(x);
1860 *leftover += fracpart;
1861 return y;
1862 }
1863
1864 PyErr_Format(PyExc_TypeError,
1865 "unsupported type for timedelta %s component: %s",
1866 tag, num->ob_type->tp_name);
1867 return NULL;
1868}
1869
1870static PyObject *
1871delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1872{
1873 PyObject *self = NULL;
1874
1875 /* Argument objects. */
1876 PyObject *day = NULL;
1877 PyObject *second = NULL;
1878 PyObject *us = NULL;
1879 PyObject *ms = NULL;
1880 PyObject *minute = NULL;
1881 PyObject *hour = NULL;
1882 PyObject *week = NULL;
1883
1884 PyObject *x = NULL; /* running sum of microseconds */
1885 PyObject *y = NULL; /* temp sum of microseconds */
1886 double leftover_us = 0.0;
1887
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001888 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001889 "days", "seconds", "microseconds", "milliseconds",
1890 "minutes", "hours", "weeks", NULL
1891 };
1892
1893 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1894 keywords,
1895 &day, &second, &us,
1896 &ms, &minute, &hour, &week) == 0)
1897 goto Done;
1898
1899 x = PyInt_FromLong(0);
1900 if (x == NULL)
1901 goto Done;
1902
1903#define CLEANUP \
1904 Py_DECREF(x); \
1905 x = y; \
1906 if (x == NULL) \
1907 goto Done
1908
1909 if (us) {
1910 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1911 CLEANUP;
1912 }
1913 if (ms) {
1914 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1915 CLEANUP;
1916 }
1917 if (second) {
1918 y = accum("seconds", x, second, us_per_second, &leftover_us);
1919 CLEANUP;
1920 }
1921 if (minute) {
1922 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1923 CLEANUP;
1924 }
1925 if (hour) {
1926 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1927 CLEANUP;
1928 }
1929 if (day) {
1930 y = accum("days", x, day, us_per_day, &leftover_us);
1931 CLEANUP;
1932 }
1933 if (week) {
1934 y = accum("weeks", x, week, us_per_week, &leftover_us);
1935 CLEANUP;
1936 }
1937 if (leftover_us) {
1938 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001939 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001940 if (temp == NULL) {
1941 Py_DECREF(x);
1942 goto Done;
1943 }
1944 y = PyNumber_Add(x, temp);
1945 Py_DECREF(temp);
1946 CLEANUP;
1947 }
1948
Tim Petersb0c854d2003-05-17 15:57:00 +00001949 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001950 Py_DECREF(x);
1951Done:
1952 return self;
1953
1954#undef CLEANUP
1955}
1956
1957static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001958delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001959{
1960 return (GET_TD_DAYS(self) != 0
1961 || GET_TD_SECONDS(self) != 0
1962 || GET_TD_MICROSECONDS(self) != 0);
1963}
1964
1965static PyObject *
1966delta_repr(PyDateTime_Delta *self)
1967{
1968 if (GET_TD_MICROSECONDS(self) != 0)
1969 return PyString_FromFormat("%s(%d, %d, %d)",
1970 self->ob_type->tp_name,
1971 GET_TD_DAYS(self),
1972 GET_TD_SECONDS(self),
1973 GET_TD_MICROSECONDS(self));
1974 if (GET_TD_SECONDS(self) != 0)
1975 return PyString_FromFormat("%s(%d, %d)",
1976 self->ob_type->tp_name,
1977 GET_TD_DAYS(self),
1978 GET_TD_SECONDS(self));
1979
1980 return PyString_FromFormat("%s(%d)",
1981 self->ob_type->tp_name,
1982 GET_TD_DAYS(self));
1983}
1984
1985static PyObject *
1986delta_str(PyDateTime_Delta *self)
1987{
1988 int days = GET_TD_DAYS(self);
1989 int seconds = GET_TD_SECONDS(self);
1990 int us = GET_TD_MICROSECONDS(self);
1991 int hours;
1992 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00001993 char buf[100];
1994 char *pbuf = buf;
1995 size_t buflen = sizeof(buf);
1996 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001997
1998 minutes = divmod(seconds, 60, &seconds);
1999 hours = divmod(minutes, 60, &minutes);
2000
2001 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002002 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2003 (days == 1 || days == -1) ? "" : "s");
2004 if (n < 0 || (size_t)n >= buflen)
2005 goto Fail;
2006 pbuf += n;
2007 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002008 }
2009
Tim Petersba873472002-12-18 20:19:21 +00002010 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2011 hours, minutes, seconds);
2012 if (n < 0 || (size_t)n >= buflen)
2013 goto Fail;
2014 pbuf += n;
2015 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002016
2017 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002018 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2019 if (n < 0 || (size_t)n >= buflen)
2020 goto Fail;
2021 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002022 }
2023
Tim Petersba873472002-12-18 20:19:21 +00002024 return PyString_FromStringAndSize(buf, pbuf - buf);
2025
2026 Fail:
2027 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2028 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002029}
2030
Tim Peters371935f2003-02-01 01:52:50 +00002031/* Pickle support, a simple use of __reduce__. */
2032
Tim Petersb57f8f02003-02-01 02:54:15 +00002033/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002034static PyObject *
2035delta_getstate(PyDateTime_Delta *self)
2036{
2037 return Py_BuildValue("iii", GET_TD_DAYS(self),
2038 GET_TD_SECONDS(self),
2039 GET_TD_MICROSECONDS(self));
2040}
2041
Tim Peters2a799bf2002-12-16 20:18:38 +00002042static PyObject *
2043delta_reduce(PyDateTime_Delta* self)
2044{
Tim Peters8a60c222003-02-01 01:47:29 +00002045 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002046}
2047
2048#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2049
2050static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002051
Neal Norwitzdfb80862002-12-19 02:30:56 +00002052 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002053 PyDoc_STR("Number of days.")},
2054
Neal Norwitzdfb80862002-12-19 02:30:56 +00002055 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002056 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2057
Neal Norwitzdfb80862002-12-19 02:30:56 +00002058 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002059 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2060 {NULL}
2061};
2062
2063static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002064 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2065 PyDoc_STR("__reduce__() -> (cls, state)")},
2066
Tim Peters2a799bf2002-12-16 20:18:38 +00002067 {NULL, NULL},
2068};
2069
2070static char delta_doc[] =
2071PyDoc_STR("Difference between two datetime values.");
2072
2073static PyNumberMethods delta_as_number = {
2074 delta_add, /* nb_add */
2075 delta_subtract, /* nb_subtract */
2076 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002077 0, /* nb_remainder */
2078 0, /* nb_divmod */
2079 0, /* nb_power */
2080 (unaryfunc)delta_negative, /* nb_negative */
2081 (unaryfunc)delta_positive, /* nb_positive */
2082 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002083 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002084 0, /*nb_invert*/
2085 0, /*nb_lshift*/
2086 0, /*nb_rshift*/
2087 0, /*nb_and*/
2088 0, /*nb_xor*/
2089 0, /*nb_or*/
2090 0, /*nb_coerce*/
2091 0, /*nb_int*/
2092 0, /*nb_long*/
2093 0, /*nb_float*/
2094 0, /*nb_oct*/
2095 0, /*nb_hex*/
2096 0, /*nb_inplace_add*/
2097 0, /*nb_inplace_subtract*/
2098 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002099 0, /*nb_inplace_remainder*/
2100 0, /*nb_inplace_power*/
2101 0, /*nb_inplace_lshift*/
2102 0, /*nb_inplace_rshift*/
2103 0, /*nb_inplace_and*/
2104 0, /*nb_inplace_xor*/
2105 0, /*nb_inplace_or*/
2106 delta_divide, /* nb_floor_divide */
2107 0, /* nb_true_divide */
2108 0, /* nb_inplace_floor_divide */
2109 0, /* nb_inplace_true_divide */
2110};
2111
2112static PyTypeObject PyDateTime_DeltaType = {
2113 PyObject_HEAD_INIT(NULL)
2114 0, /* ob_size */
2115 "datetime.timedelta", /* tp_name */
2116 sizeof(PyDateTime_Delta), /* tp_basicsize */
2117 0, /* tp_itemsize */
2118 0, /* tp_dealloc */
2119 0, /* tp_print */
2120 0, /* tp_getattr */
2121 0, /* tp_setattr */
2122 0, /* tp_compare */
2123 (reprfunc)delta_repr, /* tp_repr */
2124 &delta_as_number, /* tp_as_number */
2125 0, /* tp_as_sequence */
2126 0, /* tp_as_mapping */
2127 (hashfunc)delta_hash, /* tp_hash */
2128 0, /* tp_call */
2129 (reprfunc)delta_str, /* tp_str */
2130 PyObject_GenericGetAttr, /* tp_getattro */
2131 0, /* tp_setattro */
2132 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002133 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002134 delta_doc, /* tp_doc */
2135 0, /* tp_traverse */
2136 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002137 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002138 0, /* tp_weaklistoffset */
2139 0, /* tp_iter */
2140 0, /* tp_iternext */
2141 delta_methods, /* tp_methods */
2142 delta_members, /* tp_members */
2143 0, /* tp_getset */
2144 0, /* tp_base */
2145 0, /* tp_dict */
2146 0, /* tp_descr_get */
2147 0, /* tp_descr_set */
2148 0, /* tp_dictoffset */
2149 0, /* tp_init */
2150 0, /* tp_alloc */
2151 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002152 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002153};
2154
2155/*
2156 * PyDateTime_Date implementation.
2157 */
2158
2159/* Accessor properties. */
2160
2161static PyObject *
2162date_year(PyDateTime_Date *self, void *unused)
2163{
2164 return PyInt_FromLong(GET_YEAR(self));
2165}
2166
2167static PyObject *
2168date_month(PyDateTime_Date *self, void *unused)
2169{
2170 return PyInt_FromLong(GET_MONTH(self));
2171}
2172
2173static PyObject *
2174date_day(PyDateTime_Date *self, void *unused)
2175{
2176 return PyInt_FromLong(GET_DAY(self));
2177}
2178
2179static PyGetSetDef date_getset[] = {
2180 {"year", (getter)date_year},
2181 {"month", (getter)date_month},
2182 {"day", (getter)date_day},
2183 {NULL}
2184};
2185
2186/* Constructors. */
2187
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002188static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002189
Tim Peters2a799bf2002-12-16 20:18:38 +00002190static PyObject *
2191date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2192{
2193 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002194 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002195 int year;
2196 int month;
2197 int day;
2198
Guido van Rossum177e41a2003-01-30 22:06:23 +00002199 /* Check for invocation from pickle with __getstate__ state */
2200 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002201 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002202 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2203 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002204 {
Tim Peters70533e22003-02-01 04:40:04 +00002205 PyDateTime_Date *me;
2206
Tim Peters604c0132004-06-07 23:04:33 +00002207 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002208 if (me != NULL) {
2209 char *pdata = PyString_AS_STRING(state);
2210 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2211 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002212 }
Tim Peters70533e22003-02-01 04:40:04 +00002213 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002214 }
2215
Tim Peters12bf3392002-12-24 05:41:27 +00002216 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002217 &year, &month, &day)) {
2218 if (check_date_args(year, month, day) < 0)
2219 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002220 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002221 }
2222 return self;
2223}
2224
2225/* Return new date from localtime(t). */
2226static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002227date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002228{
2229 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002230 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002231 PyObject *result = NULL;
2232
Tim Peters1b6f7a92004-06-20 02:50:16 +00002233 t = _PyTime_DoubleToTimet(ts);
2234 if (t == (time_t)-1 && PyErr_Occurred())
2235 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002236 tm = localtime(&t);
2237 if (tm)
2238 result = PyObject_CallFunction(cls, "iii",
2239 tm->tm_year + 1900,
2240 tm->tm_mon + 1,
2241 tm->tm_mday);
2242 else
2243 PyErr_SetString(PyExc_ValueError,
2244 "timestamp out of range for "
2245 "platform localtime() function");
2246 return result;
2247}
2248
2249/* Return new date from current time.
2250 * We say this is equivalent to fromtimestamp(time.time()), and the
2251 * only way to be sure of that is to *call* time.time(). That's not
2252 * generally the same as calling C's time.
2253 */
2254static PyObject *
2255date_today(PyObject *cls, PyObject *dummy)
2256{
2257 PyObject *time;
2258 PyObject *result;
2259
2260 time = time_time();
2261 if (time == NULL)
2262 return NULL;
2263
2264 /* Note well: today() is a class method, so this may not call
2265 * date.fromtimestamp. For example, it may call
2266 * datetime.fromtimestamp. That's why we need all the accuracy
2267 * time.time() delivers; if someone were gonzo about optimization,
2268 * date.today() could get away with plain C time().
2269 */
2270 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2271 Py_DECREF(time);
2272 return result;
2273}
2274
2275/* Return new date from given timestamp (Python timestamp -- a double). */
2276static PyObject *
2277date_fromtimestamp(PyObject *cls, PyObject *args)
2278{
2279 double timestamp;
2280 PyObject *result = NULL;
2281
2282 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002283 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002284 return result;
2285}
2286
2287/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2288 * the ordinal is out of range.
2289 */
2290static PyObject *
2291date_fromordinal(PyObject *cls, PyObject *args)
2292{
2293 PyObject *result = NULL;
2294 int ordinal;
2295
2296 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2297 int year;
2298 int month;
2299 int day;
2300
2301 if (ordinal < 1)
2302 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2303 ">= 1");
2304 else {
2305 ord_to_ymd(ordinal, &year, &month, &day);
2306 result = PyObject_CallFunction(cls, "iii",
2307 year, month, day);
2308 }
2309 }
2310 return result;
2311}
2312
2313/*
2314 * Date arithmetic.
2315 */
2316
2317/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2318 * instead.
2319 */
2320static PyObject *
2321add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2322{
2323 PyObject *result = NULL;
2324 int year = GET_YEAR(date);
2325 int month = GET_MONTH(date);
2326 int deltadays = GET_TD_DAYS(delta);
2327 /* C-level overflow is impossible because |deltadays| < 1e9. */
2328 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2329
2330 if (normalize_date(&year, &month, &day) >= 0)
2331 result = new_date(year, month, day);
2332 return result;
2333}
2334
2335static PyObject *
2336date_add(PyObject *left, PyObject *right)
2337{
2338 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2339 Py_INCREF(Py_NotImplemented);
2340 return Py_NotImplemented;
2341 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002342 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002343 /* date + ??? */
2344 if (PyDelta_Check(right))
2345 /* date + delta */
2346 return add_date_timedelta((PyDateTime_Date *) left,
2347 (PyDateTime_Delta *) right,
2348 0);
2349 }
2350 else {
2351 /* ??? + date
2352 * 'right' must be one of us, or we wouldn't have been called
2353 */
2354 if (PyDelta_Check(left))
2355 /* delta + date */
2356 return add_date_timedelta((PyDateTime_Date *) right,
2357 (PyDateTime_Delta *) left,
2358 0);
2359 }
2360 Py_INCREF(Py_NotImplemented);
2361 return Py_NotImplemented;
2362}
2363
2364static PyObject *
2365date_subtract(PyObject *left, PyObject *right)
2366{
2367 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2368 Py_INCREF(Py_NotImplemented);
2369 return Py_NotImplemented;
2370 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002371 if (PyDate_Check(left)) {
2372 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002373 /* date - date */
2374 int left_ord = ymd_to_ord(GET_YEAR(left),
2375 GET_MONTH(left),
2376 GET_DAY(left));
2377 int right_ord = ymd_to_ord(GET_YEAR(right),
2378 GET_MONTH(right),
2379 GET_DAY(right));
2380 return new_delta(left_ord - right_ord, 0, 0, 0);
2381 }
2382 if (PyDelta_Check(right)) {
2383 /* date - delta */
2384 return add_date_timedelta((PyDateTime_Date *) left,
2385 (PyDateTime_Delta *) right,
2386 1);
2387 }
2388 }
2389 Py_INCREF(Py_NotImplemented);
2390 return Py_NotImplemented;
2391}
2392
2393
2394/* Various ways to turn a date into a string. */
2395
2396static PyObject *
2397date_repr(PyDateTime_Date *self)
2398{
2399 char buffer[1028];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002400 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002401
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002402 type_name = self->ob_type->tp_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002403 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002404 type_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002405 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2406
2407 return PyString_FromString(buffer);
2408}
2409
2410static PyObject *
2411date_isoformat(PyDateTime_Date *self)
2412{
2413 char buffer[128];
2414
2415 isoformat_date(self, buffer, sizeof(buffer));
2416 return PyString_FromString(buffer);
2417}
2418
Tim Peterse2df5ff2003-05-02 18:39:55 +00002419/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002420static PyObject *
2421date_str(PyDateTime_Date *self)
2422{
2423 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2424}
2425
2426
2427static PyObject *
2428date_ctime(PyDateTime_Date *self)
2429{
2430 return format_ctime(self, 0, 0, 0);
2431}
2432
2433static PyObject *
2434date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2435{
2436 /* This method can be inherited, and needs to call the
2437 * timetuple() method appropriate to self's class.
2438 */
2439 PyObject *result;
2440 PyObject *format;
2441 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002442 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002443
2444 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2445 &PyString_Type, &format))
2446 return NULL;
2447
2448 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2449 if (tuple == NULL)
2450 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002451 result = wrap_strftime((PyObject *)self, format, tuple,
2452 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002453 Py_DECREF(tuple);
2454 return result;
2455}
2456
2457/* ISO methods. */
2458
2459static PyObject *
2460date_isoweekday(PyDateTime_Date *self)
2461{
2462 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2463
2464 return PyInt_FromLong(dow + 1);
2465}
2466
2467static PyObject *
2468date_isocalendar(PyDateTime_Date *self)
2469{
2470 int year = GET_YEAR(self);
2471 int week1_monday = iso_week1_monday(year);
2472 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2473 int week;
2474 int day;
2475
2476 week = divmod(today - week1_monday, 7, &day);
2477 if (week < 0) {
2478 --year;
2479 week1_monday = iso_week1_monday(year);
2480 week = divmod(today - week1_monday, 7, &day);
2481 }
2482 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2483 ++year;
2484 week = 0;
2485 }
2486 return Py_BuildValue("iii", year, week + 1, day + 1);
2487}
2488
2489/* Miscellaneous methods. */
2490
Tim Peters2a799bf2002-12-16 20:18:38 +00002491static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002492date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002493{
Guido van Rossum19960592006-08-24 17:29:38 +00002494 if (PyDate_Check(other)) {
2495 int diff = memcmp(((PyDateTime_Date *)self)->data,
2496 ((PyDateTime_Date *)other)->data,
2497 _PyDateTime_DATE_DATASIZE);
2498 return diff_to_bool(diff, op);
2499 }
2500 else {
Tim Peters07534a62003-02-07 22:50:28 +00002501 Py_INCREF(Py_NotImplemented);
2502 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002503 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002504}
2505
2506static PyObject *
2507date_timetuple(PyDateTime_Date *self)
2508{
2509 return build_struct_time(GET_YEAR(self),
2510 GET_MONTH(self),
2511 GET_DAY(self),
2512 0, 0, 0, -1);
2513}
2514
Tim Peters12bf3392002-12-24 05:41:27 +00002515static PyObject *
2516date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2517{
2518 PyObject *clone;
2519 PyObject *tuple;
2520 int year = GET_YEAR(self);
2521 int month = GET_MONTH(self);
2522 int day = GET_DAY(self);
2523
2524 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2525 &year, &month, &day))
2526 return NULL;
2527 tuple = Py_BuildValue("iii", year, month, day);
2528 if (tuple == NULL)
2529 return NULL;
2530 clone = date_new(self->ob_type, tuple, NULL);
2531 Py_DECREF(tuple);
2532 return clone;
2533}
2534
Tim Peters2a799bf2002-12-16 20:18:38 +00002535static PyObject *date_getstate(PyDateTime_Date *self);
2536
2537static long
2538date_hash(PyDateTime_Date *self)
2539{
2540 if (self->hashcode == -1) {
2541 PyObject *temp = date_getstate(self);
2542 if (temp != NULL) {
2543 self->hashcode = PyObject_Hash(temp);
2544 Py_DECREF(temp);
2545 }
2546 }
2547 return self->hashcode;
2548}
2549
2550static PyObject *
2551date_toordinal(PyDateTime_Date *self)
2552{
2553 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2554 GET_DAY(self)));
2555}
2556
2557static PyObject *
2558date_weekday(PyDateTime_Date *self)
2559{
2560 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2561
2562 return PyInt_FromLong(dow);
2563}
2564
Tim Peters371935f2003-02-01 01:52:50 +00002565/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002566
Tim Petersb57f8f02003-02-01 02:54:15 +00002567/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002568static PyObject *
2569date_getstate(PyDateTime_Date *self)
2570{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002571 return Py_BuildValue(
2572 "(N)",
2573 PyString_FromStringAndSize((char *)self->data,
2574 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002575}
2576
2577static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002578date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002579{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002580 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002581}
2582
2583static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002584
Tim Peters2a799bf2002-12-16 20:18:38 +00002585 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002586
Tim Peters2a799bf2002-12-16 20:18:38 +00002587 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2588 METH_CLASS,
2589 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2590 "time.time()).")},
2591
2592 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2593 METH_CLASS,
2594 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2595 "ordinal.")},
2596
2597 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2598 PyDoc_STR("Current date or datetime: same as "
2599 "self.__class__.fromtimestamp(time.time()).")},
2600
2601 /* Instance methods: */
2602
2603 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2604 PyDoc_STR("Return ctime() style string.")},
2605
2606 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2607 PyDoc_STR("format -> strftime() style string.")},
2608
2609 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2610 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2611
2612 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2613 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2614 "weekday.")},
2615
2616 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2617 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2618
2619 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2620 PyDoc_STR("Return the day of the week represented by the date.\n"
2621 "Monday == 1 ... Sunday == 7")},
2622
2623 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2624 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2625 "1 is day 1.")},
2626
2627 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2628 PyDoc_STR("Return the day of the week represented by the date.\n"
2629 "Monday == 0 ... Sunday == 6")},
2630
Tim Peters12bf3392002-12-24 05:41:27 +00002631 {"replace", (PyCFunction)date_replace, METH_KEYWORDS,
2632 PyDoc_STR("Return date with new specified fields.")},
2633
Guido van Rossum177e41a2003-01-30 22:06:23 +00002634 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2635 PyDoc_STR("__reduce__() -> (cls, state)")},
2636
Tim Peters2a799bf2002-12-16 20:18:38 +00002637 {NULL, NULL}
2638};
2639
2640static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002641PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002642
2643static PyNumberMethods date_as_number = {
2644 date_add, /* nb_add */
2645 date_subtract, /* nb_subtract */
2646 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002647 0, /* nb_remainder */
2648 0, /* nb_divmod */
2649 0, /* nb_power */
2650 0, /* nb_negative */
2651 0, /* nb_positive */
2652 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002653 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002654};
2655
2656static PyTypeObject PyDateTime_DateType = {
2657 PyObject_HEAD_INIT(NULL)
2658 0, /* ob_size */
2659 "datetime.date", /* tp_name */
2660 sizeof(PyDateTime_Date), /* tp_basicsize */
2661 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002662 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002663 0, /* tp_print */
2664 0, /* tp_getattr */
2665 0, /* tp_setattr */
2666 0, /* tp_compare */
2667 (reprfunc)date_repr, /* tp_repr */
2668 &date_as_number, /* tp_as_number */
2669 0, /* tp_as_sequence */
2670 0, /* tp_as_mapping */
2671 (hashfunc)date_hash, /* tp_hash */
2672 0, /* tp_call */
2673 (reprfunc)date_str, /* tp_str */
2674 PyObject_GenericGetAttr, /* tp_getattro */
2675 0, /* tp_setattro */
2676 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002677 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002678 date_doc, /* tp_doc */
2679 0, /* tp_traverse */
2680 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002681 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002682 0, /* tp_weaklistoffset */
2683 0, /* tp_iter */
2684 0, /* tp_iternext */
2685 date_methods, /* tp_methods */
2686 0, /* tp_members */
2687 date_getset, /* tp_getset */
2688 0, /* tp_base */
2689 0, /* tp_dict */
2690 0, /* tp_descr_get */
2691 0, /* tp_descr_set */
2692 0, /* tp_dictoffset */
2693 0, /* tp_init */
2694 0, /* tp_alloc */
2695 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002696 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002697};
2698
2699/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002700 * PyDateTime_TZInfo implementation.
2701 */
2702
2703/* This is a pure abstract base class, so doesn't do anything beyond
2704 * raising NotImplemented exceptions. Real tzinfo classes need
2705 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002706 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002707 * be subclasses of this tzinfo class, which is easy and quick to check).
2708 *
2709 * Note: For reasons having to do with pickling of subclasses, we have
2710 * to allow tzinfo objects to be instantiated. This wasn't an issue
2711 * in the Python implementation (__init__() could raise NotImplementedError
2712 * there without ill effect), but doing so in the C implementation hit a
2713 * brick wall.
2714 */
2715
2716static PyObject *
2717tzinfo_nogo(const char* methodname)
2718{
2719 PyErr_Format(PyExc_NotImplementedError,
2720 "a tzinfo subclass must implement %s()",
2721 methodname);
2722 return NULL;
2723}
2724
2725/* Methods. A subclass must implement these. */
2726
Tim Peters52dcce22003-01-23 16:36:11 +00002727static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002728tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2729{
2730 return tzinfo_nogo("tzname");
2731}
2732
Tim Peters52dcce22003-01-23 16:36:11 +00002733static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002734tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2735{
2736 return tzinfo_nogo("utcoffset");
2737}
2738
Tim Peters52dcce22003-01-23 16:36:11 +00002739static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002740tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2741{
2742 return tzinfo_nogo("dst");
2743}
2744
Tim Peters52dcce22003-01-23 16:36:11 +00002745static PyObject *
2746tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2747{
2748 int y, m, d, hh, mm, ss, us;
2749
2750 PyObject *result;
2751 int off, dst;
2752 int none;
2753 int delta;
2754
2755 if (! PyDateTime_Check(dt)) {
2756 PyErr_SetString(PyExc_TypeError,
2757 "fromutc: argument must be a datetime");
2758 return NULL;
2759 }
2760 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2761 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2762 "is not self");
2763 return NULL;
2764 }
2765
2766 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2767 if (off == -1 && PyErr_Occurred())
2768 return NULL;
2769 if (none) {
2770 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2771 "utcoffset() result required");
2772 return NULL;
2773 }
2774
2775 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2776 if (dst == -1 && PyErr_Occurred())
2777 return NULL;
2778 if (none) {
2779 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2780 "dst() result required");
2781 return NULL;
2782 }
2783
2784 y = GET_YEAR(dt);
2785 m = GET_MONTH(dt);
2786 d = GET_DAY(dt);
2787 hh = DATE_GET_HOUR(dt);
2788 mm = DATE_GET_MINUTE(dt);
2789 ss = DATE_GET_SECOND(dt);
2790 us = DATE_GET_MICROSECOND(dt);
2791
2792 delta = off - dst;
2793 mm += delta;
2794 if ((mm < 0 || mm >= 60) &&
2795 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002796 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002797 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2798 if (result == NULL)
2799 return result;
2800
2801 dst = call_dst(dt->tzinfo, result, &none);
2802 if (dst == -1 && PyErr_Occurred())
2803 goto Fail;
2804 if (none)
2805 goto Inconsistent;
2806 if (dst == 0)
2807 return result;
2808
2809 mm += dst;
2810 if ((mm < 0 || mm >= 60) &&
2811 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2812 goto Fail;
2813 Py_DECREF(result);
2814 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2815 return result;
2816
2817Inconsistent:
2818 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2819 "inconsistent results; cannot convert");
2820
2821 /* fall thru to failure */
2822Fail:
2823 Py_DECREF(result);
2824 return NULL;
2825}
2826
Tim Peters2a799bf2002-12-16 20:18:38 +00002827/*
2828 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002829 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002830 */
2831
Guido van Rossum177e41a2003-01-30 22:06:23 +00002832static PyObject *
2833tzinfo_reduce(PyObject *self)
2834{
2835 PyObject *args, *state, *tmp;
2836 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002837
Guido van Rossum177e41a2003-01-30 22:06:23 +00002838 tmp = PyTuple_New(0);
2839 if (tmp == NULL)
2840 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002841
Guido van Rossum177e41a2003-01-30 22:06:23 +00002842 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2843 if (getinitargs != NULL) {
2844 args = PyObject_CallObject(getinitargs, tmp);
2845 Py_DECREF(getinitargs);
2846 if (args == NULL) {
2847 Py_DECREF(tmp);
2848 return NULL;
2849 }
2850 }
2851 else {
2852 PyErr_Clear();
2853 args = tmp;
2854 Py_INCREF(args);
2855 }
2856
2857 getstate = PyObject_GetAttrString(self, "__getstate__");
2858 if (getstate != NULL) {
2859 state = PyObject_CallObject(getstate, tmp);
2860 Py_DECREF(getstate);
2861 if (state == NULL) {
2862 Py_DECREF(args);
2863 Py_DECREF(tmp);
2864 return NULL;
2865 }
2866 }
2867 else {
2868 PyObject **dictptr;
2869 PyErr_Clear();
2870 state = Py_None;
2871 dictptr = _PyObject_GetDictPtr(self);
2872 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2873 state = *dictptr;
2874 Py_INCREF(state);
2875 }
2876
2877 Py_DECREF(tmp);
2878
2879 if (state == Py_None) {
2880 Py_DECREF(state);
2881 return Py_BuildValue("(ON)", self->ob_type, args);
2882 }
2883 else
2884 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2885}
Tim Peters2a799bf2002-12-16 20:18:38 +00002886
2887static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002888
Tim Peters2a799bf2002-12-16 20:18:38 +00002889 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2890 PyDoc_STR("datetime -> string name of time zone.")},
2891
2892 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2893 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2894 "west of UTC).")},
2895
2896 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2897 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2898
Tim Peters52dcce22003-01-23 16:36:11 +00002899 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2900 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2901
Guido van Rossum177e41a2003-01-30 22:06:23 +00002902 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2903 PyDoc_STR("-> (cls, state)")},
2904
Tim Peters2a799bf2002-12-16 20:18:38 +00002905 {NULL, NULL}
2906};
2907
2908static char tzinfo_doc[] =
2909PyDoc_STR("Abstract base class for time zone info objects.");
2910
Neal Norwitz227b5332006-03-22 09:28:35 +00002911static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002912 PyObject_HEAD_INIT(NULL)
2913 0, /* ob_size */
2914 "datetime.tzinfo", /* tp_name */
2915 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2916 0, /* tp_itemsize */
2917 0, /* tp_dealloc */
2918 0, /* tp_print */
2919 0, /* tp_getattr */
2920 0, /* tp_setattr */
2921 0, /* tp_compare */
2922 0, /* tp_repr */
2923 0, /* tp_as_number */
2924 0, /* tp_as_sequence */
2925 0, /* tp_as_mapping */
2926 0, /* tp_hash */
2927 0, /* tp_call */
2928 0, /* tp_str */
2929 PyObject_GenericGetAttr, /* tp_getattro */
2930 0, /* tp_setattro */
2931 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002932 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002933 tzinfo_doc, /* tp_doc */
2934 0, /* tp_traverse */
2935 0, /* tp_clear */
2936 0, /* tp_richcompare */
2937 0, /* tp_weaklistoffset */
2938 0, /* tp_iter */
2939 0, /* tp_iternext */
2940 tzinfo_methods, /* tp_methods */
2941 0, /* tp_members */
2942 0, /* tp_getset */
2943 0, /* tp_base */
2944 0, /* tp_dict */
2945 0, /* tp_descr_get */
2946 0, /* tp_descr_set */
2947 0, /* tp_dictoffset */
2948 0, /* tp_init */
2949 0, /* tp_alloc */
2950 PyType_GenericNew, /* tp_new */
2951 0, /* tp_free */
2952};
2953
2954/*
Tim Peters37f39822003-01-10 03:49:02 +00002955 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002956 */
2957
Tim Peters37f39822003-01-10 03:49:02 +00002958/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002959 */
2960
2961static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002962time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002963{
Tim Peters37f39822003-01-10 03:49:02 +00002964 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002965}
2966
Tim Peters37f39822003-01-10 03:49:02 +00002967static PyObject *
2968time_minute(PyDateTime_Time *self, void *unused)
2969{
2970 return PyInt_FromLong(TIME_GET_MINUTE(self));
2971}
2972
2973/* The name time_second conflicted with some platform header file. */
2974static PyObject *
2975py_time_second(PyDateTime_Time *self, void *unused)
2976{
2977 return PyInt_FromLong(TIME_GET_SECOND(self));
2978}
2979
2980static PyObject *
2981time_microsecond(PyDateTime_Time *self, void *unused)
2982{
2983 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2984}
2985
2986static PyObject *
2987time_tzinfo(PyDateTime_Time *self, void *unused)
2988{
Tim Petersa032d2e2003-01-11 00:15:54 +00002989 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002990 Py_INCREF(result);
2991 return result;
2992}
2993
2994static PyGetSetDef time_getset[] = {
2995 {"hour", (getter)time_hour},
2996 {"minute", (getter)time_minute},
2997 {"second", (getter)py_time_second},
2998 {"microsecond", (getter)time_microsecond},
2999 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003000 {NULL}
3001};
3002
3003/*
3004 * Constructors.
3005 */
3006
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003007static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003008 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003009
Tim Peters2a799bf2002-12-16 20:18:38 +00003010static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003011time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003012{
3013 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003014 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003015 int hour = 0;
3016 int minute = 0;
3017 int second = 0;
3018 int usecond = 0;
3019 PyObject *tzinfo = Py_None;
3020
Guido van Rossum177e41a2003-01-30 22:06:23 +00003021 /* Check for invocation from pickle with __getstate__ state */
3022 if (PyTuple_GET_SIZE(args) >= 1 &&
3023 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003024 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003025 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3026 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003027 {
Tim Peters70533e22003-02-01 04:40:04 +00003028 PyDateTime_Time *me;
3029 char aware;
3030
3031 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003032 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003033 if (check_tzinfo_subclass(tzinfo) < 0) {
3034 PyErr_SetString(PyExc_TypeError, "bad "
3035 "tzinfo state arg");
3036 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003037 }
3038 }
Tim Peters70533e22003-02-01 04:40:04 +00003039 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003040 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003041 if (me != NULL) {
3042 char *pdata = PyString_AS_STRING(state);
3043
3044 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3045 me->hashcode = -1;
3046 me->hastzinfo = aware;
3047 if (aware) {
3048 Py_INCREF(tzinfo);
3049 me->tzinfo = tzinfo;
3050 }
3051 }
3052 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003053 }
3054
Tim Peters37f39822003-01-10 03:49:02 +00003055 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003056 &hour, &minute, &second, &usecond,
3057 &tzinfo)) {
3058 if (check_time_args(hour, minute, second, usecond) < 0)
3059 return NULL;
3060 if (check_tzinfo_subclass(tzinfo) < 0)
3061 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003062 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3063 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003064 }
3065 return self;
3066}
3067
3068/*
3069 * Destructor.
3070 */
3071
3072static void
Tim Peters37f39822003-01-10 03:49:02 +00003073time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003074{
Tim Petersa032d2e2003-01-11 00:15:54 +00003075 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003076 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003077 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003078 self->ob_type->tp_free((PyObject *)self);
3079}
3080
3081/*
Tim Peters855fe882002-12-22 03:43:39 +00003082 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003083 */
3084
Tim Peters2a799bf2002-12-16 20:18:38 +00003085/* These are all METH_NOARGS, so don't need to check the arglist. */
3086static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003087time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003088 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003089 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003090}
3091
3092static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003093time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003094 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003095 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003096}
3097
3098static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003099time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003100 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003101 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003102}
3103
3104/*
Tim Peters37f39822003-01-10 03:49:02 +00003105 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003106 */
3107
3108static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003109time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003110{
Tim Peters37f39822003-01-10 03:49:02 +00003111 char buffer[100];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003112 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003113 int h = TIME_GET_HOUR(self);
3114 int m = TIME_GET_MINUTE(self);
3115 int s = TIME_GET_SECOND(self);
3116 int us = TIME_GET_MICROSECOND(self);
3117 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003118
Tim Peters37f39822003-01-10 03:49:02 +00003119 if (us)
3120 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003121 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003122 else if (s)
3123 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003124 "%s(%d, %d, %d)", type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003125 else
3126 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003127 "%s(%d, %d)", type_name, h, m);
Tim Peters37f39822003-01-10 03:49:02 +00003128 result = PyString_FromString(buffer);
Tim Petersa032d2e2003-01-11 00:15:54 +00003129 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003130 result = append_keyword_tzinfo(result, self->tzinfo);
3131 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003132}
3133
Tim Peters37f39822003-01-10 03:49:02 +00003134static PyObject *
3135time_str(PyDateTime_Time *self)
3136{
3137 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3138}
Tim Peters2a799bf2002-12-16 20:18:38 +00003139
3140static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003141time_isoformat(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003142{
3143 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003144 PyObject *result;
3145 /* Reuse the time format code from the datetime type. */
3146 PyDateTime_DateTime datetime;
3147 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003148
Tim Peters37f39822003-01-10 03:49:02 +00003149 /* Copy over just the time bytes. */
3150 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3151 self->data,
3152 _PyDateTime_TIME_DATASIZE);
3153
3154 isoformat_time(pdatetime, buf, sizeof(buf));
3155 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003156 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003157 return result;
3158
3159 /* We need to append the UTC offset. */
3160 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003161 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003162 Py_DECREF(result);
3163 return NULL;
3164 }
3165 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3166 return result;
3167}
3168
Tim Peters37f39822003-01-10 03:49:02 +00003169static PyObject *
3170time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3171{
3172 PyObject *result;
3173 PyObject *format;
3174 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003175 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003176
3177 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3178 &PyString_Type, &format))
3179 return NULL;
3180
3181 /* Python's strftime does insane things with the year part of the
3182 * timetuple. The year is forced to (the otherwise nonsensical)
3183 * 1900 to worm around that.
3184 */
3185 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003186 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003187 TIME_GET_HOUR(self),
3188 TIME_GET_MINUTE(self),
3189 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003190 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003191 if (tuple == NULL)
3192 return NULL;
3193 assert(PyTuple_Size(tuple) == 9);
3194 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3195 Py_DECREF(tuple);
3196 return result;
3197}
Tim Peters2a799bf2002-12-16 20:18:38 +00003198
3199/*
3200 * Miscellaneous methods.
3201 */
3202
Tim Peters37f39822003-01-10 03:49:02 +00003203static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003204time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003205{
3206 int diff;
3207 naivety n1, n2;
3208 int offset1, offset2;
3209
3210 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003211 Py_INCREF(Py_NotImplemented);
3212 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003213 }
Guido van Rossum19960592006-08-24 17:29:38 +00003214 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3215 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003216 return NULL;
3217 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3218 /* If they're both naive, or both aware and have the same offsets,
3219 * we get off cheap. Note that if they're both naive, offset1 ==
3220 * offset2 == 0 at this point.
3221 */
3222 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003223 diff = memcmp(((PyDateTime_Time *)self)->data,
3224 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003225 _PyDateTime_TIME_DATASIZE);
3226 return diff_to_bool(diff, op);
3227 }
3228
3229 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3230 assert(offset1 != offset2); /* else last "if" handled it */
3231 /* Convert everything except microseconds to seconds. These
3232 * can't overflow (no more than the # of seconds in 2 days).
3233 */
3234 offset1 = TIME_GET_HOUR(self) * 3600 +
3235 (TIME_GET_MINUTE(self) - offset1) * 60 +
3236 TIME_GET_SECOND(self);
3237 offset2 = TIME_GET_HOUR(other) * 3600 +
3238 (TIME_GET_MINUTE(other) - offset2) * 60 +
3239 TIME_GET_SECOND(other);
3240 diff = offset1 - offset2;
3241 if (diff == 0)
3242 diff = TIME_GET_MICROSECOND(self) -
3243 TIME_GET_MICROSECOND(other);
3244 return diff_to_bool(diff, op);
3245 }
3246
3247 assert(n1 != n2);
3248 PyErr_SetString(PyExc_TypeError,
3249 "can't compare offset-naive and "
3250 "offset-aware times");
3251 return NULL;
3252}
3253
3254static long
3255time_hash(PyDateTime_Time *self)
3256{
3257 if (self->hashcode == -1) {
3258 naivety n;
3259 int offset;
3260 PyObject *temp;
3261
3262 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3263 assert(n != OFFSET_UNKNOWN);
3264 if (n == OFFSET_ERROR)
3265 return -1;
3266
3267 /* Reduce this to a hash of another object. */
3268 if (offset == 0)
3269 temp = PyString_FromStringAndSize((char *)self->data,
3270 _PyDateTime_TIME_DATASIZE);
3271 else {
3272 int hour;
3273 int minute;
3274
3275 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003276 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003277 hour = divmod(TIME_GET_HOUR(self) * 60 +
3278 TIME_GET_MINUTE(self) - offset,
3279 60,
3280 &minute);
3281 if (0 <= hour && hour < 24)
3282 temp = new_time(hour, minute,
3283 TIME_GET_SECOND(self),
3284 TIME_GET_MICROSECOND(self),
3285 Py_None);
3286 else
3287 temp = Py_BuildValue("iiii",
3288 hour, minute,
3289 TIME_GET_SECOND(self),
3290 TIME_GET_MICROSECOND(self));
3291 }
3292 if (temp != NULL) {
3293 self->hashcode = PyObject_Hash(temp);
3294 Py_DECREF(temp);
3295 }
3296 }
3297 return self->hashcode;
3298}
Tim Peters2a799bf2002-12-16 20:18:38 +00003299
Tim Peters12bf3392002-12-24 05:41:27 +00003300static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003301time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003302{
3303 PyObject *clone;
3304 PyObject *tuple;
3305 int hh = TIME_GET_HOUR(self);
3306 int mm = TIME_GET_MINUTE(self);
3307 int ss = TIME_GET_SECOND(self);
3308 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003309 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003310
3311 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003312 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003313 &hh, &mm, &ss, &us, &tzinfo))
3314 return NULL;
3315 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3316 if (tuple == NULL)
3317 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003318 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003319 Py_DECREF(tuple);
3320 return clone;
3321}
3322
Tim Peters2a799bf2002-12-16 20:18:38 +00003323static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003324time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003325{
3326 int offset;
3327 int none;
3328
3329 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3330 /* Since utcoffset is in whole minutes, nothing can
3331 * alter the conclusion that this is nonzero.
3332 */
3333 return 1;
3334 }
3335 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003336 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003337 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003338 if (offset == -1 && PyErr_Occurred())
3339 return -1;
3340 }
3341 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3342}
3343
Tim Peters371935f2003-02-01 01:52:50 +00003344/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003345
Tim Peters33e0f382003-01-10 02:05:14 +00003346/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003347 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3348 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003349 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003350 */
3351static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003352time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003353{
3354 PyObject *basestate;
3355 PyObject *result = NULL;
3356
Tim Peters33e0f382003-01-10 02:05:14 +00003357 basestate = PyString_FromStringAndSize((char *)self->data,
3358 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003359 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003360 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003361 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003362 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003363 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003364 Py_DECREF(basestate);
3365 }
3366 return result;
3367}
3368
3369static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003370time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003371{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003372 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003373}
3374
Tim Peters37f39822003-01-10 03:49:02 +00003375static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003376
Tim Peters37f39822003-01-10 03:49:02 +00003377 {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003378 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3379 "[+HH:MM].")},
3380
Tim Peters37f39822003-01-10 03:49:02 +00003381 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3382 PyDoc_STR("format -> strftime() style string.")},
3383
3384 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003385 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3386
Tim Peters37f39822003-01-10 03:49:02 +00003387 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003388 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3389
Tim Peters37f39822003-01-10 03:49:02 +00003390 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003391 PyDoc_STR("Return self.tzinfo.dst(self).")},
3392
Tim Peters37f39822003-01-10 03:49:02 +00003393 {"replace", (PyCFunction)time_replace, METH_KEYWORDS,
3394 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003395
Guido van Rossum177e41a2003-01-30 22:06:23 +00003396 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3397 PyDoc_STR("__reduce__() -> (cls, state)")},
3398
Tim Peters2a799bf2002-12-16 20:18:38 +00003399 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003400};
3401
Tim Peters37f39822003-01-10 03:49:02 +00003402static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003403PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3404\n\
3405All arguments are optional. tzinfo may be None, or an instance of\n\
3406a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003407
Tim Peters37f39822003-01-10 03:49:02 +00003408static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003409 0, /* nb_add */
3410 0, /* nb_subtract */
3411 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003412 0, /* nb_remainder */
3413 0, /* nb_divmod */
3414 0, /* nb_power */
3415 0, /* nb_negative */
3416 0, /* nb_positive */
3417 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003418 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003419};
3420
Neal Norwitz227b5332006-03-22 09:28:35 +00003421static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003422 PyObject_HEAD_INIT(NULL)
3423 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003424 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003425 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003426 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003427 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 0, /* tp_print */
3429 0, /* tp_getattr */
3430 0, /* tp_setattr */
3431 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003432 (reprfunc)time_repr, /* tp_repr */
3433 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003434 0, /* tp_as_sequence */
3435 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003436 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003437 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003438 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003439 PyObject_GenericGetAttr, /* tp_getattro */
3440 0, /* tp_setattro */
3441 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003442 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003443 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003444 0, /* tp_traverse */
3445 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003446 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003447 0, /* tp_weaklistoffset */
3448 0, /* tp_iter */
3449 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003450 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003451 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003452 time_getset, /* tp_getset */
3453 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003454 0, /* tp_dict */
3455 0, /* tp_descr_get */
3456 0, /* tp_descr_set */
3457 0, /* tp_dictoffset */
3458 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003459 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003460 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003461 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003462};
3463
3464/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003465 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003466 */
3467
Tim Petersa9bc1682003-01-11 03:39:11 +00003468/* Accessor properties. Properties for day, month, and year are inherited
3469 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003470 */
3471
3472static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003473datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003474{
Tim Petersa9bc1682003-01-11 03:39:11 +00003475 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003476}
3477
Tim Petersa9bc1682003-01-11 03:39:11 +00003478static PyObject *
3479datetime_minute(PyDateTime_DateTime *self, void *unused)
3480{
3481 return PyInt_FromLong(DATE_GET_MINUTE(self));
3482}
3483
3484static PyObject *
3485datetime_second(PyDateTime_DateTime *self, void *unused)
3486{
3487 return PyInt_FromLong(DATE_GET_SECOND(self));
3488}
3489
3490static PyObject *
3491datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3492{
3493 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3494}
3495
3496static PyObject *
3497datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3498{
3499 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3500 Py_INCREF(result);
3501 return result;
3502}
3503
3504static PyGetSetDef datetime_getset[] = {
3505 {"hour", (getter)datetime_hour},
3506 {"minute", (getter)datetime_minute},
3507 {"second", (getter)datetime_second},
3508 {"microsecond", (getter)datetime_microsecond},
3509 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003510 {NULL}
3511};
3512
3513/*
3514 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003515 */
3516
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003517static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003518 "year", "month", "day", "hour", "minute", "second",
3519 "microsecond", "tzinfo", NULL
3520};
3521
Tim Peters2a799bf2002-12-16 20:18:38 +00003522static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003523datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003524{
3525 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003526 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003527 int year;
3528 int month;
3529 int day;
3530 int hour = 0;
3531 int minute = 0;
3532 int second = 0;
3533 int usecond = 0;
3534 PyObject *tzinfo = Py_None;
3535
Guido van Rossum177e41a2003-01-30 22:06:23 +00003536 /* Check for invocation from pickle with __getstate__ state */
3537 if (PyTuple_GET_SIZE(args) >= 1 &&
3538 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003539 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003540 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3541 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003542 {
Tim Peters70533e22003-02-01 04:40:04 +00003543 PyDateTime_DateTime *me;
3544 char aware;
3545
3546 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003547 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003548 if (check_tzinfo_subclass(tzinfo) < 0) {
3549 PyErr_SetString(PyExc_TypeError, "bad "
3550 "tzinfo state arg");
3551 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003552 }
3553 }
Tim Peters70533e22003-02-01 04:40:04 +00003554 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003555 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003556 if (me != NULL) {
3557 char *pdata = PyString_AS_STRING(state);
3558
3559 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3560 me->hashcode = -1;
3561 me->hastzinfo = aware;
3562 if (aware) {
3563 Py_INCREF(tzinfo);
3564 me->tzinfo = tzinfo;
3565 }
3566 }
3567 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003568 }
3569
Tim Petersa9bc1682003-01-11 03:39:11 +00003570 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003571 &year, &month, &day, &hour, &minute,
3572 &second, &usecond, &tzinfo)) {
3573 if (check_date_args(year, month, day) < 0)
3574 return NULL;
3575 if (check_time_args(hour, minute, second, usecond) < 0)
3576 return NULL;
3577 if (check_tzinfo_subclass(tzinfo) < 0)
3578 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003579 self = new_datetime_ex(year, month, day,
3580 hour, minute, second, usecond,
3581 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003582 }
3583 return self;
3584}
3585
Tim Petersa9bc1682003-01-11 03:39:11 +00003586/* TM_FUNC is the shared type of localtime() and gmtime(). */
3587typedef struct tm *(*TM_FUNC)(const time_t *timer);
3588
3589/* Internal helper.
3590 * Build datetime from a time_t and a distinct count of microseconds.
3591 * Pass localtime or gmtime for f, to control the interpretation of timet.
3592 */
3593static PyObject *
3594datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3595 PyObject *tzinfo)
3596{
3597 struct tm *tm;
3598 PyObject *result = NULL;
3599
3600 tm = f(&timet);
3601 if (tm) {
3602 /* The platform localtime/gmtime may insert leap seconds,
3603 * indicated by tm->tm_sec > 59. We don't care about them,
3604 * except to the extent that passing them on to the datetime
3605 * constructor would raise ValueError for a reason that
3606 * made no sense to the user.
3607 */
3608 if (tm->tm_sec > 59)
3609 tm->tm_sec = 59;
3610 result = PyObject_CallFunction(cls, "iiiiiiiO",
3611 tm->tm_year + 1900,
3612 tm->tm_mon + 1,
3613 tm->tm_mday,
3614 tm->tm_hour,
3615 tm->tm_min,
3616 tm->tm_sec,
3617 us,
3618 tzinfo);
3619 }
3620 else
3621 PyErr_SetString(PyExc_ValueError,
3622 "timestamp out of range for "
3623 "platform localtime()/gmtime() function");
3624 return result;
3625}
3626
3627/* Internal helper.
3628 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3629 * to control the interpretation of the timestamp. Since a double doesn't
3630 * have enough bits to cover a datetime's full range of precision, it's
3631 * better to call datetime_from_timet_and_us provided you have a way
3632 * to get that much precision (e.g., C time() isn't good enough).
3633 */
3634static PyObject *
3635datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3636 PyObject *tzinfo)
3637{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003638 time_t timet;
3639 double fraction;
3640 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003641
Tim Peters1b6f7a92004-06-20 02:50:16 +00003642 timet = _PyTime_DoubleToTimet(timestamp);
3643 if (timet == (time_t)-1 && PyErr_Occurred())
3644 return NULL;
3645 fraction = timestamp - (double)timet;
3646 us = (int)round_to_long(fraction * 1e6);
Thomas Wouters477c8d52006-05-27 19:21:47 +00003647 /* If timestamp is less than one microsecond smaller than a
3648 * full second, round up. Otherwise, ValueErrors are raised
3649 * for some floats. */
3650 if (us == 1000000) {
3651 timet += 1;
3652 us = 0;
3653 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003654 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3655}
3656
3657/* Internal helper.
3658 * Build most accurate possible datetime for current time. Pass localtime or
3659 * gmtime for f as appropriate.
3660 */
3661static PyObject *
3662datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3663{
3664#ifdef HAVE_GETTIMEOFDAY
3665 struct timeval t;
3666
3667#ifdef GETTIMEOFDAY_NO_TZ
3668 gettimeofday(&t);
3669#else
3670 gettimeofday(&t, (struct timezone *)NULL);
3671#endif
3672 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3673 tzinfo);
3674
3675#else /* ! HAVE_GETTIMEOFDAY */
3676 /* No flavor of gettimeofday exists on this platform. Python's
3677 * time.time() does a lot of other platform tricks to get the
3678 * best time it can on the platform, and we're not going to do
3679 * better than that (if we could, the better code would belong
3680 * in time.time()!) We're limited by the precision of a double,
3681 * though.
3682 */
3683 PyObject *time;
3684 double dtime;
3685
3686 time = time_time();
3687 if (time == NULL)
3688 return NULL;
3689 dtime = PyFloat_AsDouble(time);
3690 Py_DECREF(time);
3691 if (dtime == -1.0 && PyErr_Occurred())
3692 return NULL;
3693 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3694#endif /* ! HAVE_GETTIMEOFDAY */
3695}
3696
Tim Peters2a799bf2002-12-16 20:18:38 +00003697/* Return best possible local time -- this isn't constrained by the
3698 * precision of a timestamp.
3699 */
3700static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003701datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003702{
Tim Peters10cadce2003-01-23 19:58:02 +00003703 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003704 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003705 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003706
Tim Peters10cadce2003-01-23 19:58:02 +00003707 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3708 &tzinfo))
3709 return NULL;
3710 if (check_tzinfo_subclass(tzinfo) < 0)
3711 return NULL;
3712
3713 self = datetime_best_possible(cls,
3714 tzinfo == Py_None ? localtime : gmtime,
3715 tzinfo);
3716 if (self != NULL && tzinfo != Py_None) {
3717 /* Convert UTC to tzinfo's zone. */
3718 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003719 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003720 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003721 }
3722 return self;
3723}
3724
Tim Petersa9bc1682003-01-11 03:39:11 +00003725/* Return best possible UTC time -- this isn't constrained by the
3726 * precision of a timestamp.
3727 */
3728static PyObject *
3729datetime_utcnow(PyObject *cls, PyObject *dummy)
3730{
3731 return datetime_best_possible(cls, gmtime, Py_None);
3732}
3733
Tim Peters2a799bf2002-12-16 20:18:38 +00003734/* Return new local datetime from timestamp (Python timestamp -- a double). */
3735static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003736datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003737{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003738 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003739 double timestamp;
3740 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003741 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003742
Tim Peters2a44a8d2003-01-23 20:53:10 +00003743 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3744 keywords, &timestamp, &tzinfo))
3745 return NULL;
3746 if (check_tzinfo_subclass(tzinfo) < 0)
3747 return NULL;
3748
3749 self = datetime_from_timestamp(cls,
3750 tzinfo == Py_None ? localtime : gmtime,
3751 timestamp,
3752 tzinfo);
3753 if (self != NULL && tzinfo != Py_None) {
3754 /* Convert UTC to tzinfo's zone. */
3755 PyObject *temp = self;
3756 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3757 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003758 }
3759 return self;
3760}
3761
Tim Petersa9bc1682003-01-11 03:39:11 +00003762/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3763static PyObject *
3764datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3765{
3766 double timestamp;
3767 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003768
Tim Petersa9bc1682003-01-11 03:39:11 +00003769 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3770 result = datetime_from_timestamp(cls, gmtime, timestamp,
3771 Py_None);
3772 return result;
3773}
3774
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003775/* Return new datetime from time.strptime(). */
3776static PyObject *
3777datetime_strptime(PyObject *cls, PyObject *args)
3778{
3779 PyObject *result = NULL, *obj, *module;
3780 const char *string, *format;
3781
3782 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3783 return NULL;
3784
3785 if ((module = PyImport_ImportModule("time")) == NULL)
3786 return NULL;
3787 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3788 Py_DECREF(module);
3789
3790 if (obj != NULL) {
3791 int i, good_timetuple = 1;
3792 long int ia[6];
3793 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3794 for (i=0; i < 6; i++) {
3795 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003796 if (p == NULL) {
3797 Py_DECREF(obj);
3798 return NULL;
3799 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003800 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003801 ia[i] = PyInt_AsLong(p);
3802 else
3803 good_timetuple = 0;
3804 Py_DECREF(p);
3805 }
3806 else
3807 good_timetuple = 0;
3808 if (good_timetuple)
3809 result = PyObject_CallFunction(cls, "iiiiii",
3810 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3811 else
3812 PyErr_SetString(PyExc_ValueError,
3813 "unexpected value from time.strptime");
3814 Py_DECREF(obj);
3815 }
3816 return result;
3817}
3818
Tim Petersa9bc1682003-01-11 03:39:11 +00003819/* Return new datetime from date/datetime and time arguments. */
3820static PyObject *
3821datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3822{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003823 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003824 PyObject *date;
3825 PyObject *time;
3826 PyObject *result = NULL;
3827
3828 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3829 &PyDateTime_DateType, &date,
3830 &PyDateTime_TimeType, &time)) {
3831 PyObject *tzinfo = Py_None;
3832
3833 if (HASTZINFO(time))
3834 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3835 result = PyObject_CallFunction(cls, "iiiiiiiO",
3836 GET_YEAR(date),
3837 GET_MONTH(date),
3838 GET_DAY(date),
3839 TIME_GET_HOUR(time),
3840 TIME_GET_MINUTE(time),
3841 TIME_GET_SECOND(time),
3842 TIME_GET_MICROSECOND(time),
3843 tzinfo);
3844 }
3845 return result;
3846}
Tim Peters2a799bf2002-12-16 20:18:38 +00003847
3848/*
3849 * Destructor.
3850 */
3851
3852static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003853datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003854{
Tim Petersa9bc1682003-01-11 03:39:11 +00003855 if (HASTZINFO(self)) {
3856 Py_XDECREF(self->tzinfo);
3857 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003858 self->ob_type->tp_free((PyObject *)self);
3859}
3860
3861/*
3862 * Indirect access to tzinfo methods.
3863 */
3864
Tim Peters2a799bf2002-12-16 20:18:38 +00003865/* These are all METH_NOARGS, so don't need to check the arglist. */
3866static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003867datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3868 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3869 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003870}
3871
3872static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003873datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3874 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3875 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003876}
3877
3878static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003879datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3880 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3881 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003882}
3883
3884/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003885 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003886 */
3887
Tim Petersa9bc1682003-01-11 03:39:11 +00003888/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3889 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003890 */
3891static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003892add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3893 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003894{
Tim Petersa9bc1682003-01-11 03:39:11 +00003895 /* Note that the C-level additions can't overflow, because of
3896 * invariant bounds on the member values.
3897 */
3898 int year = GET_YEAR(date);
3899 int month = GET_MONTH(date);
3900 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3901 int hour = DATE_GET_HOUR(date);
3902 int minute = DATE_GET_MINUTE(date);
3903 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3904 int microsecond = DATE_GET_MICROSECOND(date) +
3905 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003906
Tim Petersa9bc1682003-01-11 03:39:11 +00003907 assert(factor == 1 || factor == -1);
3908 if (normalize_datetime(&year, &month, &day,
3909 &hour, &minute, &second, &microsecond) < 0)
3910 return NULL;
3911 else
3912 return new_datetime(year, month, day,
3913 hour, minute, second, microsecond,
3914 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003915}
3916
3917static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003918datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003919{
Tim Petersa9bc1682003-01-11 03:39:11 +00003920 if (PyDateTime_Check(left)) {
3921 /* datetime + ??? */
3922 if (PyDelta_Check(right))
3923 /* datetime + delta */
3924 return add_datetime_timedelta(
3925 (PyDateTime_DateTime *)left,
3926 (PyDateTime_Delta *)right,
3927 1);
3928 }
3929 else if (PyDelta_Check(left)) {
3930 /* delta + datetime */
3931 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3932 (PyDateTime_Delta *) left,
3933 1);
3934 }
3935 Py_INCREF(Py_NotImplemented);
3936 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003937}
3938
3939static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003940datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003941{
3942 PyObject *result = Py_NotImplemented;
3943
3944 if (PyDateTime_Check(left)) {
3945 /* datetime - ??? */
3946 if (PyDateTime_Check(right)) {
3947 /* datetime - datetime */
3948 naivety n1, n2;
3949 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003950 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003951
Tim Peterse39a80c2002-12-30 21:28:52 +00003952 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3953 right, &offset2, &n2,
3954 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003955 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003956 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003957 if (n1 != n2) {
3958 PyErr_SetString(PyExc_TypeError,
3959 "can't subtract offset-naive and "
3960 "offset-aware datetimes");
3961 return NULL;
3962 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003963 delta_d = ymd_to_ord(GET_YEAR(left),
3964 GET_MONTH(left),
3965 GET_DAY(left)) -
3966 ymd_to_ord(GET_YEAR(right),
3967 GET_MONTH(right),
3968 GET_DAY(right));
3969 /* These can't overflow, since the values are
3970 * normalized. At most this gives the number of
3971 * seconds in one day.
3972 */
3973 delta_s = (DATE_GET_HOUR(left) -
3974 DATE_GET_HOUR(right)) * 3600 +
3975 (DATE_GET_MINUTE(left) -
3976 DATE_GET_MINUTE(right)) * 60 +
3977 (DATE_GET_SECOND(left) -
3978 DATE_GET_SECOND(right));
3979 delta_us = DATE_GET_MICROSECOND(left) -
3980 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003981 /* (left - offset1) - (right - offset2) =
3982 * (left - right) + (offset2 - offset1)
3983 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003984 delta_s += (offset2 - offset1) * 60;
3985 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003986 }
3987 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003988 /* datetime - delta */
3989 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003990 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00003991 (PyDateTime_Delta *)right,
3992 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003993 }
3994 }
3995
3996 if (result == Py_NotImplemented)
3997 Py_INCREF(result);
3998 return result;
3999}
4000
4001/* Various ways to turn a datetime into a string. */
4002
4003static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004004datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004005{
Tim Petersa9bc1682003-01-11 03:39:11 +00004006 char buffer[1000];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004007 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004008 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004009
Tim Petersa9bc1682003-01-11 03:39:11 +00004010 if (DATE_GET_MICROSECOND(self)) {
4011 PyOS_snprintf(buffer, sizeof(buffer),
4012 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004013 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004014 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4015 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4016 DATE_GET_SECOND(self),
4017 DATE_GET_MICROSECOND(self));
4018 }
4019 else if (DATE_GET_SECOND(self)) {
4020 PyOS_snprintf(buffer, sizeof(buffer),
4021 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004022 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004023 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4024 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4025 DATE_GET_SECOND(self));
4026 }
4027 else {
4028 PyOS_snprintf(buffer, sizeof(buffer),
4029 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004030 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004031 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4032 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4033 }
4034 baserepr = PyString_FromString(buffer);
4035 if (baserepr == NULL || ! HASTZINFO(self))
4036 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004037 return append_keyword_tzinfo(baserepr, self->tzinfo);
4038}
4039
Tim Petersa9bc1682003-01-11 03:39:11 +00004040static PyObject *
4041datetime_str(PyDateTime_DateTime *self)
4042{
4043 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4044}
Tim Peters2a799bf2002-12-16 20:18:38 +00004045
4046static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004047datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004048{
Tim Petersa9bc1682003-01-11 03:39:11 +00004049 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004050 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004051 char buffer[100];
4052 char *cp;
4053 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004054
Tim Petersa9bc1682003-01-11 03:39:11 +00004055 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4056 &sep))
4057 return NULL;
4058 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4059 assert(cp != NULL);
4060 *cp++ = sep;
4061 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4062 result = PyString_FromString(buffer);
4063 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004064 return result;
4065
4066 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004067 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004068 (PyObject *)self) < 0) {
4069 Py_DECREF(result);
4070 return NULL;
4071 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004072 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004073 return result;
4074}
4075
Tim Petersa9bc1682003-01-11 03:39:11 +00004076static PyObject *
4077datetime_ctime(PyDateTime_DateTime *self)
4078{
4079 return format_ctime((PyDateTime_Date *)self,
4080 DATE_GET_HOUR(self),
4081 DATE_GET_MINUTE(self),
4082 DATE_GET_SECOND(self));
4083}
4084
Tim Peters2a799bf2002-12-16 20:18:38 +00004085/* Miscellaneous methods. */
4086
Tim Petersa9bc1682003-01-11 03:39:11 +00004087static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004088datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004089{
4090 int diff;
4091 naivety n1, n2;
4092 int offset1, offset2;
4093
4094 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004095 if (PyDate_Check(other)) {
4096 /* Prevent invocation of date_richcompare. We want to
4097 return NotImplemented here to give the other object
4098 a chance. But since DateTime is a subclass of
4099 Date, if the other object is a Date, it would
4100 compute an ordering based on the date part alone,
4101 and we don't want that. So force unequal or
4102 uncomparable here in that case. */
4103 if (op == Py_EQ)
4104 Py_RETURN_FALSE;
4105 if (op == Py_NE)
4106 Py_RETURN_TRUE;
4107 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004108 }
Guido van Rossum19960592006-08-24 17:29:38 +00004109 Py_INCREF(Py_NotImplemented);
4110 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004111 }
4112
Guido van Rossum19960592006-08-24 17:29:38 +00004113 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4114 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004115 return NULL;
4116 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4117 /* If they're both naive, or both aware and have the same offsets,
4118 * we get off cheap. Note that if they're both naive, offset1 ==
4119 * offset2 == 0 at this point.
4120 */
4121 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004122 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4123 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004124 _PyDateTime_DATETIME_DATASIZE);
4125 return diff_to_bool(diff, op);
4126 }
4127
4128 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4129 PyDateTime_Delta *delta;
4130
4131 assert(offset1 != offset2); /* else last "if" handled it */
4132 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4133 other);
4134 if (delta == NULL)
4135 return NULL;
4136 diff = GET_TD_DAYS(delta);
4137 if (diff == 0)
4138 diff = GET_TD_SECONDS(delta) |
4139 GET_TD_MICROSECONDS(delta);
4140 Py_DECREF(delta);
4141 return diff_to_bool(diff, op);
4142 }
4143
4144 assert(n1 != n2);
4145 PyErr_SetString(PyExc_TypeError,
4146 "can't compare offset-naive and "
4147 "offset-aware datetimes");
4148 return NULL;
4149}
4150
4151static long
4152datetime_hash(PyDateTime_DateTime *self)
4153{
4154 if (self->hashcode == -1) {
4155 naivety n;
4156 int offset;
4157 PyObject *temp;
4158
4159 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4160 &offset);
4161 assert(n != OFFSET_UNKNOWN);
4162 if (n == OFFSET_ERROR)
4163 return -1;
4164
4165 /* Reduce this to a hash of another object. */
4166 if (n == OFFSET_NAIVE)
4167 temp = PyString_FromStringAndSize(
4168 (char *)self->data,
4169 _PyDateTime_DATETIME_DATASIZE);
4170 else {
4171 int days;
4172 int seconds;
4173
4174 assert(n == OFFSET_AWARE);
4175 assert(HASTZINFO(self));
4176 days = ymd_to_ord(GET_YEAR(self),
4177 GET_MONTH(self),
4178 GET_DAY(self));
4179 seconds = DATE_GET_HOUR(self) * 3600 +
4180 (DATE_GET_MINUTE(self) - offset) * 60 +
4181 DATE_GET_SECOND(self);
4182 temp = new_delta(days,
4183 seconds,
4184 DATE_GET_MICROSECOND(self),
4185 1);
4186 }
4187 if (temp != NULL) {
4188 self->hashcode = PyObject_Hash(temp);
4189 Py_DECREF(temp);
4190 }
4191 }
4192 return self->hashcode;
4193}
Tim Peters2a799bf2002-12-16 20:18:38 +00004194
4195static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004196datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004197{
4198 PyObject *clone;
4199 PyObject *tuple;
4200 int y = GET_YEAR(self);
4201 int m = GET_MONTH(self);
4202 int d = GET_DAY(self);
4203 int hh = DATE_GET_HOUR(self);
4204 int mm = DATE_GET_MINUTE(self);
4205 int ss = DATE_GET_SECOND(self);
4206 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004207 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004208
4209 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004210 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004211 &y, &m, &d, &hh, &mm, &ss, &us,
4212 &tzinfo))
4213 return NULL;
4214 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4215 if (tuple == NULL)
4216 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004217 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004218 Py_DECREF(tuple);
4219 return clone;
4220}
4221
4222static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004223datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004224{
Tim Peters52dcce22003-01-23 16:36:11 +00004225 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004226 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004227 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004228
Tim Peters80475bb2002-12-25 07:40:55 +00004229 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004230 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004231
Tim Peters52dcce22003-01-23 16:36:11 +00004232 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4233 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004234 return NULL;
4235
Tim Peters52dcce22003-01-23 16:36:11 +00004236 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4237 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004238
Tim Peters52dcce22003-01-23 16:36:11 +00004239 /* Conversion to self's own time zone is a NOP. */
4240 if (self->tzinfo == tzinfo) {
4241 Py_INCREF(self);
4242 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004243 }
Tim Peters521fc152002-12-31 17:36:56 +00004244
Tim Peters52dcce22003-01-23 16:36:11 +00004245 /* Convert self to UTC. */
4246 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4247 if (offset == -1 && PyErr_Occurred())
4248 return NULL;
4249 if (none)
4250 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004251
Tim Peters52dcce22003-01-23 16:36:11 +00004252 y = GET_YEAR(self);
4253 m = GET_MONTH(self);
4254 d = GET_DAY(self);
4255 hh = DATE_GET_HOUR(self);
4256 mm = DATE_GET_MINUTE(self);
4257 ss = DATE_GET_SECOND(self);
4258 us = DATE_GET_MICROSECOND(self);
4259
4260 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004261 if ((mm < 0 || mm >= 60) &&
4262 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004263 return NULL;
4264
4265 /* Attach new tzinfo and let fromutc() do the rest. */
4266 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4267 if (result != NULL) {
4268 PyObject *temp = result;
4269
4270 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4271 Py_DECREF(temp);
4272 }
Tim Petersadf64202003-01-04 06:03:15 +00004273 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004274
Tim Peters52dcce22003-01-23 16:36:11 +00004275NeedAware:
4276 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4277 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004278 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004279}
4280
4281static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004282datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004283{
4284 int dstflag = -1;
4285
Tim Petersa9bc1682003-01-11 03:39:11 +00004286 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004287 int none;
4288
4289 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4290 if (dstflag == -1 && PyErr_Occurred())
4291 return NULL;
4292
4293 if (none)
4294 dstflag = -1;
4295 else if (dstflag != 0)
4296 dstflag = 1;
4297
4298 }
4299 return build_struct_time(GET_YEAR(self),
4300 GET_MONTH(self),
4301 GET_DAY(self),
4302 DATE_GET_HOUR(self),
4303 DATE_GET_MINUTE(self),
4304 DATE_GET_SECOND(self),
4305 dstflag);
4306}
4307
4308static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004309datetime_getdate(PyDateTime_DateTime *self)
4310{
4311 return new_date(GET_YEAR(self),
4312 GET_MONTH(self),
4313 GET_DAY(self));
4314}
4315
4316static PyObject *
4317datetime_gettime(PyDateTime_DateTime *self)
4318{
4319 return new_time(DATE_GET_HOUR(self),
4320 DATE_GET_MINUTE(self),
4321 DATE_GET_SECOND(self),
4322 DATE_GET_MICROSECOND(self),
4323 Py_None);
4324}
4325
4326static PyObject *
4327datetime_gettimetz(PyDateTime_DateTime *self)
4328{
4329 return new_time(DATE_GET_HOUR(self),
4330 DATE_GET_MINUTE(self),
4331 DATE_GET_SECOND(self),
4332 DATE_GET_MICROSECOND(self),
4333 HASTZINFO(self) ? self->tzinfo : Py_None);
4334}
4335
4336static PyObject *
4337datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004338{
4339 int y = GET_YEAR(self);
4340 int m = GET_MONTH(self);
4341 int d = GET_DAY(self);
4342 int hh = DATE_GET_HOUR(self);
4343 int mm = DATE_GET_MINUTE(self);
4344 int ss = DATE_GET_SECOND(self);
4345 int us = 0; /* microseconds are ignored in a timetuple */
4346 int offset = 0;
4347
Tim Petersa9bc1682003-01-11 03:39:11 +00004348 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004349 int none;
4350
4351 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4352 if (offset == -1 && PyErr_Occurred())
4353 return NULL;
4354 }
4355 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4356 * 0 in a UTC timetuple regardless of what dst() says.
4357 */
4358 if (offset) {
4359 /* Subtract offset minutes & normalize. */
4360 int stat;
4361
4362 mm -= offset;
4363 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4364 if (stat < 0) {
4365 /* At the edges, it's possible we overflowed
4366 * beyond MINYEAR or MAXYEAR.
4367 */
4368 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4369 PyErr_Clear();
4370 else
4371 return NULL;
4372 }
4373 }
4374 return build_struct_time(y, m, d, hh, mm, ss, 0);
4375}
4376
Tim Peters371935f2003-02-01 01:52:50 +00004377/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004378
Tim Petersa9bc1682003-01-11 03:39:11 +00004379/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004380 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4381 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004382 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004383 */
4384static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004385datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004386{
4387 PyObject *basestate;
4388 PyObject *result = NULL;
4389
Tim Peters33e0f382003-01-10 02:05:14 +00004390 basestate = PyString_FromStringAndSize((char *)self->data,
4391 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004392 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004393 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004394 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004395 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004396 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004397 Py_DECREF(basestate);
4398 }
4399 return result;
4400}
4401
4402static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004403datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004404{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004405 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004406}
4407
Tim Petersa9bc1682003-01-11 03:39:11 +00004408static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004409
Tim Peters2a799bf2002-12-16 20:18:38 +00004410 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004411
Tim Petersa9bc1682003-01-11 03:39:11 +00004412 {"now", (PyCFunction)datetime_now,
Tim Peters2a799bf2002-12-16 20:18:38 +00004413 METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004414 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004415
Tim Petersa9bc1682003-01-11 03:39:11 +00004416 {"utcnow", (PyCFunction)datetime_utcnow,
4417 METH_NOARGS | METH_CLASS,
4418 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4419
4420 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Tim Peters2a799bf2002-12-16 20:18:38 +00004421 METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004422 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004423
Tim Petersa9bc1682003-01-11 03:39:11 +00004424 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4425 METH_VARARGS | METH_CLASS,
4426 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4427 "(like time.time()).")},
4428
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004429 {"strptime", (PyCFunction)datetime_strptime,
4430 METH_VARARGS | METH_CLASS,
4431 PyDoc_STR("string, format -> new datetime parsed from a string "
4432 "(like time.strptime()).")},
4433
Tim Petersa9bc1682003-01-11 03:39:11 +00004434 {"combine", (PyCFunction)datetime_combine,
4435 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4436 PyDoc_STR("date, time -> datetime with same date and time fields")},
4437
Tim Peters2a799bf2002-12-16 20:18:38 +00004438 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004439
Tim Petersa9bc1682003-01-11 03:39:11 +00004440 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4441 PyDoc_STR("Return date object with same year, month and day.")},
4442
4443 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4444 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4445
4446 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4447 PyDoc_STR("Return time object with same time and tzinfo.")},
4448
4449 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4450 PyDoc_STR("Return ctime() style string.")},
4451
4452 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004453 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4454
Tim Petersa9bc1682003-01-11 03:39:11 +00004455 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004456 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4457
Tim Petersa9bc1682003-01-11 03:39:11 +00004458 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004459 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4460 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4461 "sep is used to separate the year from the time, and "
4462 "defaults to 'T'.")},
4463
Tim Petersa9bc1682003-01-11 03:39:11 +00004464 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004465 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4466
Tim Petersa9bc1682003-01-11 03:39:11 +00004467 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004468 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4469
Tim Petersa9bc1682003-01-11 03:39:11 +00004470 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004471 PyDoc_STR("Return self.tzinfo.dst(self).")},
4472
Tim Petersa9bc1682003-01-11 03:39:11 +00004473 {"replace", (PyCFunction)datetime_replace, METH_KEYWORDS,
4474 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004475
Tim Petersa9bc1682003-01-11 03:39:11 +00004476 {"astimezone", (PyCFunction)datetime_astimezone, METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004477 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4478
Guido van Rossum177e41a2003-01-30 22:06:23 +00004479 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4480 PyDoc_STR("__reduce__() -> (cls, state)")},
4481
Tim Peters2a799bf2002-12-16 20:18:38 +00004482 {NULL, NULL}
4483};
4484
Tim Petersa9bc1682003-01-11 03:39:11 +00004485static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004486PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4487\n\
4488The year, month and day arguments are required. tzinfo may be None, or an\n\
4489instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004490
Tim Petersa9bc1682003-01-11 03:39:11 +00004491static PyNumberMethods datetime_as_number = {
4492 datetime_add, /* nb_add */
4493 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004494 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004495 0, /* nb_remainder */
4496 0, /* nb_divmod */
4497 0, /* nb_power */
4498 0, /* nb_negative */
4499 0, /* nb_positive */
4500 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004501 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004502};
4503
Neal Norwitz227b5332006-03-22 09:28:35 +00004504static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004505 PyObject_HEAD_INIT(NULL)
4506 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004507 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004508 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004509 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004510 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004511 0, /* tp_print */
4512 0, /* tp_getattr */
4513 0, /* tp_setattr */
4514 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004515 (reprfunc)datetime_repr, /* tp_repr */
4516 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004517 0, /* tp_as_sequence */
4518 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004519 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004520 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004521 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004522 PyObject_GenericGetAttr, /* tp_getattro */
4523 0, /* tp_setattro */
4524 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004525 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004526 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 0, /* tp_traverse */
4528 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004529 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004530 0, /* tp_weaklistoffset */
4531 0, /* tp_iter */
4532 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004533 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004534 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004535 datetime_getset, /* tp_getset */
4536 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004537 0, /* tp_dict */
4538 0, /* tp_descr_get */
4539 0, /* tp_descr_set */
4540 0, /* tp_dictoffset */
4541 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004542 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004543 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004544 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004545};
4546
4547/* ---------------------------------------------------------------------------
4548 * Module methods and initialization.
4549 */
4550
4551static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004552 {NULL, NULL}
4553};
4554
Tim Peters9ddf40b2004-06-20 22:41:32 +00004555/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4556 * datetime.h.
4557 */
4558static PyDateTime_CAPI CAPI = {
4559 &PyDateTime_DateType,
4560 &PyDateTime_DateTimeType,
4561 &PyDateTime_TimeType,
4562 &PyDateTime_DeltaType,
4563 &PyDateTime_TZInfoType,
4564 new_date_ex,
4565 new_datetime_ex,
4566 new_time_ex,
4567 new_delta_ex,
4568 datetime_fromtimestamp,
4569 date_fromtimestamp
4570};
4571
4572
Tim Peters2a799bf2002-12-16 20:18:38 +00004573PyMODINIT_FUNC
4574initdatetime(void)
4575{
4576 PyObject *m; /* a module object */
4577 PyObject *d; /* its dict */
4578 PyObject *x;
4579
Tim Peters2a799bf2002-12-16 20:18:38 +00004580 m = Py_InitModule3("datetime", module_methods,
4581 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004582 if (m == NULL)
4583 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004584
4585 if (PyType_Ready(&PyDateTime_DateType) < 0)
4586 return;
4587 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4588 return;
4589 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4590 return;
4591 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4592 return;
4593 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4594 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004595
Tim Peters2a799bf2002-12-16 20:18:38 +00004596 /* timedelta values */
4597 d = PyDateTime_DeltaType.tp_dict;
4598
Tim Peters2a799bf2002-12-16 20:18:38 +00004599 x = new_delta(0, 0, 1, 0);
4600 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4601 return;
4602 Py_DECREF(x);
4603
4604 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4605 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4606 return;
4607 Py_DECREF(x);
4608
4609 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4610 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4611 return;
4612 Py_DECREF(x);
4613
4614 /* date values */
4615 d = PyDateTime_DateType.tp_dict;
4616
4617 x = new_date(1, 1, 1);
4618 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4619 return;
4620 Py_DECREF(x);
4621
4622 x = new_date(MAXYEAR, 12, 31);
4623 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4624 return;
4625 Py_DECREF(x);
4626
4627 x = new_delta(1, 0, 0, 0);
4628 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4629 return;
4630 Py_DECREF(x);
4631
Tim Peters37f39822003-01-10 03:49:02 +00004632 /* time values */
4633 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004634
Tim Peters37f39822003-01-10 03:49:02 +00004635 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004636 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4637 return;
4638 Py_DECREF(x);
4639
Tim Peters37f39822003-01-10 03:49:02 +00004640 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004641 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4642 return;
4643 Py_DECREF(x);
4644
4645 x = new_delta(0, 0, 1, 0);
4646 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4647 return;
4648 Py_DECREF(x);
4649
Tim Petersa9bc1682003-01-11 03:39:11 +00004650 /* datetime values */
4651 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004652
Tim Petersa9bc1682003-01-11 03:39:11 +00004653 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004654 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4655 return;
4656 Py_DECREF(x);
4657
Tim Petersa9bc1682003-01-11 03:39:11 +00004658 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004659 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4660 return;
4661 Py_DECREF(x);
4662
4663 x = new_delta(0, 0, 1, 0);
4664 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4665 return;
4666 Py_DECREF(x);
4667
Tim Peters2a799bf2002-12-16 20:18:38 +00004668 /* module initialization */
4669 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4670 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4671
4672 Py_INCREF(&PyDateTime_DateType);
4673 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4674
Tim Petersa9bc1682003-01-11 03:39:11 +00004675 Py_INCREF(&PyDateTime_DateTimeType);
4676 PyModule_AddObject(m, "datetime",
4677 (PyObject *)&PyDateTime_DateTimeType);
4678
4679 Py_INCREF(&PyDateTime_TimeType);
4680 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4681
Tim Peters2a799bf2002-12-16 20:18:38 +00004682 Py_INCREF(&PyDateTime_DeltaType);
4683 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4684
Tim Peters2a799bf2002-12-16 20:18:38 +00004685 Py_INCREF(&PyDateTime_TZInfoType);
4686 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4687
Tim Peters9ddf40b2004-06-20 22:41:32 +00004688 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4689 NULL);
4690 if (x == NULL)
4691 return;
4692 PyModule_AddObject(m, "datetime_CAPI", x);
4693
Tim Peters2a799bf2002-12-16 20:18:38 +00004694 /* A 4-year cycle has an extra leap day over what we'd get from
4695 * pasting together 4 single years.
4696 */
4697 assert(DI4Y == 4 * 365 + 1);
4698 assert(DI4Y == days_before_year(4+1));
4699
4700 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4701 * get from pasting together 4 100-year cycles.
4702 */
4703 assert(DI400Y == 4 * DI100Y + 1);
4704 assert(DI400Y == days_before_year(400+1));
4705
4706 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4707 * pasting together 25 4-year cycles.
4708 */
4709 assert(DI100Y == 25 * DI4Y - 1);
4710 assert(DI100Y == days_before_year(100+1));
4711
4712 us_per_us = PyInt_FromLong(1);
4713 us_per_ms = PyInt_FromLong(1000);
4714 us_per_second = PyInt_FromLong(1000000);
4715 us_per_minute = PyInt_FromLong(60000000);
4716 seconds_per_day = PyInt_FromLong(24 * 3600);
4717 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4718 us_per_minute == NULL || seconds_per_day == NULL)
4719 return;
4720
4721 /* The rest are too big for 32-bit ints, but even
4722 * us_per_week fits in 40 bits, so doubles should be exact.
4723 */
4724 us_per_hour = PyLong_FromDouble(3600000000.0);
4725 us_per_day = PyLong_FromDouble(86400000000.0);
4726 us_per_week = PyLong_FromDouble(604800000000.0);
4727 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4728 return;
4729}
Tim Petersf3615152003-01-01 21:51:37 +00004730
4731/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004732Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004733 x.n = x stripped of its timezone -- its naive time.
4734 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4735 return None
4736 x.d = x.dst(), and assuming that doesn't raise an exception or
4737 return None
4738 x.s = x's standard offset, x.o - x.d
4739
4740Now some derived rules, where k is a duration (timedelta).
4741
47421. x.o = x.s + x.d
4743 This follows from the definition of x.s.
4744
Tim Petersc5dc4da2003-01-02 17:55:03 +000047452. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004746 This is actually a requirement, an assumption we need to make about
4747 sane tzinfo classes.
4748
47493. The naive UTC time corresponding to x is x.n - x.o.
4750 This is again a requirement for a sane tzinfo class.
4751
47524. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004753 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004754
Tim Petersc5dc4da2003-01-02 17:55:03 +000047555. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004756 Again follows from how arithmetic is defined.
4757
Tim Peters8bb5ad22003-01-24 02:44:45 +00004758Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004759(meaning that the various tzinfo methods exist, and don't blow up or return
4760None when called).
4761
Tim Petersa9bc1682003-01-11 03:39:11 +00004762The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004763x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004764
4765By #3, we want
4766
Tim Peters8bb5ad22003-01-24 02:44:45 +00004767 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004768
4769The algorithm starts by attaching tz to x.n, and calling that y. So
4770x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4771becomes true; in effect, we want to solve [2] for k:
4772
Tim Peters8bb5ad22003-01-24 02:44:45 +00004773 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004774
4775By #1, this is the same as
4776
Tim Peters8bb5ad22003-01-24 02:44:45 +00004777 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004778
4779By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4780Substituting that into [3],
4781
Tim Peters8bb5ad22003-01-24 02:44:45 +00004782 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4783 k - (y+k).s - (y+k).d = 0; rearranging,
4784 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4785 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004786
Tim Peters8bb5ad22003-01-24 02:44:45 +00004787On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4788approximate k by ignoring the (y+k).d term at first. Note that k can't be
4789very large, since all offset-returning methods return a duration of magnitude
4790less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4791be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004792
4793In any case, the new value is
4794
Tim Peters8bb5ad22003-01-24 02:44:45 +00004795 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004796
Tim Peters8bb5ad22003-01-24 02:44:45 +00004797It's helpful to step back at look at [4] from a higher level: it's simply
4798mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004799
4800At this point, if
4801
Tim Peters8bb5ad22003-01-24 02:44:45 +00004802 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004803
4804we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004805at the start of daylight time. Picture US Eastern for concreteness. The wall
4806time 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 +00004807sense then. The docs ask that an Eastern tzinfo class consider such a time to
4808be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4809on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004810the only spelling that makes sense on the local wall clock.
4811
Tim Petersc5dc4da2003-01-02 17:55:03 +00004812In fact, if [5] holds at this point, we do have the standard-time spelling,
4813but that takes a bit of proof. We first prove a stronger result. What's the
4814difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004815
Tim Peters8bb5ad22003-01-24 02:44:45 +00004816 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004817
Tim Petersc5dc4da2003-01-02 17:55:03 +00004818Now
4819 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004820 (y + y.s).n = by #5
4821 y.n + y.s = since y.n = x.n
4822 x.n + y.s = since z and y are have the same tzinfo member,
4823 y.s = z.s by #2
4824 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004825
Tim Petersc5dc4da2003-01-02 17:55:03 +00004826Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004827
Tim Petersc5dc4da2003-01-02 17:55:03 +00004828 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004829 x.n - ((x.n + z.s) - z.o) = expanding
4830 x.n - x.n - z.s + z.o = cancelling
4831 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004832 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004833
Tim Petersc5dc4da2003-01-02 17:55:03 +00004834So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004835
Tim Petersc5dc4da2003-01-02 17:55:03 +00004836If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004837spelling we wanted in the endcase described above. We're done. Contrarily,
4838if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004839
Tim Petersc5dc4da2003-01-02 17:55:03 +00004840If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4841add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004842local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004843
Tim Petersc5dc4da2003-01-02 17:55:03 +00004844Let
Tim Petersf3615152003-01-01 21:51:37 +00004845
Tim Peters4fede1a2003-01-04 00:26:59 +00004846 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004847
Tim Peters4fede1a2003-01-04 00:26:59 +00004848and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004849
Tim Peters8bb5ad22003-01-24 02:44:45 +00004850 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004851
Tim Peters8bb5ad22003-01-24 02:44:45 +00004852If so, we're done. If not, the tzinfo class is insane, according to the
4853assumptions we've made. This also requires a bit of proof. As before, let's
4854compute the difference between the LHS and RHS of [8] (and skipping some of
4855the justifications for the kinds of substitutions we've done several times
4856already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004857
Tim Peters8bb5ad22003-01-24 02:44:45 +00004858 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4859 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4860 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4861 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4862 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004863 - z.o + z'.o = #1 twice
4864 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4865 z'.d - z.d
4866
4867So 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 +00004868we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4869return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004870
Tim Peters8bb5ad22003-01-24 02:44:45 +00004871How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4872a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4873would have to change the result dst() returns: we start in DST, and moving
4874a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004875
Tim Peters8bb5ad22003-01-24 02:44:45 +00004876There isn't a sane case where this can happen. The closest it gets is at
4877the end of DST, where there's an hour in UTC with no spelling in a hybrid
4878tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4879that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4880UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4881time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4882clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4883standard time. Since that's what the local clock *does*, we want to map both
4884UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004885in local time, but so it goes -- it's the way the local clock works.
4886
Tim Peters8bb5ad22003-01-24 02:44:45 +00004887When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4888so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4889z' = 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 +00004890(correctly) concludes that z' is not UTC-equivalent to x.
4891
4892Because we know z.d said z was in daylight time (else [5] would have held and
4893we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004894and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004895return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4896but the reasoning doesn't depend on the example -- it depends on there being
4897two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004898z' must be in standard time, and is the spelling we want in this case.
4899
4900Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4901concerned (because it takes z' as being in standard time rather than the
4902daylight time we intend here), but returning it gives the real-life "local
4903clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4904tz.
4905
4906When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4907the 1:MM standard time spelling we want.
4908
4909So how can this break? One of the assumptions must be violated. Two
4910possibilities:
4911
49121) [2] effectively says that y.s is invariant across all y belong to a given
4913 time zone. This isn't true if, for political reasons or continental drift,
4914 a region decides to change its base offset from UTC.
4915
49162) There may be versions of "double daylight" time where the tail end of
4917 the analysis gives up a step too early. I haven't thought about that
4918 enough to say.
4919
4920In any case, it's clear that the default fromutc() is strong enough to handle
4921"almost all" time zones: so long as the standard offset is invariant, it
4922doesn't matter if daylight time transition points change from year to year, or
4923if daylight time is skipped in some years; it doesn't matter how large or
4924small dst() may get within its bounds; and it doesn't even matter if some
4925perverse time zone returns a negative dst()). So a breaking case must be
4926pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004927--------------------------------------------------------------------------- */