blob: 27c404f7d974275cadf15589ed00e4193c974f23 [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'",
Christian Heimes90aa7642007-12-19 02:45:37 +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'",
Christian Heimes90aa7642007-12-19 02:45:37 +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'",
Christian Heimes90aa7642007-12-19 02:45:37 +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);
Christian Heimes90aa7642007-12-19 02:45:37 +00001296 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;
Christian Heimes072c0f12008-01-03 23:01:04 +00001332 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001333 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;
Christian Heimes072c0f12008-01-03 23:01:04 +00001360 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001361
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
Christian Heimes072c0f12008-01-03 23:01:04 +00001378 time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001379 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",
Christian Heimes90aa7642007-12-19 02:45:37 +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",
Christian Heimes90aa7642007-12-19 02:45:37 +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)",
Christian Heimes90aa7642007-12-19 02:45:37 +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)",
Christian Heimes90aa7642007-12-19 02:45:37 +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)",
Christian Heimes90aa7642007-12-19 02:45:37 +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{
Christian Heimes90aa7642007-12-19 02:45:37 +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)",
Christian Heimes90aa7642007-12-19 02:45:37 +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;
Christian Heimes90aa7642007-12-19 02:45:37 +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{
Christian Heimes90aa7642007-12-19 02:45:37 +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);
Christian Heimes90aa7642007-12-19 02:45:37 +00002896 return Py_BuildValue("(ON)", Py_TYPE(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002897 }
2898 else
Christian Heimes90aa7642007-12-19 02:45:37 +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 }
Christian Heimes90aa7642007-12-19 02:45:37 +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{
Christian Heimes90aa7642007-12-19 02:45:37 +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
3213/*
3214 * Miscellaneous methods.
3215 */
3216
Tim Peters37f39822003-01-10 03:49:02 +00003217static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003218time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003219{
3220 int diff;
3221 naivety n1, n2;
3222 int offset1, offset2;
3223
3224 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003225 Py_INCREF(Py_NotImplemented);
3226 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003227 }
Guido van Rossum19960592006-08-24 17:29:38 +00003228 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3229 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003230 return NULL;
3231 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3232 /* If they're both naive, or both aware and have the same offsets,
3233 * we get off cheap. Note that if they're both naive, offset1 ==
3234 * offset2 == 0 at this point.
3235 */
3236 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003237 diff = memcmp(((PyDateTime_Time *)self)->data,
3238 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003239 _PyDateTime_TIME_DATASIZE);
3240 return diff_to_bool(diff, op);
3241 }
3242
3243 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3244 assert(offset1 != offset2); /* else last "if" handled it */
3245 /* Convert everything except microseconds to seconds. These
3246 * can't overflow (no more than the # of seconds in 2 days).
3247 */
3248 offset1 = TIME_GET_HOUR(self) * 3600 +
3249 (TIME_GET_MINUTE(self) - offset1) * 60 +
3250 TIME_GET_SECOND(self);
3251 offset2 = TIME_GET_HOUR(other) * 3600 +
3252 (TIME_GET_MINUTE(other) - offset2) * 60 +
3253 TIME_GET_SECOND(other);
3254 diff = offset1 - offset2;
3255 if (diff == 0)
3256 diff = TIME_GET_MICROSECOND(self) -
3257 TIME_GET_MICROSECOND(other);
3258 return diff_to_bool(diff, op);
3259 }
3260
3261 assert(n1 != n2);
3262 PyErr_SetString(PyExc_TypeError,
3263 "can't compare offset-naive and "
3264 "offset-aware times");
3265 return NULL;
3266}
3267
3268static long
3269time_hash(PyDateTime_Time *self)
3270{
3271 if (self->hashcode == -1) {
3272 naivety n;
3273 int offset;
3274 PyObject *temp;
3275
3276 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3277 assert(n != OFFSET_UNKNOWN);
3278 if (n == OFFSET_ERROR)
3279 return -1;
3280
3281 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003282 if (offset == 0) {
3283 self->hashcode = generic_hash(
3284 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3285 return self->hashcode;
3286 }
Tim Peters37f39822003-01-10 03:49:02 +00003287 else {
3288 int hour;
3289 int minute;
3290
3291 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003292 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003293 hour = divmod(TIME_GET_HOUR(self) * 60 +
3294 TIME_GET_MINUTE(self) - offset,
3295 60,
3296 &minute);
3297 if (0 <= hour && hour < 24)
3298 temp = new_time(hour, minute,
3299 TIME_GET_SECOND(self),
3300 TIME_GET_MICROSECOND(self),
3301 Py_None);
3302 else
3303 temp = Py_BuildValue("iiii",
3304 hour, minute,
3305 TIME_GET_SECOND(self),
3306 TIME_GET_MICROSECOND(self));
3307 }
3308 if (temp != NULL) {
3309 self->hashcode = PyObject_Hash(temp);
3310 Py_DECREF(temp);
3311 }
3312 }
3313 return self->hashcode;
3314}
Tim Peters2a799bf2002-12-16 20:18:38 +00003315
Tim Peters12bf3392002-12-24 05:41:27 +00003316static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003317time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003318{
3319 PyObject *clone;
3320 PyObject *tuple;
3321 int hh = TIME_GET_HOUR(self);
3322 int mm = TIME_GET_MINUTE(self);
3323 int ss = TIME_GET_SECOND(self);
3324 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003325 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003326
3327 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003328 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003329 &hh, &mm, &ss, &us, &tzinfo))
3330 return NULL;
3331 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3332 if (tuple == NULL)
3333 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003334 clone = time_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003335 Py_DECREF(tuple);
3336 return clone;
3337}
3338
Tim Peters2a799bf2002-12-16 20:18:38 +00003339static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003340time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003341{
3342 int offset;
3343 int none;
3344
3345 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3346 /* Since utcoffset is in whole minutes, nothing can
3347 * alter the conclusion that this is nonzero.
3348 */
3349 return 1;
3350 }
3351 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003352 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003353 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003354 if (offset == -1 && PyErr_Occurred())
3355 return -1;
3356 }
3357 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3358}
3359
Tim Peters371935f2003-02-01 01:52:50 +00003360/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003361
Tim Peters33e0f382003-01-10 02:05:14 +00003362/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003363 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3364 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003365 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003366 */
3367static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003368time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003369{
3370 PyObject *basestate;
3371 PyObject *result = NULL;
3372
Guido van Rossum254348e2007-11-21 19:29:53 +00003373 basestate = PyString_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003374 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003375 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003376 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003377 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003378 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003379 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003380 Py_DECREF(basestate);
3381 }
3382 return result;
3383}
3384
3385static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003386time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003387{
Christian Heimes90aa7642007-12-19 02:45:37 +00003388 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003389}
3390
Tim Peters37f39822003-01-10 03:49:02 +00003391static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003392
Thomas Wouterscf297e42007-02-23 15:07:44 +00003393 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003394 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3395 "[+HH:MM].")},
3396
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003397 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003398 PyDoc_STR("format -> strftime() style string.")},
3399
Eric Smith8fd3eba2008-02-17 19:48:00 +00003400 {"__format__", (PyCFunction)date_format, METH_VARARGS,
Eric Smith1ba31142007-09-11 18:06:02 +00003401 PyDoc_STR("Formats self with strftime.")},
3402
Tim Peters37f39822003-01-10 03:49:02 +00003403 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003404 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3405
Tim Peters37f39822003-01-10 03:49:02 +00003406 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003407 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3408
Tim Peters37f39822003-01-10 03:49:02 +00003409 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003410 PyDoc_STR("Return self.tzinfo.dst(self).")},
3411
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003412 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003413 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003414
Guido van Rossum177e41a2003-01-30 22:06:23 +00003415 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3416 PyDoc_STR("__reduce__() -> (cls, state)")},
3417
Tim Peters2a799bf2002-12-16 20:18:38 +00003418 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003419};
3420
Tim Peters37f39822003-01-10 03:49:02 +00003421static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003422PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3423\n\
3424All arguments are optional. tzinfo may be None, or an instance of\n\
3425a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003426
Tim Peters37f39822003-01-10 03:49:02 +00003427static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 0, /* nb_add */
3429 0, /* nb_subtract */
3430 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003431 0, /* nb_remainder */
3432 0, /* nb_divmod */
3433 0, /* nb_power */
3434 0, /* nb_negative */
3435 0, /* nb_positive */
3436 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003437 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003438};
3439
Neal Norwitz227b5332006-03-22 09:28:35 +00003440static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003441 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003442 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003443 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003444 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003445 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003446 0, /* tp_print */
3447 0, /* tp_getattr */
3448 0, /* tp_setattr */
3449 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003450 (reprfunc)time_repr, /* tp_repr */
3451 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003452 0, /* tp_as_sequence */
3453 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003454 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003455 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003456 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003457 PyObject_GenericGetAttr, /* tp_getattro */
3458 0, /* tp_setattro */
3459 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003460 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003461 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003462 0, /* tp_traverse */
3463 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003464 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003465 0, /* tp_weaklistoffset */
3466 0, /* tp_iter */
3467 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003468 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003469 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003470 time_getset, /* tp_getset */
3471 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003472 0, /* tp_dict */
3473 0, /* tp_descr_get */
3474 0, /* tp_descr_set */
3475 0, /* tp_dictoffset */
3476 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003477 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003478 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003479 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003480};
3481
3482/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003483 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003484 */
3485
Tim Petersa9bc1682003-01-11 03:39:11 +00003486/* Accessor properties. Properties for day, month, and year are inherited
3487 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003488 */
3489
3490static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003491datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003492{
Christian Heimes217cfd12007-12-02 14:31:20 +00003493 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003494}
3495
Tim Petersa9bc1682003-01-11 03:39:11 +00003496static PyObject *
3497datetime_minute(PyDateTime_DateTime *self, void *unused)
3498{
Christian Heimes217cfd12007-12-02 14:31:20 +00003499 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003500}
3501
3502static PyObject *
3503datetime_second(PyDateTime_DateTime *self, void *unused)
3504{
Christian Heimes217cfd12007-12-02 14:31:20 +00003505 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003506}
3507
3508static PyObject *
3509datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3510{
Christian Heimes217cfd12007-12-02 14:31:20 +00003511 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003512}
3513
3514static PyObject *
3515datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3516{
3517 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3518 Py_INCREF(result);
3519 return result;
3520}
3521
3522static PyGetSetDef datetime_getset[] = {
3523 {"hour", (getter)datetime_hour},
3524 {"minute", (getter)datetime_minute},
3525 {"second", (getter)datetime_second},
3526 {"microsecond", (getter)datetime_microsecond},
3527 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003528 {NULL}
3529};
3530
3531/*
3532 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003533 */
3534
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003535static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003536 "year", "month", "day", "hour", "minute", "second",
3537 "microsecond", "tzinfo", NULL
3538};
3539
Tim Peters2a799bf2002-12-16 20:18:38 +00003540static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003541datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003542{
3543 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003544 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003545 int year;
3546 int month;
3547 int day;
3548 int hour = 0;
3549 int minute = 0;
3550 int second = 0;
3551 int usecond = 0;
3552 PyObject *tzinfo = Py_None;
3553
Guido van Rossum177e41a2003-01-30 22:06:23 +00003554 /* Check for invocation from pickle with __getstate__ state */
3555 if (PyTuple_GET_SIZE(args) >= 1 &&
3556 PyTuple_GET_SIZE(args) <= 2 &&
Guido van Rossum254348e2007-11-21 19:29:53 +00003557 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3558 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3559 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003560 {
Tim Peters70533e22003-02-01 04:40:04 +00003561 PyDateTime_DateTime *me;
3562 char aware;
3563
3564 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003565 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003566 if (check_tzinfo_subclass(tzinfo) < 0) {
3567 PyErr_SetString(PyExc_TypeError, "bad "
3568 "tzinfo state arg");
3569 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003570 }
3571 }
Tim Peters70533e22003-02-01 04:40:04 +00003572 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003573 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003574 if (me != NULL) {
Guido van Rossum254348e2007-11-21 19:29:53 +00003575 char *pdata = PyString_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003576
3577 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3578 me->hashcode = -1;
3579 me->hastzinfo = aware;
3580 if (aware) {
3581 Py_INCREF(tzinfo);
3582 me->tzinfo = tzinfo;
3583 }
3584 }
3585 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003586 }
3587
Tim Petersa9bc1682003-01-11 03:39:11 +00003588 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003589 &year, &month, &day, &hour, &minute,
3590 &second, &usecond, &tzinfo)) {
3591 if (check_date_args(year, month, day) < 0)
3592 return NULL;
3593 if (check_time_args(hour, minute, second, usecond) < 0)
3594 return NULL;
3595 if (check_tzinfo_subclass(tzinfo) < 0)
3596 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003597 self = new_datetime_ex(year, month, day,
3598 hour, minute, second, usecond,
3599 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003600 }
3601 return self;
3602}
3603
Tim Petersa9bc1682003-01-11 03:39:11 +00003604/* TM_FUNC is the shared type of localtime() and gmtime(). */
3605typedef struct tm *(*TM_FUNC)(const time_t *timer);
3606
3607/* Internal helper.
3608 * Build datetime from a time_t and a distinct count of microseconds.
3609 * Pass localtime or gmtime for f, to control the interpretation of timet.
3610 */
3611static PyObject *
3612datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3613 PyObject *tzinfo)
3614{
3615 struct tm *tm;
3616 PyObject *result = NULL;
3617
3618 tm = f(&timet);
3619 if (tm) {
3620 /* The platform localtime/gmtime may insert leap seconds,
3621 * indicated by tm->tm_sec > 59. We don't care about them,
3622 * except to the extent that passing them on to the datetime
3623 * constructor would raise ValueError for a reason that
3624 * made no sense to the user.
3625 */
3626 if (tm->tm_sec > 59)
3627 tm->tm_sec = 59;
3628 result = PyObject_CallFunction(cls, "iiiiiiiO",
3629 tm->tm_year + 1900,
3630 tm->tm_mon + 1,
3631 tm->tm_mday,
3632 tm->tm_hour,
3633 tm->tm_min,
3634 tm->tm_sec,
3635 us,
3636 tzinfo);
3637 }
3638 else
3639 PyErr_SetString(PyExc_ValueError,
3640 "timestamp out of range for "
3641 "platform localtime()/gmtime() function");
3642 return result;
3643}
3644
3645/* Internal helper.
3646 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3647 * to control the interpretation of the timestamp. Since a double doesn't
3648 * have enough bits to cover a datetime's full range of precision, it's
3649 * better to call datetime_from_timet_and_us provided you have a way
3650 * to get that much precision (e.g., C time() isn't good enough).
3651 */
3652static PyObject *
3653datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3654 PyObject *tzinfo)
3655{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003656 time_t timet;
3657 double fraction;
3658 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003659
Tim Peters1b6f7a92004-06-20 02:50:16 +00003660 timet = _PyTime_DoubleToTimet(timestamp);
3661 if (timet == (time_t)-1 && PyErr_Occurred())
3662 return NULL;
3663 fraction = timestamp - (double)timet;
3664 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003665 if (us < 0) {
3666 /* Truncation towards zero is not what we wanted
3667 for negative numbers (Python's mod semantics) */
3668 timet -= 1;
3669 us += 1000000;
3670 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003671 /* If timestamp is less than one microsecond smaller than a
3672 * full second, round up. Otherwise, ValueErrors are raised
3673 * for some floats. */
3674 if (us == 1000000) {
3675 timet += 1;
3676 us = 0;
3677 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003678 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3679}
3680
3681/* Internal helper.
3682 * Build most accurate possible datetime for current time. Pass localtime or
3683 * gmtime for f as appropriate.
3684 */
3685static PyObject *
3686datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3687{
3688#ifdef HAVE_GETTIMEOFDAY
3689 struct timeval t;
3690
3691#ifdef GETTIMEOFDAY_NO_TZ
3692 gettimeofday(&t);
3693#else
3694 gettimeofday(&t, (struct timezone *)NULL);
3695#endif
3696 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3697 tzinfo);
3698
3699#else /* ! HAVE_GETTIMEOFDAY */
3700 /* No flavor of gettimeofday exists on this platform. Python's
3701 * time.time() does a lot of other platform tricks to get the
3702 * best time it can on the platform, and we're not going to do
3703 * better than that (if we could, the better code would belong
3704 * in time.time()!) We're limited by the precision of a double,
3705 * though.
3706 */
3707 PyObject *time;
3708 double dtime;
3709
3710 time = time_time();
3711 if (time == NULL)
3712 return NULL;
3713 dtime = PyFloat_AsDouble(time);
3714 Py_DECREF(time);
3715 if (dtime == -1.0 && PyErr_Occurred())
3716 return NULL;
3717 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3718#endif /* ! HAVE_GETTIMEOFDAY */
3719}
3720
Tim Peters2a799bf2002-12-16 20:18:38 +00003721/* Return best possible local time -- this isn't constrained by the
3722 * precision of a timestamp.
3723 */
3724static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003725datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003726{
Tim Peters10cadce2003-01-23 19:58:02 +00003727 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003728 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003729 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003730
Tim Peters10cadce2003-01-23 19:58:02 +00003731 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3732 &tzinfo))
3733 return NULL;
3734 if (check_tzinfo_subclass(tzinfo) < 0)
3735 return NULL;
3736
3737 self = datetime_best_possible(cls,
3738 tzinfo == Py_None ? localtime : gmtime,
3739 tzinfo);
3740 if (self != NULL && tzinfo != Py_None) {
3741 /* Convert UTC to tzinfo's zone. */
3742 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003743 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003744 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003745 }
3746 return self;
3747}
3748
Tim Petersa9bc1682003-01-11 03:39:11 +00003749/* Return best possible UTC time -- this isn't constrained by the
3750 * precision of a timestamp.
3751 */
3752static PyObject *
3753datetime_utcnow(PyObject *cls, PyObject *dummy)
3754{
3755 return datetime_best_possible(cls, gmtime, Py_None);
3756}
3757
Tim Peters2a799bf2002-12-16 20:18:38 +00003758/* Return new local datetime from timestamp (Python timestamp -- a double). */
3759static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003760datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003761{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003762 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003763 double timestamp;
3764 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003765 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003766
Tim Peters2a44a8d2003-01-23 20:53:10 +00003767 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3768 keywords, &timestamp, &tzinfo))
3769 return NULL;
3770 if (check_tzinfo_subclass(tzinfo) < 0)
3771 return NULL;
3772
3773 self = datetime_from_timestamp(cls,
3774 tzinfo == Py_None ? localtime : gmtime,
3775 timestamp,
3776 tzinfo);
3777 if (self != NULL && tzinfo != Py_None) {
3778 /* Convert UTC to tzinfo's zone. */
3779 PyObject *temp = self;
3780 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3781 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003782 }
3783 return self;
3784}
3785
Tim Petersa9bc1682003-01-11 03:39:11 +00003786/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3787static PyObject *
3788datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3789{
3790 double timestamp;
3791 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003792
Tim Petersa9bc1682003-01-11 03:39:11 +00003793 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3794 result = datetime_from_timestamp(cls, gmtime, timestamp,
3795 Py_None);
3796 return result;
3797}
3798
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003799/* Return new datetime from time.strptime(). */
3800static PyObject *
3801datetime_strptime(PyObject *cls, PyObject *args)
3802{
3803 PyObject *result = NULL, *obj, *module;
Guido van Rossume8a17aa2007-08-29 17:28:42 +00003804 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003805
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003806 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003807 return NULL;
3808
Christian Heimes072c0f12008-01-03 23:01:04 +00003809 if ((module = PyImport_ImportModuleNoBlock("time")) == NULL)
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003810 return NULL;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003811 obj = PyObject_CallMethod(module, "strptime", "uu", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003812 Py_DECREF(module);
3813
3814 if (obj != NULL) {
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00003815 int i, good_timetuple = 1, overflow;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003816 long int ia[6];
3817 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3818 for (i=0; i < 6; i++) {
3819 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003820 if (p == NULL) {
3821 Py_DECREF(obj);
3822 return NULL;
3823 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00003824 if (PyLong_CheckExact(p)) {
3825 ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
3826 if (overflow)
3827 good_timetuple = 0;
3828 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003829 else
3830 good_timetuple = 0;
3831 Py_DECREF(p);
3832 }
3833 else
3834 good_timetuple = 0;
3835 if (good_timetuple)
3836 result = PyObject_CallFunction(cls, "iiiiii",
3837 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3838 else
3839 PyErr_SetString(PyExc_ValueError,
3840 "unexpected value from time.strptime");
3841 Py_DECREF(obj);
3842 }
3843 return result;
3844}
3845
Tim Petersa9bc1682003-01-11 03:39:11 +00003846/* Return new datetime from date/datetime and time arguments. */
3847static PyObject *
3848datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3849{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003850 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003851 PyObject *date;
3852 PyObject *time;
3853 PyObject *result = NULL;
3854
3855 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3856 &PyDateTime_DateType, &date,
3857 &PyDateTime_TimeType, &time)) {
3858 PyObject *tzinfo = Py_None;
3859
3860 if (HASTZINFO(time))
3861 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3862 result = PyObject_CallFunction(cls, "iiiiiiiO",
3863 GET_YEAR(date),
3864 GET_MONTH(date),
3865 GET_DAY(date),
3866 TIME_GET_HOUR(time),
3867 TIME_GET_MINUTE(time),
3868 TIME_GET_SECOND(time),
3869 TIME_GET_MICROSECOND(time),
3870 tzinfo);
3871 }
3872 return result;
3873}
Tim Peters2a799bf2002-12-16 20:18:38 +00003874
3875/*
3876 * Destructor.
3877 */
3878
3879static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003880datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003881{
Tim Petersa9bc1682003-01-11 03:39:11 +00003882 if (HASTZINFO(self)) {
3883 Py_XDECREF(self->tzinfo);
3884 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003885 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003886}
3887
3888/*
3889 * Indirect access to tzinfo methods.
3890 */
3891
Tim Peters2a799bf2002-12-16 20:18:38 +00003892/* These are all METH_NOARGS, so don't need to check the arglist. */
3893static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003894datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3895 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3896 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003897}
3898
3899static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003900datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3901 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3902 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003903}
3904
3905static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003906datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3907 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3908 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003909}
3910
3911/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003912 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003913 */
3914
Tim Petersa9bc1682003-01-11 03:39:11 +00003915/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3916 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003917 */
3918static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003919add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3920 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003921{
Tim Petersa9bc1682003-01-11 03:39:11 +00003922 /* Note that the C-level additions can't overflow, because of
3923 * invariant bounds on the member values.
3924 */
3925 int year = GET_YEAR(date);
3926 int month = GET_MONTH(date);
3927 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3928 int hour = DATE_GET_HOUR(date);
3929 int minute = DATE_GET_MINUTE(date);
3930 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3931 int microsecond = DATE_GET_MICROSECOND(date) +
3932 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003933
Tim Petersa9bc1682003-01-11 03:39:11 +00003934 assert(factor == 1 || factor == -1);
3935 if (normalize_datetime(&year, &month, &day,
3936 &hour, &minute, &second, &microsecond) < 0)
3937 return NULL;
3938 else
3939 return new_datetime(year, month, day,
3940 hour, minute, second, microsecond,
3941 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003942}
3943
3944static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003945datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003946{
Tim Petersa9bc1682003-01-11 03:39:11 +00003947 if (PyDateTime_Check(left)) {
3948 /* datetime + ??? */
3949 if (PyDelta_Check(right))
3950 /* datetime + delta */
3951 return add_datetime_timedelta(
3952 (PyDateTime_DateTime *)left,
3953 (PyDateTime_Delta *)right,
3954 1);
3955 }
3956 else if (PyDelta_Check(left)) {
3957 /* delta + datetime */
3958 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3959 (PyDateTime_Delta *) left,
3960 1);
3961 }
3962 Py_INCREF(Py_NotImplemented);
3963 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003964}
3965
3966static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003967datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003968{
3969 PyObject *result = Py_NotImplemented;
3970
3971 if (PyDateTime_Check(left)) {
3972 /* datetime - ??? */
3973 if (PyDateTime_Check(right)) {
3974 /* datetime - datetime */
3975 naivety n1, n2;
3976 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003977 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003978
Tim Peterse39a80c2002-12-30 21:28:52 +00003979 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3980 right, &offset2, &n2,
3981 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003982 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003983 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003984 if (n1 != n2) {
3985 PyErr_SetString(PyExc_TypeError,
3986 "can't subtract offset-naive and "
3987 "offset-aware datetimes");
3988 return NULL;
3989 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003990 delta_d = ymd_to_ord(GET_YEAR(left),
3991 GET_MONTH(left),
3992 GET_DAY(left)) -
3993 ymd_to_ord(GET_YEAR(right),
3994 GET_MONTH(right),
3995 GET_DAY(right));
3996 /* These can't overflow, since the values are
3997 * normalized. At most this gives the number of
3998 * seconds in one day.
3999 */
4000 delta_s = (DATE_GET_HOUR(left) -
4001 DATE_GET_HOUR(right)) * 3600 +
4002 (DATE_GET_MINUTE(left) -
4003 DATE_GET_MINUTE(right)) * 60 +
4004 (DATE_GET_SECOND(left) -
4005 DATE_GET_SECOND(right));
4006 delta_us = DATE_GET_MICROSECOND(left) -
4007 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004008 /* (left - offset1) - (right - offset2) =
4009 * (left - right) + (offset2 - offset1)
4010 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004011 delta_s += (offset2 - offset1) * 60;
4012 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004013 }
4014 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004015 /* datetime - delta */
4016 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004017 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004018 (PyDateTime_Delta *)right,
4019 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004020 }
4021 }
4022
4023 if (result == Py_NotImplemented)
4024 Py_INCREF(result);
4025 return result;
4026}
4027
4028/* Various ways to turn a datetime into a string. */
4029
4030static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004031datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004032{
Christian Heimes90aa7642007-12-19 02:45:37 +00004033 const char *type_name = Py_TYPE(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004034 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004035
Tim Petersa9bc1682003-01-11 03:39:11 +00004036 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004037 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004038 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004039 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004040 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4041 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4042 DATE_GET_SECOND(self),
4043 DATE_GET_MICROSECOND(self));
4044 }
4045 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004046 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004047 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004048 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004049 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4050 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4051 DATE_GET_SECOND(self));
4052 }
4053 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004054 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004055 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004056 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004057 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4058 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4059 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004060 if (baserepr == NULL || ! HASTZINFO(self))
4061 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004062 return append_keyword_tzinfo(baserepr, self->tzinfo);
4063}
4064
Tim Petersa9bc1682003-01-11 03:39:11 +00004065static PyObject *
4066datetime_str(PyDateTime_DateTime *self)
4067{
4068 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4069}
Tim Peters2a799bf2002-12-16 20:18:38 +00004070
4071static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004072datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004073{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004074 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004075 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004076 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004077 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004078 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004079
Walter Dörwaldd0941302007-07-01 21:58:22 +00004080 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004081 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004082 if (us)
4083 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4084 GET_YEAR(self), GET_MONTH(self),
4085 GET_DAY(self), (int)sep,
4086 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4087 DATE_GET_SECOND(self), us);
4088 else
4089 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4090 GET_YEAR(self), GET_MONTH(self),
4091 GET_DAY(self), (int)sep,
4092 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4093 DATE_GET_SECOND(self));
4094
4095 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004096 return result;
4097
4098 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004099 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004100 (PyObject *)self) < 0) {
4101 Py_DECREF(result);
4102 return NULL;
4103 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004104 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004105 return result;
4106}
4107
Tim Petersa9bc1682003-01-11 03:39:11 +00004108static PyObject *
4109datetime_ctime(PyDateTime_DateTime *self)
4110{
4111 return format_ctime((PyDateTime_Date *)self,
4112 DATE_GET_HOUR(self),
4113 DATE_GET_MINUTE(self),
4114 DATE_GET_SECOND(self));
4115}
4116
Tim Peters2a799bf2002-12-16 20:18:38 +00004117/* Miscellaneous methods. */
4118
Tim Petersa9bc1682003-01-11 03:39:11 +00004119static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004120datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004121{
4122 int diff;
4123 naivety n1, n2;
4124 int offset1, offset2;
4125
4126 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004127 if (PyDate_Check(other)) {
4128 /* Prevent invocation of date_richcompare. We want to
4129 return NotImplemented here to give the other object
4130 a chance. But since DateTime is a subclass of
4131 Date, if the other object is a Date, it would
4132 compute an ordering based on the date part alone,
4133 and we don't want that. So force unequal or
4134 uncomparable here in that case. */
4135 if (op == Py_EQ)
4136 Py_RETURN_FALSE;
4137 if (op == Py_NE)
4138 Py_RETURN_TRUE;
4139 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004140 }
Guido van Rossum19960592006-08-24 17:29:38 +00004141 Py_INCREF(Py_NotImplemented);
4142 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004143 }
4144
Guido van Rossum19960592006-08-24 17:29:38 +00004145 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4146 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004147 return NULL;
4148 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4149 /* If they're both naive, or both aware and have the same offsets,
4150 * we get off cheap. Note that if they're both naive, offset1 ==
4151 * offset2 == 0 at this point.
4152 */
4153 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004154 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4155 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004156 _PyDateTime_DATETIME_DATASIZE);
4157 return diff_to_bool(diff, op);
4158 }
4159
4160 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4161 PyDateTime_Delta *delta;
4162
4163 assert(offset1 != offset2); /* else last "if" handled it */
4164 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4165 other);
4166 if (delta == NULL)
4167 return NULL;
4168 diff = GET_TD_DAYS(delta);
4169 if (diff == 0)
4170 diff = GET_TD_SECONDS(delta) |
4171 GET_TD_MICROSECONDS(delta);
4172 Py_DECREF(delta);
4173 return diff_to_bool(diff, op);
4174 }
4175
4176 assert(n1 != n2);
4177 PyErr_SetString(PyExc_TypeError,
4178 "can't compare offset-naive and "
4179 "offset-aware datetimes");
4180 return NULL;
4181}
4182
4183static long
4184datetime_hash(PyDateTime_DateTime *self)
4185{
4186 if (self->hashcode == -1) {
4187 naivety n;
4188 int offset;
4189 PyObject *temp;
4190
4191 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4192 &offset);
4193 assert(n != OFFSET_UNKNOWN);
4194 if (n == OFFSET_ERROR)
4195 return -1;
4196
4197 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00004198 if (n == OFFSET_NAIVE) {
4199 self->hashcode = generic_hash(
4200 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4201 return self->hashcode;
4202 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004203 else {
4204 int days;
4205 int seconds;
4206
4207 assert(n == OFFSET_AWARE);
4208 assert(HASTZINFO(self));
4209 days = ymd_to_ord(GET_YEAR(self),
4210 GET_MONTH(self),
4211 GET_DAY(self));
4212 seconds = DATE_GET_HOUR(self) * 3600 +
4213 (DATE_GET_MINUTE(self) - offset) * 60 +
4214 DATE_GET_SECOND(self);
4215 temp = new_delta(days,
4216 seconds,
4217 DATE_GET_MICROSECOND(self),
4218 1);
4219 }
4220 if (temp != NULL) {
4221 self->hashcode = PyObject_Hash(temp);
4222 Py_DECREF(temp);
4223 }
4224 }
4225 return self->hashcode;
4226}
Tim Peters2a799bf2002-12-16 20:18:38 +00004227
4228static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004229datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004230{
4231 PyObject *clone;
4232 PyObject *tuple;
4233 int y = GET_YEAR(self);
4234 int m = GET_MONTH(self);
4235 int d = GET_DAY(self);
4236 int hh = DATE_GET_HOUR(self);
4237 int mm = DATE_GET_MINUTE(self);
4238 int ss = DATE_GET_SECOND(self);
4239 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004240 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004241
4242 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004243 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004244 &y, &m, &d, &hh, &mm, &ss, &us,
4245 &tzinfo))
4246 return NULL;
4247 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4248 if (tuple == NULL)
4249 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00004250 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004251 Py_DECREF(tuple);
4252 return clone;
4253}
4254
4255static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004256datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004257{
Tim Peters52dcce22003-01-23 16:36:11 +00004258 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004259 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004260 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004261
Tim Peters80475bb2002-12-25 07:40:55 +00004262 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004263 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004264
Tim Peters52dcce22003-01-23 16:36:11 +00004265 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4266 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004267 return NULL;
4268
Tim Peters52dcce22003-01-23 16:36:11 +00004269 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4270 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004271
Tim Peters52dcce22003-01-23 16:36:11 +00004272 /* Conversion to self's own time zone is a NOP. */
4273 if (self->tzinfo == tzinfo) {
4274 Py_INCREF(self);
4275 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004276 }
Tim Peters521fc152002-12-31 17:36:56 +00004277
Tim Peters52dcce22003-01-23 16:36:11 +00004278 /* Convert self to UTC. */
4279 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4280 if (offset == -1 && PyErr_Occurred())
4281 return NULL;
4282 if (none)
4283 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004284
Tim Peters52dcce22003-01-23 16:36:11 +00004285 y = GET_YEAR(self);
4286 m = GET_MONTH(self);
4287 d = GET_DAY(self);
4288 hh = DATE_GET_HOUR(self);
4289 mm = DATE_GET_MINUTE(self);
4290 ss = DATE_GET_SECOND(self);
4291 us = DATE_GET_MICROSECOND(self);
4292
4293 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004294 if ((mm < 0 || mm >= 60) &&
4295 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004296 return NULL;
4297
4298 /* Attach new tzinfo and let fromutc() do the rest. */
4299 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4300 if (result != NULL) {
4301 PyObject *temp = result;
4302
4303 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4304 Py_DECREF(temp);
4305 }
Tim Petersadf64202003-01-04 06:03:15 +00004306 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004307
Tim Peters52dcce22003-01-23 16:36:11 +00004308NeedAware:
4309 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4310 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004311 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004312}
4313
4314static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004315datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004316{
4317 int dstflag = -1;
4318
Tim Petersa9bc1682003-01-11 03:39:11 +00004319 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004320 int none;
4321
4322 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4323 if (dstflag == -1 && PyErr_Occurred())
4324 return NULL;
4325
4326 if (none)
4327 dstflag = -1;
4328 else if (dstflag != 0)
4329 dstflag = 1;
4330
4331 }
4332 return build_struct_time(GET_YEAR(self),
4333 GET_MONTH(self),
4334 GET_DAY(self),
4335 DATE_GET_HOUR(self),
4336 DATE_GET_MINUTE(self),
4337 DATE_GET_SECOND(self),
4338 dstflag);
4339}
4340
4341static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004342datetime_getdate(PyDateTime_DateTime *self)
4343{
4344 return new_date(GET_YEAR(self),
4345 GET_MONTH(self),
4346 GET_DAY(self));
4347}
4348
4349static PyObject *
4350datetime_gettime(PyDateTime_DateTime *self)
4351{
4352 return new_time(DATE_GET_HOUR(self),
4353 DATE_GET_MINUTE(self),
4354 DATE_GET_SECOND(self),
4355 DATE_GET_MICROSECOND(self),
4356 Py_None);
4357}
4358
4359static PyObject *
4360datetime_gettimetz(PyDateTime_DateTime *self)
4361{
4362 return new_time(DATE_GET_HOUR(self),
4363 DATE_GET_MINUTE(self),
4364 DATE_GET_SECOND(self),
4365 DATE_GET_MICROSECOND(self),
4366 HASTZINFO(self) ? self->tzinfo : Py_None);
4367}
4368
4369static PyObject *
4370datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004371{
4372 int y = GET_YEAR(self);
4373 int m = GET_MONTH(self);
4374 int d = GET_DAY(self);
4375 int hh = DATE_GET_HOUR(self);
4376 int mm = DATE_GET_MINUTE(self);
4377 int ss = DATE_GET_SECOND(self);
4378 int us = 0; /* microseconds are ignored in a timetuple */
4379 int offset = 0;
4380
Tim Petersa9bc1682003-01-11 03:39:11 +00004381 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004382 int none;
4383
4384 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4385 if (offset == -1 && PyErr_Occurred())
4386 return NULL;
4387 }
4388 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4389 * 0 in a UTC timetuple regardless of what dst() says.
4390 */
4391 if (offset) {
4392 /* Subtract offset minutes & normalize. */
4393 int stat;
4394
4395 mm -= offset;
4396 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4397 if (stat < 0) {
4398 /* At the edges, it's possible we overflowed
4399 * beyond MINYEAR or MAXYEAR.
4400 */
4401 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4402 PyErr_Clear();
4403 else
4404 return NULL;
4405 }
4406 }
4407 return build_struct_time(y, m, d, hh, mm, ss, 0);
4408}
4409
Tim Peters371935f2003-02-01 01:52:50 +00004410/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004411
Tim Petersa9bc1682003-01-11 03:39:11 +00004412/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004413 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4414 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004415 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004416 */
4417static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004418datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004419{
4420 PyObject *basestate;
4421 PyObject *result = NULL;
4422
Guido van Rossum254348e2007-11-21 19:29:53 +00004423 basestate = PyString_FromStringAndSize((char *)self->data,
4424 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004425 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004426 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004427 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004428 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004429 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004430 Py_DECREF(basestate);
4431 }
4432 return result;
4433}
4434
4435static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004436datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004437{
Christian Heimes90aa7642007-12-19 02:45:37 +00004438 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004439}
4440
Tim Petersa9bc1682003-01-11 03:39:11 +00004441static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004442
Tim Peters2a799bf2002-12-16 20:18:38 +00004443 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004444
Tim Petersa9bc1682003-01-11 03:39:11 +00004445 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004446 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004447 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004448
Tim Petersa9bc1682003-01-11 03:39:11 +00004449 {"utcnow", (PyCFunction)datetime_utcnow,
4450 METH_NOARGS | METH_CLASS,
4451 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4452
4453 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004454 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004455 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004456
Tim Petersa9bc1682003-01-11 03:39:11 +00004457 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4458 METH_VARARGS | METH_CLASS,
4459 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4460 "(like time.time()).")},
4461
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004462 {"strptime", (PyCFunction)datetime_strptime,
4463 METH_VARARGS | METH_CLASS,
4464 PyDoc_STR("string, format -> new datetime parsed from a string "
4465 "(like time.strptime()).")},
4466
Tim Petersa9bc1682003-01-11 03:39:11 +00004467 {"combine", (PyCFunction)datetime_combine,
4468 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4469 PyDoc_STR("date, time -> datetime with same date and time fields")},
4470
Tim Peters2a799bf2002-12-16 20:18:38 +00004471 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004472
Tim Petersa9bc1682003-01-11 03:39:11 +00004473 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4474 PyDoc_STR("Return date object with same year, month and day.")},
4475
4476 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4477 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4478
4479 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4480 PyDoc_STR("Return time object with same time and tzinfo.")},
4481
4482 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4483 PyDoc_STR("Return ctime() style string.")},
4484
4485 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004486 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4487
Tim Petersa9bc1682003-01-11 03:39:11 +00004488 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004489 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4490
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004491 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004492 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4493 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4494 "sep is used to separate the year from the time, and "
4495 "defaults to 'T'.")},
4496
Tim Petersa9bc1682003-01-11 03:39:11 +00004497 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004498 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4499
Tim Petersa9bc1682003-01-11 03:39:11 +00004500 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004501 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4502
Tim Petersa9bc1682003-01-11 03:39:11 +00004503 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004504 PyDoc_STR("Return self.tzinfo.dst(self).")},
4505
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004506 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004507 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004508
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004509 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004510 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4511
Guido van Rossum177e41a2003-01-30 22:06:23 +00004512 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4513 PyDoc_STR("__reduce__() -> (cls, state)")},
4514
Tim Peters2a799bf2002-12-16 20:18:38 +00004515 {NULL, NULL}
4516};
4517
Tim Petersa9bc1682003-01-11 03:39:11 +00004518static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004519PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4520\n\
4521The year, month and day arguments are required. tzinfo may be None, or an\n\
4522instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004523
Tim Petersa9bc1682003-01-11 03:39:11 +00004524static PyNumberMethods datetime_as_number = {
4525 datetime_add, /* nb_add */
4526 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004528 0, /* nb_remainder */
4529 0, /* nb_divmod */
4530 0, /* nb_power */
4531 0, /* nb_negative */
4532 0, /* nb_positive */
4533 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004534 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004535};
4536
Neal Norwitz227b5332006-03-22 09:28:35 +00004537static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004538 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004539 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004540 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004541 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004542 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004543 0, /* tp_print */
4544 0, /* tp_getattr */
4545 0, /* tp_setattr */
4546 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004547 (reprfunc)datetime_repr, /* tp_repr */
4548 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004549 0, /* tp_as_sequence */
4550 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004551 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004552 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004553 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004554 PyObject_GenericGetAttr, /* tp_getattro */
4555 0, /* tp_setattro */
4556 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004557 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004558 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004559 0, /* tp_traverse */
4560 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004561 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004562 0, /* tp_weaklistoffset */
4563 0, /* tp_iter */
4564 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004565 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004566 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004567 datetime_getset, /* tp_getset */
4568 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004569 0, /* tp_dict */
4570 0, /* tp_descr_get */
4571 0, /* tp_descr_set */
4572 0, /* tp_dictoffset */
4573 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004574 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004575 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004576 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004577};
4578
4579/* ---------------------------------------------------------------------------
4580 * Module methods and initialization.
4581 */
4582
4583static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004584 {NULL, NULL}
4585};
4586
Tim Peters9ddf40b2004-06-20 22:41:32 +00004587/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4588 * datetime.h.
4589 */
4590static PyDateTime_CAPI CAPI = {
4591 &PyDateTime_DateType,
4592 &PyDateTime_DateTimeType,
4593 &PyDateTime_TimeType,
4594 &PyDateTime_DeltaType,
4595 &PyDateTime_TZInfoType,
4596 new_date_ex,
4597 new_datetime_ex,
4598 new_time_ex,
4599 new_delta_ex,
4600 datetime_fromtimestamp,
4601 date_fromtimestamp
4602};
4603
4604
Tim Peters2a799bf2002-12-16 20:18:38 +00004605PyMODINIT_FUNC
4606initdatetime(void)
4607{
4608 PyObject *m; /* a module object */
4609 PyObject *d; /* its dict */
4610 PyObject *x;
4611
Tim Peters2a799bf2002-12-16 20:18:38 +00004612 m = Py_InitModule3("datetime", module_methods,
4613 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004614 if (m == NULL)
4615 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004616
4617 if (PyType_Ready(&PyDateTime_DateType) < 0)
4618 return;
4619 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4620 return;
4621 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4622 return;
4623 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4624 return;
4625 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4626 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004627
Tim Peters2a799bf2002-12-16 20:18:38 +00004628 /* timedelta values */
4629 d = PyDateTime_DeltaType.tp_dict;
4630
Tim Peters2a799bf2002-12-16 20:18:38 +00004631 x = new_delta(0, 0, 1, 0);
4632 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4633 return;
4634 Py_DECREF(x);
4635
4636 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4637 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4638 return;
4639 Py_DECREF(x);
4640
4641 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4642 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4643 return;
4644 Py_DECREF(x);
4645
4646 /* date values */
4647 d = PyDateTime_DateType.tp_dict;
4648
4649 x = new_date(1, 1, 1);
4650 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4651 return;
4652 Py_DECREF(x);
4653
4654 x = new_date(MAXYEAR, 12, 31);
4655 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4656 return;
4657 Py_DECREF(x);
4658
4659 x = new_delta(1, 0, 0, 0);
4660 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4661 return;
4662 Py_DECREF(x);
4663
Tim Peters37f39822003-01-10 03:49:02 +00004664 /* time values */
4665 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004666
Tim Peters37f39822003-01-10 03:49:02 +00004667 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004668 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4669 return;
4670 Py_DECREF(x);
4671
Tim Peters37f39822003-01-10 03:49:02 +00004672 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004673 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4674 return;
4675 Py_DECREF(x);
4676
4677 x = new_delta(0, 0, 1, 0);
4678 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4679 return;
4680 Py_DECREF(x);
4681
Tim Petersa9bc1682003-01-11 03:39:11 +00004682 /* datetime values */
4683 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004684
Tim Petersa9bc1682003-01-11 03:39:11 +00004685 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004686 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4687 return;
4688 Py_DECREF(x);
4689
Tim Petersa9bc1682003-01-11 03:39:11 +00004690 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004691 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4692 return;
4693 Py_DECREF(x);
4694
4695 x = new_delta(0, 0, 1, 0);
4696 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4697 return;
4698 Py_DECREF(x);
4699
Tim Peters2a799bf2002-12-16 20:18:38 +00004700 /* module initialization */
4701 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4702 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4703
4704 Py_INCREF(&PyDateTime_DateType);
4705 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4706
Tim Petersa9bc1682003-01-11 03:39:11 +00004707 Py_INCREF(&PyDateTime_DateTimeType);
4708 PyModule_AddObject(m, "datetime",
4709 (PyObject *)&PyDateTime_DateTimeType);
4710
4711 Py_INCREF(&PyDateTime_TimeType);
4712 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4713
Tim Peters2a799bf2002-12-16 20:18:38 +00004714 Py_INCREF(&PyDateTime_DeltaType);
4715 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4716
Tim Peters2a799bf2002-12-16 20:18:38 +00004717 Py_INCREF(&PyDateTime_TZInfoType);
4718 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4719
Tim Peters9ddf40b2004-06-20 22:41:32 +00004720 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4721 NULL);
4722 if (x == NULL)
4723 return;
4724 PyModule_AddObject(m, "datetime_CAPI", x);
4725
Tim Peters2a799bf2002-12-16 20:18:38 +00004726 /* A 4-year cycle has an extra leap day over what we'd get from
4727 * pasting together 4 single years.
4728 */
4729 assert(DI4Y == 4 * 365 + 1);
4730 assert(DI4Y == days_before_year(4+1));
4731
4732 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4733 * get from pasting together 4 100-year cycles.
4734 */
4735 assert(DI400Y == 4 * DI100Y + 1);
4736 assert(DI400Y == days_before_year(400+1));
4737
4738 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4739 * pasting together 25 4-year cycles.
4740 */
4741 assert(DI100Y == 25 * DI4Y - 1);
4742 assert(DI100Y == days_before_year(100+1));
4743
Christian Heimes217cfd12007-12-02 14:31:20 +00004744 us_per_us = PyLong_FromLong(1);
4745 us_per_ms = PyLong_FromLong(1000);
4746 us_per_second = PyLong_FromLong(1000000);
4747 us_per_minute = PyLong_FromLong(60000000);
4748 seconds_per_day = PyLong_FromLong(24 * 3600);
Tim Peters2a799bf2002-12-16 20:18:38 +00004749 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4750 us_per_minute == NULL || seconds_per_day == NULL)
4751 return;
4752
4753 /* The rest are too big for 32-bit ints, but even
4754 * us_per_week fits in 40 bits, so doubles should be exact.
4755 */
4756 us_per_hour = PyLong_FromDouble(3600000000.0);
4757 us_per_day = PyLong_FromDouble(86400000000.0);
4758 us_per_week = PyLong_FromDouble(604800000000.0);
4759 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4760 return;
4761}
Tim Petersf3615152003-01-01 21:51:37 +00004762
4763/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004764Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004765 x.n = x stripped of its timezone -- its naive time.
4766 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4767 return None
4768 x.d = x.dst(), and assuming that doesn't raise an exception or
4769 return None
4770 x.s = x's standard offset, x.o - x.d
4771
4772Now some derived rules, where k is a duration (timedelta).
4773
47741. x.o = x.s + x.d
4775 This follows from the definition of x.s.
4776
Tim Petersc5dc4da2003-01-02 17:55:03 +000047772. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004778 This is actually a requirement, an assumption we need to make about
4779 sane tzinfo classes.
4780
47813. The naive UTC time corresponding to x is x.n - x.o.
4782 This is again a requirement for a sane tzinfo class.
4783
47844. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004785 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004786
Tim Petersc5dc4da2003-01-02 17:55:03 +000047875. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004788 Again follows from how arithmetic is defined.
4789
Tim Peters8bb5ad22003-01-24 02:44:45 +00004790Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004791(meaning that the various tzinfo methods exist, and don't blow up or return
4792None when called).
4793
Tim Petersa9bc1682003-01-11 03:39:11 +00004794The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004795x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004796
4797By #3, we want
4798
Tim Peters8bb5ad22003-01-24 02:44:45 +00004799 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004800
4801The algorithm starts by attaching tz to x.n, and calling that y. So
4802x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4803becomes true; in effect, we want to solve [2] for k:
4804
Tim Peters8bb5ad22003-01-24 02:44:45 +00004805 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004806
4807By #1, this is the same as
4808
Tim Peters8bb5ad22003-01-24 02:44:45 +00004809 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004810
4811By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4812Substituting that into [3],
4813
Tim Peters8bb5ad22003-01-24 02:44:45 +00004814 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4815 k - (y+k).s - (y+k).d = 0; rearranging,
4816 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4817 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004818
Tim Peters8bb5ad22003-01-24 02:44:45 +00004819On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4820approximate k by ignoring the (y+k).d term at first. Note that k can't be
4821very large, since all offset-returning methods return a duration of magnitude
4822less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4823be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004824
4825In any case, the new value is
4826
Tim Peters8bb5ad22003-01-24 02:44:45 +00004827 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004828
Tim Peters8bb5ad22003-01-24 02:44:45 +00004829It's helpful to step back at look at [4] from a higher level: it's simply
4830mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004831
4832At this point, if
4833
Tim Peters8bb5ad22003-01-24 02:44:45 +00004834 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004835
4836we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004837at the start of daylight time. Picture US Eastern for concreteness. The wall
4838time 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 +00004839sense then. The docs ask that an Eastern tzinfo class consider such a time to
4840be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4841on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004842the only spelling that makes sense on the local wall clock.
4843
Tim Petersc5dc4da2003-01-02 17:55:03 +00004844In fact, if [5] holds at this point, we do have the standard-time spelling,
4845but that takes a bit of proof. We first prove a stronger result. What's the
4846difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004847
Tim Peters8bb5ad22003-01-24 02:44:45 +00004848 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004849
Tim Petersc5dc4da2003-01-02 17:55:03 +00004850Now
4851 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004852 (y + y.s).n = by #5
4853 y.n + y.s = since y.n = x.n
4854 x.n + y.s = since z and y are have the same tzinfo member,
4855 y.s = z.s by #2
4856 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004857
Tim Petersc5dc4da2003-01-02 17:55:03 +00004858Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004859
Tim Petersc5dc4da2003-01-02 17:55:03 +00004860 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004861 x.n - ((x.n + z.s) - z.o) = expanding
4862 x.n - x.n - z.s + z.o = cancelling
4863 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004864 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004865
Tim Petersc5dc4da2003-01-02 17:55:03 +00004866So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004867
Tim Petersc5dc4da2003-01-02 17:55:03 +00004868If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004869spelling we wanted in the endcase described above. We're done. Contrarily,
4870if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004871
Tim Petersc5dc4da2003-01-02 17:55:03 +00004872If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4873add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004874local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004875
Tim Petersc5dc4da2003-01-02 17:55:03 +00004876Let
Tim Petersf3615152003-01-01 21:51:37 +00004877
Tim Peters4fede1a2003-01-04 00:26:59 +00004878 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004879
Tim Peters4fede1a2003-01-04 00:26:59 +00004880and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004881
Tim Peters8bb5ad22003-01-24 02:44:45 +00004882 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004883
Tim Peters8bb5ad22003-01-24 02:44:45 +00004884If so, we're done. If not, the tzinfo class is insane, according to the
4885assumptions we've made. This also requires a bit of proof. As before, let's
4886compute the difference between the LHS and RHS of [8] (and skipping some of
4887the justifications for the kinds of substitutions we've done several times
4888already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004889
Tim Peters8bb5ad22003-01-24 02:44:45 +00004890 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4891 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4892 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4893 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4894 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004895 - z.o + z'.o = #1 twice
4896 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4897 z'.d - z.d
4898
4899So 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 +00004900we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4901return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004902
Tim Peters8bb5ad22003-01-24 02:44:45 +00004903How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4904a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4905would have to change the result dst() returns: we start in DST, and moving
4906a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004907
Tim Peters8bb5ad22003-01-24 02:44:45 +00004908There isn't a sane case where this can happen. The closest it gets is at
4909the end of DST, where there's an hour in UTC with no spelling in a hybrid
4910tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4911that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4912UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4913time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4914clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4915standard time. Since that's what the local clock *does*, we want to map both
4916UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004917in local time, but so it goes -- it's the way the local clock works.
4918
Tim Peters8bb5ad22003-01-24 02:44:45 +00004919When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4920so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4921z' = 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 +00004922(correctly) concludes that z' is not UTC-equivalent to x.
4923
4924Because we know z.d said z was in daylight time (else [5] would have held and
4925we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004926and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004927return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4928but the reasoning doesn't depend on the example -- it depends on there being
4929two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004930z' must be in standard time, and is the spelling we want in this case.
4931
4932Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4933concerned (because it takes z' as being in standard time rather than the
4934daylight time we intend here), but returning it gives the real-life "local
4935clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4936tz.
4937
4938When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4939the 1:MM standard time spelling we want.
4940
4941So how can this break? One of the assumptions must be violated. Two
4942possibilities:
4943
49441) [2] effectively says that y.s is invariant across all y belong to a given
4945 time zone. This isn't true if, for political reasons or continental drift,
4946 a region decides to change its base offset from UTC.
4947
49482) There may be versions of "double daylight" time where the tail end of
4949 the analysis gives up a step too early. I haven't thought about that
4950 enough to say.
4951
4952In any case, it's clear that the default fromutc() is strong enough to handle
4953"almost all" time zones: so long as the standard offset is invariant, it
4954doesn't matter if daylight time transition points change from year to year, or
4955if daylight time is skipped in some years; it doesn't matter how large or
4956small dst() may get within its bounds; and it doesn't even matter if some
4957perverse time zone returns a negative dst()). So a breaking case must be
4958pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004959--------------------------------------------------------------------------- */