blob: 6955c784433297090d657fb825c9dcb65e69826e [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 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
28# error "datetime.c requires that C int have at least 32 bits"
29#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
33
34/* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
38 */
39#define MAX_DELTA_DAYS 999999999
40
41/* Rename the long macros in datetime.h to more reasonable short names. */
42#define GET_YEAR PyDateTime_GET_YEAR
43#define GET_MONTH PyDateTime_GET_MONTH
44#define GET_DAY PyDateTime_GET_DAY
45#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
49
50/* Date accessors for date and datetime. */
51#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
55
56/* Date/Time accessors for datetime. */
57#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60#define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
64
65/* Time accessors for time. */
66#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73#define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
77
78/* Delta accessors for timedelta. */
79#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
82
83#define SET_TD_DAYS(o, v) ((o)->days = (v))
84#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
85#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
86
Tim Petersa032d2e2003-01-11 00:15:54 +000087/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
89 */
90#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
91
Tim Peters3f606292004-03-21 23:38:41 +000092/* M is a char or int claiming to be a valid month. The macro is equivalent
93 * to the two-sided Python test
94 * 1 <= M <= 12
95 */
96#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
97
Tim Peters2a799bf2002-12-16 20:18:38 +000098/* Forward declarations. */
99static PyTypeObject PyDateTime_DateType;
100static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000101static PyTypeObject PyDateTime_DeltaType;
102static PyTypeObject PyDateTime_TimeType;
103static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000104
105/* ---------------------------------------------------------------------------
106 * Math utilities.
107 */
108
109/* k = i+j overflows iff k differs in sign from both inputs,
110 * iff k^i has sign bit set and k^j has sign bit set,
111 * iff (k^i)&(k^j) has sign bit set.
112 */
113#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
114 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
115
116/* Compute Python divmod(x, y), returning the quotient and storing the
117 * remainder into *r. The quotient is the floor of x/y, and that's
118 * the real point of this. C will probably truncate instead (C99
119 * requires truncation; C89 left it implementation-defined).
120 * Simplification: we *require* that y > 0 here. That's appropriate
121 * for all the uses made of it. This simplifies the code and makes
122 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
123 * overflow case).
124 */
125static int
126divmod(int x, int y, int *r)
127{
128 int quo;
129
130 assert(y > 0);
131 quo = x / y;
132 *r = x - quo * y;
133 if (*r < 0) {
134 --quo;
135 *r += y;
136 }
137 assert(0 <= *r && *r < y);
138 return quo;
139}
140
Tim Peters5d644dd2003-01-02 16:32:54 +0000141/* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
143 */
144static long
145round_to_long(double x)
146{
147 if (x >= 0.0)
148 x = floor(x + 0.5);
149 else
150 x = ceil(x - 0.5);
151 return (long)x;
152}
153
Tim Peters2a799bf2002-12-16 20:18:38 +0000154/* ---------------------------------------------------------------------------
155 * General calendrical helper functions
156 */
157
158/* For each month ordinal in 1..12, the number of days in that month,
159 * and the number of days before that month in the same year. These
160 * are correct for non-leap years only.
161 */
162static int _days_in_month[] = {
163 0, /* unused; this vector uses 1-based indexing */
164 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
165};
166
167static int _days_before_month[] = {
168 0, /* unused; this vector uses 1-based indexing */
169 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
170};
171
172/* year -> 1 if leap year, else 0. */
173static int
174is_leap(int year)
175{
176 /* Cast year to unsigned. The result is the same either way, but
177 * C can generate faster code for unsigned mod than for signed
178 * mod (especially for % 4 -- a good compiler should just grab
179 * the last 2 bits when the LHS is unsigned).
180 */
181 const unsigned int ayear = (unsigned int)year;
182 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
183}
184
185/* year, month -> number of days in that month in that year */
186static int
187days_in_month(int year, int month)
188{
189 assert(month >= 1);
190 assert(month <= 12);
191 if (month == 2 && is_leap(year))
192 return 29;
193 else
194 return _days_in_month[month];
195}
196
197/* year, month -> number of days in year preceeding first day of month */
198static int
199days_before_month(int year, int month)
200{
201 int days;
202
203 assert(month >= 1);
204 assert(month <= 12);
205 days = _days_before_month[month];
206 if (month > 2 && is_leap(year))
207 ++days;
208 return days;
209}
210
211/* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
213 */
214static int
215days_before_year(int year)
216{
217 int y = year - 1;
218 /* This is incorrect if year <= 0; we really want the floor
219 * here. But so long as MINYEAR is 1, the smallest year this
220 * can see is 0 (this can happen in some normalization endcases),
221 * so we'll just special-case that.
222 */
223 assert (year >= 0);
224 if (y >= 0)
225 return y*365 + y/4 - y/100 + y/400;
226 else {
227 assert(y == -1);
228 return -366;
229 }
230}
231
232/* Number of days in 4, 100, and 400 year cycles. That these have
233 * the correct values is asserted in the module init function.
234 */
235#define DI4Y 1461 /* days_before_year(5); days in 4 years */
236#define DI100Y 36524 /* days_before_year(101); days in 100 years */
237#define DI400Y 146097 /* days_before_year(401); days in 400 years */
238
239/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
240static void
241ord_to_ymd(int ordinal, int *year, int *month, int *day)
242{
243 int n, n1, n4, n100, n400, leapyear, preceding;
244
245 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
246 * leap years repeats exactly every 400 years. The basic strategy is
247 * to find the closest 400-year boundary at or before ordinal, then
248 * work with the offset from that boundary to ordinal. Life is much
249 * clearer if we subtract 1 from ordinal first -- then the values
250 * of ordinal at 400-year boundaries are exactly those divisible
251 * by DI400Y:
252 *
253 * D M Y n n-1
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
257 * ...
258 * 30 Dec 000 -1 -2
259 * 31 Dec 000 0 -1
260 * 1 Jan 001 1 0 400-year boundary
261 * 2 Jan 001 2 1
262 * 3 Jan 001 3 2
263 * ...
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
266 */
267 assert(ordinal >= 1);
268 --ordinal;
269 n400 = ordinal / DI400Y;
270 n = ordinal % DI400Y;
271 *year = n400 * 400 + 1;
272
273 /* Now n is the (non-negative) offset, in days, from January 1 of
274 * year, to the desired date. Now compute how many 100-year cycles
275 * precede n.
276 * Note that it's possible for n100 to equal 4! In that case 4 full
277 * 100-year cycles precede the desired day, which implies the
278 * desired day is December 31 at the end of a 400-year cycle.
279 */
280 n100 = n / DI100Y;
281 n = n % DI100Y;
282
283 /* Now compute how many 4-year cycles precede it. */
284 n4 = n / DI4Y;
285 n = n % DI4Y;
286
287 /* And now how many single years. Again n1 can be 4, and again
288 * meaning that the desired day is December 31 at the end of the
289 * 4-year cycle.
290 */
291 n1 = n / 365;
292 n = n % 365;
293
294 *year += n100 * 100 + n4 * 4 + n1;
295 if (n1 == 4 || n100 == 4) {
296 assert(n == 0);
297 *year -= 1;
298 *month = 12;
299 *day = 31;
300 return;
301 }
302
303 /* Now the year is correct, and n is the offset from January 1. We
304 * find the month via an estimate that's either exact or one too
305 * large.
306 */
307 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
308 assert(leapyear == is_leap(*year));
309 *month = (n + 50) >> 5;
310 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
311 if (preceding > n) {
312 /* estimate is too large */
313 *month -= 1;
314 preceding -= days_in_month(*year, *month);
315 }
316 n -= preceding;
317 assert(0 <= n);
318 assert(n < days_in_month(*year, *month));
319
320 *day = n + 1;
321}
322
323/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
324static int
325ymd_to_ord(int year, int month, int day)
326{
327 return days_before_year(year) + days_before_month(year, month) + day;
328}
329
330/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
331static int
332weekday(int year, int month, int day)
333{
334 return (ymd_to_ord(year, month, day) + 6) % 7;
335}
336
337/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
338 * first calendar week containing a Thursday.
339 */
340static int
341iso_week1_monday(int year)
342{
343 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
344 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
345 int first_weekday = (first_day + 6) % 7;
346 /* ordinal of closest Monday at or before 1/1 */
347 int week1_monday = first_day - first_weekday;
348
349 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
350 week1_monday += 7;
351 return week1_monday;
352}
353
354/* ---------------------------------------------------------------------------
355 * Range checkers.
356 */
357
358/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
360 */
361static int
362check_delta_day_range(int days)
363{
364 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
365 return 0;
366 PyErr_Format(PyExc_OverflowError,
367 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000368 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000369 return -1;
370}
371
372/* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
374 */
375static int
376check_date_args(int year, int month, int day)
377{
378
379 if (year < MINYEAR || year > MAXYEAR) {
380 PyErr_SetString(PyExc_ValueError,
381 "year is out of range");
382 return -1;
383 }
384 if (month < 1 || month > 12) {
385 PyErr_SetString(PyExc_ValueError,
386 "month must be in 1..12");
387 return -1;
388 }
389 if (day < 1 || day > days_in_month(year, month)) {
390 PyErr_SetString(PyExc_ValueError,
391 "day is out of range for month");
392 return -1;
393 }
394 return 0;
395}
396
397/* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_time_args(int h, int m, int s, int us)
402{
403 if (h < 0 || h > 23) {
404 PyErr_SetString(PyExc_ValueError,
405 "hour must be in 0..23");
406 return -1;
407 }
408 if (m < 0 || m > 59) {
409 PyErr_SetString(PyExc_ValueError,
410 "minute must be in 0..59");
411 return -1;
412 }
413 if (s < 0 || s > 59) {
414 PyErr_SetString(PyExc_ValueError,
415 "second must be in 0..59");
416 return -1;
417 }
418 if (us < 0 || us > 999999) {
419 PyErr_SetString(PyExc_ValueError,
420 "microsecond must be in 0..999999");
421 return -1;
422 }
423 return 0;
424}
425
426/* ---------------------------------------------------------------------------
427 * Normalization utilities.
428 */
429
430/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
431 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
432 * at least factor, enough of *lo is converted into "hi" units so that
433 * 0 <= *lo < factor. The input values must be such that int overflow
434 * is impossible.
435 */
436static void
437normalize_pair(int *hi, int *lo, int factor)
438{
439 assert(factor > 0);
440 assert(lo != hi);
441 if (*lo < 0 || *lo >= factor) {
442 const int num_hi = divmod(*lo, factor, lo);
443 const int new_hi = *hi + num_hi;
444 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
445 *hi = new_hi;
446 }
447 assert(0 <= *lo && *lo < factor);
448}
449
450/* Fiddle days (d), seconds (s), and microseconds (us) so that
451 * 0 <= *s < 24*3600
452 * 0 <= *us < 1000000
453 * The input values must be such that the internals don't overflow.
454 * The way this routine is used, we don't get close.
455 */
456static void
457normalize_d_s_us(int *d, int *s, int *us)
458{
459 if (*us < 0 || *us >= 1000000) {
460 normalize_pair(s, us, 1000000);
461 /* |s| can't be bigger than about
462 * |original s| + |original us|/1000000 now.
463 */
464
465 }
466 if (*s < 0 || *s >= 24*3600) {
467 normalize_pair(d, s, 24*3600);
468 /* |d| can't be bigger than about
469 * |original d| +
470 * (|original s| + |original us|/1000000) / (24*3600) now.
471 */
472 }
473 assert(0 <= *s && *s < 24*3600);
474 assert(0 <= *us && *us < 1000000);
475}
476
477/* Fiddle years (y), months (m), and days (d) so that
478 * 1 <= *m <= 12
479 * 1 <= *d <= days_in_month(*y, *m)
480 * The input values must be such that the internals don't overflow.
481 * The way this routine is used, we don't get close.
482 */
483static void
484normalize_y_m_d(int *y, int *m, int *d)
485{
486 int dim; /* # of days in month */
487
488 /* This gets muddy: the proper range for day can't be determined
489 * without knowing the correct month and year, but if day is, e.g.,
490 * plus or minus a million, the current month and year values make
491 * no sense (and may also be out of bounds themselves).
492 * Saying 12 months == 1 year should be non-controversial.
493 */
494 if (*m < 1 || *m > 12) {
495 --*m;
496 normalize_pair(y, m, 12);
497 ++*m;
498 /* |y| can't be bigger than about
499 * |original y| + |original m|/12 now.
500 */
501 }
502 assert(1 <= *m && *m <= 12);
503
504 /* Now only day can be out of bounds (year may also be out of bounds
505 * for a datetime object, but we don't care about that here).
506 * If day is out of bounds, what to do is arguable, but at least the
507 * method here is principled and explainable.
508 */
509 dim = days_in_month(*y, *m);
510 if (*d < 1 || *d > dim) {
511 /* Move day-1 days from the first of the month. First try to
512 * get off cheap if we're only one day out of range
513 * (adjustments for timezone alone can't be worse than that).
514 */
515 if (*d == 0) {
516 --*m;
517 if (*m > 0)
518 *d = days_in_month(*y, *m);
519 else {
520 --*y;
521 *m = 12;
522 *d = 31;
523 }
524 }
525 else if (*d == dim + 1) {
526 /* move forward a day */
527 ++*m;
528 *d = 1;
529 if (*m > 12) {
530 *m = 1;
531 ++*y;
532 }
533 }
534 else {
535 int ordinal = ymd_to_ord(*y, *m, 1) +
536 *d - 1;
537 ord_to_ymd(ordinal, y, m, d);
538 }
539 }
540 assert(*m > 0);
541 assert(*d > 0);
542}
543
544/* Fiddle out-of-bounds months and days so that the result makes some kind
545 * of sense. The parameters are both inputs and outputs. Returns < 0 on
546 * failure, where failure means the adjusted year is out of bounds.
547 */
548static int
549normalize_date(int *year, int *month, int *day)
550{
551 int result;
552
553 normalize_y_m_d(year, month, day);
554 if (MINYEAR <= *year && *year <= MAXYEAR)
555 result = 0;
556 else {
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 result = -1;
560 }
561 return result;
562}
563
564/* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
566 */
567static int
568normalize_datetime(int *year, int *month, int *day,
569 int *hour, int *minute, int *second,
570 int *microsecond)
571{
572 normalize_pair(second, microsecond, 1000000);
573 normalize_pair(minute, second, 60);
574 normalize_pair(hour, minute, 60);
575 normalize_pair(day, hour, 24);
576 return normalize_date(year, month, day);
577}
578
579/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000580 * Basic object allocation: tp_alloc implementations. These allocate
581 * Python objects of the right size and type, and do the Python object-
582 * initialization bit. If there's not enough memory, they return NULL after
583 * setting MemoryError. All data members remain uninitialized trash.
584 *
585 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000586 * member is needed. This is ugly, imprecise, and possibly insecure.
587 * tp_basicsize for the time and datetime types is set to the size of the
588 * struct that has room for the tzinfo member, so subclasses in Python will
589 * allocate enough space for a tzinfo member whether or not one is actually
590 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
591 * part is that PyType_GenericAlloc() (which subclasses in Python end up
592 * using) just happens today to effectively ignore the nitems argument
593 * when tp_itemsize is 0, which it is for these type objects. If that
594 * changes, perhaps the callers of tp_alloc slots in this file should
595 * be changed to force a 0 nitems argument unless the type being allocated
596 * is a base type implemented in this file (so that tp_alloc is time_alloc
597 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000598 */
599
600static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000601time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000602{
603 PyObject *self;
604
605 self = (PyObject *)
606 PyObject_MALLOC(aware ?
607 sizeof(PyDateTime_Time) :
608 sizeof(_PyDateTime_BaseTime));
609 if (self == NULL)
610 return (PyObject *)PyErr_NoMemory();
611 PyObject_INIT(self, type);
612 return self;
613}
614
615static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000616datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000617{
618 PyObject *self;
619
620 self = (PyObject *)
621 PyObject_MALLOC(aware ?
622 sizeof(PyDateTime_DateTime) :
623 sizeof(_PyDateTime_BaseDateTime));
624 if (self == NULL)
625 return (PyObject *)PyErr_NoMemory();
626 PyObject_INIT(self, type);
627 return self;
628}
629
630/* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
633 */
634
635/* For date and datetime. */
636static void
637set_date_fields(PyDateTime_Date *self, int y, int m, int d)
638{
639 self->hashcode = -1;
640 SET_YEAR(self, y);
641 SET_MONTH(self, m);
642 SET_DAY(self, d);
643}
644
645/* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
647 */
648
649/* Create a date instance with no range checking. */
650static PyObject *
651new_date_ex(int year, int month, int day, PyTypeObject *type)
652{
653 PyDateTime_Date *self;
654
655 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
656 if (self != NULL)
657 set_date_fields(self, year, month, day);
658 return (PyObject *) self;
659}
660
661#define new_date(year, month, day) \
662 new_date_ex(year, month, day, &PyDateTime_DateType)
663
664/* Create a datetime instance with no range checking. */
665static PyObject *
666new_datetime_ex(int year, int month, int day, int hour, int minute,
667 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
668{
669 PyDateTime_DateTime *self;
670 char aware = tzinfo != Py_None;
671
672 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
673 if (self != NULL) {
674 self->hastzinfo = aware;
675 set_date_fields((PyDateTime_Date *)self, year, month, day);
676 DATE_SET_HOUR(self, hour);
677 DATE_SET_MINUTE(self, minute);
678 DATE_SET_SECOND(self, second);
679 DATE_SET_MICROSECOND(self, usecond);
680 if (aware) {
681 Py_INCREF(tzinfo);
682 self->tzinfo = tzinfo;
683 }
684 }
685 return (PyObject *)self;
686}
687
688#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
689 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
690 &PyDateTime_DateTimeType)
691
692/* Create a time instance with no range checking. */
693static PyObject *
694new_time_ex(int hour, int minute, int second, int usecond,
695 PyObject *tzinfo, PyTypeObject *type)
696{
697 PyDateTime_Time *self;
698 char aware = tzinfo != Py_None;
699
700 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
701 if (self != NULL) {
702 self->hastzinfo = aware;
703 self->hashcode = -1;
704 TIME_SET_HOUR(self, hour);
705 TIME_SET_MINUTE(self, minute);
706 TIME_SET_SECOND(self, second);
707 TIME_SET_MICROSECOND(self, usecond);
708 if (aware) {
709 Py_INCREF(tzinfo);
710 self->tzinfo = tzinfo;
711 }
712 }
713 return (PyObject *)self;
714}
715
716#define new_time(hh, mm, ss, us, tzinfo) \
717 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
718
719/* Create a timedelta instance. Normalize the members iff normalize is
720 * true. Passing false is a speed optimization, if you know for sure
721 * that seconds and microseconds are already in their proper ranges. In any
722 * case, raises OverflowError and returns NULL if the normalized days is out
723 * of range).
724 */
725static PyObject *
726new_delta_ex(int days, int seconds, int microseconds, int normalize,
727 PyTypeObject *type)
728{
729 PyDateTime_Delta *self;
730
731 if (normalize)
732 normalize_d_s_us(&days, &seconds, &microseconds);
733 assert(0 <= seconds && seconds < 24*3600);
734 assert(0 <= microseconds && microseconds < 1000000);
735
736 if (check_delta_day_range(days) < 0)
737 return NULL;
738
739 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
740 if (self != NULL) {
741 self->hashcode = -1;
742 SET_TD_DAYS(self, days);
743 SET_TD_SECONDS(self, seconds);
744 SET_TD_MICROSECONDS(self, microseconds);
745 }
746 return (PyObject *) self;
747}
748
749#define new_delta(d, s, us, normalize) \
750 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
751
752/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000753 * tzinfo helpers.
754 */
755
Tim Peters855fe882002-12-22 03:43:39 +0000756/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
758 */
759static int
760check_tzinfo_subclass(PyObject *p)
761{
762 if (p == Py_None || PyTZInfo_Check(p))
763 return 0;
764 PyErr_Format(PyExc_TypeError,
765 "tzinfo argument must be None or of a tzinfo subclass, "
766 "not type '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000767 Py_Type(p)->tp_name);
Tim Peters855fe882002-12-22 03:43:39 +0000768 return -1;
769}
770
Tim Petersbad8ff02002-12-30 20:52:32 +0000771/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000772 * If tzinfo is None, returns None.
773 */
774static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000775call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000776{
777 PyObject *result;
778
Tim Petersbad8ff02002-12-30 20:52:32 +0000779 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
784 }
785 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000787 return result;
788}
789
Tim Peters2a799bf2002-12-16 20:18:38 +0000790/* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
793 */
794static PyObject *
795get_tzinfo_member(PyObject *self)
796{
797 PyObject *tzinfo = NULL;
798
Tim Petersa9bc1682003-01-11 03:39:11 +0000799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000801 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
804 return tzinfo;
805}
806
Tim Petersbad8ff02002-12-30 20:52:32 +0000807/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * Else *none is set to 0 and the integer method result is returned.
814 */
815static int
816call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
818{
819 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000820 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000821
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
825
826 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 if (u == NULL)
829 return -1;
830
Tim Peters27362852002-12-23 16:17:39 +0000831 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 result = 0;
833 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000834 }
Tim Peters855fe882002-12-22 03:43:39 +0000835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
842 */
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000851 }
852 }
853 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000854 else {
855 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000856 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000857 "timedelta, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000858 name, Py_Type(u)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 }
860
Tim Peters2a799bf2002-12-16 20:18:38 +0000861 Py_DECREF(u);
862 if (result < -1439 || result > 1439) {
863 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000864 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000865 "-1439 .. 1439",
866 name, result);
867 result = -1;
868 }
Tim Peters397301e2003-01-02 21:28:08 +0000869 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000870}
871
872/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
873 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
874 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000875 * doesn't return None or timedelta, TypeError is raised and this returns -1.
876 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
877 * # of minutes), ValueError is raised and this returns -1. Else *none is
878 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000879 */
880static int
881call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
882{
883 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
884}
885
Tim Petersbad8ff02002-12-30 20:52:32 +0000886/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
887 */
Tim Peters855fe882002-12-22 03:43:39 +0000888static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000889offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000890 PyObject *result;
891
Tim Petersbad8ff02002-12-30 20:52:32 +0000892 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000893 if (tzinfo == Py_None) {
894 result = Py_None;
895 Py_INCREF(result);
896 }
897 else {
898 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000899 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
900 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000901 if (offset < 0 && PyErr_Occurred())
902 return NULL;
903 if (none) {
904 result = Py_None;
905 Py_INCREF(result);
906 }
907 else
908 result = new_delta(0, offset * 60, 0, 1);
909 }
910 return result;
911}
912
Tim Peters2a799bf2002-12-16 20:18:38 +0000913/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If dst()
915 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000916 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000917 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000918 * ValueError is raised and this returns -1. Else *none is set to 0 and
919 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000920 */
921static int
922call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
923{
924 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
925}
926
Tim Petersbad8ff02002-12-30 20:52:32 +0000927/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000928 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000929 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000930 * returns NULL. If the result is a string, we ensure it is a Unicode
931 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000932 */
933static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000934call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000935{
936 PyObject *result;
937
938 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000939 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000940 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000941
Tim Peters855fe882002-12-22 03:43:39 +0000942 if (tzinfo == Py_None) {
943 result = Py_None;
944 Py_INCREF(result);
945 }
946 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000947 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000948
Guido van Rossume3d1d412007-05-23 21:24:35 +0000949 if (result != NULL && result != Py_None) {
Guido van Rossumfd53fd62007-08-24 04:05:13 +0000950 if (!PyUnicode_Check(result)) {
Guido van Rossume3d1d412007-05-23 21:24:35 +0000951 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
952 "return None or a string, not '%s'",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +0000953 Py_Type(result)->tp_name);
Guido van Rossume3d1d412007-05-23 21:24:35 +0000954 Py_DECREF(result);
955 result = NULL;
956 }
957 else if (!PyUnicode_Check(result)) {
958 PyObject *temp = PyUnicode_FromObject(result);
959 Py_DECREF(result);
960 result = temp;
961 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000962 }
963 return result;
964}
965
966typedef enum {
967 /* an exception has been set; the caller should pass it on */
968 OFFSET_ERROR,
969
Tim Petersa9bc1682003-01-11 03:39:11 +0000970 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000971 OFFSET_UNKNOWN,
972
973 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000974 * datetime with !hastzinfo
975 * datetime with None tzinfo,
976 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000977 * time with !hastzinfo
978 * time with None tzinfo,
979 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 */
981 OFFSET_NAIVE,
982
Tim Petersa9bc1682003-01-11 03:39:11 +0000983 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000984 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000985} naivety;
986
Tim Peters14b69412002-12-22 18:10:22 +0000987/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000988 * the "naivety" typedef for details. If the type is aware, *offset is set
989 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000990 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 */
993static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000994classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000995{
996 int none;
997 PyObject *tzinfo;
998
Tim Peterse39a80c2002-12-30 21:28:52 +0000999 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001000 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +00001001 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (tzinfo == Py_None)
1003 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +00001004 if (tzinfo == NULL) {
1005 /* note that a datetime passes the PyDate_Check test */
1006 return (PyTime_Check(op) || PyDate_Check(op)) ?
1007 OFFSET_NAIVE : OFFSET_UNKNOWN;
1008 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001009 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001010 if (*offset == -1 && PyErr_Occurred())
1011 return OFFSET_ERROR;
1012 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1013}
1014
Tim Peters00237032002-12-27 02:21:51 +00001015/* Classify two objects as to whether they're naive or offset-aware.
1016 * This isn't quite the same as calling classify_utcoffset() twice: for
1017 * binary operations (comparison and subtraction), we generally want to
1018 * ignore the tzinfo members if they're identical. This is by design,
1019 * so that results match "naive" expectations when mixing objects from a
1020 * single timezone. So in that case, this sets both offsets to 0 and
1021 * both naiveties to OFFSET_NAIVE.
1022 * The function returns 0 if everything's OK, and -1 on error.
1023 */
1024static int
1025classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001026 PyObject *tzinfoarg1,
1027 PyObject *o2, int *offset2, naivety *n2,
1028 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001029{
1030 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1031 *offset1 = *offset2 = 0;
1032 *n1 = *n2 = OFFSET_NAIVE;
1033 }
1034 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001035 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001036 if (*n1 == OFFSET_ERROR)
1037 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001038 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001039 if (*n2 == OFFSET_ERROR)
1040 return -1;
1041 }
1042 return 0;
1043}
1044
Tim Peters2a799bf2002-12-16 20:18:38 +00001045/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1046 * stuff
1047 * ", tzinfo=" + repr(tzinfo)
1048 * before the closing ")".
1049 */
1050static PyObject *
1051append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1052{
1053 PyObject *temp;
1054
Walter Dörwald1ab83302007-05-18 17:15:44 +00001055 assert(PyUnicode_Check(repr));
Tim Peters2a799bf2002-12-16 20:18:38 +00001056 assert(tzinfo);
1057 if (tzinfo == Py_None)
1058 return repr;
1059 /* Get rid of the trailing ')'. */
Walter Dörwald1ab83302007-05-18 17:15:44 +00001060 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1061 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1062 PyUnicode_GET_SIZE(repr) - 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001063 Py_DECREF(repr);
1064 if (temp == NULL)
1065 return NULL;
Walter Dörwald517bcfe2007-05-23 20:45:05 +00001066 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1067 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00001068 return repr;
1069}
1070
1071/* ---------------------------------------------------------------------------
1072 * String format helpers.
1073 */
1074
1075static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001076format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001077{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001078 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001079 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1080 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001081 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001082 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1083 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1084 };
1085
Tim Peters2a799bf2002-12-16 20:18:38 +00001086 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1087
Walter Dörwald4af32b32007-05-31 16:19:50 +00001088 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1089 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1090 GET_DAY(date), hours, minutes, seconds,
1091 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001092}
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
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001131static PyObject *
1132make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1133{
Neal Norwitzaea70e02007-08-12 04:32:26 +00001134 PyObject *temp;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001135 PyObject *tzinfo = get_tzinfo_member(object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001136 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001137 if (Zreplacement == NULL)
1138 return NULL;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001139 if (tzinfo == Py_None || tzinfo == NULL)
1140 return Zreplacement;
1141
1142 assert(tzinfoarg != NULL);
1143 temp = call_tzname(tzinfo, tzinfoarg);
1144 if (temp == NULL)
1145 goto Error;
1146 if (temp == Py_None) {
1147 Py_DECREF(temp);
1148 return Zreplacement;
1149 }
1150
1151 assert(PyUnicode_Check(temp));
1152 /* Since the tzname is getting stuffed into the
1153 * format, we have to double any % signs so that
1154 * strftime doesn't treat them as format codes.
1155 */
1156 Py_DECREF(Zreplacement);
1157 Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1158 Py_DECREF(temp);
1159 if (Zreplacement == NULL)
1160 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001161 if (!PyUnicode_Check(Zreplacement)) {
Neal Norwitzaea70e02007-08-12 04:32:26 +00001162 PyErr_SetString(PyExc_TypeError,
1163 "tzname.replace() did not return a string");
1164 goto Error;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001165 }
1166 return Zreplacement;
1167
1168 Error:
1169 Py_DECREF(Zreplacement);
1170 return NULL;
1171}
1172
Tim Peters2a799bf2002-12-16 20:18:38 +00001173/* I sure don't want to reproduce the strftime code from the time module,
1174 * so this imports the module and calls it. All the hair is due to
1175 * giving special meanings to the %z and %Z format codes via a preprocessing
1176 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001177 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1178 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001179 */
1180static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001181wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1182 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001183{
1184 PyObject *result = NULL; /* guilty until proved innocent */
1185
1186 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1187 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1188
Guido van Rossumbce56a62007-05-10 18:04:33 +00001189 const char *pin;/* pointer to next char in input format */
1190 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001191 char ch; /* next char in input format */
1192
1193 PyObject *newfmt = NULL; /* py string, the output format */
1194 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001195 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001196 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001197 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001198
Guido van Rossumbce56a62007-05-10 18:04:33 +00001199 const char *ptoappend;/* pointer to string to append to output buffer */
Brett Cannon27da8122007-11-06 23:15:11 +00001200 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001201
Tim Peters2a799bf2002-12-16 20:18:38 +00001202 assert(object && format && timetuple);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001203 assert(PyUnicode_Check(format));
Neal Norwitz908c8712007-08-27 04:58:38 +00001204 /* Convert the input format to a C string and size */
1205 pin = PyUnicode_AsString(format);
1206 if (!pin)
1207 return NULL;
1208 flen = PyUnicode_GetSize(format);
Tim Peters2a799bf2002-12-16 20:18:38 +00001209
Tim Petersd6844152002-12-22 20:58:42 +00001210 /* Give up if the year is before 1900.
1211 * Python strftime() plays games with the year, and different
1212 * games depending on whether envar PYTHON2K is set. This makes
1213 * years before 1900 a nightmare, even if the platform strftime
1214 * supports them (and not all do).
1215 * We could get a lot farther here by avoiding Python's strftime
1216 * wrapper and calling the C strftime() directly, but that isn't
1217 * an option in the Python implementation of this module.
1218 */
1219 {
1220 long year;
1221 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1222 if (pyyear == NULL) return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001223 assert(PyLong_Check(pyyear));
1224 year = PyLong_AsLong(pyyear);
Tim Petersd6844152002-12-22 20:58:42 +00001225 Py_DECREF(pyyear);
1226 if (year < 1900) {
1227 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1228 "1900; the datetime strftime() "
1229 "methods require year >= 1900",
1230 year);
1231 return NULL;
1232 }
1233 }
1234
Tim Peters2a799bf2002-12-16 20:18:38 +00001235 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001236 * a new format. Since computing the replacements for those codes
1237 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001238 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001239 totalnew = flen + 1; /* realistic if no %z/%Z */
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001240 newfmt = PyString_FromStringAndSize(NULL, totalnew);
Tim Peters2a799bf2002-12-16 20:18:38 +00001241 if (newfmt == NULL) goto Done;
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001242 pnew = PyString_AsString(newfmt);
Tim Peters2a799bf2002-12-16 20:18:38 +00001243 usednew = 0;
1244
Tim Peters2a799bf2002-12-16 20:18:38 +00001245 while ((ch = *pin++) != '\0') {
1246 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001247 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001248 ntoappend = 1;
1249 }
1250 else if ((ch = *pin++) == '\0') {
1251 /* There's a lone trailing %; doesn't make sense. */
1252 PyErr_SetString(PyExc_ValueError, "strftime format "
1253 "ends with raw %");
1254 goto Done;
1255 }
1256 /* A % has been seen and ch is the character after it. */
1257 else if (ch == 'z') {
1258 if (zreplacement == NULL) {
1259 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001260 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001261 PyObject *tzinfo = get_tzinfo_member(object);
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001262 zreplacement = PyString_FromStringAndSize("", 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001263 if (zreplacement == NULL) goto Done;
1264 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001265 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001266 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001267 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001268 "",
1269 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001270 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001271 goto Done;
1272 Py_DECREF(zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001273 zreplacement =
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001274 PyString_FromStringAndSize(buf,
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001275 strlen(buf));
1276 if (zreplacement == NULL)
1277 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001278 }
1279 }
1280 assert(zreplacement != NULL);
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001281 ptoappend = PyString_AS_STRING(zreplacement);
1282 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001283 }
1284 else if (ch == 'Z') {
1285 /* format tzname */
1286 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001287 Zreplacement = make_Zreplacement(object,
1288 tzinfoarg);
1289 if (Zreplacement == NULL)
1290 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001291 }
1292 assert(Zreplacement != NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001293 assert(PyUnicode_Check(Zreplacement));
1294 ptoappend = PyUnicode_AsStringAndSize(Zreplacement,
1295 &ntoappend);
1296 ntoappend = Py_Size(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001297 }
1298 else {
Tim Peters328fff72002-12-20 01:31:27 +00001299 /* percent followed by neither z nor Z */
1300 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001301 ntoappend = 2;
1302 }
1303
1304 /* Append the ntoappend chars starting at ptoappend to
1305 * the new format.
1306 */
Tim Peters2a799bf2002-12-16 20:18:38 +00001307 if (ntoappend == 0)
1308 continue;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001309 assert(ptoappend != NULL);
1310 assert(ntoappend > 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001311 while (usednew + ntoappend > totalnew) {
1312 int bigger = totalnew << 1;
1313 if ((bigger >> 1) != totalnew) { /* overflow */
1314 PyErr_NoMemory();
1315 goto Done;
1316 }
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001317 if (_PyString_Resize(&newfmt, bigger) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001318 goto Done;
1319 totalnew = bigger;
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001320 pnew = PyString_AsString(newfmt) + usednew;
Tim Peters2a799bf2002-12-16 20:18:38 +00001321 }
1322 memcpy(pnew, ptoappend, ntoappend);
1323 pnew += ntoappend;
1324 usednew += ntoappend;
1325 assert(usednew <= totalnew);
1326 } /* end while() */
1327
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001328 if (_PyString_Resize(&newfmt, usednew) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001329 goto Done;
1330 {
Neal Norwitz908c8712007-08-27 04:58:38 +00001331 PyObject *format;
Tim Peters2a799bf2002-12-16 20:18:38 +00001332 PyObject *time = PyImport_ImportModule("time");
1333 if (time == NULL)
1334 goto Done;
Walter Dörwald6bd238c2007-11-22 09:38:52 +00001335 format = PyUnicode_FromString(PyString_AS_STRING(newfmt));
Neal Norwitz908c8712007-08-27 04:58:38 +00001336 if (format != NULL) {
1337 result = PyObject_CallMethod(time, "strftime", "OO",
1338 format, timetuple);
1339 Py_DECREF(format);
1340 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001341 Py_DECREF(time);
1342 }
1343 Done:
1344 Py_XDECREF(zreplacement);
1345 Py_XDECREF(Zreplacement);
1346 Py_XDECREF(newfmt);
1347 return result;
1348}
1349
Tim Peters2a799bf2002-12-16 20:18:38 +00001350/* ---------------------------------------------------------------------------
1351 * Wrap functions from the time module. These aren't directly available
1352 * from C. Perhaps they should be.
1353 */
1354
1355/* Call time.time() and return its result (a Python float). */
1356static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001357time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001358{
1359 PyObject *result = NULL;
1360 PyObject *time = PyImport_ImportModule("time");
1361
1362 if (time != NULL) {
1363 result = PyObject_CallMethod(time, "time", "()");
1364 Py_DECREF(time);
1365 }
1366 return result;
1367}
1368
1369/* Build a time.struct_time. The weekday and day number are automatically
1370 * computed from the y,m,d args.
1371 */
1372static PyObject *
1373build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1374{
1375 PyObject *time;
1376 PyObject *result = NULL;
1377
1378 time = PyImport_ImportModule("time");
1379 if (time != NULL) {
1380 result = PyObject_CallMethod(time, "struct_time",
1381 "((iiiiiiiii))",
1382 y, m, d,
1383 hh, mm, ss,
1384 weekday(y, m, d),
1385 days_before_month(y, m) + d,
1386 dstflag);
1387 Py_DECREF(time);
1388 }
1389 return result;
1390}
1391
1392/* ---------------------------------------------------------------------------
1393 * Miscellaneous helpers.
1394 */
1395
Guido van Rossum19960592006-08-24 17:29:38 +00001396/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001397 * The comparisons here all most naturally compute a cmp()-like result.
1398 * This little helper turns that into a bool result for rich comparisons.
1399 */
1400static PyObject *
1401diff_to_bool(int diff, int op)
1402{
1403 PyObject *result;
1404 int istrue;
1405
1406 switch (op) {
1407 case Py_EQ: istrue = diff == 0; break;
1408 case Py_NE: istrue = diff != 0; break;
1409 case Py_LE: istrue = diff <= 0; break;
1410 case Py_GE: istrue = diff >= 0; break;
1411 case Py_LT: istrue = diff < 0; break;
1412 case Py_GT: istrue = diff > 0; break;
1413 default:
1414 assert(! "op unknown");
1415 istrue = 0; /* To shut up compiler */
1416 }
1417 result = istrue ? Py_True : Py_False;
1418 Py_INCREF(result);
1419 return result;
1420}
1421
Tim Peters07534a62003-02-07 22:50:28 +00001422/* Raises a "can't compare" TypeError and returns NULL. */
1423static PyObject *
1424cmperror(PyObject *a, PyObject *b)
1425{
1426 PyErr_Format(PyExc_TypeError,
1427 "can't compare %s to %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001428 Py_Type(a)->tp_name, Py_Type(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001429 return NULL;
1430}
1431
Tim Peters2a799bf2002-12-16 20:18:38 +00001432/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001433 * Cached Python objects; these are set by the module init function.
1434 */
1435
1436/* Conversion factors. */
1437static PyObject *us_per_us = NULL; /* 1 */
1438static PyObject *us_per_ms = NULL; /* 1000 */
1439static PyObject *us_per_second = NULL; /* 1000000 */
1440static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1441static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1442static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1443static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1444static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1445
Tim Peters2a799bf2002-12-16 20:18:38 +00001446/* ---------------------------------------------------------------------------
1447 * Class implementations.
1448 */
1449
1450/*
1451 * PyDateTime_Delta implementation.
1452 */
1453
1454/* Convert a timedelta to a number of us,
1455 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1456 * as a Python int or long.
1457 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1458 * due to ubiquitous overflow possibilities.
1459 */
1460static PyObject *
1461delta_to_microseconds(PyDateTime_Delta *self)
1462{
1463 PyObject *x1 = NULL;
1464 PyObject *x2 = NULL;
1465 PyObject *x3 = NULL;
1466 PyObject *result = NULL;
1467
Christian Heimes217cfd12007-12-02 14:31:20 +00001468 x1 = PyLong_FromLong(GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001469 if (x1 == NULL)
1470 goto Done;
1471 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1472 if (x2 == NULL)
1473 goto Done;
1474 Py_DECREF(x1);
1475 x1 = NULL;
1476
1477 /* x2 has days in seconds */
Christian Heimes217cfd12007-12-02 14:31:20 +00001478 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
Tim Peters2a799bf2002-12-16 20:18:38 +00001479 if (x1 == NULL)
1480 goto Done;
1481 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1482 if (x3 == NULL)
1483 goto Done;
1484 Py_DECREF(x1);
1485 Py_DECREF(x2);
1486 x1 = x2 = NULL;
1487
1488 /* x3 has days+seconds in seconds */
1489 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1490 if (x1 == NULL)
1491 goto Done;
1492 Py_DECREF(x3);
1493 x3 = NULL;
1494
1495 /* x1 has days+seconds in us */
Christian Heimes217cfd12007-12-02 14:31:20 +00001496 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001497 if (x2 == NULL)
1498 goto Done;
1499 result = PyNumber_Add(x1, x2);
1500
1501Done:
1502 Py_XDECREF(x1);
1503 Py_XDECREF(x2);
1504 Py_XDECREF(x3);
1505 return result;
1506}
1507
1508/* Convert a number of us (as a Python int or long) to a timedelta.
1509 */
1510static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001511microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001512{
1513 int us;
1514 int s;
1515 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001516 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001517
1518 PyObject *tuple = NULL;
1519 PyObject *num = NULL;
1520 PyObject *result = NULL;
1521
1522 tuple = PyNumber_Divmod(pyus, us_per_second);
1523 if (tuple == NULL)
1524 goto Done;
1525
1526 num = PyTuple_GetItem(tuple, 1); /* us */
1527 if (num == NULL)
1528 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001529 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001530 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001531 if (temp == -1 && PyErr_Occurred())
1532 goto Done;
1533 assert(0 <= temp && temp < 1000000);
1534 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001535 if (us < 0) {
1536 /* The divisor was positive, so this must be an error. */
1537 assert(PyErr_Occurred());
1538 goto Done;
1539 }
1540
1541 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1542 if (num == NULL)
1543 goto Done;
1544 Py_INCREF(num);
1545 Py_DECREF(tuple);
1546
1547 tuple = PyNumber_Divmod(num, seconds_per_day);
1548 if (tuple == NULL)
1549 goto Done;
1550 Py_DECREF(num);
1551
1552 num = PyTuple_GetItem(tuple, 1); /* seconds */
1553 if (num == NULL)
1554 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001555 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001556 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001557 if (temp == -1 && PyErr_Occurred())
1558 goto Done;
1559 assert(0 <= temp && temp < 24*3600);
1560 s = (int)temp;
1561
Tim Peters2a799bf2002-12-16 20:18:38 +00001562 if (s < 0) {
1563 /* The divisor was positive, so this must be an error. */
1564 assert(PyErr_Occurred());
1565 goto Done;
1566 }
1567
1568 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1569 if (num == NULL)
1570 goto Done;
1571 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001572 temp = PyLong_AsLong(num);
1573 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001574 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001575 d = (int)temp;
1576 if ((long)d != temp) {
1577 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1578 "large to fit in a C int");
1579 goto Done;
1580 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001581 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001582
1583Done:
1584 Py_XDECREF(tuple);
1585 Py_XDECREF(num);
1586 return result;
1587}
1588
Tim Petersb0c854d2003-05-17 15:57:00 +00001589#define microseconds_to_delta(pymicros) \
1590 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1591
Tim Peters2a799bf2002-12-16 20:18:38 +00001592static PyObject *
1593multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1594{
1595 PyObject *pyus_in;
1596 PyObject *pyus_out;
1597 PyObject *result;
1598
1599 pyus_in = delta_to_microseconds(delta);
1600 if (pyus_in == NULL)
1601 return NULL;
1602
1603 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1604 Py_DECREF(pyus_in);
1605 if (pyus_out == NULL)
1606 return NULL;
1607
1608 result = microseconds_to_delta(pyus_out);
1609 Py_DECREF(pyus_out);
1610 return result;
1611}
1612
1613static PyObject *
1614divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1615{
1616 PyObject *pyus_in;
1617 PyObject *pyus_out;
1618 PyObject *result;
1619
1620 pyus_in = delta_to_microseconds(delta);
1621 if (pyus_in == NULL)
1622 return NULL;
1623
1624 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1625 Py_DECREF(pyus_in);
1626 if (pyus_out == NULL)
1627 return NULL;
1628
1629 result = microseconds_to_delta(pyus_out);
1630 Py_DECREF(pyus_out);
1631 return result;
1632}
1633
1634static PyObject *
1635delta_add(PyObject *left, PyObject *right)
1636{
1637 PyObject *result = Py_NotImplemented;
1638
1639 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1640 /* delta + delta */
1641 /* The C-level additions can't overflow because of the
1642 * invariant bounds.
1643 */
1644 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1645 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1646 int microseconds = GET_TD_MICROSECONDS(left) +
1647 GET_TD_MICROSECONDS(right);
1648 result = new_delta(days, seconds, microseconds, 1);
1649 }
1650
1651 if (result == Py_NotImplemented)
1652 Py_INCREF(result);
1653 return result;
1654}
1655
1656static PyObject *
1657delta_negative(PyDateTime_Delta *self)
1658{
1659 return new_delta(-GET_TD_DAYS(self),
1660 -GET_TD_SECONDS(self),
1661 -GET_TD_MICROSECONDS(self),
1662 1);
1663}
1664
1665static PyObject *
1666delta_positive(PyDateTime_Delta *self)
1667{
1668 /* Could optimize this (by returning self) if this isn't a
1669 * subclass -- but who uses unary + ? Approximately nobody.
1670 */
1671 return new_delta(GET_TD_DAYS(self),
1672 GET_TD_SECONDS(self),
1673 GET_TD_MICROSECONDS(self),
1674 0);
1675}
1676
1677static PyObject *
1678delta_abs(PyDateTime_Delta *self)
1679{
1680 PyObject *result;
1681
1682 assert(GET_TD_MICROSECONDS(self) >= 0);
1683 assert(GET_TD_SECONDS(self) >= 0);
1684
1685 if (GET_TD_DAYS(self) < 0)
1686 result = delta_negative(self);
1687 else
1688 result = delta_positive(self);
1689
1690 return result;
1691}
1692
1693static PyObject *
1694delta_subtract(PyObject *left, PyObject *right)
1695{
1696 PyObject *result = Py_NotImplemented;
1697
1698 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1699 /* delta - delta */
1700 PyObject *minus_right = PyNumber_Negative(right);
1701 if (minus_right) {
1702 result = delta_add(left, minus_right);
1703 Py_DECREF(minus_right);
1704 }
1705 else
1706 result = NULL;
1707 }
1708
1709 if (result == Py_NotImplemented)
1710 Py_INCREF(result);
1711 return result;
1712}
1713
Tim Peters2a799bf2002-12-16 20:18:38 +00001714static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001715delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001716{
Tim Petersaa7d8492003-02-08 03:28:59 +00001717 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001718 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001719 if (diff == 0) {
1720 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1721 if (diff == 0)
1722 diff = GET_TD_MICROSECONDS(self) -
1723 GET_TD_MICROSECONDS(other);
1724 }
Guido van Rossum19960592006-08-24 17:29:38 +00001725 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001726 }
Guido van Rossum19960592006-08-24 17:29:38 +00001727 else {
1728 Py_INCREF(Py_NotImplemented);
1729 return Py_NotImplemented;
1730 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001731}
1732
1733static PyObject *delta_getstate(PyDateTime_Delta *self);
1734
1735static long
1736delta_hash(PyDateTime_Delta *self)
1737{
1738 if (self->hashcode == -1) {
1739 PyObject *temp = delta_getstate(self);
1740 if (temp != NULL) {
1741 self->hashcode = PyObject_Hash(temp);
1742 Py_DECREF(temp);
1743 }
1744 }
1745 return self->hashcode;
1746}
1747
1748static PyObject *
1749delta_multiply(PyObject *left, PyObject *right)
1750{
1751 PyObject *result = Py_NotImplemented;
1752
1753 if (PyDelta_Check(left)) {
1754 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001755 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001756 result = multiply_int_timedelta(right,
1757 (PyDateTime_Delta *) left);
1758 }
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001759 else if (PyLong_Check(left))
Tim Peters2a799bf2002-12-16 20:18:38 +00001760 result = multiply_int_timedelta(left,
1761 (PyDateTime_Delta *) right);
1762
1763 if (result == Py_NotImplemented)
1764 Py_INCREF(result);
1765 return result;
1766}
1767
1768static PyObject *
1769delta_divide(PyObject *left, PyObject *right)
1770{
1771 PyObject *result = Py_NotImplemented;
1772
1773 if (PyDelta_Check(left)) {
1774 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001775 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001776 result = divide_timedelta_int(
1777 (PyDateTime_Delta *)left,
1778 right);
1779 }
1780
1781 if (result == Py_NotImplemented)
1782 Py_INCREF(result);
1783 return result;
1784}
1785
1786/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1787 * timedelta constructor. sofar is the # of microseconds accounted for
1788 * so far, and there are factor microseconds per current unit, the number
1789 * of which is given by num. num * factor is added to sofar in a
1790 * numerically careful way, and that's the result. Any fractional
1791 * microseconds left over (this can happen if num is a float type) are
1792 * added into *leftover.
1793 * Note that there are many ways this can give an error (NULL) return.
1794 */
1795static PyObject *
1796accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1797 double *leftover)
1798{
1799 PyObject *prod;
1800 PyObject *sum;
1801
1802 assert(num != NULL);
1803
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001804 if (PyLong_Check(num)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00001805 prod = PyNumber_Multiply(num, factor);
1806 if (prod == NULL)
1807 return NULL;
1808 sum = PyNumber_Add(sofar, prod);
1809 Py_DECREF(prod);
1810 return sum;
1811 }
1812
1813 if (PyFloat_Check(num)) {
1814 double dnum;
1815 double fracpart;
1816 double intpart;
1817 PyObject *x;
1818 PyObject *y;
1819
1820 /* The Plan: decompose num into an integer part and a
1821 * fractional part, num = intpart + fracpart.
1822 * Then num * factor ==
1823 * intpart * factor + fracpart * factor
1824 * and the LHS can be computed exactly in long arithmetic.
1825 * The RHS is again broken into an int part and frac part.
1826 * and the frac part is added into *leftover.
1827 */
1828 dnum = PyFloat_AsDouble(num);
1829 if (dnum == -1.0 && PyErr_Occurred())
1830 return NULL;
1831 fracpart = modf(dnum, &intpart);
1832 x = PyLong_FromDouble(intpart);
1833 if (x == NULL)
1834 return NULL;
1835
1836 prod = PyNumber_Multiply(x, factor);
1837 Py_DECREF(x);
1838 if (prod == NULL)
1839 return NULL;
1840
1841 sum = PyNumber_Add(sofar, prod);
1842 Py_DECREF(prod);
1843 if (sum == NULL)
1844 return NULL;
1845
1846 if (fracpart == 0.0)
1847 return sum;
1848 /* So far we've lost no information. Dealing with the
1849 * fractional part requires float arithmetic, and may
1850 * lose a little info.
1851 */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001852 assert(PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001853 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001854
1855 dnum *= fracpart;
1856 fracpart = modf(dnum, &intpart);
1857 x = PyLong_FromDouble(intpart);
1858 if (x == NULL) {
1859 Py_DECREF(sum);
1860 return NULL;
1861 }
1862
1863 y = PyNumber_Add(sum, x);
1864 Py_DECREF(sum);
1865 Py_DECREF(x);
1866 *leftover += fracpart;
1867 return y;
1868 }
1869
1870 PyErr_Format(PyExc_TypeError,
1871 "unsupported type for timedelta %s component: %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001872 tag, Py_Type(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001873 return NULL;
1874}
1875
1876static PyObject *
1877delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1878{
1879 PyObject *self = NULL;
1880
1881 /* Argument objects. */
1882 PyObject *day = NULL;
1883 PyObject *second = NULL;
1884 PyObject *us = NULL;
1885 PyObject *ms = NULL;
1886 PyObject *minute = NULL;
1887 PyObject *hour = NULL;
1888 PyObject *week = NULL;
1889
1890 PyObject *x = NULL; /* running sum of microseconds */
1891 PyObject *y = NULL; /* temp sum of microseconds */
1892 double leftover_us = 0.0;
1893
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001894 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001895 "days", "seconds", "microseconds", "milliseconds",
1896 "minutes", "hours", "weeks", NULL
1897 };
1898
1899 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1900 keywords,
1901 &day, &second, &us,
1902 &ms, &minute, &hour, &week) == 0)
1903 goto Done;
1904
Christian Heimes217cfd12007-12-02 14:31:20 +00001905 x = PyLong_FromLong(0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001906 if (x == NULL)
1907 goto Done;
1908
1909#define CLEANUP \
1910 Py_DECREF(x); \
1911 x = y; \
1912 if (x == NULL) \
1913 goto Done
1914
1915 if (us) {
1916 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1917 CLEANUP;
1918 }
1919 if (ms) {
1920 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1921 CLEANUP;
1922 }
1923 if (second) {
1924 y = accum("seconds", x, second, us_per_second, &leftover_us);
1925 CLEANUP;
1926 }
1927 if (minute) {
1928 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1929 CLEANUP;
1930 }
1931 if (hour) {
1932 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1933 CLEANUP;
1934 }
1935 if (day) {
1936 y = accum("days", x, day, us_per_day, &leftover_us);
1937 CLEANUP;
1938 }
1939 if (week) {
1940 y = accum("weeks", x, week, us_per_week, &leftover_us);
1941 CLEANUP;
1942 }
1943 if (leftover_us) {
1944 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001945 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001946 if (temp == NULL) {
1947 Py_DECREF(x);
1948 goto Done;
1949 }
1950 y = PyNumber_Add(x, temp);
1951 Py_DECREF(temp);
1952 CLEANUP;
1953 }
1954
Tim Petersb0c854d2003-05-17 15:57:00 +00001955 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001956 Py_DECREF(x);
1957Done:
1958 return self;
1959
1960#undef CLEANUP
1961}
1962
1963static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001964delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001965{
1966 return (GET_TD_DAYS(self) != 0
1967 || GET_TD_SECONDS(self) != 0
1968 || GET_TD_MICROSECONDS(self) != 0);
1969}
1970
1971static PyObject *
1972delta_repr(PyDateTime_Delta *self)
1973{
1974 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001975 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001976 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001977 GET_TD_DAYS(self),
1978 GET_TD_SECONDS(self),
1979 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001980 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001981 return PyUnicode_FromFormat("%s(%d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001982 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001983 GET_TD_DAYS(self),
1984 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001985
Walter Dörwald1ab83302007-05-18 17:15:44 +00001986 return PyUnicode_FromFormat("%s(%d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001987 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001988 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001989}
1990
1991static PyObject *
1992delta_str(PyDateTime_Delta *self)
1993{
Tim Peters2a799bf2002-12-16 20:18:38 +00001994 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00001995 int seconds = GET_TD_SECONDS(self);
1996 int minutes = divmod(seconds, 60, &seconds);
1997 int hours = divmod(minutes, 60, &minutes);
1998 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001999
2000 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002001 if (us)
2002 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2003 days, (days == 1 || days == -1) ? "" : "s",
2004 hours, minutes, seconds, us);
2005 else
2006 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2007 days, (days == 1 || days == -1) ? "" : "s",
2008 hours, minutes, seconds);
2009 } else {
2010 if (us)
2011 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2012 hours, minutes, seconds, us);
2013 else
2014 return PyUnicode_FromFormat("%d:%02d:%02d",
2015 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002016 }
2017
Tim Peters2a799bf2002-12-16 20:18:38 +00002018}
2019
Tim Peters371935f2003-02-01 01:52:50 +00002020/* Pickle support, a simple use of __reduce__. */
2021
Tim Petersb57f8f02003-02-01 02:54:15 +00002022/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002023static PyObject *
2024delta_getstate(PyDateTime_Delta *self)
2025{
2026 return Py_BuildValue("iii", GET_TD_DAYS(self),
2027 GET_TD_SECONDS(self),
2028 GET_TD_MICROSECONDS(self));
2029}
2030
Tim Peters2a799bf2002-12-16 20:18:38 +00002031static PyObject *
2032delta_reduce(PyDateTime_Delta* self)
2033{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002034 return Py_BuildValue("ON", Py_Type(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002035}
2036
2037#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2038
2039static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002040
Neal Norwitzdfb80862002-12-19 02:30:56 +00002041 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002042 PyDoc_STR("Number of days.")},
2043
Neal Norwitzdfb80862002-12-19 02:30:56 +00002044 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002045 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2046
Neal Norwitzdfb80862002-12-19 02:30:56 +00002047 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002048 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2049 {NULL}
2050};
2051
2052static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002053 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2054 PyDoc_STR("__reduce__() -> (cls, state)")},
2055
Tim Peters2a799bf2002-12-16 20:18:38 +00002056 {NULL, NULL},
2057};
2058
2059static char delta_doc[] =
2060PyDoc_STR("Difference between two datetime values.");
2061
2062static PyNumberMethods delta_as_number = {
2063 delta_add, /* nb_add */
2064 delta_subtract, /* nb_subtract */
2065 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002066 0, /* nb_remainder */
2067 0, /* nb_divmod */
2068 0, /* nb_power */
2069 (unaryfunc)delta_negative, /* nb_negative */
2070 (unaryfunc)delta_positive, /* nb_positive */
2071 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002072 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002073 0, /*nb_invert*/
2074 0, /*nb_lshift*/
2075 0, /*nb_rshift*/
2076 0, /*nb_and*/
2077 0, /*nb_xor*/
2078 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00002079 0, /*nb_reserved*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002080 0, /*nb_int*/
2081 0, /*nb_long*/
2082 0, /*nb_float*/
2083 0, /*nb_oct*/
2084 0, /*nb_hex*/
2085 0, /*nb_inplace_add*/
2086 0, /*nb_inplace_subtract*/
2087 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002088 0, /*nb_inplace_remainder*/
2089 0, /*nb_inplace_power*/
2090 0, /*nb_inplace_lshift*/
2091 0, /*nb_inplace_rshift*/
2092 0, /*nb_inplace_and*/
2093 0, /*nb_inplace_xor*/
2094 0, /*nb_inplace_or*/
2095 delta_divide, /* nb_floor_divide */
2096 0, /* nb_true_divide */
2097 0, /* nb_inplace_floor_divide */
2098 0, /* nb_inplace_true_divide */
2099};
2100
2101static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002102 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002103 "datetime.timedelta", /* tp_name */
2104 sizeof(PyDateTime_Delta), /* tp_basicsize */
2105 0, /* tp_itemsize */
2106 0, /* tp_dealloc */
2107 0, /* tp_print */
2108 0, /* tp_getattr */
2109 0, /* tp_setattr */
2110 0, /* tp_compare */
2111 (reprfunc)delta_repr, /* tp_repr */
2112 &delta_as_number, /* tp_as_number */
2113 0, /* tp_as_sequence */
2114 0, /* tp_as_mapping */
2115 (hashfunc)delta_hash, /* tp_hash */
2116 0, /* tp_call */
2117 (reprfunc)delta_str, /* tp_str */
2118 PyObject_GenericGetAttr, /* tp_getattro */
2119 0, /* tp_setattro */
2120 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002121 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002122 delta_doc, /* tp_doc */
2123 0, /* tp_traverse */
2124 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002125 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002126 0, /* tp_weaklistoffset */
2127 0, /* tp_iter */
2128 0, /* tp_iternext */
2129 delta_methods, /* tp_methods */
2130 delta_members, /* tp_members */
2131 0, /* tp_getset */
2132 0, /* tp_base */
2133 0, /* tp_dict */
2134 0, /* tp_descr_get */
2135 0, /* tp_descr_set */
2136 0, /* tp_dictoffset */
2137 0, /* tp_init */
2138 0, /* tp_alloc */
2139 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002140 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002141};
2142
2143/*
2144 * PyDateTime_Date implementation.
2145 */
2146
2147/* Accessor properties. */
2148
2149static PyObject *
2150date_year(PyDateTime_Date *self, void *unused)
2151{
Christian Heimes217cfd12007-12-02 14:31:20 +00002152 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002153}
2154
2155static PyObject *
2156date_month(PyDateTime_Date *self, void *unused)
2157{
Christian Heimes217cfd12007-12-02 14:31:20 +00002158 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002159}
2160
2161static PyObject *
2162date_day(PyDateTime_Date *self, void *unused)
2163{
Christian Heimes217cfd12007-12-02 14:31:20 +00002164 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002165}
2166
2167static PyGetSetDef date_getset[] = {
2168 {"year", (getter)date_year},
2169 {"month", (getter)date_month},
2170 {"day", (getter)date_day},
2171 {NULL}
2172};
2173
2174/* Constructors. */
2175
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002176static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002177
Tim Peters2a799bf2002-12-16 20:18:38 +00002178static PyObject *
2179date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2180{
2181 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002182 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002183 int year;
2184 int month;
2185 int day;
2186
Guido van Rossum177e41a2003-01-30 22:06:23 +00002187 /* Check for invocation from pickle with __getstate__ state */
2188 if (PyTuple_GET_SIZE(args) == 1 &&
Guido van Rossum254348e2007-11-21 19:29:53 +00002189 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2190 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2191 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002192 {
Tim Peters70533e22003-02-01 04:40:04 +00002193 PyDateTime_Date *me;
2194
Tim Peters604c0132004-06-07 23:04:33 +00002195 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002196 if (me != NULL) {
Guido van Rossum254348e2007-11-21 19:29:53 +00002197 char *pdata = PyString_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002198 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2199 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002200 }
Tim Peters70533e22003-02-01 04:40:04 +00002201 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002202 }
2203
Tim Peters12bf3392002-12-24 05:41:27 +00002204 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002205 &year, &month, &day)) {
2206 if (check_date_args(year, month, day) < 0)
2207 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002208 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002209 }
2210 return self;
2211}
2212
2213/* Return new date from localtime(t). */
2214static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002215date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002216{
2217 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002218 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002219 PyObject *result = NULL;
2220
Tim Peters1b6f7a92004-06-20 02:50:16 +00002221 t = _PyTime_DoubleToTimet(ts);
2222 if (t == (time_t)-1 && PyErr_Occurred())
2223 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002224 tm = localtime(&t);
2225 if (tm)
2226 result = PyObject_CallFunction(cls, "iii",
2227 tm->tm_year + 1900,
2228 tm->tm_mon + 1,
2229 tm->tm_mday);
2230 else
2231 PyErr_SetString(PyExc_ValueError,
2232 "timestamp out of range for "
2233 "platform localtime() function");
2234 return result;
2235}
2236
2237/* Return new date from current time.
2238 * We say this is equivalent to fromtimestamp(time.time()), and the
2239 * only way to be sure of that is to *call* time.time(). That's not
2240 * generally the same as calling C's time.
2241 */
2242static PyObject *
2243date_today(PyObject *cls, PyObject *dummy)
2244{
2245 PyObject *time;
2246 PyObject *result;
2247
2248 time = time_time();
2249 if (time == NULL)
2250 return NULL;
2251
2252 /* Note well: today() is a class method, so this may not call
2253 * date.fromtimestamp. For example, it may call
2254 * datetime.fromtimestamp. That's why we need all the accuracy
2255 * time.time() delivers; if someone were gonzo about optimization,
2256 * date.today() could get away with plain C time().
2257 */
2258 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2259 Py_DECREF(time);
2260 return result;
2261}
2262
2263/* Return new date from given timestamp (Python timestamp -- a double). */
2264static PyObject *
2265date_fromtimestamp(PyObject *cls, PyObject *args)
2266{
2267 double timestamp;
2268 PyObject *result = NULL;
2269
2270 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002271 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002272 return result;
2273}
2274
2275/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2276 * the ordinal is out of range.
2277 */
2278static PyObject *
2279date_fromordinal(PyObject *cls, PyObject *args)
2280{
2281 PyObject *result = NULL;
2282 int ordinal;
2283
2284 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2285 int year;
2286 int month;
2287 int day;
2288
2289 if (ordinal < 1)
2290 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2291 ">= 1");
2292 else {
2293 ord_to_ymd(ordinal, &year, &month, &day);
2294 result = PyObject_CallFunction(cls, "iii",
2295 year, month, day);
2296 }
2297 }
2298 return result;
2299}
2300
2301/*
2302 * Date arithmetic.
2303 */
2304
2305/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2306 * instead.
2307 */
2308static PyObject *
2309add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2310{
2311 PyObject *result = NULL;
2312 int year = GET_YEAR(date);
2313 int month = GET_MONTH(date);
2314 int deltadays = GET_TD_DAYS(delta);
2315 /* C-level overflow is impossible because |deltadays| < 1e9. */
2316 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2317
2318 if (normalize_date(&year, &month, &day) >= 0)
2319 result = new_date(year, month, day);
2320 return result;
2321}
2322
2323static PyObject *
2324date_add(PyObject *left, PyObject *right)
2325{
2326 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2327 Py_INCREF(Py_NotImplemented);
2328 return Py_NotImplemented;
2329 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002330 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002331 /* date + ??? */
2332 if (PyDelta_Check(right))
2333 /* date + delta */
2334 return add_date_timedelta((PyDateTime_Date *) left,
2335 (PyDateTime_Delta *) right,
2336 0);
2337 }
2338 else {
2339 /* ??? + date
2340 * 'right' must be one of us, or we wouldn't have been called
2341 */
2342 if (PyDelta_Check(left))
2343 /* delta + date */
2344 return add_date_timedelta((PyDateTime_Date *) right,
2345 (PyDateTime_Delta *) left,
2346 0);
2347 }
2348 Py_INCREF(Py_NotImplemented);
2349 return Py_NotImplemented;
2350}
2351
2352static PyObject *
2353date_subtract(PyObject *left, PyObject *right)
2354{
2355 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2356 Py_INCREF(Py_NotImplemented);
2357 return Py_NotImplemented;
2358 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002359 if (PyDate_Check(left)) {
2360 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002361 /* date - date */
2362 int left_ord = ymd_to_ord(GET_YEAR(left),
2363 GET_MONTH(left),
2364 GET_DAY(left));
2365 int right_ord = ymd_to_ord(GET_YEAR(right),
2366 GET_MONTH(right),
2367 GET_DAY(right));
2368 return new_delta(left_ord - right_ord, 0, 0, 0);
2369 }
2370 if (PyDelta_Check(right)) {
2371 /* date - delta */
2372 return add_date_timedelta((PyDateTime_Date *) left,
2373 (PyDateTime_Delta *) right,
2374 1);
2375 }
2376 }
2377 Py_INCREF(Py_NotImplemented);
2378 return Py_NotImplemented;
2379}
2380
2381
2382/* Various ways to turn a date into a string. */
2383
2384static PyObject *
2385date_repr(PyDateTime_Date *self)
2386{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002387 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00002388 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002389 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002390}
2391
2392static PyObject *
2393date_isoformat(PyDateTime_Date *self)
2394{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002395 return PyUnicode_FromFormat("%04d-%02d-%02d",
2396 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002397}
2398
Tim Peterse2df5ff2003-05-02 18:39:55 +00002399/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002400static PyObject *
2401date_str(PyDateTime_Date *self)
2402{
2403 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2404}
2405
2406
2407static PyObject *
2408date_ctime(PyDateTime_Date *self)
2409{
2410 return format_ctime(self, 0, 0, 0);
2411}
2412
2413static PyObject *
2414date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2415{
2416 /* This method can be inherited, and needs to call the
2417 * timetuple() method appropriate to self's class.
2418 */
2419 PyObject *result;
2420 PyObject *format;
2421 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002422 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002423
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002424 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00002425 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002426 return NULL;
2427
2428 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2429 if (tuple == NULL)
2430 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002431 result = wrap_strftime((PyObject *)self, format, tuple,
2432 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002433 Py_DECREF(tuple);
2434 return result;
2435}
2436
Eric Smith1ba31142007-09-11 18:06:02 +00002437static PyObject *
2438date_format(PyDateTime_Date *self, PyObject *args)
2439{
2440 PyObject *format;
2441
2442 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2443 return NULL;
2444
2445 /* if the format is zero length, return str(self) */
2446 if (PyUnicode_GetSize(format) == 0)
Thomas Heller519a0422007-11-15 20:48:54 +00002447 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002448
2449 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
2450}
2451
Tim Peters2a799bf2002-12-16 20:18:38 +00002452/* ISO methods. */
2453
2454static PyObject *
2455date_isoweekday(PyDateTime_Date *self)
2456{
2457 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2458
Christian Heimes217cfd12007-12-02 14:31:20 +00002459 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002460}
2461
2462static PyObject *
2463date_isocalendar(PyDateTime_Date *self)
2464{
2465 int year = GET_YEAR(self);
2466 int week1_monday = iso_week1_monday(year);
2467 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2468 int week;
2469 int day;
2470
2471 week = divmod(today - week1_monday, 7, &day);
2472 if (week < 0) {
2473 --year;
2474 week1_monday = iso_week1_monday(year);
2475 week = divmod(today - week1_monday, 7, &day);
2476 }
2477 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2478 ++year;
2479 week = 0;
2480 }
2481 return Py_BuildValue("iii", year, week + 1, day + 1);
2482}
2483
2484/* Miscellaneous methods. */
2485
Tim Peters2a799bf2002-12-16 20:18:38 +00002486static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002487date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002488{
Guido van Rossum19960592006-08-24 17:29:38 +00002489 if (PyDate_Check(other)) {
2490 int diff = memcmp(((PyDateTime_Date *)self)->data,
2491 ((PyDateTime_Date *)other)->data,
2492 _PyDateTime_DATE_DATASIZE);
2493 return diff_to_bool(diff, op);
2494 }
2495 else {
Tim Peters07534a62003-02-07 22:50:28 +00002496 Py_INCREF(Py_NotImplemented);
2497 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002498 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002499}
2500
2501static PyObject *
2502date_timetuple(PyDateTime_Date *self)
2503{
2504 return build_struct_time(GET_YEAR(self),
2505 GET_MONTH(self),
2506 GET_DAY(self),
2507 0, 0, 0, -1);
2508}
2509
Tim Peters12bf3392002-12-24 05:41:27 +00002510static PyObject *
2511date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2512{
2513 PyObject *clone;
2514 PyObject *tuple;
2515 int year = GET_YEAR(self);
2516 int month = GET_MONTH(self);
2517 int day = GET_DAY(self);
2518
2519 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2520 &year, &month, &day))
2521 return NULL;
2522 tuple = Py_BuildValue("iii", year, month, day);
2523 if (tuple == NULL)
2524 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002525 clone = date_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002526 Py_DECREF(tuple);
2527 return clone;
2528}
2529
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002530/*
2531 Borrowed from stringobject.c, originally it was string_hash()
2532*/
2533static long
2534generic_hash(unsigned char *data, int len)
2535{
2536 register unsigned char *p;
2537 register long x;
2538
2539 p = (unsigned char *) data;
2540 x = *p << 7;
2541 while (--len >= 0)
2542 x = (1000003*x) ^ *p++;
2543 x ^= len;
2544 if (x == -1)
2545 x = -2;
2546
2547 return x;
2548}
2549
2550
2551static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002552
2553static long
2554date_hash(PyDateTime_Date *self)
2555{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002556 if (self->hashcode == -1)
2557 self->hashcode = generic_hash(
2558 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002559
Tim Peters2a799bf2002-12-16 20:18:38 +00002560 return self->hashcode;
2561}
2562
2563static PyObject *
2564date_toordinal(PyDateTime_Date *self)
2565{
Christian Heimes217cfd12007-12-02 14:31:20 +00002566 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
Tim Peters2a799bf2002-12-16 20:18:38 +00002567 GET_DAY(self)));
2568}
2569
2570static PyObject *
2571date_weekday(PyDateTime_Date *self)
2572{
2573 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2574
Christian Heimes217cfd12007-12-02 14:31:20 +00002575 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002576}
2577
Tim Peters371935f2003-02-01 01:52:50 +00002578/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002579
Tim Petersb57f8f02003-02-01 02:54:15 +00002580/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002581static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002582date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002583{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002584 PyObject* field;
Guido van Rossum254348e2007-11-21 19:29:53 +00002585 field = PyString_FromStringAndSize((char*)self->data,
2586 _PyDateTime_DATE_DATASIZE);
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002587 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002588}
2589
2590static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002591date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002592{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002593 return Py_BuildValue("(ON)", Py_Type(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002594}
2595
2596static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002597
Tim Peters2a799bf2002-12-16 20:18:38 +00002598 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002599
Tim Peters2a799bf2002-12-16 20:18:38 +00002600 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2601 METH_CLASS,
2602 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2603 "time.time()).")},
2604
2605 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2606 METH_CLASS,
2607 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2608 "ordinal.")},
2609
2610 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2611 PyDoc_STR("Current date or datetime: same as "
2612 "self.__class__.fromtimestamp(time.time()).")},
2613
2614 /* Instance methods: */
2615
2616 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2617 PyDoc_STR("Return ctime() style string.")},
2618
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002619 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002620 PyDoc_STR("format -> strftime() style string.")},
2621
Eric Smith1ba31142007-09-11 18:06:02 +00002622 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2623 PyDoc_STR("Formats self with strftime.")},
2624
Tim Peters2a799bf2002-12-16 20:18:38 +00002625 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2626 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2627
2628 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2629 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2630 "weekday.")},
2631
2632 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2633 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2634
2635 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2636 PyDoc_STR("Return the day of the week represented by the date.\n"
2637 "Monday == 1 ... Sunday == 7")},
2638
2639 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2640 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2641 "1 is day 1.")},
2642
2643 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2644 PyDoc_STR("Return the day of the week represented by the date.\n"
2645 "Monday == 0 ... Sunday == 6")},
2646
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002647 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002648 PyDoc_STR("Return date with new specified fields.")},
2649
Guido van Rossum177e41a2003-01-30 22:06:23 +00002650 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2651 PyDoc_STR("__reduce__() -> (cls, state)")},
2652
Tim Peters2a799bf2002-12-16 20:18:38 +00002653 {NULL, NULL}
2654};
2655
2656static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002657PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002658
2659static PyNumberMethods date_as_number = {
2660 date_add, /* nb_add */
2661 date_subtract, /* nb_subtract */
2662 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002663 0, /* nb_remainder */
2664 0, /* nb_divmod */
2665 0, /* nb_power */
2666 0, /* nb_negative */
2667 0, /* nb_positive */
2668 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002669 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002670};
2671
2672static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002673 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002674 "datetime.date", /* tp_name */
2675 sizeof(PyDateTime_Date), /* tp_basicsize */
2676 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002677 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002678 0, /* tp_print */
2679 0, /* tp_getattr */
2680 0, /* tp_setattr */
2681 0, /* tp_compare */
2682 (reprfunc)date_repr, /* tp_repr */
2683 &date_as_number, /* tp_as_number */
2684 0, /* tp_as_sequence */
2685 0, /* tp_as_mapping */
2686 (hashfunc)date_hash, /* tp_hash */
2687 0, /* tp_call */
2688 (reprfunc)date_str, /* tp_str */
2689 PyObject_GenericGetAttr, /* tp_getattro */
2690 0, /* tp_setattro */
2691 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002692 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002693 date_doc, /* tp_doc */
2694 0, /* tp_traverse */
2695 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002696 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002697 0, /* tp_weaklistoffset */
2698 0, /* tp_iter */
2699 0, /* tp_iternext */
2700 date_methods, /* tp_methods */
2701 0, /* tp_members */
2702 date_getset, /* tp_getset */
2703 0, /* tp_base */
2704 0, /* tp_dict */
2705 0, /* tp_descr_get */
2706 0, /* tp_descr_set */
2707 0, /* tp_dictoffset */
2708 0, /* tp_init */
2709 0, /* tp_alloc */
2710 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002711 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002712};
2713
2714/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002715 * PyDateTime_TZInfo implementation.
2716 */
2717
2718/* This is a pure abstract base class, so doesn't do anything beyond
2719 * raising NotImplemented exceptions. Real tzinfo classes need
2720 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002721 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002722 * be subclasses of this tzinfo class, which is easy and quick to check).
2723 *
2724 * Note: For reasons having to do with pickling of subclasses, we have
2725 * to allow tzinfo objects to be instantiated. This wasn't an issue
2726 * in the Python implementation (__init__() could raise NotImplementedError
2727 * there without ill effect), but doing so in the C implementation hit a
2728 * brick wall.
2729 */
2730
2731static PyObject *
2732tzinfo_nogo(const char* methodname)
2733{
2734 PyErr_Format(PyExc_NotImplementedError,
2735 "a tzinfo subclass must implement %s()",
2736 methodname);
2737 return NULL;
2738}
2739
2740/* Methods. A subclass must implement these. */
2741
Tim Peters52dcce22003-01-23 16:36:11 +00002742static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002743tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2744{
2745 return tzinfo_nogo("tzname");
2746}
2747
Tim Peters52dcce22003-01-23 16:36:11 +00002748static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002749tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2750{
2751 return tzinfo_nogo("utcoffset");
2752}
2753
Tim Peters52dcce22003-01-23 16:36:11 +00002754static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002755tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2756{
2757 return tzinfo_nogo("dst");
2758}
2759
Tim Peters52dcce22003-01-23 16:36:11 +00002760static PyObject *
2761tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2762{
2763 int y, m, d, hh, mm, ss, us;
2764
2765 PyObject *result;
2766 int off, dst;
2767 int none;
2768 int delta;
2769
2770 if (! PyDateTime_Check(dt)) {
2771 PyErr_SetString(PyExc_TypeError,
2772 "fromutc: argument must be a datetime");
2773 return NULL;
2774 }
2775 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2776 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2777 "is not self");
2778 return NULL;
2779 }
2780
2781 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2782 if (off == -1 && PyErr_Occurred())
2783 return NULL;
2784 if (none) {
2785 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2786 "utcoffset() result required");
2787 return NULL;
2788 }
2789
2790 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2791 if (dst == -1 && PyErr_Occurred())
2792 return NULL;
2793 if (none) {
2794 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2795 "dst() result required");
2796 return NULL;
2797 }
2798
2799 y = GET_YEAR(dt);
2800 m = GET_MONTH(dt);
2801 d = GET_DAY(dt);
2802 hh = DATE_GET_HOUR(dt);
2803 mm = DATE_GET_MINUTE(dt);
2804 ss = DATE_GET_SECOND(dt);
2805 us = DATE_GET_MICROSECOND(dt);
2806
2807 delta = off - dst;
2808 mm += delta;
2809 if ((mm < 0 || mm >= 60) &&
2810 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002811 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002812 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2813 if (result == NULL)
2814 return result;
2815
2816 dst = call_dst(dt->tzinfo, result, &none);
2817 if (dst == -1 && PyErr_Occurred())
2818 goto Fail;
2819 if (none)
2820 goto Inconsistent;
2821 if (dst == 0)
2822 return result;
2823
2824 mm += dst;
2825 if ((mm < 0 || mm >= 60) &&
2826 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2827 goto Fail;
2828 Py_DECREF(result);
2829 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2830 return result;
2831
2832Inconsistent:
2833 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2834 "inconsistent results; cannot convert");
2835
2836 /* fall thru to failure */
2837Fail:
2838 Py_DECREF(result);
2839 return NULL;
2840}
2841
Tim Peters2a799bf2002-12-16 20:18:38 +00002842/*
2843 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002844 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002845 */
2846
Guido van Rossum177e41a2003-01-30 22:06:23 +00002847static PyObject *
2848tzinfo_reduce(PyObject *self)
2849{
2850 PyObject *args, *state, *tmp;
2851 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002852
Guido van Rossum177e41a2003-01-30 22:06:23 +00002853 tmp = PyTuple_New(0);
2854 if (tmp == NULL)
2855 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002856
Guido van Rossum177e41a2003-01-30 22:06:23 +00002857 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2858 if (getinitargs != NULL) {
2859 args = PyObject_CallObject(getinitargs, tmp);
2860 Py_DECREF(getinitargs);
2861 if (args == NULL) {
2862 Py_DECREF(tmp);
2863 return NULL;
2864 }
2865 }
2866 else {
2867 PyErr_Clear();
2868 args = tmp;
2869 Py_INCREF(args);
2870 }
2871
2872 getstate = PyObject_GetAttrString(self, "__getstate__");
2873 if (getstate != NULL) {
2874 state = PyObject_CallObject(getstate, tmp);
2875 Py_DECREF(getstate);
2876 if (state == NULL) {
2877 Py_DECREF(args);
2878 Py_DECREF(tmp);
2879 return NULL;
2880 }
2881 }
2882 else {
2883 PyObject **dictptr;
2884 PyErr_Clear();
2885 state = Py_None;
2886 dictptr = _PyObject_GetDictPtr(self);
2887 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2888 state = *dictptr;
2889 Py_INCREF(state);
2890 }
2891
2892 Py_DECREF(tmp);
2893
2894 if (state == Py_None) {
2895 Py_DECREF(state);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002896 return Py_BuildValue("(ON)", Py_Type(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002897 }
2898 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002899 return Py_BuildValue("(ONN)", Py_Type(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002900}
Tim Peters2a799bf2002-12-16 20:18:38 +00002901
2902static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002903
Tim Peters2a799bf2002-12-16 20:18:38 +00002904 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2905 PyDoc_STR("datetime -> string name of time zone.")},
2906
2907 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2908 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2909 "west of UTC).")},
2910
2911 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2912 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2913
Tim Peters52dcce22003-01-23 16:36:11 +00002914 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2915 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2916
Guido van Rossum177e41a2003-01-30 22:06:23 +00002917 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2918 PyDoc_STR("-> (cls, state)")},
2919
Tim Peters2a799bf2002-12-16 20:18:38 +00002920 {NULL, NULL}
2921};
2922
2923static char tzinfo_doc[] =
2924PyDoc_STR("Abstract base class for time zone info objects.");
2925
Neal Norwitz227b5332006-03-22 09:28:35 +00002926static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002927 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002928 "datetime.tzinfo", /* tp_name */
2929 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2930 0, /* tp_itemsize */
2931 0, /* tp_dealloc */
2932 0, /* tp_print */
2933 0, /* tp_getattr */
2934 0, /* tp_setattr */
2935 0, /* tp_compare */
2936 0, /* tp_repr */
2937 0, /* tp_as_number */
2938 0, /* tp_as_sequence */
2939 0, /* tp_as_mapping */
2940 0, /* tp_hash */
2941 0, /* tp_call */
2942 0, /* tp_str */
2943 PyObject_GenericGetAttr, /* tp_getattro */
2944 0, /* tp_setattro */
2945 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002946 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002947 tzinfo_doc, /* tp_doc */
2948 0, /* tp_traverse */
2949 0, /* tp_clear */
2950 0, /* tp_richcompare */
2951 0, /* tp_weaklistoffset */
2952 0, /* tp_iter */
2953 0, /* tp_iternext */
2954 tzinfo_methods, /* tp_methods */
2955 0, /* tp_members */
2956 0, /* tp_getset */
2957 0, /* tp_base */
2958 0, /* tp_dict */
2959 0, /* tp_descr_get */
2960 0, /* tp_descr_set */
2961 0, /* tp_dictoffset */
2962 0, /* tp_init */
2963 0, /* tp_alloc */
2964 PyType_GenericNew, /* tp_new */
2965 0, /* tp_free */
2966};
2967
2968/*
Tim Peters37f39822003-01-10 03:49:02 +00002969 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002970 */
2971
Tim Peters37f39822003-01-10 03:49:02 +00002972/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002973 */
2974
2975static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002976time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002977{
Christian Heimes217cfd12007-12-02 14:31:20 +00002978 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002979}
2980
Tim Peters37f39822003-01-10 03:49:02 +00002981static PyObject *
2982time_minute(PyDateTime_Time *self, void *unused)
2983{
Christian Heimes217cfd12007-12-02 14:31:20 +00002984 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00002985}
2986
2987/* The name time_second conflicted with some platform header file. */
2988static PyObject *
2989py_time_second(PyDateTime_Time *self, void *unused)
2990{
Christian Heimes217cfd12007-12-02 14:31:20 +00002991 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00002992}
2993
2994static PyObject *
2995time_microsecond(PyDateTime_Time *self, void *unused)
2996{
Christian Heimes217cfd12007-12-02 14:31:20 +00002997 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00002998}
2999
3000static PyObject *
3001time_tzinfo(PyDateTime_Time *self, void *unused)
3002{
Tim Petersa032d2e2003-01-11 00:15:54 +00003003 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003004 Py_INCREF(result);
3005 return result;
3006}
3007
3008static PyGetSetDef time_getset[] = {
3009 {"hour", (getter)time_hour},
3010 {"minute", (getter)time_minute},
3011 {"second", (getter)py_time_second},
3012 {"microsecond", (getter)time_microsecond},
3013 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003014 {NULL}
3015};
3016
3017/*
3018 * Constructors.
3019 */
3020
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003021static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003022 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003023
Tim Peters2a799bf2002-12-16 20:18:38 +00003024static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003025time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003026{
3027 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003028 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003029 int hour = 0;
3030 int minute = 0;
3031 int second = 0;
3032 int usecond = 0;
3033 PyObject *tzinfo = Py_None;
3034
Guido van Rossum177e41a2003-01-30 22:06:23 +00003035 /* Check for invocation from pickle with __getstate__ state */
3036 if (PyTuple_GET_SIZE(args) >= 1 &&
3037 PyTuple_GET_SIZE(args) <= 2 &&
Guido van Rossum254348e2007-11-21 19:29:53 +00003038 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3039 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3040 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003041 {
Tim Peters70533e22003-02-01 04:40:04 +00003042 PyDateTime_Time *me;
3043 char aware;
3044
3045 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003046 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003047 if (check_tzinfo_subclass(tzinfo) < 0) {
3048 PyErr_SetString(PyExc_TypeError, "bad "
3049 "tzinfo state arg");
3050 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003051 }
3052 }
Tim Peters70533e22003-02-01 04:40:04 +00003053 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003054 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003055 if (me != NULL) {
Guido van Rossum254348e2007-11-21 19:29:53 +00003056 char *pdata = PyString_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003057
3058 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3059 me->hashcode = -1;
3060 me->hastzinfo = aware;
3061 if (aware) {
3062 Py_INCREF(tzinfo);
3063 me->tzinfo = tzinfo;
3064 }
3065 }
3066 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003067 }
3068
Tim Peters37f39822003-01-10 03:49:02 +00003069 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003070 &hour, &minute, &second, &usecond,
3071 &tzinfo)) {
3072 if (check_time_args(hour, minute, second, usecond) < 0)
3073 return NULL;
3074 if (check_tzinfo_subclass(tzinfo) < 0)
3075 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003076 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3077 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003078 }
3079 return self;
3080}
3081
3082/*
3083 * Destructor.
3084 */
3085
3086static void
Tim Peters37f39822003-01-10 03:49:02 +00003087time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003088{
Tim Petersa032d2e2003-01-11 00:15:54 +00003089 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003090 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003091 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003092 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003093}
3094
3095/*
Tim Peters855fe882002-12-22 03:43:39 +00003096 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003097 */
3098
Tim Peters2a799bf2002-12-16 20:18:38 +00003099/* These are all METH_NOARGS, so don't need to check the arglist. */
3100static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003101time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003102 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003103 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003104}
3105
3106static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003107time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003108 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003109 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003110}
3111
3112static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003113time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003114 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003115 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003116}
3117
3118/*
Tim Peters37f39822003-01-10 03:49:02 +00003119 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003120 */
3121
3122static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003123time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003124{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003125 const char *type_name = Py_Type(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003126 int h = TIME_GET_HOUR(self);
3127 int m = TIME_GET_MINUTE(self);
3128 int s = TIME_GET_SECOND(self);
3129 int us = TIME_GET_MICROSECOND(self);
3130 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003131
Tim Peters37f39822003-01-10 03:49:02 +00003132 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003133 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3134 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003135 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003136 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3137 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003138 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003139 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003140 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003141 result = append_keyword_tzinfo(result, self->tzinfo);
3142 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003143}
3144
Tim Peters37f39822003-01-10 03:49:02 +00003145static PyObject *
3146time_str(PyDateTime_Time *self)
3147{
3148 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3149}
Tim Peters2a799bf2002-12-16 20:18:38 +00003150
3151static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003152time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003153{
3154 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003155 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003156 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003157
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003158 if (us)
3159 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3160 TIME_GET_HOUR(self),
3161 TIME_GET_MINUTE(self),
3162 TIME_GET_SECOND(self),
3163 us);
3164 else
3165 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3166 TIME_GET_HOUR(self),
3167 TIME_GET_MINUTE(self),
3168 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003169
Tim Petersa032d2e2003-01-11 00:15:54 +00003170 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003171 return result;
3172
3173 /* We need to append the UTC offset. */
3174 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003175 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003176 Py_DECREF(result);
3177 return NULL;
3178 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003179 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003180 return result;
3181}
3182
Tim Peters37f39822003-01-10 03:49:02 +00003183static PyObject *
3184time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3185{
3186 PyObject *result;
3187 PyObject *format;
3188 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003189 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003190
Guido van Rossum98297ee2007-11-06 21:34:58 +00003191 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00003192 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003193 return NULL;
3194
3195 /* Python's strftime does insane things with the year part of the
3196 * timetuple. The year is forced to (the otherwise nonsensical)
3197 * 1900 to worm around that.
3198 */
3199 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003200 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003201 TIME_GET_HOUR(self),
3202 TIME_GET_MINUTE(self),
3203 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003204 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003205 if (tuple == NULL)
3206 return NULL;
3207 assert(PyTuple_Size(tuple) == 9);
3208 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3209 Py_DECREF(tuple);
3210 return result;
3211}
Tim Peters2a799bf2002-12-16 20:18:38 +00003212
Eric Smith1ba31142007-09-11 18:06:02 +00003213static PyObject *
3214time_format(PyDateTime_Time *self, PyObject *args)
3215{
3216 PyObject *format;
3217
3218 if (!PyArg_ParseTuple(args, "U:__format__", &format))
3219 return NULL;
3220
3221 /* if the format is zero length, return str(self) */
3222 if (PyUnicode_GetSize(format) == 0)
Thomas Heller519a0422007-11-15 20:48:54 +00003223 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00003224
3225 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
3226}
3227
Tim Peters2a799bf2002-12-16 20:18:38 +00003228/*
3229 * Miscellaneous methods.
3230 */
3231
Tim Peters37f39822003-01-10 03:49:02 +00003232static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003233time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003234{
3235 int diff;
3236 naivety n1, n2;
3237 int offset1, offset2;
3238
3239 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003240 Py_INCREF(Py_NotImplemented);
3241 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003242 }
Guido van Rossum19960592006-08-24 17:29:38 +00003243 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3244 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003245 return NULL;
3246 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3247 /* If they're both naive, or both aware and have the same offsets,
3248 * we get off cheap. Note that if they're both naive, offset1 ==
3249 * offset2 == 0 at this point.
3250 */
3251 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003252 diff = memcmp(((PyDateTime_Time *)self)->data,
3253 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003254 _PyDateTime_TIME_DATASIZE);
3255 return diff_to_bool(diff, op);
3256 }
3257
3258 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3259 assert(offset1 != offset2); /* else last "if" handled it */
3260 /* Convert everything except microseconds to seconds. These
3261 * can't overflow (no more than the # of seconds in 2 days).
3262 */
3263 offset1 = TIME_GET_HOUR(self) * 3600 +
3264 (TIME_GET_MINUTE(self) - offset1) * 60 +
3265 TIME_GET_SECOND(self);
3266 offset2 = TIME_GET_HOUR(other) * 3600 +
3267 (TIME_GET_MINUTE(other) - offset2) * 60 +
3268 TIME_GET_SECOND(other);
3269 diff = offset1 - offset2;
3270 if (diff == 0)
3271 diff = TIME_GET_MICROSECOND(self) -
3272 TIME_GET_MICROSECOND(other);
3273 return diff_to_bool(diff, op);
3274 }
3275
3276 assert(n1 != n2);
3277 PyErr_SetString(PyExc_TypeError,
3278 "can't compare offset-naive and "
3279 "offset-aware times");
3280 return NULL;
3281}
3282
3283static long
3284time_hash(PyDateTime_Time *self)
3285{
3286 if (self->hashcode == -1) {
3287 naivety n;
3288 int offset;
3289 PyObject *temp;
3290
3291 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3292 assert(n != OFFSET_UNKNOWN);
3293 if (n == OFFSET_ERROR)
3294 return -1;
3295
3296 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003297 if (offset == 0) {
3298 self->hashcode = generic_hash(
3299 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3300 return self->hashcode;
3301 }
Tim Peters37f39822003-01-10 03:49:02 +00003302 else {
3303 int hour;
3304 int minute;
3305
3306 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003307 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003308 hour = divmod(TIME_GET_HOUR(self) * 60 +
3309 TIME_GET_MINUTE(self) - offset,
3310 60,
3311 &minute);
3312 if (0 <= hour && hour < 24)
3313 temp = new_time(hour, minute,
3314 TIME_GET_SECOND(self),
3315 TIME_GET_MICROSECOND(self),
3316 Py_None);
3317 else
3318 temp = Py_BuildValue("iiii",
3319 hour, minute,
3320 TIME_GET_SECOND(self),
3321 TIME_GET_MICROSECOND(self));
3322 }
3323 if (temp != NULL) {
3324 self->hashcode = PyObject_Hash(temp);
3325 Py_DECREF(temp);
3326 }
3327 }
3328 return self->hashcode;
3329}
Tim Peters2a799bf2002-12-16 20:18:38 +00003330
Tim Peters12bf3392002-12-24 05:41:27 +00003331static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003332time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003333{
3334 PyObject *clone;
3335 PyObject *tuple;
3336 int hh = TIME_GET_HOUR(self);
3337 int mm = TIME_GET_MINUTE(self);
3338 int ss = TIME_GET_SECOND(self);
3339 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003340 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003341
3342 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003343 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003344 &hh, &mm, &ss, &us, &tzinfo))
3345 return NULL;
3346 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3347 if (tuple == NULL)
3348 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003349 clone = time_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003350 Py_DECREF(tuple);
3351 return clone;
3352}
3353
Tim Peters2a799bf2002-12-16 20:18:38 +00003354static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003355time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003356{
3357 int offset;
3358 int none;
3359
3360 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3361 /* Since utcoffset is in whole minutes, nothing can
3362 * alter the conclusion that this is nonzero.
3363 */
3364 return 1;
3365 }
3366 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003367 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003368 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003369 if (offset == -1 && PyErr_Occurred())
3370 return -1;
3371 }
3372 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3373}
3374
Tim Peters371935f2003-02-01 01:52:50 +00003375/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003376
Tim Peters33e0f382003-01-10 02:05:14 +00003377/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003378 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3379 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003380 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003381 */
3382static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003383time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003384{
3385 PyObject *basestate;
3386 PyObject *result = NULL;
3387
Guido van Rossum254348e2007-11-21 19:29:53 +00003388 basestate = PyString_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003389 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003390 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003391 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003392 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003393 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003394 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003395 Py_DECREF(basestate);
3396 }
3397 return result;
3398}
3399
3400static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003401time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003402{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003403 return Py_BuildValue("(ON)", Py_Type(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003404}
3405
Tim Peters37f39822003-01-10 03:49:02 +00003406static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003407
Thomas Wouterscf297e42007-02-23 15:07:44 +00003408 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003409 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3410 "[+HH:MM].")},
3411
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003412 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003413 PyDoc_STR("format -> strftime() style string.")},
3414
Eric Smith1ba31142007-09-11 18:06:02 +00003415 {"__format__", (PyCFunction)time_format, METH_VARARGS,
3416 PyDoc_STR("Formats self with strftime.")},
3417
Tim Peters37f39822003-01-10 03:49:02 +00003418 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003419 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3420
Tim Peters37f39822003-01-10 03:49:02 +00003421 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003422 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3423
Tim Peters37f39822003-01-10 03:49:02 +00003424 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003425 PyDoc_STR("Return self.tzinfo.dst(self).")},
3426
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003427 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003428 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003429
Guido van Rossum177e41a2003-01-30 22:06:23 +00003430 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3431 PyDoc_STR("__reduce__() -> (cls, state)")},
3432
Tim Peters2a799bf2002-12-16 20:18:38 +00003433 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003434};
3435
Tim Peters37f39822003-01-10 03:49:02 +00003436static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003437PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3438\n\
3439All arguments are optional. tzinfo may be None, or an instance of\n\
3440a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003441
Tim Peters37f39822003-01-10 03:49:02 +00003442static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003443 0, /* nb_add */
3444 0, /* nb_subtract */
3445 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003446 0, /* nb_remainder */
3447 0, /* nb_divmod */
3448 0, /* nb_power */
3449 0, /* nb_negative */
3450 0, /* nb_positive */
3451 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003452 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003453};
3454
Neal Norwitz227b5332006-03-22 09:28:35 +00003455static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003456 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003457 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003458 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003459 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003460 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003461 0, /* tp_print */
3462 0, /* tp_getattr */
3463 0, /* tp_setattr */
3464 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003465 (reprfunc)time_repr, /* tp_repr */
3466 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003467 0, /* tp_as_sequence */
3468 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003469 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003470 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003471 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003472 PyObject_GenericGetAttr, /* tp_getattro */
3473 0, /* tp_setattro */
3474 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003475 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003476 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003477 0, /* tp_traverse */
3478 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003479 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003480 0, /* tp_weaklistoffset */
3481 0, /* tp_iter */
3482 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003483 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003484 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003485 time_getset, /* tp_getset */
3486 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003487 0, /* tp_dict */
3488 0, /* tp_descr_get */
3489 0, /* tp_descr_set */
3490 0, /* tp_dictoffset */
3491 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003492 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003493 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003494 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003495};
3496
3497/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003498 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003499 */
3500
Tim Petersa9bc1682003-01-11 03:39:11 +00003501/* Accessor properties. Properties for day, month, and year are inherited
3502 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003503 */
3504
3505static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003506datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003507{
Christian Heimes217cfd12007-12-02 14:31:20 +00003508 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003509}
3510
Tim Petersa9bc1682003-01-11 03:39:11 +00003511static PyObject *
3512datetime_minute(PyDateTime_DateTime *self, void *unused)
3513{
Christian Heimes217cfd12007-12-02 14:31:20 +00003514 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003515}
3516
3517static PyObject *
3518datetime_second(PyDateTime_DateTime *self, void *unused)
3519{
Christian Heimes217cfd12007-12-02 14:31:20 +00003520 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003521}
3522
3523static PyObject *
3524datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3525{
Christian Heimes217cfd12007-12-02 14:31:20 +00003526 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003527}
3528
3529static PyObject *
3530datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3531{
3532 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3533 Py_INCREF(result);
3534 return result;
3535}
3536
3537static PyGetSetDef datetime_getset[] = {
3538 {"hour", (getter)datetime_hour},
3539 {"minute", (getter)datetime_minute},
3540 {"second", (getter)datetime_second},
3541 {"microsecond", (getter)datetime_microsecond},
3542 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003543 {NULL}
3544};
3545
3546/*
3547 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003548 */
3549
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003550static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003551 "year", "month", "day", "hour", "minute", "second",
3552 "microsecond", "tzinfo", NULL
3553};
3554
Tim Peters2a799bf2002-12-16 20:18:38 +00003555static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003556datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003557{
3558 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003559 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003560 int year;
3561 int month;
3562 int day;
3563 int hour = 0;
3564 int minute = 0;
3565 int second = 0;
3566 int usecond = 0;
3567 PyObject *tzinfo = Py_None;
3568
Guido van Rossum177e41a2003-01-30 22:06:23 +00003569 /* Check for invocation from pickle with __getstate__ state */
3570 if (PyTuple_GET_SIZE(args) >= 1 &&
3571 PyTuple_GET_SIZE(args) <= 2 &&
Guido van Rossum254348e2007-11-21 19:29:53 +00003572 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3573 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3574 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003575 {
Tim Peters70533e22003-02-01 04:40:04 +00003576 PyDateTime_DateTime *me;
3577 char aware;
3578
3579 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003580 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003581 if (check_tzinfo_subclass(tzinfo) < 0) {
3582 PyErr_SetString(PyExc_TypeError, "bad "
3583 "tzinfo state arg");
3584 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003585 }
3586 }
Tim Peters70533e22003-02-01 04:40:04 +00003587 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003588 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003589 if (me != NULL) {
Guido van Rossum254348e2007-11-21 19:29:53 +00003590 char *pdata = PyString_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003591
3592 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3593 me->hashcode = -1;
3594 me->hastzinfo = aware;
3595 if (aware) {
3596 Py_INCREF(tzinfo);
3597 me->tzinfo = tzinfo;
3598 }
3599 }
3600 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003601 }
3602
Tim Petersa9bc1682003-01-11 03:39:11 +00003603 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003604 &year, &month, &day, &hour, &minute,
3605 &second, &usecond, &tzinfo)) {
3606 if (check_date_args(year, month, day) < 0)
3607 return NULL;
3608 if (check_time_args(hour, minute, second, usecond) < 0)
3609 return NULL;
3610 if (check_tzinfo_subclass(tzinfo) < 0)
3611 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003612 self = new_datetime_ex(year, month, day,
3613 hour, minute, second, usecond,
3614 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003615 }
3616 return self;
3617}
3618
Tim Petersa9bc1682003-01-11 03:39:11 +00003619/* TM_FUNC is the shared type of localtime() and gmtime(). */
3620typedef struct tm *(*TM_FUNC)(const time_t *timer);
3621
3622/* Internal helper.
3623 * Build datetime from a time_t and a distinct count of microseconds.
3624 * Pass localtime or gmtime for f, to control the interpretation of timet.
3625 */
3626static PyObject *
3627datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3628 PyObject *tzinfo)
3629{
3630 struct tm *tm;
3631 PyObject *result = NULL;
3632
3633 tm = f(&timet);
3634 if (tm) {
3635 /* The platform localtime/gmtime may insert leap seconds,
3636 * indicated by tm->tm_sec > 59. We don't care about them,
3637 * except to the extent that passing them on to the datetime
3638 * constructor would raise ValueError for a reason that
3639 * made no sense to the user.
3640 */
3641 if (tm->tm_sec > 59)
3642 tm->tm_sec = 59;
3643 result = PyObject_CallFunction(cls, "iiiiiiiO",
3644 tm->tm_year + 1900,
3645 tm->tm_mon + 1,
3646 tm->tm_mday,
3647 tm->tm_hour,
3648 tm->tm_min,
3649 tm->tm_sec,
3650 us,
3651 tzinfo);
3652 }
3653 else
3654 PyErr_SetString(PyExc_ValueError,
3655 "timestamp out of range for "
3656 "platform localtime()/gmtime() function");
3657 return result;
3658}
3659
3660/* Internal helper.
3661 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3662 * to control the interpretation of the timestamp. Since a double doesn't
3663 * have enough bits to cover a datetime's full range of precision, it's
3664 * better to call datetime_from_timet_and_us provided you have a way
3665 * to get that much precision (e.g., C time() isn't good enough).
3666 */
3667static PyObject *
3668datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3669 PyObject *tzinfo)
3670{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003671 time_t timet;
3672 double fraction;
3673 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003674
Tim Peters1b6f7a92004-06-20 02:50:16 +00003675 timet = _PyTime_DoubleToTimet(timestamp);
3676 if (timet == (time_t)-1 && PyErr_Occurred())
3677 return NULL;
3678 fraction = timestamp - (double)timet;
3679 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003680 if (us < 0) {
3681 /* Truncation towards zero is not what we wanted
3682 for negative numbers (Python's mod semantics) */
3683 timet -= 1;
3684 us += 1000000;
3685 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003686 /* If timestamp is less than one microsecond smaller than a
3687 * full second, round up. Otherwise, ValueErrors are raised
3688 * for some floats. */
3689 if (us == 1000000) {
3690 timet += 1;
3691 us = 0;
3692 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003693 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3694}
3695
3696/* Internal helper.
3697 * Build most accurate possible datetime for current time. Pass localtime or
3698 * gmtime for f as appropriate.
3699 */
3700static PyObject *
3701datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3702{
3703#ifdef HAVE_GETTIMEOFDAY
3704 struct timeval t;
3705
3706#ifdef GETTIMEOFDAY_NO_TZ
3707 gettimeofday(&t);
3708#else
3709 gettimeofday(&t, (struct timezone *)NULL);
3710#endif
3711 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3712 tzinfo);
3713
3714#else /* ! HAVE_GETTIMEOFDAY */
3715 /* No flavor of gettimeofday exists on this platform. Python's
3716 * time.time() does a lot of other platform tricks to get the
3717 * best time it can on the platform, and we're not going to do
3718 * better than that (if we could, the better code would belong
3719 * in time.time()!) We're limited by the precision of a double,
3720 * though.
3721 */
3722 PyObject *time;
3723 double dtime;
3724
3725 time = time_time();
3726 if (time == NULL)
3727 return NULL;
3728 dtime = PyFloat_AsDouble(time);
3729 Py_DECREF(time);
3730 if (dtime == -1.0 && PyErr_Occurred())
3731 return NULL;
3732 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3733#endif /* ! HAVE_GETTIMEOFDAY */
3734}
3735
Tim Peters2a799bf2002-12-16 20:18:38 +00003736/* Return best possible local time -- this isn't constrained by the
3737 * precision of a timestamp.
3738 */
3739static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003740datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003741{
Tim Peters10cadce2003-01-23 19:58:02 +00003742 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003743 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003744 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003745
Tim Peters10cadce2003-01-23 19:58:02 +00003746 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3747 &tzinfo))
3748 return NULL;
3749 if (check_tzinfo_subclass(tzinfo) < 0)
3750 return NULL;
3751
3752 self = datetime_best_possible(cls,
3753 tzinfo == Py_None ? localtime : gmtime,
3754 tzinfo);
3755 if (self != NULL && tzinfo != Py_None) {
3756 /* Convert UTC to tzinfo's zone. */
3757 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003758 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003759 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003760 }
3761 return self;
3762}
3763
Tim Petersa9bc1682003-01-11 03:39:11 +00003764/* Return best possible UTC time -- this isn't constrained by the
3765 * precision of a timestamp.
3766 */
3767static PyObject *
3768datetime_utcnow(PyObject *cls, PyObject *dummy)
3769{
3770 return datetime_best_possible(cls, gmtime, Py_None);
3771}
3772
Tim Peters2a799bf2002-12-16 20:18:38 +00003773/* Return new local datetime from timestamp (Python timestamp -- a double). */
3774static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003775datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003776{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003777 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003778 double timestamp;
3779 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003780 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003781
Tim Peters2a44a8d2003-01-23 20:53:10 +00003782 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3783 keywords, &timestamp, &tzinfo))
3784 return NULL;
3785 if (check_tzinfo_subclass(tzinfo) < 0)
3786 return NULL;
3787
3788 self = datetime_from_timestamp(cls,
3789 tzinfo == Py_None ? localtime : gmtime,
3790 timestamp,
3791 tzinfo);
3792 if (self != NULL && tzinfo != Py_None) {
3793 /* Convert UTC to tzinfo's zone. */
3794 PyObject *temp = self;
3795 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3796 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003797 }
3798 return self;
3799}
3800
Tim Petersa9bc1682003-01-11 03:39:11 +00003801/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3802static PyObject *
3803datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3804{
3805 double timestamp;
3806 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003807
Tim Petersa9bc1682003-01-11 03:39:11 +00003808 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3809 result = datetime_from_timestamp(cls, gmtime, timestamp,
3810 Py_None);
3811 return result;
3812}
3813
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003814/* Return new datetime from time.strptime(). */
3815static PyObject *
3816datetime_strptime(PyObject *cls, PyObject *args)
3817{
3818 PyObject *result = NULL, *obj, *module;
Guido van Rossume8a17aa2007-08-29 17:28:42 +00003819 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003820
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003821 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003822 return NULL;
3823
3824 if ((module = PyImport_ImportModule("time")) == NULL)
3825 return NULL;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003826 obj = PyObject_CallMethod(module, "strptime", "uu", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003827 Py_DECREF(module);
3828
3829 if (obj != NULL) {
3830 int i, good_timetuple = 1;
3831 long int ia[6];
3832 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3833 for (i=0; i < 6; i++) {
3834 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003835 if (p == NULL) {
3836 Py_DECREF(obj);
3837 return NULL;
3838 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003839 if (PyInt_CheckExact(p))
Christian Heimes217cfd12007-12-02 14:31:20 +00003840 ia[i] = PyLong_AsLong(p);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003841 else
3842 good_timetuple = 0;
3843 Py_DECREF(p);
3844 }
3845 else
3846 good_timetuple = 0;
3847 if (good_timetuple)
3848 result = PyObject_CallFunction(cls, "iiiiii",
3849 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3850 else
3851 PyErr_SetString(PyExc_ValueError,
3852 "unexpected value from time.strptime");
3853 Py_DECREF(obj);
3854 }
3855 return result;
3856}
3857
Tim Petersa9bc1682003-01-11 03:39:11 +00003858/* Return new datetime from date/datetime and time arguments. */
3859static PyObject *
3860datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3861{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003862 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003863 PyObject *date;
3864 PyObject *time;
3865 PyObject *result = NULL;
3866
3867 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3868 &PyDateTime_DateType, &date,
3869 &PyDateTime_TimeType, &time)) {
3870 PyObject *tzinfo = Py_None;
3871
3872 if (HASTZINFO(time))
3873 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3874 result = PyObject_CallFunction(cls, "iiiiiiiO",
3875 GET_YEAR(date),
3876 GET_MONTH(date),
3877 GET_DAY(date),
3878 TIME_GET_HOUR(time),
3879 TIME_GET_MINUTE(time),
3880 TIME_GET_SECOND(time),
3881 TIME_GET_MICROSECOND(time),
3882 tzinfo);
3883 }
3884 return result;
3885}
Tim Peters2a799bf2002-12-16 20:18:38 +00003886
3887/*
3888 * Destructor.
3889 */
3890
3891static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003892datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003893{
Tim Petersa9bc1682003-01-11 03:39:11 +00003894 if (HASTZINFO(self)) {
3895 Py_XDECREF(self->tzinfo);
3896 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003897 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003898}
3899
3900/*
3901 * Indirect access to tzinfo methods.
3902 */
3903
Tim Peters2a799bf2002-12-16 20:18:38 +00003904/* These are all METH_NOARGS, so don't need to check the arglist. */
3905static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003906datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3907 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3908 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003909}
3910
3911static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003912datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3913 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3914 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003915}
3916
3917static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003918datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3919 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3920 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003921}
3922
3923/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003924 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003925 */
3926
Tim Petersa9bc1682003-01-11 03:39:11 +00003927/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3928 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003929 */
3930static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003931add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3932 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003933{
Tim Petersa9bc1682003-01-11 03:39:11 +00003934 /* Note that the C-level additions can't overflow, because of
3935 * invariant bounds on the member values.
3936 */
3937 int year = GET_YEAR(date);
3938 int month = GET_MONTH(date);
3939 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3940 int hour = DATE_GET_HOUR(date);
3941 int minute = DATE_GET_MINUTE(date);
3942 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3943 int microsecond = DATE_GET_MICROSECOND(date) +
3944 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003945
Tim Petersa9bc1682003-01-11 03:39:11 +00003946 assert(factor == 1 || factor == -1);
3947 if (normalize_datetime(&year, &month, &day,
3948 &hour, &minute, &second, &microsecond) < 0)
3949 return NULL;
3950 else
3951 return new_datetime(year, month, day,
3952 hour, minute, second, microsecond,
3953 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003954}
3955
3956static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003957datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003958{
Tim Petersa9bc1682003-01-11 03:39:11 +00003959 if (PyDateTime_Check(left)) {
3960 /* datetime + ??? */
3961 if (PyDelta_Check(right))
3962 /* datetime + delta */
3963 return add_datetime_timedelta(
3964 (PyDateTime_DateTime *)left,
3965 (PyDateTime_Delta *)right,
3966 1);
3967 }
3968 else if (PyDelta_Check(left)) {
3969 /* delta + datetime */
3970 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3971 (PyDateTime_Delta *) left,
3972 1);
3973 }
3974 Py_INCREF(Py_NotImplemented);
3975 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003976}
3977
3978static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003979datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003980{
3981 PyObject *result = Py_NotImplemented;
3982
3983 if (PyDateTime_Check(left)) {
3984 /* datetime - ??? */
3985 if (PyDateTime_Check(right)) {
3986 /* datetime - datetime */
3987 naivety n1, n2;
3988 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003989 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003990
Tim Peterse39a80c2002-12-30 21:28:52 +00003991 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3992 right, &offset2, &n2,
3993 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003994 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003995 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003996 if (n1 != n2) {
3997 PyErr_SetString(PyExc_TypeError,
3998 "can't subtract offset-naive and "
3999 "offset-aware datetimes");
4000 return NULL;
4001 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004002 delta_d = ymd_to_ord(GET_YEAR(left),
4003 GET_MONTH(left),
4004 GET_DAY(left)) -
4005 ymd_to_ord(GET_YEAR(right),
4006 GET_MONTH(right),
4007 GET_DAY(right));
4008 /* These can't overflow, since the values are
4009 * normalized. At most this gives the number of
4010 * seconds in one day.
4011 */
4012 delta_s = (DATE_GET_HOUR(left) -
4013 DATE_GET_HOUR(right)) * 3600 +
4014 (DATE_GET_MINUTE(left) -
4015 DATE_GET_MINUTE(right)) * 60 +
4016 (DATE_GET_SECOND(left) -
4017 DATE_GET_SECOND(right));
4018 delta_us = DATE_GET_MICROSECOND(left) -
4019 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004020 /* (left - offset1) - (right - offset2) =
4021 * (left - right) + (offset2 - offset1)
4022 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004023 delta_s += (offset2 - offset1) * 60;
4024 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004025 }
4026 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004027 /* datetime - delta */
4028 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004029 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004030 (PyDateTime_Delta *)right,
4031 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004032 }
4033 }
4034
4035 if (result == Py_NotImplemented)
4036 Py_INCREF(result);
4037 return result;
4038}
4039
4040/* Various ways to turn a datetime into a string. */
4041
4042static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004043datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004044{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004045 const char *type_name = Py_Type(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004046 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004047
Tim Petersa9bc1682003-01-11 03:39:11 +00004048 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004049 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004050 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004051 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004052 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4053 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4054 DATE_GET_SECOND(self),
4055 DATE_GET_MICROSECOND(self));
4056 }
4057 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004058 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004059 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004060 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004061 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4062 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4063 DATE_GET_SECOND(self));
4064 }
4065 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004066 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004067 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004068 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004069 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4070 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4071 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004072 if (baserepr == NULL || ! HASTZINFO(self))
4073 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004074 return append_keyword_tzinfo(baserepr, self->tzinfo);
4075}
4076
Tim Petersa9bc1682003-01-11 03:39:11 +00004077static PyObject *
4078datetime_str(PyDateTime_DateTime *self)
4079{
4080 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4081}
Tim Peters2a799bf2002-12-16 20:18:38 +00004082
4083static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004084datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004085{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004086 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004087 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004088 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004089 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004090 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004091
Walter Dörwaldd0941302007-07-01 21:58:22 +00004092 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004093 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004094 if (us)
4095 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4096 GET_YEAR(self), GET_MONTH(self),
4097 GET_DAY(self), (int)sep,
4098 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4099 DATE_GET_SECOND(self), us);
4100 else
4101 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4102 GET_YEAR(self), GET_MONTH(self),
4103 GET_DAY(self), (int)sep,
4104 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4105 DATE_GET_SECOND(self));
4106
4107 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004108 return result;
4109
4110 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004111 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004112 (PyObject *)self) < 0) {
4113 Py_DECREF(result);
4114 return NULL;
4115 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004116 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004117 return result;
4118}
4119
Tim Petersa9bc1682003-01-11 03:39:11 +00004120static PyObject *
4121datetime_ctime(PyDateTime_DateTime *self)
4122{
4123 return format_ctime((PyDateTime_Date *)self,
4124 DATE_GET_HOUR(self),
4125 DATE_GET_MINUTE(self),
4126 DATE_GET_SECOND(self));
4127}
4128
Tim Peters2a799bf2002-12-16 20:18:38 +00004129/* Miscellaneous methods. */
4130
Tim Petersa9bc1682003-01-11 03:39:11 +00004131static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004132datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004133{
4134 int diff;
4135 naivety n1, n2;
4136 int offset1, offset2;
4137
4138 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004139 if (PyDate_Check(other)) {
4140 /* Prevent invocation of date_richcompare. We want to
4141 return NotImplemented here to give the other object
4142 a chance. But since DateTime is a subclass of
4143 Date, if the other object is a Date, it would
4144 compute an ordering based on the date part alone,
4145 and we don't want that. So force unequal or
4146 uncomparable here in that case. */
4147 if (op == Py_EQ)
4148 Py_RETURN_FALSE;
4149 if (op == Py_NE)
4150 Py_RETURN_TRUE;
4151 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004152 }
Guido van Rossum19960592006-08-24 17:29:38 +00004153 Py_INCREF(Py_NotImplemented);
4154 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004155 }
4156
Guido van Rossum19960592006-08-24 17:29:38 +00004157 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4158 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004159 return NULL;
4160 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4161 /* If they're both naive, or both aware and have the same offsets,
4162 * we get off cheap. Note that if they're both naive, offset1 ==
4163 * offset2 == 0 at this point.
4164 */
4165 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004166 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4167 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004168 _PyDateTime_DATETIME_DATASIZE);
4169 return diff_to_bool(diff, op);
4170 }
4171
4172 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4173 PyDateTime_Delta *delta;
4174
4175 assert(offset1 != offset2); /* else last "if" handled it */
4176 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4177 other);
4178 if (delta == NULL)
4179 return NULL;
4180 diff = GET_TD_DAYS(delta);
4181 if (diff == 0)
4182 diff = GET_TD_SECONDS(delta) |
4183 GET_TD_MICROSECONDS(delta);
4184 Py_DECREF(delta);
4185 return diff_to_bool(diff, op);
4186 }
4187
4188 assert(n1 != n2);
4189 PyErr_SetString(PyExc_TypeError,
4190 "can't compare offset-naive and "
4191 "offset-aware datetimes");
4192 return NULL;
4193}
4194
4195static long
4196datetime_hash(PyDateTime_DateTime *self)
4197{
4198 if (self->hashcode == -1) {
4199 naivety n;
4200 int offset;
4201 PyObject *temp;
4202
4203 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4204 &offset);
4205 assert(n != OFFSET_UNKNOWN);
4206 if (n == OFFSET_ERROR)
4207 return -1;
4208
4209 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00004210 if (n == OFFSET_NAIVE) {
4211 self->hashcode = generic_hash(
4212 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4213 return self->hashcode;
4214 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004215 else {
4216 int days;
4217 int seconds;
4218
4219 assert(n == OFFSET_AWARE);
4220 assert(HASTZINFO(self));
4221 days = ymd_to_ord(GET_YEAR(self),
4222 GET_MONTH(self),
4223 GET_DAY(self));
4224 seconds = DATE_GET_HOUR(self) * 3600 +
4225 (DATE_GET_MINUTE(self) - offset) * 60 +
4226 DATE_GET_SECOND(self);
4227 temp = new_delta(days,
4228 seconds,
4229 DATE_GET_MICROSECOND(self),
4230 1);
4231 }
4232 if (temp != NULL) {
4233 self->hashcode = PyObject_Hash(temp);
4234 Py_DECREF(temp);
4235 }
4236 }
4237 return self->hashcode;
4238}
Tim Peters2a799bf2002-12-16 20:18:38 +00004239
4240static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004241datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004242{
4243 PyObject *clone;
4244 PyObject *tuple;
4245 int y = GET_YEAR(self);
4246 int m = GET_MONTH(self);
4247 int d = GET_DAY(self);
4248 int hh = DATE_GET_HOUR(self);
4249 int mm = DATE_GET_MINUTE(self);
4250 int ss = DATE_GET_SECOND(self);
4251 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004252 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004253
4254 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004255 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004256 &y, &m, &d, &hh, &mm, &ss, &us,
4257 &tzinfo))
4258 return NULL;
4259 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4260 if (tuple == NULL)
4261 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004262 clone = datetime_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004263 Py_DECREF(tuple);
4264 return clone;
4265}
4266
4267static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004268datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004269{
Tim Peters52dcce22003-01-23 16:36:11 +00004270 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004271 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004272 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004273
Tim Peters80475bb2002-12-25 07:40:55 +00004274 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004275 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004276
Tim Peters52dcce22003-01-23 16:36:11 +00004277 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4278 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004279 return NULL;
4280
Tim Peters52dcce22003-01-23 16:36:11 +00004281 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4282 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004283
Tim Peters52dcce22003-01-23 16:36:11 +00004284 /* Conversion to self's own time zone is a NOP. */
4285 if (self->tzinfo == tzinfo) {
4286 Py_INCREF(self);
4287 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004288 }
Tim Peters521fc152002-12-31 17:36:56 +00004289
Tim Peters52dcce22003-01-23 16:36:11 +00004290 /* Convert self to UTC. */
4291 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4292 if (offset == -1 && PyErr_Occurred())
4293 return NULL;
4294 if (none)
4295 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004296
Tim Peters52dcce22003-01-23 16:36:11 +00004297 y = GET_YEAR(self);
4298 m = GET_MONTH(self);
4299 d = GET_DAY(self);
4300 hh = DATE_GET_HOUR(self);
4301 mm = DATE_GET_MINUTE(self);
4302 ss = DATE_GET_SECOND(self);
4303 us = DATE_GET_MICROSECOND(self);
4304
4305 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004306 if ((mm < 0 || mm >= 60) &&
4307 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004308 return NULL;
4309
4310 /* Attach new tzinfo and let fromutc() do the rest. */
4311 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4312 if (result != NULL) {
4313 PyObject *temp = result;
4314
4315 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4316 Py_DECREF(temp);
4317 }
Tim Petersadf64202003-01-04 06:03:15 +00004318 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004319
Tim Peters52dcce22003-01-23 16:36:11 +00004320NeedAware:
4321 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4322 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004323 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004324}
4325
4326static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004327datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004328{
4329 int dstflag = -1;
4330
Tim Petersa9bc1682003-01-11 03:39:11 +00004331 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004332 int none;
4333
4334 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4335 if (dstflag == -1 && PyErr_Occurred())
4336 return NULL;
4337
4338 if (none)
4339 dstflag = -1;
4340 else if (dstflag != 0)
4341 dstflag = 1;
4342
4343 }
4344 return build_struct_time(GET_YEAR(self),
4345 GET_MONTH(self),
4346 GET_DAY(self),
4347 DATE_GET_HOUR(self),
4348 DATE_GET_MINUTE(self),
4349 DATE_GET_SECOND(self),
4350 dstflag);
4351}
4352
4353static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004354datetime_getdate(PyDateTime_DateTime *self)
4355{
4356 return new_date(GET_YEAR(self),
4357 GET_MONTH(self),
4358 GET_DAY(self));
4359}
4360
4361static PyObject *
4362datetime_gettime(PyDateTime_DateTime *self)
4363{
4364 return new_time(DATE_GET_HOUR(self),
4365 DATE_GET_MINUTE(self),
4366 DATE_GET_SECOND(self),
4367 DATE_GET_MICROSECOND(self),
4368 Py_None);
4369}
4370
4371static PyObject *
4372datetime_gettimetz(PyDateTime_DateTime *self)
4373{
4374 return new_time(DATE_GET_HOUR(self),
4375 DATE_GET_MINUTE(self),
4376 DATE_GET_SECOND(self),
4377 DATE_GET_MICROSECOND(self),
4378 HASTZINFO(self) ? self->tzinfo : Py_None);
4379}
4380
4381static PyObject *
4382datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004383{
4384 int y = GET_YEAR(self);
4385 int m = GET_MONTH(self);
4386 int d = GET_DAY(self);
4387 int hh = DATE_GET_HOUR(self);
4388 int mm = DATE_GET_MINUTE(self);
4389 int ss = DATE_GET_SECOND(self);
4390 int us = 0; /* microseconds are ignored in a timetuple */
4391 int offset = 0;
4392
Tim Petersa9bc1682003-01-11 03:39:11 +00004393 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004394 int none;
4395
4396 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4397 if (offset == -1 && PyErr_Occurred())
4398 return NULL;
4399 }
4400 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4401 * 0 in a UTC timetuple regardless of what dst() says.
4402 */
4403 if (offset) {
4404 /* Subtract offset minutes & normalize. */
4405 int stat;
4406
4407 mm -= offset;
4408 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4409 if (stat < 0) {
4410 /* At the edges, it's possible we overflowed
4411 * beyond MINYEAR or MAXYEAR.
4412 */
4413 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4414 PyErr_Clear();
4415 else
4416 return NULL;
4417 }
4418 }
4419 return build_struct_time(y, m, d, hh, mm, ss, 0);
4420}
4421
Tim Peters371935f2003-02-01 01:52:50 +00004422/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004423
Tim Petersa9bc1682003-01-11 03:39:11 +00004424/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004425 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4426 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004427 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004428 */
4429static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004430datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004431{
4432 PyObject *basestate;
4433 PyObject *result = NULL;
4434
Guido van Rossum254348e2007-11-21 19:29:53 +00004435 basestate = PyString_FromStringAndSize((char *)self->data,
4436 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004437 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004438 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004439 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004440 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004441 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004442 Py_DECREF(basestate);
4443 }
4444 return result;
4445}
4446
4447static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004448datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004449{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004450 return Py_BuildValue("(ON)", Py_Type(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004451}
4452
Tim Petersa9bc1682003-01-11 03:39:11 +00004453static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004454
Tim Peters2a799bf2002-12-16 20:18:38 +00004455 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004456
Tim Petersa9bc1682003-01-11 03:39:11 +00004457 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004458 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004459 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004460
Tim Petersa9bc1682003-01-11 03:39:11 +00004461 {"utcnow", (PyCFunction)datetime_utcnow,
4462 METH_NOARGS | METH_CLASS,
4463 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4464
4465 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004466 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004467 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004468
Tim Petersa9bc1682003-01-11 03:39:11 +00004469 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4470 METH_VARARGS | METH_CLASS,
4471 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4472 "(like time.time()).")},
4473
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004474 {"strptime", (PyCFunction)datetime_strptime,
4475 METH_VARARGS | METH_CLASS,
4476 PyDoc_STR("string, format -> new datetime parsed from a string "
4477 "(like time.strptime()).")},
4478
Tim Petersa9bc1682003-01-11 03:39:11 +00004479 {"combine", (PyCFunction)datetime_combine,
4480 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4481 PyDoc_STR("date, time -> datetime with same date and time fields")},
4482
Tim Peters2a799bf2002-12-16 20:18:38 +00004483 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004484
Tim Petersa9bc1682003-01-11 03:39:11 +00004485 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4486 PyDoc_STR("Return date object with same year, month and day.")},
4487
4488 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4489 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4490
4491 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4492 PyDoc_STR("Return time object with same time and tzinfo.")},
4493
4494 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4495 PyDoc_STR("Return ctime() style string.")},
4496
4497 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004498 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4499
Tim Petersa9bc1682003-01-11 03:39:11 +00004500 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004501 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4502
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004503 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004504 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4505 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4506 "sep is used to separate the year from the time, and "
4507 "defaults to 'T'.")},
4508
Tim Petersa9bc1682003-01-11 03:39:11 +00004509 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004510 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4511
Tim Petersa9bc1682003-01-11 03:39:11 +00004512 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004513 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4514
Tim Petersa9bc1682003-01-11 03:39:11 +00004515 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004516 PyDoc_STR("Return self.tzinfo.dst(self).")},
4517
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004518 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004519 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004520
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004521 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004522 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4523
Guido van Rossum177e41a2003-01-30 22:06:23 +00004524 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4525 PyDoc_STR("__reduce__() -> (cls, state)")},
4526
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 {NULL, NULL}
4528};
4529
Tim Petersa9bc1682003-01-11 03:39:11 +00004530static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004531PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4532\n\
4533The year, month and day arguments are required. tzinfo may be None, or an\n\
4534instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004535
Tim Petersa9bc1682003-01-11 03:39:11 +00004536static PyNumberMethods datetime_as_number = {
4537 datetime_add, /* nb_add */
4538 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004539 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004540 0, /* nb_remainder */
4541 0, /* nb_divmod */
4542 0, /* nb_power */
4543 0, /* nb_negative */
4544 0, /* nb_positive */
4545 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004546 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004547};
4548
Neal Norwitz227b5332006-03-22 09:28:35 +00004549static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004550 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004551 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004552 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004553 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004554 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004555 0, /* tp_print */
4556 0, /* tp_getattr */
4557 0, /* tp_setattr */
4558 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004559 (reprfunc)datetime_repr, /* tp_repr */
4560 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004561 0, /* tp_as_sequence */
4562 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004563 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004564 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004565 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004566 PyObject_GenericGetAttr, /* tp_getattro */
4567 0, /* tp_setattro */
4568 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004569 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004570 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004571 0, /* tp_traverse */
4572 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004573 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004574 0, /* tp_weaklistoffset */
4575 0, /* tp_iter */
4576 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004577 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004578 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004579 datetime_getset, /* tp_getset */
4580 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004581 0, /* tp_dict */
4582 0, /* tp_descr_get */
4583 0, /* tp_descr_set */
4584 0, /* tp_dictoffset */
4585 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004586 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004587 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004588 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004589};
4590
4591/* ---------------------------------------------------------------------------
4592 * Module methods and initialization.
4593 */
4594
4595static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004596 {NULL, NULL}
4597};
4598
Tim Peters9ddf40b2004-06-20 22:41:32 +00004599/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4600 * datetime.h.
4601 */
4602static PyDateTime_CAPI CAPI = {
4603 &PyDateTime_DateType,
4604 &PyDateTime_DateTimeType,
4605 &PyDateTime_TimeType,
4606 &PyDateTime_DeltaType,
4607 &PyDateTime_TZInfoType,
4608 new_date_ex,
4609 new_datetime_ex,
4610 new_time_ex,
4611 new_delta_ex,
4612 datetime_fromtimestamp,
4613 date_fromtimestamp
4614};
4615
4616
Tim Peters2a799bf2002-12-16 20:18:38 +00004617PyMODINIT_FUNC
4618initdatetime(void)
4619{
4620 PyObject *m; /* a module object */
4621 PyObject *d; /* its dict */
4622 PyObject *x;
4623
Tim Peters2a799bf2002-12-16 20:18:38 +00004624 m = Py_InitModule3("datetime", module_methods,
4625 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004626 if (m == NULL)
4627 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004628
4629 if (PyType_Ready(&PyDateTime_DateType) < 0)
4630 return;
4631 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4632 return;
4633 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4634 return;
4635 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4636 return;
4637 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4638 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004639
Tim Peters2a799bf2002-12-16 20:18:38 +00004640 /* timedelta values */
4641 d = PyDateTime_DeltaType.tp_dict;
4642
Tim Peters2a799bf2002-12-16 20:18:38 +00004643 x = new_delta(0, 0, 1, 0);
4644 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4645 return;
4646 Py_DECREF(x);
4647
4648 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4649 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4650 return;
4651 Py_DECREF(x);
4652
4653 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4654 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4655 return;
4656 Py_DECREF(x);
4657
4658 /* date values */
4659 d = PyDateTime_DateType.tp_dict;
4660
4661 x = new_date(1, 1, 1);
4662 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4663 return;
4664 Py_DECREF(x);
4665
4666 x = new_date(MAXYEAR, 12, 31);
4667 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4668 return;
4669 Py_DECREF(x);
4670
4671 x = new_delta(1, 0, 0, 0);
4672 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4673 return;
4674 Py_DECREF(x);
4675
Tim Peters37f39822003-01-10 03:49:02 +00004676 /* time values */
4677 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004678
Tim Peters37f39822003-01-10 03:49:02 +00004679 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004680 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4681 return;
4682 Py_DECREF(x);
4683
Tim Peters37f39822003-01-10 03:49:02 +00004684 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004685 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4686 return;
4687 Py_DECREF(x);
4688
4689 x = new_delta(0, 0, 1, 0);
4690 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4691 return;
4692 Py_DECREF(x);
4693
Tim Petersa9bc1682003-01-11 03:39:11 +00004694 /* datetime values */
4695 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004696
Tim Petersa9bc1682003-01-11 03:39:11 +00004697 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004698 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4699 return;
4700 Py_DECREF(x);
4701
Tim Petersa9bc1682003-01-11 03:39:11 +00004702 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004703 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4704 return;
4705 Py_DECREF(x);
4706
4707 x = new_delta(0, 0, 1, 0);
4708 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4709 return;
4710 Py_DECREF(x);
4711
Tim Peters2a799bf2002-12-16 20:18:38 +00004712 /* module initialization */
4713 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4714 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4715
4716 Py_INCREF(&PyDateTime_DateType);
4717 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4718
Tim Petersa9bc1682003-01-11 03:39:11 +00004719 Py_INCREF(&PyDateTime_DateTimeType);
4720 PyModule_AddObject(m, "datetime",
4721 (PyObject *)&PyDateTime_DateTimeType);
4722
4723 Py_INCREF(&PyDateTime_TimeType);
4724 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4725
Tim Peters2a799bf2002-12-16 20:18:38 +00004726 Py_INCREF(&PyDateTime_DeltaType);
4727 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4728
Tim Peters2a799bf2002-12-16 20:18:38 +00004729 Py_INCREF(&PyDateTime_TZInfoType);
4730 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4731
Tim Peters9ddf40b2004-06-20 22:41:32 +00004732 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4733 NULL);
4734 if (x == NULL)
4735 return;
4736 PyModule_AddObject(m, "datetime_CAPI", x);
4737
Tim Peters2a799bf2002-12-16 20:18:38 +00004738 /* A 4-year cycle has an extra leap day over what we'd get from
4739 * pasting together 4 single years.
4740 */
4741 assert(DI4Y == 4 * 365 + 1);
4742 assert(DI4Y == days_before_year(4+1));
4743
4744 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4745 * get from pasting together 4 100-year cycles.
4746 */
4747 assert(DI400Y == 4 * DI100Y + 1);
4748 assert(DI400Y == days_before_year(400+1));
4749
4750 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4751 * pasting together 25 4-year cycles.
4752 */
4753 assert(DI100Y == 25 * DI4Y - 1);
4754 assert(DI100Y == days_before_year(100+1));
4755
Christian Heimes217cfd12007-12-02 14:31:20 +00004756 us_per_us = PyLong_FromLong(1);
4757 us_per_ms = PyLong_FromLong(1000);
4758 us_per_second = PyLong_FromLong(1000000);
4759 us_per_minute = PyLong_FromLong(60000000);
4760 seconds_per_day = PyLong_FromLong(24 * 3600);
Tim Peters2a799bf2002-12-16 20:18:38 +00004761 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4762 us_per_minute == NULL || seconds_per_day == NULL)
4763 return;
4764
4765 /* The rest are too big for 32-bit ints, but even
4766 * us_per_week fits in 40 bits, so doubles should be exact.
4767 */
4768 us_per_hour = PyLong_FromDouble(3600000000.0);
4769 us_per_day = PyLong_FromDouble(86400000000.0);
4770 us_per_week = PyLong_FromDouble(604800000000.0);
4771 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4772 return;
4773}
Tim Petersf3615152003-01-01 21:51:37 +00004774
4775/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004776Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004777 x.n = x stripped of its timezone -- its naive time.
4778 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4779 return None
4780 x.d = x.dst(), and assuming that doesn't raise an exception or
4781 return None
4782 x.s = x's standard offset, x.o - x.d
4783
4784Now some derived rules, where k is a duration (timedelta).
4785
47861. x.o = x.s + x.d
4787 This follows from the definition of x.s.
4788
Tim Petersc5dc4da2003-01-02 17:55:03 +000047892. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004790 This is actually a requirement, an assumption we need to make about
4791 sane tzinfo classes.
4792
47933. The naive UTC time corresponding to x is x.n - x.o.
4794 This is again a requirement for a sane tzinfo class.
4795
47964. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004797 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004798
Tim Petersc5dc4da2003-01-02 17:55:03 +000047995. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004800 Again follows from how arithmetic is defined.
4801
Tim Peters8bb5ad22003-01-24 02:44:45 +00004802Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004803(meaning that the various tzinfo methods exist, and don't blow up or return
4804None when called).
4805
Tim Petersa9bc1682003-01-11 03:39:11 +00004806The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004807x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004808
4809By #3, we want
4810
Tim Peters8bb5ad22003-01-24 02:44:45 +00004811 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004812
4813The algorithm starts by attaching tz to x.n, and calling that y. So
4814x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4815becomes true; in effect, we want to solve [2] for k:
4816
Tim Peters8bb5ad22003-01-24 02:44:45 +00004817 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004818
4819By #1, this is the same as
4820
Tim Peters8bb5ad22003-01-24 02:44:45 +00004821 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004822
4823By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4824Substituting that into [3],
4825
Tim Peters8bb5ad22003-01-24 02:44:45 +00004826 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4827 k - (y+k).s - (y+k).d = 0; rearranging,
4828 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4829 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004830
Tim Peters8bb5ad22003-01-24 02:44:45 +00004831On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4832approximate k by ignoring the (y+k).d term at first. Note that k can't be
4833very large, since all offset-returning methods return a duration of magnitude
4834less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4835be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004836
4837In any case, the new value is
4838
Tim Peters8bb5ad22003-01-24 02:44:45 +00004839 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004840
Tim Peters8bb5ad22003-01-24 02:44:45 +00004841It's helpful to step back at look at [4] from a higher level: it's simply
4842mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004843
4844At this point, if
4845
Tim Peters8bb5ad22003-01-24 02:44:45 +00004846 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004847
4848we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004849at the start of daylight time. Picture US Eastern for concreteness. The wall
4850time 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 +00004851sense then. The docs ask that an Eastern tzinfo class consider such a time to
4852be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4853on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004854the only spelling that makes sense on the local wall clock.
4855
Tim Petersc5dc4da2003-01-02 17:55:03 +00004856In fact, if [5] holds at this point, we do have the standard-time spelling,
4857but that takes a bit of proof. We first prove a stronger result. What's the
4858difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004859
Tim Peters8bb5ad22003-01-24 02:44:45 +00004860 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004861
Tim Petersc5dc4da2003-01-02 17:55:03 +00004862Now
4863 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004864 (y + y.s).n = by #5
4865 y.n + y.s = since y.n = x.n
4866 x.n + y.s = since z and y are have the same tzinfo member,
4867 y.s = z.s by #2
4868 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004869
Tim Petersc5dc4da2003-01-02 17:55:03 +00004870Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004871
Tim Petersc5dc4da2003-01-02 17:55:03 +00004872 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004873 x.n - ((x.n + z.s) - z.o) = expanding
4874 x.n - x.n - z.s + z.o = cancelling
4875 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004876 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004877
Tim Petersc5dc4da2003-01-02 17:55:03 +00004878So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004879
Tim Petersc5dc4da2003-01-02 17:55:03 +00004880If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004881spelling we wanted in the endcase described above. We're done. Contrarily,
4882if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004883
Tim Petersc5dc4da2003-01-02 17:55:03 +00004884If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4885add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004886local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004887
Tim Petersc5dc4da2003-01-02 17:55:03 +00004888Let
Tim Petersf3615152003-01-01 21:51:37 +00004889
Tim Peters4fede1a2003-01-04 00:26:59 +00004890 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004891
Tim Peters4fede1a2003-01-04 00:26:59 +00004892and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004893
Tim Peters8bb5ad22003-01-24 02:44:45 +00004894 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004895
Tim Peters8bb5ad22003-01-24 02:44:45 +00004896If so, we're done. If not, the tzinfo class is insane, according to the
4897assumptions we've made. This also requires a bit of proof. As before, let's
4898compute the difference between the LHS and RHS of [8] (and skipping some of
4899the justifications for the kinds of substitutions we've done several times
4900already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004901
Tim Peters8bb5ad22003-01-24 02:44:45 +00004902 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4903 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4904 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4905 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4906 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004907 - z.o + z'.o = #1 twice
4908 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4909 z'.d - z.d
4910
4911So 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 +00004912we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4913return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004914
Tim Peters8bb5ad22003-01-24 02:44:45 +00004915How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4916a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4917would have to change the result dst() returns: we start in DST, and moving
4918a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004919
Tim Peters8bb5ad22003-01-24 02:44:45 +00004920There isn't a sane case where this can happen. The closest it gets is at
4921the end of DST, where there's an hour in UTC with no spelling in a hybrid
4922tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4923that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4924UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4925time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4926clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4927standard time. Since that's what the local clock *does*, we want to map both
4928UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004929in local time, but so it goes -- it's the way the local clock works.
4930
Tim Peters8bb5ad22003-01-24 02:44:45 +00004931When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4932so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4933z' = 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 +00004934(correctly) concludes that z' is not UTC-equivalent to x.
4935
4936Because we know z.d said z was in daylight time (else [5] would have held and
4937we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004938and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004939return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4940but the reasoning doesn't depend on the example -- it depends on there being
4941two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004942z' must be in standard time, and is the spelling we want in this case.
4943
4944Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4945concerned (because it takes z' as being in standard time rather than the
4946daylight time we intend here), but returning it gives the real-life "local
4947clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4948tz.
4949
4950When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4951the 1:MM standard time spelling we want.
4952
4953So how can this break? One of the assumptions must be violated. Two
4954possibilities:
4955
49561) [2] effectively says that y.s is invariant across all y belong to a given
4957 time zone. This isn't true if, for political reasons or continental drift,
4958 a region decides to change its base offset from UTC.
4959
49602) There may be versions of "double daylight" time where the tail end of
4961 the analysis gives up a step too early. I haven't thought about that
4962 enough to say.
4963
4964In any case, it's clear that the default fromutc() is strong enough to handle
4965"almost all" time zones: so long as the standard offset is invariant, it
4966doesn't matter if daylight time transition points change from year to year, or
4967if daylight time is skipped in some years; it doesn't matter how large or
4968small dst() may get within its bounds; and it doesn't even matter if some
4969perverse time zone returns a negative dst()). So a breaking case must be
4970pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004971--------------------------------------------------------------------------- */