blob: 3f9e78b0abd77f00f5d353969c82c7bc5f253b48 [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 */
Kristján Valur Jónsson7a0da192007-04-30 15:17:46 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Kristján Valur Jónsson7a0da192007-04-30 15:17:46 +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 Heimese93237d2007-12-19 02:37:44 +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 Heimese93237d2007-12-19 02:37:44 +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
Tim Peters855fe882002-12-22 03:43:39 +0000930 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000931 */
932static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000933call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000934{
935 PyObject *result;
936
937 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000938 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000939 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000940
Tim Peters855fe882002-12-22 03:43:39 +0000941 if (tzinfo == Py_None) {
942 result = Py_None;
943 Py_INCREF(result);
944 }
945 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000946 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000947
948 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
949 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
Tim Peters2a799bf2002-12-16 20:18:38 +0000950 "return None or a string, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000951 Py_TYPE(result)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000952 Py_DECREF(result);
953 result = NULL;
954 }
955 return result;
956}
957
958typedef enum {
959 /* an exception has been set; the caller should pass it on */
960 OFFSET_ERROR,
961
Tim Petersa9bc1682003-01-11 03:39:11 +0000962 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000963 OFFSET_UNKNOWN,
964
965 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000966 * datetime with !hastzinfo
967 * datetime with None tzinfo,
968 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000969 * time with !hastzinfo
970 * time with None tzinfo,
971 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000972 */
973 OFFSET_NAIVE,
974
Tim Petersa9bc1682003-01-11 03:39:11 +0000975 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000976 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000977} naivety;
978
Tim Peters14b69412002-12-22 18:10:22 +0000979/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 * the "naivety" typedef for details. If the type is aware, *offset is set
981 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000982 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000983 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000984 */
985static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000986classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000987{
988 int none;
989 PyObject *tzinfo;
990
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +0000993 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +0000994 if (tzinfo == Py_None)
995 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +0000996 if (tzinfo == NULL) {
997 /* note that a datetime passes the PyDate_Check test */
998 return (PyTime_Check(op) || PyDate_Check(op)) ?
999 OFFSET_NAIVE : OFFSET_UNKNOWN;
1000 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001001 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (*offset == -1 && PyErr_Occurred())
1003 return OFFSET_ERROR;
1004 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1005}
1006
Tim Peters00237032002-12-27 02:21:51 +00001007/* Classify two objects as to whether they're naive or offset-aware.
1008 * This isn't quite the same as calling classify_utcoffset() twice: for
1009 * binary operations (comparison and subtraction), we generally want to
1010 * ignore the tzinfo members if they're identical. This is by design,
1011 * so that results match "naive" expectations when mixing objects from a
1012 * single timezone. So in that case, this sets both offsets to 0 and
1013 * both naiveties to OFFSET_NAIVE.
1014 * The function returns 0 if everything's OK, and -1 on error.
1015 */
1016static int
1017classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001018 PyObject *tzinfoarg1,
1019 PyObject *o2, int *offset2, naivety *n2,
1020 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001021{
1022 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1023 *offset1 = *offset2 = 0;
1024 *n1 = *n2 = OFFSET_NAIVE;
1025 }
1026 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001027 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001028 if (*n1 == OFFSET_ERROR)
1029 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001030 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001031 if (*n2 == OFFSET_ERROR)
1032 return -1;
1033 }
1034 return 0;
1035}
1036
Tim Peters2a799bf2002-12-16 20:18:38 +00001037/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1038 * stuff
1039 * ", tzinfo=" + repr(tzinfo)
1040 * before the closing ")".
1041 */
1042static PyObject *
1043append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1044{
1045 PyObject *temp;
1046
1047 assert(PyString_Check(repr));
1048 assert(tzinfo);
1049 if (tzinfo == Py_None)
1050 return repr;
1051 /* Get rid of the trailing ')'. */
1052 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1053 temp = PyString_FromStringAndSize(PyString_AsString(repr),
1054 PyString_Size(repr) - 1);
1055 Py_DECREF(repr);
1056 if (temp == NULL)
1057 return NULL;
1058 repr = temp;
1059
1060 /* Append ", tzinfo=". */
1061 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
1062
1063 /* Append repr(tzinfo). */
1064 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
1065
1066 /* Add a closing paren. */
1067 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1068 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
1086 char buffer[128];
1087 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1088
1089 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1090 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1091 GET_DAY(date), hours, minutes, seconds,
1092 GET_YEAR(date));
1093 return PyString_FromString(buffer);
1094}
1095
1096/* Add an hours & minutes UTC offset string to buf. buf has no more than
1097 * buflen bytes remaining. The UTC offset is gotten by calling
1098 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1099 * *buf, and that's all. Else the returned value is checked for sanity (an
1100 * integer in range), and if that's OK it's converted to an hours & minutes
1101 * string of the form
1102 * sign HH sep MM
1103 * Returns 0 if everything is OK. If the return value from utcoffset() is
1104 * bogus, an appropriate exception is set and -1 is returned.
1105 */
1106static int
Tim Peters328fff72002-12-20 01:31:27 +00001107format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001108 PyObject *tzinfo, PyObject *tzinfoarg)
1109{
1110 int offset;
1111 int hours;
1112 int minutes;
1113 char sign;
1114 int none;
1115
1116 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1117 if (offset == -1 && PyErr_Occurred())
1118 return -1;
1119 if (none) {
1120 *buf = '\0';
1121 return 0;
1122 }
1123 sign = '+';
1124 if (offset < 0) {
1125 sign = '-';
1126 offset = - offset;
1127 }
1128 hours = divmod(offset, 60, &minutes);
1129 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1130 return 0;
1131}
1132
Skip Montanarofc070d22008-03-15 16:04:45 +00001133static PyObject *
1134make_freplacement(PyObject *object)
1135{
Neal Norwitzf13572d2008-03-17 19:02:45 +00001136 char freplacement[64];
Skip Montanarofc070d22008-03-15 16:04:45 +00001137 if (PyTime_Check(object))
1138 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1139 else if (PyDateTime_Check(object))
1140 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1141 else
1142 sprintf(freplacement, "%06d", 0);
1143
1144 return PyString_FromStringAndSize(freplacement, strlen(freplacement));
1145}
1146
Tim Peters2a799bf2002-12-16 20:18:38 +00001147/* I sure don't want to reproduce the strftime code from the time module,
1148 * so this imports the module and calls it. All the hair is due to
Skip Montanarofc070d22008-03-15 16:04:45 +00001149 * giving special meanings to the %z, %Z and %f format codes via a
1150 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001151 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1152 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001153 */
1154static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001155wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1156 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001157{
1158 PyObject *result = NULL; /* guilty until proved innocent */
1159
1160 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1161 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
Skip Montanarofc070d22008-03-15 16:04:45 +00001162 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001163
1164 char *pin; /* pointer to next char in input format */
1165 char ch; /* next char in input format */
1166
1167 PyObject *newfmt = NULL; /* py string, the output format */
1168 char *pnew; /* pointer to available byte in output format */
Georg Brandl4ddfcd32006-09-30 11:17:34 +00001169 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001170 exclusive of trailing \0 */
Georg Brandl4ddfcd32006-09-30 11:17:34 +00001171 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001172
1173 char *ptoappend; /* pointer to string to append to output buffer */
1174 int ntoappend; /* # of bytes to append to output buffer */
1175
Tim Peters2a799bf2002-12-16 20:18:38 +00001176 assert(object && format && timetuple);
1177 assert(PyString_Check(format));
1178
Tim Petersd6844152002-12-22 20:58:42 +00001179 /* Give up if the year is before 1900.
1180 * Python strftime() plays games with the year, and different
1181 * games depending on whether envar PYTHON2K is set. This makes
1182 * years before 1900 a nightmare, even if the platform strftime
1183 * supports them (and not all do).
1184 * We could get a lot farther here by avoiding Python's strftime
1185 * wrapper and calling the C strftime() directly, but that isn't
1186 * an option in the Python implementation of this module.
1187 */
1188 {
1189 long year;
1190 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1191 if (pyyear == NULL) return NULL;
1192 assert(PyInt_Check(pyyear));
1193 year = PyInt_AsLong(pyyear);
1194 Py_DECREF(pyyear);
1195 if (year < 1900) {
1196 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1197 "1900; the datetime strftime() "
1198 "methods require year >= 1900",
1199 year);
1200 return NULL;
1201 }
1202 }
1203
Skip Montanarofc070d22008-03-15 16:04:45 +00001204 /* Scan the input format, looking for %z/%Z/%f escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001205 * a new format. Since computing the replacements for those codes
1206 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001207 */
Skip Montanarofc070d22008-03-15 16:04:45 +00001208 totalnew = PyString_Size(format) + 1; /* realistic if no %z/%Z/%f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001209 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1210 if (newfmt == NULL) goto Done;
1211 pnew = PyString_AsString(newfmt);
1212 usednew = 0;
1213
1214 pin = PyString_AsString(format);
1215 while ((ch = *pin++) != '\0') {
1216 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001217 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001218 ntoappend = 1;
1219 }
1220 else if ((ch = *pin++) == '\0') {
1221 /* There's a lone trailing %; doesn't make sense. */
1222 PyErr_SetString(PyExc_ValueError, "strftime format "
1223 "ends with raw %");
1224 goto Done;
1225 }
1226 /* A % has been seen and ch is the character after it. */
1227 else if (ch == 'z') {
1228 if (zreplacement == NULL) {
1229 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001230 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001231 PyObject *tzinfo = get_tzinfo_member(object);
1232 zreplacement = PyString_FromString("");
1233 if (zreplacement == NULL) goto Done;
1234 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001235 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001236 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001237 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001238 "",
1239 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001240 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001241 goto Done;
1242 Py_DECREF(zreplacement);
1243 zreplacement = PyString_FromString(buf);
1244 if (zreplacement == NULL) goto Done;
1245 }
1246 }
1247 assert(zreplacement != NULL);
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001248 ptoappend = PyString_AS_STRING(zreplacement);
1249 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001250 }
1251 else if (ch == 'Z') {
1252 /* format tzname */
1253 if (Zreplacement == NULL) {
1254 PyObject *tzinfo = get_tzinfo_member(object);
1255 Zreplacement = PyString_FromString("");
1256 if (Zreplacement == NULL) goto Done;
1257 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001258 PyObject *temp;
1259 assert(tzinfoarg != NULL);
1260 temp = call_tzname(tzinfo, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001261 if (temp == NULL) goto Done;
1262 if (temp != Py_None) {
1263 assert(PyString_Check(temp));
1264 /* Since the tzname is getting
1265 * stuffed into the format, we
1266 * have to double any % signs
1267 * so that strftime doesn't
1268 * treat them as format codes.
1269 */
1270 Py_DECREF(Zreplacement);
1271 Zreplacement = PyObject_CallMethod(
1272 temp, "replace",
1273 "ss", "%", "%%");
1274 Py_DECREF(temp);
1275 if (Zreplacement == NULL)
1276 goto Done;
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001277 if (!PyString_Check(Zreplacement)) {
1278 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1279 goto Done;
1280 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001281 }
1282 else
1283 Py_DECREF(temp);
1284 }
1285 }
1286 assert(Zreplacement != NULL);
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001287 ptoappend = PyString_AS_STRING(Zreplacement);
1288 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001289 }
Skip Montanarofc070d22008-03-15 16:04:45 +00001290 else if (ch == 'f') {
1291 /* format microseconds */
1292 if (freplacement == NULL) {
1293 freplacement = make_freplacement(object);
1294 if (freplacement == NULL)
1295 goto Done;
1296 }
1297 assert(freplacement != NULL);
1298 assert(PyString_Check(freplacement));
1299 ptoappend = PyString_AS_STRING(freplacement);
1300 ntoappend = PyString_GET_SIZE(freplacement);
1301 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001302 else {
Tim Peters328fff72002-12-20 01:31:27 +00001303 /* percent followed by neither z nor Z */
1304 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001305 ntoappend = 2;
1306 }
1307
1308 /* Append the ntoappend chars starting at ptoappend to
1309 * the new format.
1310 */
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001311 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001312 assert(ntoappend >= 0);
1313 if (ntoappend == 0)
1314 continue;
1315 while (usednew + ntoappend > totalnew) {
1316 int bigger = totalnew << 1;
1317 if ((bigger >> 1) != totalnew) { /* overflow */
1318 PyErr_NoMemory();
1319 goto Done;
1320 }
1321 if (_PyString_Resize(&newfmt, bigger) < 0)
1322 goto Done;
1323 totalnew = bigger;
1324 pnew = PyString_AsString(newfmt) + usednew;
1325 }
1326 memcpy(pnew, ptoappend, ntoappend);
1327 pnew += ntoappend;
1328 usednew += ntoappend;
1329 assert(usednew <= totalnew);
1330 } /* end while() */
1331
1332 if (_PyString_Resize(&newfmt, usednew) < 0)
1333 goto Done;
1334 {
Christian Heimes000a0742008-01-03 22:16:32 +00001335 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001336 if (time == NULL)
1337 goto Done;
1338 result = PyObject_CallMethod(time, "strftime", "OO",
1339 newfmt, timetuple);
1340 Py_DECREF(time);
1341 }
1342 Done:
Skip Montanarofc070d22008-03-15 16:04:45 +00001343 Py_XDECREF(freplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001344 Py_XDECREF(zreplacement);
1345 Py_XDECREF(Zreplacement);
1346 Py_XDECREF(newfmt);
1347 return result;
1348}
1349
1350static char *
1351isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1352{
1353 int x;
1354 x = PyOS_snprintf(buffer, bufflen,
1355 "%04d-%02d-%02d",
1356 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1357 return buffer + x;
1358}
1359
1360static void
1361isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1362{
1363 int us = DATE_GET_MICROSECOND(dt);
1364
1365 PyOS_snprintf(buffer, bufflen,
1366 "%02d:%02d:%02d", /* 8 characters */
1367 DATE_GET_HOUR(dt),
1368 DATE_GET_MINUTE(dt),
1369 DATE_GET_SECOND(dt));
1370 if (us)
1371 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1372}
1373
1374/* ---------------------------------------------------------------------------
1375 * Wrap functions from the time module. These aren't directly available
1376 * from C. Perhaps they should be.
1377 */
1378
1379/* Call time.time() and return its result (a Python float). */
1380static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001381time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001382{
1383 PyObject *result = NULL;
Christian Heimes000a0742008-01-03 22:16:32 +00001384 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001385
1386 if (time != NULL) {
1387 result = PyObject_CallMethod(time, "time", "()");
1388 Py_DECREF(time);
1389 }
1390 return result;
1391}
1392
1393/* Build a time.struct_time. The weekday and day number are automatically
1394 * computed from the y,m,d args.
1395 */
1396static PyObject *
1397build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1398{
1399 PyObject *time;
1400 PyObject *result = NULL;
1401
Christian Heimes000a0742008-01-03 22:16:32 +00001402 time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001403 if (time != NULL) {
1404 result = PyObject_CallMethod(time, "struct_time",
1405 "((iiiiiiiii))",
1406 y, m, d,
1407 hh, mm, ss,
1408 weekday(y, m, d),
1409 days_before_month(y, m) + d,
1410 dstflag);
1411 Py_DECREF(time);
1412 }
1413 return result;
1414}
1415
1416/* ---------------------------------------------------------------------------
1417 * Miscellaneous helpers.
1418 */
1419
1420/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1421 * The comparisons here all most naturally compute a cmp()-like result.
1422 * This little helper turns that into a bool result for rich comparisons.
1423 */
1424static PyObject *
1425diff_to_bool(int diff, int op)
1426{
1427 PyObject *result;
1428 int istrue;
1429
1430 switch (op) {
1431 case Py_EQ: istrue = diff == 0; break;
1432 case Py_NE: istrue = diff != 0; break;
1433 case Py_LE: istrue = diff <= 0; break;
1434 case Py_GE: istrue = diff >= 0; break;
1435 case Py_LT: istrue = diff < 0; break;
1436 case Py_GT: istrue = diff > 0; break;
1437 default:
1438 assert(! "op unknown");
1439 istrue = 0; /* To shut up compiler */
1440 }
1441 result = istrue ? Py_True : Py_False;
1442 Py_INCREF(result);
1443 return result;
1444}
1445
Tim Peters07534a62003-02-07 22:50:28 +00001446/* Raises a "can't compare" TypeError and returns NULL. */
1447static PyObject *
1448cmperror(PyObject *a, PyObject *b)
1449{
1450 PyErr_Format(PyExc_TypeError,
1451 "can't compare %s to %s",
Christian Heimese93237d2007-12-19 02:37:44 +00001452 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001453 return NULL;
1454}
1455
Tim Peters2a799bf2002-12-16 20:18:38 +00001456/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001457 * Cached Python objects; these are set by the module init function.
1458 */
1459
1460/* Conversion factors. */
1461static PyObject *us_per_us = NULL; /* 1 */
1462static PyObject *us_per_ms = NULL; /* 1000 */
1463static PyObject *us_per_second = NULL; /* 1000000 */
1464static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1465static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1466static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1467static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1468static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1469
Tim Peters2a799bf2002-12-16 20:18:38 +00001470/* ---------------------------------------------------------------------------
1471 * Class implementations.
1472 */
1473
1474/*
1475 * PyDateTime_Delta implementation.
1476 */
1477
1478/* Convert a timedelta to a number of us,
1479 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1480 * as a Python int or long.
1481 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1482 * due to ubiquitous overflow possibilities.
1483 */
1484static PyObject *
1485delta_to_microseconds(PyDateTime_Delta *self)
1486{
1487 PyObject *x1 = NULL;
1488 PyObject *x2 = NULL;
1489 PyObject *x3 = NULL;
1490 PyObject *result = NULL;
1491
1492 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1493 if (x1 == NULL)
1494 goto Done;
1495 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1496 if (x2 == NULL)
1497 goto Done;
1498 Py_DECREF(x1);
1499 x1 = NULL;
1500
1501 /* x2 has days in seconds */
1502 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1503 if (x1 == NULL)
1504 goto Done;
1505 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1506 if (x3 == NULL)
1507 goto Done;
1508 Py_DECREF(x1);
1509 Py_DECREF(x2);
1510 x1 = x2 = NULL;
1511
1512 /* x3 has days+seconds in seconds */
1513 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1514 if (x1 == NULL)
1515 goto Done;
1516 Py_DECREF(x3);
1517 x3 = NULL;
1518
1519 /* x1 has days+seconds in us */
1520 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1521 if (x2 == NULL)
1522 goto Done;
1523 result = PyNumber_Add(x1, x2);
1524
1525Done:
1526 Py_XDECREF(x1);
1527 Py_XDECREF(x2);
1528 Py_XDECREF(x3);
1529 return result;
1530}
1531
1532/* Convert a number of us (as a Python int or long) to a timedelta.
1533 */
1534static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001535microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001536{
1537 int us;
1538 int s;
1539 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001540 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001541
1542 PyObject *tuple = NULL;
1543 PyObject *num = NULL;
1544 PyObject *result = NULL;
1545
1546 tuple = PyNumber_Divmod(pyus, us_per_second);
1547 if (tuple == NULL)
1548 goto Done;
1549
1550 num = PyTuple_GetItem(tuple, 1); /* us */
1551 if (num == NULL)
1552 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001553 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001554 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001555 if (temp == -1 && PyErr_Occurred())
1556 goto Done;
1557 assert(0 <= temp && temp < 1000000);
1558 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001559 if (us < 0) {
1560 /* The divisor was positive, so this must be an error. */
1561 assert(PyErr_Occurred());
1562 goto Done;
1563 }
1564
1565 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1566 if (num == NULL)
1567 goto Done;
1568 Py_INCREF(num);
1569 Py_DECREF(tuple);
1570
1571 tuple = PyNumber_Divmod(num, seconds_per_day);
1572 if (tuple == NULL)
1573 goto Done;
1574 Py_DECREF(num);
1575
1576 num = PyTuple_GetItem(tuple, 1); /* seconds */
1577 if (num == NULL)
1578 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001579 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001580 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001581 if (temp == -1 && PyErr_Occurred())
1582 goto Done;
1583 assert(0 <= temp && temp < 24*3600);
1584 s = (int)temp;
1585
Tim Peters2a799bf2002-12-16 20:18:38 +00001586 if (s < 0) {
1587 /* The divisor was positive, so this must be an error. */
1588 assert(PyErr_Occurred());
1589 goto Done;
1590 }
1591
1592 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1593 if (num == NULL)
1594 goto Done;
1595 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001596 temp = PyLong_AsLong(num);
1597 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001598 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001599 d = (int)temp;
1600 if ((long)d != temp) {
1601 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1602 "large to fit in a C int");
1603 goto Done;
1604 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001605 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001606
1607Done:
1608 Py_XDECREF(tuple);
1609 Py_XDECREF(num);
1610 return result;
1611}
1612
Tim Petersb0c854d2003-05-17 15:57:00 +00001613#define microseconds_to_delta(pymicros) \
1614 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1615
Tim Peters2a799bf2002-12-16 20:18:38 +00001616static PyObject *
1617multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1618{
1619 PyObject *pyus_in;
1620 PyObject *pyus_out;
1621 PyObject *result;
1622
1623 pyus_in = delta_to_microseconds(delta);
1624 if (pyus_in == NULL)
1625 return NULL;
1626
1627 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1628 Py_DECREF(pyus_in);
1629 if (pyus_out == NULL)
1630 return NULL;
1631
1632 result = microseconds_to_delta(pyus_out);
1633 Py_DECREF(pyus_out);
1634 return result;
1635}
1636
1637static PyObject *
1638divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1639{
1640 PyObject *pyus_in;
1641 PyObject *pyus_out;
1642 PyObject *result;
1643
1644 pyus_in = delta_to_microseconds(delta);
1645 if (pyus_in == NULL)
1646 return NULL;
1647
1648 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1649 Py_DECREF(pyus_in);
1650 if (pyus_out == NULL)
1651 return NULL;
1652
1653 result = microseconds_to_delta(pyus_out);
1654 Py_DECREF(pyus_out);
1655 return result;
1656}
1657
1658static PyObject *
1659delta_add(PyObject *left, PyObject *right)
1660{
1661 PyObject *result = Py_NotImplemented;
1662
1663 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1664 /* delta + delta */
1665 /* The C-level additions can't overflow because of the
1666 * invariant bounds.
1667 */
1668 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1669 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1670 int microseconds = GET_TD_MICROSECONDS(left) +
1671 GET_TD_MICROSECONDS(right);
1672 result = new_delta(days, seconds, microseconds, 1);
1673 }
1674
1675 if (result == Py_NotImplemented)
1676 Py_INCREF(result);
1677 return result;
1678}
1679
1680static PyObject *
1681delta_negative(PyDateTime_Delta *self)
1682{
1683 return new_delta(-GET_TD_DAYS(self),
1684 -GET_TD_SECONDS(self),
1685 -GET_TD_MICROSECONDS(self),
1686 1);
1687}
1688
1689static PyObject *
1690delta_positive(PyDateTime_Delta *self)
1691{
1692 /* Could optimize this (by returning self) if this isn't a
1693 * subclass -- but who uses unary + ? Approximately nobody.
1694 */
1695 return new_delta(GET_TD_DAYS(self),
1696 GET_TD_SECONDS(self),
1697 GET_TD_MICROSECONDS(self),
1698 0);
1699}
1700
1701static PyObject *
1702delta_abs(PyDateTime_Delta *self)
1703{
1704 PyObject *result;
1705
1706 assert(GET_TD_MICROSECONDS(self) >= 0);
1707 assert(GET_TD_SECONDS(self) >= 0);
1708
1709 if (GET_TD_DAYS(self) < 0)
1710 result = delta_negative(self);
1711 else
1712 result = delta_positive(self);
1713
1714 return result;
1715}
1716
1717static PyObject *
1718delta_subtract(PyObject *left, PyObject *right)
1719{
1720 PyObject *result = Py_NotImplemented;
1721
1722 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1723 /* delta - delta */
1724 PyObject *minus_right = PyNumber_Negative(right);
1725 if (minus_right) {
1726 result = delta_add(left, minus_right);
1727 Py_DECREF(minus_right);
1728 }
1729 else
1730 result = NULL;
1731 }
1732
1733 if (result == Py_NotImplemented)
1734 Py_INCREF(result);
1735 return result;
1736}
1737
1738/* This is more natural as a tp_compare, but doesn't work then: for whatever
1739 * reason, Python's try_3way_compare ignores tp_compare unless
1740 * PyInstance_Check returns true, but these aren't old-style classes.
1741 */
1742static PyObject *
1743delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1744{
Tim Peters07534a62003-02-07 22:50:28 +00001745 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00001746
Tim Petersaa7d8492003-02-08 03:28:59 +00001747 if (PyDelta_Check(other)) {
Tim Peters07534a62003-02-07 22:50:28 +00001748 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1749 if (diff == 0) {
1750 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1751 if (diff == 0)
1752 diff = GET_TD_MICROSECONDS(self) -
1753 GET_TD_MICROSECONDS(other);
1754 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001755 }
Tim Peters07534a62003-02-07 22:50:28 +00001756 else if (op == Py_EQ || op == Py_NE)
1757 diff = 1; /* any non-zero value will do */
1758
1759 else /* stop this from falling back to address comparison */
1760 return cmperror((PyObject *)self, other);
1761
Tim Peters2a799bf2002-12-16 20:18:38 +00001762 return diff_to_bool(diff, op);
1763}
1764
1765static PyObject *delta_getstate(PyDateTime_Delta *self);
1766
1767static long
1768delta_hash(PyDateTime_Delta *self)
1769{
1770 if (self->hashcode == -1) {
1771 PyObject *temp = delta_getstate(self);
1772 if (temp != NULL) {
1773 self->hashcode = PyObject_Hash(temp);
1774 Py_DECREF(temp);
1775 }
1776 }
1777 return self->hashcode;
1778}
1779
1780static PyObject *
1781delta_multiply(PyObject *left, PyObject *right)
1782{
1783 PyObject *result = Py_NotImplemented;
1784
1785 if (PyDelta_Check(left)) {
1786 /* delta * ??? */
1787 if (PyInt_Check(right) || PyLong_Check(right))
1788 result = multiply_int_timedelta(right,
1789 (PyDateTime_Delta *) left);
1790 }
1791 else if (PyInt_Check(left) || PyLong_Check(left))
1792 result = multiply_int_timedelta(left,
1793 (PyDateTime_Delta *) right);
1794
1795 if (result == Py_NotImplemented)
1796 Py_INCREF(result);
1797 return result;
1798}
1799
1800static PyObject *
1801delta_divide(PyObject *left, PyObject *right)
1802{
1803 PyObject *result = Py_NotImplemented;
1804
1805 if (PyDelta_Check(left)) {
1806 /* delta * ??? */
1807 if (PyInt_Check(right) || PyLong_Check(right))
1808 result = divide_timedelta_int(
1809 (PyDateTime_Delta *)left,
1810 right);
1811 }
1812
1813 if (result == Py_NotImplemented)
1814 Py_INCREF(result);
1815 return result;
1816}
1817
1818/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1819 * timedelta constructor. sofar is the # of microseconds accounted for
1820 * so far, and there are factor microseconds per current unit, the number
1821 * of which is given by num. num * factor is added to sofar in a
1822 * numerically careful way, and that's the result. Any fractional
1823 * microseconds left over (this can happen if num is a float type) are
1824 * added into *leftover.
1825 * Note that there are many ways this can give an error (NULL) return.
1826 */
1827static PyObject *
1828accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1829 double *leftover)
1830{
1831 PyObject *prod;
1832 PyObject *sum;
1833
1834 assert(num != NULL);
1835
1836 if (PyInt_Check(num) || PyLong_Check(num)) {
1837 prod = PyNumber_Multiply(num, factor);
1838 if (prod == NULL)
1839 return NULL;
1840 sum = PyNumber_Add(sofar, prod);
1841 Py_DECREF(prod);
1842 return sum;
1843 }
1844
1845 if (PyFloat_Check(num)) {
1846 double dnum;
1847 double fracpart;
1848 double intpart;
1849 PyObject *x;
1850 PyObject *y;
1851
1852 /* The Plan: decompose num into an integer part and a
1853 * fractional part, num = intpart + fracpart.
1854 * Then num * factor ==
1855 * intpart * factor + fracpart * factor
1856 * and the LHS can be computed exactly in long arithmetic.
1857 * The RHS is again broken into an int part and frac part.
1858 * and the frac part is added into *leftover.
1859 */
1860 dnum = PyFloat_AsDouble(num);
1861 if (dnum == -1.0 && PyErr_Occurred())
1862 return NULL;
1863 fracpart = modf(dnum, &intpart);
1864 x = PyLong_FromDouble(intpart);
1865 if (x == NULL)
1866 return NULL;
1867
1868 prod = PyNumber_Multiply(x, factor);
1869 Py_DECREF(x);
1870 if (prod == NULL)
1871 return NULL;
1872
1873 sum = PyNumber_Add(sofar, prod);
1874 Py_DECREF(prod);
1875 if (sum == NULL)
1876 return NULL;
1877
1878 if (fracpart == 0.0)
1879 return sum;
1880 /* So far we've lost no information. Dealing with the
1881 * fractional part requires float arithmetic, and may
1882 * lose a little info.
1883 */
1884 assert(PyInt_Check(factor) || PyLong_Check(factor));
1885 if (PyInt_Check(factor))
1886 dnum = (double)PyInt_AsLong(factor);
1887 else
1888 dnum = PyLong_AsDouble(factor);
1889
1890 dnum *= fracpart;
1891 fracpart = modf(dnum, &intpart);
1892 x = PyLong_FromDouble(intpart);
1893 if (x == NULL) {
1894 Py_DECREF(sum);
1895 return NULL;
1896 }
1897
1898 y = PyNumber_Add(sum, x);
1899 Py_DECREF(sum);
1900 Py_DECREF(x);
1901 *leftover += fracpart;
1902 return y;
1903 }
1904
1905 PyErr_Format(PyExc_TypeError,
1906 "unsupported type for timedelta %s component: %s",
Christian Heimese93237d2007-12-19 02:37:44 +00001907 tag, Py_TYPE(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001908 return NULL;
1909}
1910
1911static PyObject *
1912delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1913{
1914 PyObject *self = NULL;
1915
1916 /* Argument objects. */
1917 PyObject *day = NULL;
1918 PyObject *second = NULL;
1919 PyObject *us = NULL;
1920 PyObject *ms = NULL;
1921 PyObject *minute = NULL;
1922 PyObject *hour = NULL;
1923 PyObject *week = NULL;
1924
1925 PyObject *x = NULL; /* running sum of microseconds */
1926 PyObject *y = NULL; /* temp sum of microseconds */
1927 double leftover_us = 0.0;
1928
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001929 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001930 "days", "seconds", "microseconds", "milliseconds",
1931 "minutes", "hours", "weeks", NULL
1932 };
1933
1934 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1935 keywords,
1936 &day, &second, &us,
1937 &ms, &minute, &hour, &week) == 0)
1938 goto Done;
1939
1940 x = PyInt_FromLong(0);
1941 if (x == NULL)
1942 goto Done;
1943
1944#define CLEANUP \
1945 Py_DECREF(x); \
1946 x = y; \
1947 if (x == NULL) \
1948 goto Done
1949
1950 if (us) {
1951 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1952 CLEANUP;
1953 }
1954 if (ms) {
1955 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1956 CLEANUP;
1957 }
1958 if (second) {
1959 y = accum("seconds", x, second, us_per_second, &leftover_us);
1960 CLEANUP;
1961 }
1962 if (minute) {
1963 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1964 CLEANUP;
1965 }
1966 if (hour) {
1967 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1968 CLEANUP;
1969 }
1970 if (day) {
1971 y = accum("days", x, day, us_per_day, &leftover_us);
1972 CLEANUP;
1973 }
1974 if (week) {
1975 y = accum("weeks", x, week, us_per_week, &leftover_us);
1976 CLEANUP;
1977 }
1978 if (leftover_us) {
1979 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001980 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001981 if (temp == NULL) {
1982 Py_DECREF(x);
1983 goto Done;
1984 }
1985 y = PyNumber_Add(x, temp);
1986 Py_DECREF(temp);
1987 CLEANUP;
1988 }
1989
Tim Petersb0c854d2003-05-17 15:57:00 +00001990 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001991 Py_DECREF(x);
1992Done:
1993 return self;
1994
1995#undef CLEANUP
1996}
1997
1998static int
1999delta_nonzero(PyDateTime_Delta *self)
2000{
2001 return (GET_TD_DAYS(self) != 0
2002 || GET_TD_SECONDS(self) != 0
2003 || GET_TD_MICROSECONDS(self) != 0);
2004}
2005
2006static PyObject *
2007delta_repr(PyDateTime_Delta *self)
2008{
2009 if (GET_TD_MICROSECONDS(self) != 0)
2010 return PyString_FromFormat("%s(%d, %d, %d)",
Christian Heimese93237d2007-12-19 02:37:44 +00002011 Py_TYPE(self)->tp_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002012 GET_TD_DAYS(self),
2013 GET_TD_SECONDS(self),
2014 GET_TD_MICROSECONDS(self));
2015 if (GET_TD_SECONDS(self) != 0)
2016 return PyString_FromFormat("%s(%d, %d)",
Christian Heimese93237d2007-12-19 02:37:44 +00002017 Py_TYPE(self)->tp_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002018 GET_TD_DAYS(self),
2019 GET_TD_SECONDS(self));
2020
2021 return PyString_FromFormat("%s(%d)",
Christian Heimese93237d2007-12-19 02:37:44 +00002022 Py_TYPE(self)->tp_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002023 GET_TD_DAYS(self));
2024}
2025
2026static PyObject *
2027delta_str(PyDateTime_Delta *self)
2028{
2029 int days = GET_TD_DAYS(self);
2030 int seconds = GET_TD_SECONDS(self);
2031 int us = GET_TD_MICROSECONDS(self);
2032 int hours;
2033 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00002034 char buf[100];
2035 char *pbuf = buf;
2036 size_t buflen = sizeof(buf);
2037 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002038
2039 minutes = divmod(seconds, 60, &seconds);
2040 hours = divmod(minutes, 60, &minutes);
2041
2042 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002043 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2044 (days == 1 || days == -1) ? "" : "s");
2045 if (n < 0 || (size_t)n >= buflen)
2046 goto Fail;
2047 pbuf += n;
2048 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002049 }
2050
Tim Petersba873472002-12-18 20:19:21 +00002051 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2052 hours, minutes, seconds);
2053 if (n < 0 || (size_t)n >= buflen)
2054 goto Fail;
2055 pbuf += n;
2056 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002057
2058 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002059 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2060 if (n < 0 || (size_t)n >= buflen)
2061 goto Fail;
2062 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002063 }
2064
Tim Petersba873472002-12-18 20:19:21 +00002065 return PyString_FromStringAndSize(buf, pbuf - buf);
2066
2067 Fail:
2068 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2069 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002070}
2071
Tim Peters371935f2003-02-01 01:52:50 +00002072/* Pickle support, a simple use of __reduce__. */
2073
Tim Petersb57f8f02003-02-01 02:54:15 +00002074/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002075static PyObject *
2076delta_getstate(PyDateTime_Delta *self)
2077{
2078 return Py_BuildValue("iii", GET_TD_DAYS(self),
2079 GET_TD_SECONDS(self),
2080 GET_TD_MICROSECONDS(self));
2081}
2082
Tim Peters2a799bf2002-12-16 20:18:38 +00002083static PyObject *
2084delta_reduce(PyDateTime_Delta* self)
2085{
Christian Heimese93237d2007-12-19 02:37:44 +00002086 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002087}
2088
2089#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2090
2091static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002092
Neal Norwitzdfb80862002-12-19 02:30:56 +00002093 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002094 PyDoc_STR("Number of days.")},
2095
Neal Norwitzdfb80862002-12-19 02:30:56 +00002096 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002097 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2098
Neal Norwitzdfb80862002-12-19 02:30:56 +00002099 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002100 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2101 {NULL}
2102};
2103
2104static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002105 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2106 PyDoc_STR("__reduce__() -> (cls, state)")},
2107
Tim Peters2a799bf2002-12-16 20:18:38 +00002108 {NULL, NULL},
2109};
2110
2111static char delta_doc[] =
2112PyDoc_STR("Difference between two datetime values.");
2113
2114static PyNumberMethods delta_as_number = {
2115 delta_add, /* nb_add */
2116 delta_subtract, /* nb_subtract */
2117 delta_multiply, /* nb_multiply */
2118 delta_divide, /* nb_divide */
2119 0, /* nb_remainder */
2120 0, /* nb_divmod */
2121 0, /* nb_power */
2122 (unaryfunc)delta_negative, /* nb_negative */
2123 (unaryfunc)delta_positive, /* nb_positive */
2124 (unaryfunc)delta_abs, /* nb_absolute */
2125 (inquiry)delta_nonzero, /* nb_nonzero */
2126 0, /*nb_invert*/
2127 0, /*nb_lshift*/
2128 0, /*nb_rshift*/
2129 0, /*nb_and*/
2130 0, /*nb_xor*/
2131 0, /*nb_or*/
2132 0, /*nb_coerce*/
2133 0, /*nb_int*/
2134 0, /*nb_long*/
2135 0, /*nb_float*/
2136 0, /*nb_oct*/
2137 0, /*nb_hex*/
2138 0, /*nb_inplace_add*/
2139 0, /*nb_inplace_subtract*/
2140 0, /*nb_inplace_multiply*/
2141 0, /*nb_inplace_divide*/
2142 0, /*nb_inplace_remainder*/
2143 0, /*nb_inplace_power*/
2144 0, /*nb_inplace_lshift*/
2145 0, /*nb_inplace_rshift*/
2146 0, /*nb_inplace_and*/
2147 0, /*nb_inplace_xor*/
2148 0, /*nb_inplace_or*/
2149 delta_divide, /* nb_floor_divide */
2150 0, /* nb_true_divide */
2151 0, /* nb_inplace_floor_divide */
2152 0, /* nb_inplace_true_divide */
2153};
2154
2155static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002156 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002157 "datetime.timedelta", /* tp_name */
2158 sizeof(PyDateTime_Delta), /* tp_basicsize */
2159 0, /* tp_itemsize */
2160 0, /* tp_dealloc */
2161 0, /* tp_print */
2162 0, /* tp_getattr */
2163 0, /* tp_setattr */
2164 0, /* tp_compare */
2165 (reprfunc)delta_repr, /* tp_repr */
2166 &delta_as_number, /* tp_as_number */
2167 0, /* tp_as_sequence */
2168 0, /* tp_as_mapping */
2169 (hashfunc)delta_hash, /* tp_hash */
2170 0, /* tp_call */
2171 (reprfunc)delta_str, /* tp_str */
2172 PyObject_GenericGetAttr, /* tp_getattro */
2173 0, /* tp_setattro */
2174 0, /* tp_as_buffer */
Tim Petersb0c854d2003-05-17 15:57:00 +00002175 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2176 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002177 delta_doc, /* tp_doc */
2178 0, /* tp_traverse */
2179 0, /* tp_clear */
2180 (richcmpfunc)delta_richcompare, /* tp_richcompare */
2181 0, /* tp_weaklistoffset */
2182 0, /* tp_iter */
2183 0, /* tp_iternext */
2184 delta_methods, /* tp_methods */
2185 delta_members, /* tp_members */
2186 0, /* tp_getset */
2187 0, /* tp_base */
2188 0, /* tp_dict */
2189 0, /* tp_descr_get */
2190 0, /* tp_descr_set */
2191 0, /* tp_dictoffset */
2192 0, /* tp_init */
2193 0, /* tp_alloc */
2194 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002195 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002196};
2197
2198/*
2199 * PyDateTime_Date implementation.
2200 */
2201
2202/* Accessor properties. */
2203
2204static PyObject *
2205date_year(PyDateTime_Date *self, void *unused)
2206{
2207 return PyInt_FromLong(GET_YEAR(self));
2208}
2209
2210static PyObject *
2211date_month(PyDateTime_Date *self, void *unused)
2212{
2213 return PyInt_FromLong(GET_MONTH(self));
2214}
2215
2216static PyObject *
2217date_day(PyDateTime_Date *self, void *unused)
2218{
2219 return PyInt_FromLong(GET_DAY(self));
2220}
2221
2222static PyGetSetDef date_getset[] = {
2223 {"year", (getter)date_year},
2224 {"month", (getter)date_month},
2225 {"day", (getter)date_day},
2226 {NULL}
2227};
2228
2229/* Constructors. */
2230
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002231static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002232
Tim Peters2a799bf2002-12-16 20:18:38 +00002233static PyObject *
2234date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2235{
2236 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002237 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002238 int year;
2239 int month;
2240 int day;
2241
Guido van Rossum177e41a2003-01-30 22:06:23 +00002242 /* Check for invocation from pickle with __getstate__ state */
2243 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002244 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002245 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2246 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002247 {
Tim Peters70533e22003-02-01 04:40:04 +00002248 PyDateTime_Date *me;
2249
Tim Peters604c0132004-06-07 23:04:33 +00002250 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002251 if (me != NULL) {
2252 char *pdata = PyString_AS_STRING(state);
2253 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2254 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002255 }
Tim Peters70533e22003-02-01 04:40:04 +00002256 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002257 }
2258
Tim Peters12bf3392002-12-24 05:41:27 +00002259 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002260 &year, &month, &day)) {
2261 if (check_date_args(year, month, day) < 0)
2262 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002263 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002264 }
2265 return self;
2266}
2267
2268/* Return new date from localtime(t). */
2269static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002270date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002271{
2272 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002273 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002274 PyObject *result = NULL;
2275
Tim Peters1b6f7a92004-06-20 02:50:16 +00002276 t = _PyTime_DoubleToTimet(ts);
2277 if (t == (time_t)-1 && PyErr_Occurred())
2278 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002279 tm = localtime(&t);
2280 if (tm)
2281 result = PyObject_CallFunction(cls, "iii",
2282 tm->tm_year + 1900,
2283 tm->tm_mon + 1,
2284 tm->tm_mday);
2285 else
2286 PyErr_SetString(PyExc_ValueError,
2287 "timestamp out of range for "
2288 "platform localtime() function");
2289 return result;
2290}
2291
2292/* Return new date from current time.
2293 * We say this is equivalent to fromtimestamp(time.time()), and the
2294 * only way to be sure of that is to *call* time.time(). That's not
2295 * generally the same as calling C's time.
2296 */
2297static PyObject *
2298date_today(PyObject *cls, PyObject *dummy)
2299{
2300 PyObject *time;
2301 PyObject *result;
2302
2303 time = time_time();
2304 if (time == NULL)
2305 return NULL;
2306
2307 /* Note well: today() is a class method, so this may not call
2308 * date.fromtimestamp. For example, it may call
2309 * datetime.fromtimestamp. That's why we need all the accuracy
2310 * time.time() delivers; if someone were gonzo about optimization,
2311 * date.today() could get away with plain C time().
2312 */
2313 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2314 Py_DECREF(time);
2315 return result;
2316}
2317
2318/* Return new date from given timestamp (Python timestamp -- a double). */
2319static PyObject *
2320date_fromtimestamp(PyObject *cls, PyObject *args)
2321{
2322 double timestamp;
2323 PyObject *result = NULL;
2324
2325 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002326 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002327 return result;
2328}
2329
2330/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2331 * the ordinal is out of range.
2332 */
2333static PyObject *
2334date_fromordinal(PyObject *cls, PyObject *args)
2335{
2336 PyObject *result = NULL;
2337 int ordinal;
2338
2339 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2340 int year;
2341 int month;
2342 int day;
2343
2344 if (ordinal < 1)
2345 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2346 ">= 1");
2347 else {
2348 ord_to_ymd(ordinal, &year, &month, &day);
2349 result = PyObject_CallFunction(cls, "iii",
2350 year, month, day);
2351 }
2352 }
2353 return result;
2354}
2355
2356/*
2357 * Date arithmetic.
2358 */
2359
2360/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2361 * instead.
2362 */
2363static PyObject *
2364add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2365{
2366 PyObject *result = NULL;
2367 int year = GET_YEAR(date);
2368 int month = GET_MONTH(date);
2369 int deltadays = GET_TD_DAYS(delta);
2370 /* C-level overflow is impossible because |deltadays| < 1e9. */
2371 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2372
2373 if (normalize_date(&year, &month, &day) >= 0)
2374 result = new_date(year, month, day);
2375 return result;
2376}
2377
2378static PyObject *
2379date_add(PyObject *left, PyObject *right)
2380{
2381 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2382 Py_INCREF(Py_NotImplemented);
2383 return Py_NotImplemented;
2384 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002385 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002386 /* date + ??? */
2387 if (PyDelta_Check(right))
2388 /* date + delta */
2389 return add_date_timedelta((PyDateTime_Date *) left,
2390 (PyDateTime_Delta *) right,
2391 0);
2392 }
2393 else {
2394 /* ??? + date
2395 * 'right' must be one of us, or we wouldn't have been called
2396 */
2397 if (PyDelta_Check(left))
2398 /* delta + date */
2399 return add_date_timedelta((PyDateTime_Date *) right,
2400 (PyDateTime_Delta *) left,
2401 0);
2402 }
2403 Py_INCREF(Py_NotImplemented);
2404 return Py_NotImplemented;
2405}
2406
2407static PyObject *
2408date_subtract(PyObject *left, PyObject *right)
2409{
2410 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2411 Py_INCREF(Py_NotImplemented);
2412 return Py_NotImplemented;
2413 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002414 if (PyDate_Check(left)) {
2415 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002416 /* date - date */
2417 int left_ord = ymd_to_ord(GET_YEAR(left),
2418 GET_MONTH(left),
2419 GET_DAY(left));
2420 int right_ord = ymd_to_ord(GET_YEAR(right),
2421 GET_MONTH(right),
2422 GET_DAY(right));
2423 return new_delta(left_ord - right_ord, 0, 0, 0);
2424 }
2425 if (PyDelta_Check(right)) {
2426 /* date - delta */
2427 return add_date_timedelta((PyDateTime_Date *) left,
2428 (PyDateTime_Delta *) right,
2429 1);
2430 }
2431 }
2432 Py_INCREF(Py_NotImplemented);
2433 return Py_NotImplemented;
2434}
2435
2436
2437/* Various ways to turn a date into a string. */
2438
2439static PyObject *
2440date_repr(PyDateTime_Date *self)
2441{
2442 char buffer[1028];
Skip Montanaro14f88992006-04-18 19:35:04 +00002443 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002444
Christian Heimese93237d2007-12-19 02:37:44 +00002445 type_name = Py_TYPE(self)->tp_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002446 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00002447 type_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002448 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2449
2450 return PyString_FromString(buffer);
2451}
2452
2453static PyObject *
2454date_isoformat(PyDateTime_Date *self)
2455{
2456 char buffer[128];
2457
2458 isoformat_date(self, buffer, sizeof(buffer));
2459 return PyString_FromString(buffer);
2460}
2461
Tim Peterse2df5ff2003-05-02 18:39:55 +00002462/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002463static PyObject *
2464date_str(PyDateTime_Date *self)
2465{
2466 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2467}
2468
2469
2470static PyObject *
2471date_ctime(PyDateTime_Date *self)
2472{
2473 return format_ctime(self, 0, 0, 0);
2474}
2475
2476static PyObject *
2477date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2478{
2479 /* This method can be inherited, and needs to call the
2480 * timetuple() method appropriate to self's class.
2481 */
2482 PyObject *result;
2483 PyObject *format;
2484 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002485 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002486
2487 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2488 &PyString_Type, &format))
2489 return NULL;
2490
2491 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2492 if (tuple == NULL)
2493 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002494 result = wrap_strftime((PyObject *)self, format, tuple,
2495 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002496 Py_DECREF(tuple);
2497 return result;
2498}
2499
Eric Smitha9f7d622008-02-17 19:46:49 +00002500static PyObject *
2501date_format(PyDateTime_Date *self, PyObject *args)
2502{
2503 PyObject *format;
2504
2505 if (!PyArg_ParseTuple(args, "O:__format__", &format))
2506 return NULL;
2507
2508 /* Check for str or unicode */
2509 if (PyString_Check(format)) {
2510 /* If format is zero length, return str(self) */
2511 if (PyString_GET_SIZE(format) == 0)
2512 return PyObject_Str((PyObject *)self);
2513 } else if (PyUnicode_Check(format)) {
2514 /* If format is zero length, return str(self) */
2515 if (PyUnicode_GET_SIZE(format) == 0)
2516 return PyObject_Unicode((PyObject *)self);
2517 } else {
2518 PyErr_Format(PyExc_ValueError,
2519 "__format__ expects str or unicode, not %.200s",
2520 Py_TYPE(format)->tp_name);
2521 return NULL;
2522 }
2523 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
2524}
2525
Tim Peters2a799bf2002-12-16 20:18:38 +00002526/* ISO methods. */
2527
2528static PyObject *
2529date_isoweekday(PyDateTime_Date *self)
2530{
2531 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2532
2533 return PyInt_FromLong(dow + 1);
2534}
2535
2536static PyObject *
2537date_isocalendar(PyDateTime_Date *self)
2538{
2539 int year = GET_YEAR(self);
2540 int week1_monday = iso_week1_monday(year);
2541 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2542 int week;
2543 int day;
2544
2545 week = divmod(today - week1_monday, 7, &day);
2546 if (week < 0) {
2547 --year;
2548 week1_monday = iso_week1_monday(year);
2549 week = divmod(today - week1_monday, 7, &day);
2550 }
2551 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2552 ++year;
2553 week = 0;
2554 }
2555 return Py_BuildValue("iii", year, week + 1, day + 1);
2556}
2557
2558/* Miscellaneous methods. */
2559
2560/* This is more natural as a tp_compare, but doesn't work then: for whatever
2561 * reason, Python's try_3way_compare ignores tp_compare unless
2562 * PyInstance_Check returns true, but these aren't old-style classes.
2563 */
2564static PyObject *
2565date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2566{
Tim Peters07534a62003-02-07 22:50:28 +00002567 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00002568
Tim Peters07534a62003-02-07 22:50:28 +00002569 if (PyDate_Check(other))
2570 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2571 _PyDateTime_DATE_DATASIZE);
2572
2573 else if (PyObject_HasAttrString(other, "timetuple")) {
2574 /* A hook for other kinds of date objects. */
2575 Py_INCREF(Py_NotImplemented);
2576 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002577 }
Tim Peters07534a62003-02-07 22:50:28 +00002578 else if (op == Py_EQ || op == Py_NE)
2579 diff = 1; /* any non-zero value will do */
2580
2581 else /* stop this from falling back to address comparison */
2582 return cmperror((PyObject *)self, other);
2583
Tim Peters2a799bf2002-12-16 20:18:38 +00002584 return diff_to_bool(diff, op);
2585}
2586
2587static PyObject *
2588date_timetuple(PyDateTime_Date *self)
2589{
2590 return build_struct_time(GET_YEAR(self),
2591 GET_MONTH(self),
2592 GET_DAY(self),
2593 0, 0, 0, -1);
2594}
2595
Tim Peters12bf3392002-12-24 05:41:27 +00002596static PyObject *
2597date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2598{
2599 PyObject *clone;
2600 PyObject *tuple;
2601 int year = GET_YEAR(self);
2602 int month = GET_MONTH(self);
2603 int day = GET_DAY(self);
2604
2605 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2606 &year, &month, &day))
2607 return NULL;
2608 tuple = Py_BuildValue("iii", year, month, day);
2609 if (tuple == NULL)
2610 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002611 clone = date_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002612 Py_DECREF(tuple);
2613 return clone;
2614}
2615
Tim Peters2a799bf2002-12-16 20:18:38 +00002616static PyObject *date_getstate(PyDateTime_Date *self);
2617
2618static long
2619date_hash(PyDateTime_Date *self)
2620{
2621 if (self->hashcode == -1) {
2622 PyObject *temp = date_getstate(self);
2623 if (temp != NULL) {
2624 self->hashcode = PyObject_Hash(temp);
2625 Py_DECREF(temp);
2626 }
2627 }
2628 return self->hashcode;
2629}
2630
2631static PyObject *
2632date_toordinal(PyDateTime_Date *self)
2633{
2634 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2635 GET_DAY(self)));
2636}
2637
2638static PyObject *
2639date_weekday(PyDateTime_Date *self)
2640{
2641 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2642
2643 return PyInt_FromLong(dow);
2644}
2645
Tim Peters371935f2003-02-01 01:52:50 +00002646/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002647
Tim Petersb57f8f02003-02-01 02:54:15 +00002648/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002649static PyObject *
2650date_getstate(PyDateTime_Date *self)
2651{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002652 return Py_BuildValue(
2653 "(N)",
2654 PyString_FromStringAndSize((char *)self->data,
2655 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002656}
2657
2658static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002659date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002660{
Christian Heimese93237d2007-12-19 02:37:44 +00002661 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002662}
2663
2664static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002665
Tim Peters2a799bf2002-12-16 20:18:38 +00002666 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002667
Tim Peters2a799bf2002-12-16 20:18:38 +00002668 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2669 METH_CLASS,
2670 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2671 "time.time()).")},
2672
2673 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2674 METH_CLASS,
2675 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2676 "ordinal.")},
2677
2678 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2679 PyDoc_STR("Current date or datetime: same as "
2680 "self.__class__.fromtimestamp(time.time()).")},
2681
2682 /* Instance methods: */
2683
2684 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2685 PyDoc_STR("Return ctime() style string.")},
2686
Neal Norwitza84dcd72007-05-22 07:16:44 +00002687 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002688 PyDoc_STR("format -> strftime() style string.")},
2689
Eric Smitha9f7d622008-02-17 19:46:49 +00002690 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2691 PyDoc_STR("Formats self with strftime.")},
2692
Tim Peters2a799bf2002-12-16 20:18:38 +00002693 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2694 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2695
2696 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2697 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2698 "weekday.")},
2699
2700 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2701 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2702
2703 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2704 PyDoc_STR("Return the day of the week represented by the date.\n"
2705 "Monday == 1 ... Sunday == 7")},
2706
2707 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2708 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2709 "1 is day 1.")},
2710
2711 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2712 PyDoc_STR("Return the day of the week represented by the date.\n"
2713 "Monday == 0 ... Sunday == 6")},
2714
Neal Norwitza84dcd72007-05-22 07:16:44 +00002715 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002716 PyDoc_STR("Return date with new specified fields.")},
2717
Guido van Rossum177e41a2003-01-30 22:06:23 +00002718 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2719 PyDoc_STR("__reduce__() -> (cls, state)")},
2720
Tim Peters2a799bf2002-12-16 20:18:38 +00002721 {NULL, NULL}
2722};
2723
2724static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002725PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002726
2727static PyNumberMethods date_as_number = {
2728 date_add, /* nb_add */
2729 date_subtract, /* nb_subtract */
2730 0, /* nb_multiply */
2731 0, /* nb_divide */
2732 0, /* nb_remainder */
2733 0, /* nb_divmod */
2734 0, /* nb_power */
2735 0, /* nb_negative */
2736 0, /* nb_positive */
2737 0, /* nb_absolute */
2738 0, /* nb_nonzero */
2739};
2740
2741static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002742 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002743 "datetime.date", /* tp_name */
2744 sizeof(PyDateTime_Date), /* tp_basicsize */
2745 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002746 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002747 0, /* tp_print */
2748 0, /* tp_getattr */
2749 0, /* tp_setattr */
2750 0, /* tp_compare */
2751 (reprfunc)date_repr, /* tp_repr */
2752 &date_as_number, /* tp_as_number */
2753 0, /* tp_as_sequence */
2754 0, /* tp_as_mapping */
2755 (hashfunc)date_hash, /* tp_hash */
2756 0, /* tp_call */
2757 (reprfunc)date_str, /* tp_str */
2758 PyObject_GenericGetAttr, /* tp_getattro */
2759 0, /* tp_setattro */
2760 0, /* tp_as_buffer */
2761 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2762 Py_TPFLAGS_BASETYPE, /* tp_flags */
2763 date_doc, /* tp_doc */
2764 0, /* tp_traverse */
2765 0, /* tp_clear */
2766 (richcmpfunc)date_richcompare, /* tp_richcompare */
2767 0, /* tp_weaklistoffset */
2768 0, /* tp_iter */
2769 0, /* tp_iternext */
2770 date_methods, /* tp_methods */
2771 0, /* tp_members */
2772 date_getset, /* tp_getset */
2773 0, /* tp_base */
2774 0, /* tp_dict */
2775 0, /* tp_descr_get */
2776 0, /* tp_descr_set */
2777 0, /* tp_dictoffset */
2778 0, /* tp_init */
2779 0, /* tp_alloc */
2780 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002781 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002782};
2783
2784/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002785 * PyDateTime_TZInfo implementation.
2786 */
2787
2788/* This is a pure abstract base class, so doesn't do anything beyond
2789 * raising NotImplemented exceptions. Real tzinfo classes need
2790 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002791 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002792 * be subclasses of this tzinfo class, which is easy and quick to check).
2793 *
2794 * Note: For reasons having to do with pickling of subclasses, we have
2795 * to allow tzinfo objects to be instantiated. This wasn't an issue
2796 * in the Python implementation (__init__() could raise NotImplementedError
2797 * there without ill effect), but doing so in the C implementation hit a
2798 * brick wall.
2799 */
2800
2801static PyObject *
2802tzinfo_nogo(const char* methodname)
2803{
2804 PyErr_Format(PyExc_NotImplementedError,
2805 "a tzinfo subclass must implement %s()",
2806 methodname);
2807 return NULL;
2808}
2809
2810/* Methods. A subclass must implement these. */
2811
Tim Peters52dcce22003-01-23 16:36:11 +00002812static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002813tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2814{
2815 return tzinfo_nogo("tzname");
2816}
2817
Tim Peters52dcce22003-01-23 16:36:11 +00002818static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002819tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2820{
2821 return tzinfo_nogo("utcoffset");
2822}
2823
Tim Peters52dcce22003-01-23 16:36:11 +00002824static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002825tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2826{
2827 return tzinfo_nogo("dst");
2828}
2829
Tim Peters52dcce22003-01-23 16:36:11 +00002830static PyObject *
2831tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2832{
2833 int y, m, d, hh, mm, ss, us;
2834
2835 PyObject *result;
2836 int off, dst;
2837 int none;
2838 int delta;
2839
2840 if (! PyDateTime_Check(dt)) {
2841 PyErr_SetString(PyExc_TypeError,
2842 "fromutc: argument must be a datetime");
2843 return NULL;
2844 }
2845 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2846 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2847 "is not self");
2848 return NULL;
2849 }
2850
2851 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2852 if (off == -1 && PyErr_Occurred())
2853 return NULL;
2854 if (none) {
2855 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2856 "utcoffset() result required");
2857 return NULL;
2858 }
2859
2860 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2861 if (dst == -1 && PyErr_Occurred())
2862 return NULL;
2863 if (none) {
2864 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2865 "dst() result required");
2866 return NULL;
2867 }
2868
2869 y = GET_YEAR(dt);
2870 m = GET_MONTH(dt);
2871 d = GET_DAY(dt);
2872 hh = DATE_GET_HOUR(dt);
2873 mm = DATE_GET_MINUTE(dt);
2874 ss = DATE_GET_SECOND(dt);
2875 us = DATE_GET_MICROSECOND(dt);
2876
2877 delta = off - dst;
2878 mm += delta;
2879 if ((mm < 0 || mm >= 60) &&
2880 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002881 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002882 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2883 if (result == NULL)
2884 return result;
2885
2886 dst = call_dst(dt->tzinfo, result, &none);
2887 if (dst == -1 && PyErr_Occurred())
2888 goto Fail;
2889 if (none)
2890 goto Inconsistent;
2891 if (dst == 0)
2892 return result;
2893
2894 mm += dst;
2895 if ((mm < 0 || mm >= 60) &&
2896 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2897 goto Fail;
2898 Py_DECREF(result);
2899 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2900 return result;
2901
2902Inconsistent:
2903 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2904 "inconsistent results; cannot convert");
2905
2906 /* fall thru to failure */
2907Fail:
2908 Py_DECREF(result);
2909 return NULL;
2910}
2911
Tim Peters2a799bf2002-12-16 20:18:38 +00002912/*
2913 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002914 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002915 */
2916
Guido van Rossum177e41a2003-01-30 22:06:23 +00002917static PyObject *
2918tzinfo_reduce(PyObject *self)
2919{
2920 PyObject *args, *state, *tmp;
2921 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002922
Guido van Rossum177e41a2003-01-30 22:06:23 +00002923 tmp = PyTuple_New(0);
2924 if (tmp == NULL)
2925 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002926
Guido van Rossum177e41a2003-01-30 22:06:23 +00002927 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2928 if (getinitargs != NULL) {
2929 args = PyObject_CallObject(getinitargs, tmp);
2930 Py_DECREF(getinitargs);
2931 if (args == NULL) {
2932 Py_DECREF(tmp);
2933 return NULL;
2934 }
2935 }
2936 else {
2937 PyErr_Clear();
2938 args = tmp;
2939 Py_INCREF(args);
2940 }
2941
2942 getstate = PyObject_GetAttrString(self, "__getstate__");
2943 if (getstate != NULL) {
2944 state = PyObject_CallObject(getstate, tmp);
2945 Py_DECREF(getstate);
2946 if (state == NULL) {
2947 Py_DECREF(args);
2948 Py_DECREF(tmp);
2949 return NULL;
2950 }
2951 }
2952 else {
2953 PyObject **dictptr;
2954 PyErr_Clear();
2955 state = Py_None;
2956 dictptr = _PyObject_GetDictPtr(self);
2957 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2958 state = *dictptr;
2959 Py_INCREF(state);
2960 }
2961
2962 Py_DECREF(tmp);
2963
2964 if (state == Py_None) {
2965 Py_DECREF(state);
Christian Heimese93237d2007-12-19 02:37:44 +00002966 return Py_BuildValue("(ON)", Py_TYPE(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002967 }
2968 else
Christian Heimese93237d2007-12-19 02:37:44 +00002969 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002970}
Tim Peters2a799bf2002-12-16 20:18:38 +00002971
2972static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002973
Tim Peters2a799bf2002-12-16 20:18:38 +00002974 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2975 PyDoc_STR("datetime -> string name of time zone.")},
2976
2977 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2978 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2979 "west of UTC).")},
2980
2981 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2982 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2983
Tim Peters52dcce22003-01-23 16:36:11 +00002984 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2985 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2986
Guido van Rossum177e41a2003-01-30 22:06:23 +00002987 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2988 PyDoc_STR("-> (cls, state)")},
2989
Tim Peters2a799bf2002-12-16 20:18:38 +00002990 {NULL, NULL}
2991};
2992
2993static char tzinfo_doc[] =
2994PyDoc_STR("Abstract base class for time zone info objects.");
2995
Neal Norwitzce3d34d2003-02-04 20:45:17 +00002996statichere PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002997 PyObject_HEAD_INIT(NULL)
2998 0, /* ob_size */
2999 "datetime.tzinfo", /* tp_name */
3000 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3001 0, /* tp_itemsize */
3002 0, /* tp_dealloc */
3003 0, /* tp_print */
3004 0, /* tp_getattr */
3005 0, /* tp_setattr */
3006 0, /* tp_compare */
3007 0, /* tp_repr */
3008 0, /* tp_as_number */
3009 0, /* tp_as_sequence */
3010 0, /* tp_as_mapping */
3011 0, /* tp_hash */
3012 0, /* tp_call */
3013 0, /* tp_str */
3014 PyObject_GenericGetAttr, /* tp_getattro */
3015 0, /* tp_setattro */
3016 0, /* tp_as_buffer */
3017 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3018 Py_TPFLAGS_BASETYPE, /* tp_flags */
3019 tzinfo_doc, /* tp_doc */
3020 0, /* tp_traverse */
3021 0, /* tp_clear */
3022 0, /* tp_richcompare */
3023 0, /* tp_weaklistoffset */
3024 0, /* tp_iter */
3025 0, /* tp_iternext */
3026 tzinfo_methods, /* tp_methods */
3027 0, /* tp_members */
3028 0, /* tp_getset */
3029 0, /* tp_base */
3030 0, /* tp_dict */
3031 0, /* tp_descr_get */
3032 0, /* tp_descr_set */
3033 0, /* tp_dictoffset */
3034 0, /* tp_init */
3035 0, /* tp_alloc */
3036 PyType_GenericNew, /* tp_new */
3037 0, /* tp_free */
3038};
3039
3040/*
Tim Peters37f39822003-01-10 03:49:02 +00003041 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003042 */
3043
Tim Peters37f39822003-01-10 03:49:02 +00003044/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003045 */
3046
3047static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003048time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003049{
Tim Peters37f39822003-01-10 03:49:02 +00003050 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003051}
3052
Tim Peters37f39822003-01-10 03:49:02 +00003053static PyObject *
3054time_minute(PyDateTime_Time *self, void *unused)
3055{
3056 return PyInt_FromLong(TIME_GET_MINUTE(self));
3057}
3058
3059/* The name time_second conflicted with some platform header file. */
3060static PyObject *
3061py_time_second(PyDateTime_Time *self, void *unused)
3062{
3063 return PyInt_FromLong(TIME_GET_SECOND(self));
3064}
3065
3066static PyObject *
3067time_microsecond(PyDateTime_Time *self, void *unused)
3068{
3069 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3070}
3071
3072static PyObject *
3073time_tzinfo(PyDateTime_Time *self, void *unused)
3074{
Tim Petersa032d2e2003-01-11 00:15:54 +00003075 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003076 Py_INCREF(result);
3077 return result;
3078}
3079
3080static PyGetSetDef time_getset[] = {
3081 {"hour", (getter)time_hour},
3082 {"minute", (getter)time_minute},
3083 {"second", (getter)py_time_second},
3084 {"microsecond", (getter)time_microsecond},
3085 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003086 {NULL}
3087};
3088
3089/*
3090 * Constructors.
3091 */
3092
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003093static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003094 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003095
Tim Peters2a799bf2002-12-16 20:18:38 +00003096static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003097time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003098{
3099 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003100 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003101 int hour = 0;
3102 int minute = 0;
3103 int second = 0;
3104 int usecond = 0;
3105 PyObject *tzinfo = Py_None;
3106
Guido van Rossum177e41a2003-01-30 22:06:23 +00003107 /* Check for invocation from pickle with __getstate__ state */
3108 if (PyTuple_GET_SIZE(args) >= 1 &&
3109 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003110 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003111 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3112 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003113 {
Tim Peters70533e22003-02-01 04:40:04 +00003114 PyDateTime_Time *me;
3115 char aware;
3116
3117 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003118 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003119 if (check_tzinfo_subclass(tzinfo) < 0) {
3120 PyErr_SetString(PyExc_TypeError, "bad "
3121 "tzinfo state arg");
3122 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003123 }
3124 }
Tim Peters70533e22003-02-01 04:40:04 +00003125 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003126 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003127 if (me != NULL) {
3128 char *pdata = PyString_AS_STRING(state);
3129
3130 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3131 me->hashcode = -1;
3132 me->hastzinfo = aware;
3133 if (aware) {
3134 Py_INCREF(tzinfo);
3135 me->tzinfo = tzinfo;
3136 }
3137 }
3138 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003139 }
3140
Tim Peters37f39822003-01-10 03:49:02 +00003141 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003142 &hour, &minute, &second, &usecond,
3143 &tzinfo)) {
3144 if (check_time_args(hour, minute, second, usecond) < 0)
3145 return NULL;
3146 if (check_tzinfo_subclass(tzinfo) < 0)
3147 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003148 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3149 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003150 }
3151 return self;
3152}
3153
3154/*
3155 * Destructor.
3156 */
3157
3158static void
Tim Peters37f39822003-01-10 03:49:02 +00003159time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003160{
Tim Petersa032d2e2003-01-11 00:15:54 +00003161 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003162 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003163 }
Christian Heimese93237d2007-12-19 02:37:44 +00003164 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003165}
3166
3167/*
Tim Peters855fe882002-12-22 03:43:39 +00003168 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003169 */
3170
Tim Peters2a799bf2002-12-16 20:18:38 +00003171/* These are all METH_NOARGS, so don't need to check the arglist. */
3172static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003173time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003174 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003175 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003176}
3177
3178static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003179time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003180 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003181 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003182}
3183
3184static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003185time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003186 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003187 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003188}
3189
3190/*
Tim Peters37f39822003-01-10 03:49:02 +00003191 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003192 */
3193
3194static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003195time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003196{
Tim Peters37f39822003-01-10 03:49:02 +00003197 char buffer[100];
Christian Heimese93237d2007-12-19 02:37:44 +00003198 const char *type_name = Py_TYPE(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003199 int h = TIME_GET_HOUR(self);
3200 int m = TIME_GET_MINUTE(self);
3201 int s = TIME_GET_SECOND(self);
3202 int us = TIME_GET_MICROSECOND(self);
3203 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003204
Tim Peters37f39822003-01-10 03:49:02 +00003205 if (us)
3206 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003207 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003208 else if (s)
3209 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003210 "%s(%d, %d, %d)", type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003211 else
3212 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003213 "%s(%d, %d)", type_name, h, m);
Tim Peters37f39822003-01-10 03:49:02 +00003214 result = PyString_FromString(buffer);
Tim Petersa032d2e2003-01-11 00:15:54 +00003215 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003216 result = append_keyword_tzinfo(result, self->tzinfo);
3217 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003218}
3219
Tim Peters37f39822003-01-10 03:49:02 +00003220static PyObject *
3221time_str(PyDateTime_Time *self)
3222{
3223 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3224}
Tim Peters2a799bf2002-12-16 20:18:38 +00003225
3226static PyObject *
Martin v. Löwis4c11a922007-02-08 09:13:36 +00003227time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003228{
3229 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003230 PyObject *result;
3231 /* Reuse the time format code from the datetime type. */
3232 PyDateTime_DateTime datetime;
3233 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003234
Tim Peters37f39822003-01-10 03:49:02 +00003235 /* Copy over just the time bytes. */
3236 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3237 self->data,
3238 _PyDateTime_TIME_DATASIZE);
3239
3240 isoformat_time(pdatetime, buf, sizeof(buf));
3241 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003242 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003243 return result;
3244
3245 /* We need to append the UTC offset. */
3246 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003247 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003248 Py_DECREF(result);
3249 return NULL;
3250 }
3251 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3252 return result;
3253}
3254
Tim Peters37f39822003-01-10 03:49:02 +00003255static PyObject *
3256time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3257{
3258 PyObject *result;
3259 PyObject *format;
3260 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003261 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003262
3263 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3264 &PyString_Type, &format))
3265 return NULL;
3266
3267 /* Python's strftime does insane things with the year part of the
3268 * timetuple. The year is forced to (the otherwise nonsensical)
3269 * 1900 to worm around that.
3270 */
3271 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003272 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003273 TIME_GET_HOUR(self),
3274 TIME_GET_MINUTE(self),
3275 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003276 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003277 if (tuple == NULL)
3278 return NULL;
3279 assert(PyTuple_Size(tuple) == 9);
3280 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3281 Py_DECREF(tuple);
3282 return result;
3283}
Tim Peters2a799bf2002-12-16 20:18:38 +00003284
3285/*
3286 * Miscellaneous methods.
3287 */
3288
Tim Peters37f39822003-01-10 03:49:02 +00003289/* This is more natural as a tp_compare, but doesn't work then: for whatever
3290 * reason, Python's try_3way_compare ignores tp_compare unless
3291 * PyInstance_Check returns true, but these aren't old-style classes.
3292 */
3293static PyObject *
3294time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3295{
3296 int diff;
3297 naivety n1, n2;
3298 int offset1, offset2;
3299
3300 if (! PyTime_Check(other)) {
Tim Peters07534a62003-02-07 22:50:28 +00003301 if (op == Py_EQ || op == Py_NE) {
3302 PyObject *result = op == Py_EQ ? Py_False : Py_True;
3303 Py_INCREF(result);
3304 return result;
3305 }
Tim Peters37f39822003-01-10 03:49:02 +00003306 /* Stop this from falling back to address comparison. */
Tim Peters07534a62003-02-07 22:50:28 +00003307 return cmperror((PyObject *)self, other);
Tim Peters37f39822003-01-10 03:49:02 +00003308 }
3309 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
3310 other, &offset2, &n2, Py_None) < 0)
3311 return NULL;
3312 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3313 /* If they're both naive, or both aware and have the same offsets,
3314 * we get off cheap. Note that if they're both naive, offset1 ==
3315 * offset2 == 0 at this point.
3316 */
3317 if (n1 == n2 && offset1 == offset2) {
3318 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3319 _PyDateTime_TIME_DATASIZE);
3320 return diff_to_bool(diff, op);
3321 }
3322
3323 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3324 assert(offset1 != offset2); /* else last "if" handled it */
3325 /* Convert everything except microseconds to seconds. These
3326 * can't overflow (no more than the # of seconds in 2 days).
3327 */
3328 offset1 = TIME_GET_HOUR(self) * 3600 +
3329 (TIME_GET_MINUTE(self) - offset1) * 60 +
3330 TIME_GET_SECOND(self);
3331 offset2 = TIME_GET_HOUR(other) * 3600 +
3332 (TIME_GET_MINUTE(other) - offset2) * 60 +
3333 TIME_GET_SECOND(other);
3334 diff = offset1 - offset2;
3335 if (diff == 0)
3336 diff = TIME_GET_MICROSECOND(self) -
3337 TIME_GET_MICROSECOND(other);
3338 return diff_to_bool(diff, op);
3339 }
3340
3341 assert(n1 != n2);
3342 PyErr_SetString(PyExc_TypeError,
3343 "can't compare offset-naive and "
3344 "offset-aware times");
3345 return NULL;
3346}
3347
3348static long
3349time_hash(PyDateTime_Time *self)
3350{
3351 if (self->hashcode == -1) {
3352 naivety n;
3353 int offset;
3354 PyObject *temp;
3355
3356 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3357 assert(n != OFFSET_UNKNOWN);
3358 if (n == OFFSET_ERROR)
3359 return -1;
3360
3361 /* Reduce this to a hash of another object. */
3362 if (offset == 0)
3363 temp = PyString_FromStringAndSize((char *)self->data,
3364 _PyDateTime_TIME_DATASIZE);
3365 else {
3366 int hour;
3367 int minute;
3368
3369 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003370 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003371 hour = divmod(TIME_GET_HOUR(self) * 60 +
3372 TIME_GET_MINUTE(self) - offset,
3373 60,
3374 &minute);
3375 if (0 <= hour && hour < 24)
3376 temp = new_time(hour, minute,
3377 TIME_GET_SECOND(self),
3378 TIME_GET_MICROSECOND(self),
3379 Py_None);
3380 else
3381 temp = Py_BuildValue("iiii",
3382 hour, minute,
3383 TIME_GET_SECOND(self),
3384 TIME_GET_MICROSECOND(self));
3385 }
3386 if (temp != NULL) {
3387 self->hashcode = PyObject_Hash(temp);
3388 Py_DECREF(temp);
3389 }
3390 }
3391 return self->hashcode;
3392}
Tim Peters2a799bf2002-12-16 20:18:38 +00003393
Tim Peters12bf3392002-12-24 05:41:27 +00003394static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003395time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003396{
3397 PyObject *clone;
3398 PyObject *tuple;
3399 int hh = TIME_GET_HOUR(self);
3400 int mm = TIME_GET_MINUTE(self);
3401 int ss = TIME_GET_SECOND(self);
3402 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003403 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003404
3405 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003406 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003407 &hh, &mm, &ss, &us, &tzinfo))
3408 return NULL;
3409 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3410 if (tuple == NULL)
3411 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00003412 clone = time_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003413 Py_DECREF(tuple);
3414 return clone;
3415}
3416
Tim Peters2a799bf2002-12-16 20:18:38 +00003417static int
Tim Peters37f39822003-01-10 03:49:02 +00003418time_nonzero(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003419{
3420 int offset;
3421 int none;
3422
3423 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3424 /* Since utcoffset is in whole minutes, nothing can
3425 * alter the conclusion that this is nonzero.
3426 */
3427 return 1;
3428 }
3429 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003430 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003431 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003432 if (offset == -1 && PyErr_Occurred())
3433 return -1;
3434 }
3435 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3436}
3437
Tim Peters371935f2003-02-01 01:52:50 +00003438/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003439
Tim Peters33e0f382003-01-10 02:05:14 +00003440/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003441 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3442 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003443 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003444 */
3445static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003446time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003447{
3448 PyObject *basestate;
3449 PyObject *result = NULL;
3450
Tim Peters33e0f382003-01-10 02:05:14 +00003451 basestate = PyString_FromStringAndSize((char *)self->data,
3452 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003453 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003454 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003455 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003456 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003457 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003458 Py_DECREF(basestate);
3459 }
3460 return result;
3461}
3462
3463static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003464time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003465{
Christian Heimese93237d2007-12-19 02:37:44 +00003466 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003467}
3468
Tim Peters37f39822003-01-10 03:49:02 +00003469static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003470
Martin v. Löwis4c11a922007-02-08 09:13:36 +00003471 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003472 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3473 "[+HH:MM].")},
3474
Neal Norwitza84dcd72007-05-22 07:16:44 +00003475 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003476 PyDoc_STR("format -> strftime() style string.")},
3477
Eric Smitha9f7d622008-02-17 19:46:49 +00003478 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3479 PyDoc_STR("Formats self with strftime.")},
3480
Tim Peters37f39822003-01-10 03:49:02 +00003481 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003482 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3483
Tim Peters37f39822003-01-10 03:49:02 +00003484 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003485 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3486
Tim Peters37f39822003-01-10 03:49:02 +00003487 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003488 PyDoc_STR("Return self.tzinfo.dst(self).")},
3489
Neal Norwitza84dcd72007-05-22 07:16:44 +00003490 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003491 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003492
Guido van Rossum177e41a2003-01-30 22:06:23 +00003493 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3494 PyDoc_STR("__reduce__() -> (cls, state)")},
3495
Tim Peters2a799bf2002-12-16 20:18:38 +00003496 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003497};
3498
Tim Peters37f39822003-01-10 03:49:02 +00003499static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003500PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3501\n\
3502All arguments are optional. tzinfo may be None, or an instance of\n\
3503a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003504
Tim Peters37f39822003-01-10 03:49:02 +00003505static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003506 0, /* nb_add */
3507 0, /* nb_subtract */
3508 0, /* nb_multiply */
3509 0, /* nb_divide */
3510 0, /* nb_remainder */
3511 0, /* nb_divmod */
3512 0, /* nb_power */
3513 0, /* nb_negative */
3514 0, /* nb_positive */
3515 0, /* nb_absolute */
Tim Peters37f39822003-01-10 03:49:02 +00003516 (inquiry)time_nonzero, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00003517};
3518
Tim Peters37f39822003-01-10 03:49:02 +00003519statichere PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003520 PyObject_HEAD_INIT(NULL)
3521 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003522 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003523 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003524 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003525 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003526 0, /* tp_print */
3527 0, /* tp_getattr */
3528 0, /* tp_setattr */
3529 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003530 (reprfunc)time_repr, /* tp_repr */
3531 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003532 0, /* tp_as_sequence */
3533 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003534 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003535 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003536 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003537 PyObject_GenericGetAttr, /* tp_getattro */
3538 0, /* tp_setattro */
3539 0, /* tp_as_buffer */
3540 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3541 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003542 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003543 0, /* tp_traverse */
3544 0, /* tp_clear */
Tim Peters37f39822003-01-10 03:49:02 +00003545 (richcmpfunc)time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003546 0, /* tp_weaklistoffset */
3547 0, /* tp_iter */
3548 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003549 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003550 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003551 time_getset, /* tp_getset */
3552 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003553 0, /* tp_dict */
3554 0, /* tp_descr_get */
3555 0, /* tp_descr_set */
3556 0, /* tp_dictoffset */
3557 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003558 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003559 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003560 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003561};
3562
3563/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003564 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003565 */
3566
Tim Petersa9bc1682003-01-11 03:39:11 +00003567/* Accessor properties. Properties for day, month, and year are inherited
3568 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003569 */
3570
3571static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003572datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003573{
Tim Petersa9bc1682003-01-11 03:39:11 +00003574 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003575}
3576
Tim Petersa9bc1682003-01-11 03:39:11 +00003577static PyObject *
3578datetime_minute(PyDateTime_DateTime *self, void *unused)
3579{
3580 return PyInt_FromLong(DATE_GET_MINUTE(self));
3581}
3582
3583static PyObject *
3584datetime_second(PyDateTime_DateTime *self, void *unused)
3585{
3586 return PyInt_FromLong(DATE_GET_SECOND(self));
3587}
3588
3589static PyObject *
3590datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3591{
3592 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3593}
3594
3595static PyObject *
3596datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3597{
3598 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3599 Py_INCREF(result);
3600 return result;
3601}
3602
3603static PyGetSetDef datetime_getset[] = {
3604 {"hour", (getter)datetime_hour},
3605 {"minute", (getter)datetime_minute},
3606 {"second", (getter)datetime_second},
3607 {"microsecond", (getter)datetime_microsecond},
3608 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003609 {NULL}
3610};
3611
3612/*
3613 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003614 */
3615
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003616static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003617 "year", "month", "day", "hour", "minute", "second",
3618 "microsecond", "tzinfo", NULL
3619};
3620
Tim Peters2a799bf2002-12-16 20:18:38 +00003621static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003622datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003623{
3624 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003625 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003626 int year;
3627 int month;
3628 int day;
3629 int hour = 0;
3630 int minute = 0;
3631 int second = 0;
3632 int usecond = 0;
3633 PyObject *tzinfo = Py_None;
3634
Guido van Rossum177e41a2003-01-30 22:06:23 +00003635 /* Check for invocation from pickle with __getstate__ state */
3636 if (PyTuple_GET_SIZE(args) >= 1 &&
3637 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003638 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003639 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3640 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003641 {
Tim Peters70533e22003-02-01 04:40:04 +00003642 PyDateTime_DateTime *me;
3643 char aware;
3644
3645 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003646 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003647 if (check_tzinfo_subclass(tzinfo) < 0) {
3648 PyErr_SetString(PyExc_TypeError, "bad "
3649 "tzinfo state arg");
3650 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003651 }
3652 }
Tim Peters70533e22003-02-01 04:40:04 +00003653 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003654 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003655 if (me != NULL) {
3656 char *pdata = PyString_AS_STRING(state);
3657
3658 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3659 me->hashcode = -1;
3660 me->hastzinfo = aware;
3661 if (aware) {
3662 Py_INCREF(tzinfo);
3663 me->tzinfo = tzinfo;
3664 }
3665 }
3666 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003667 }
3668
Tim Petersa9bc1682003-01-11 03:39:11 +00003669 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003670 &year, &month, &day, &hour, &minute,
3671 &second, &usecond, &tzinfo)) {
3672 if (check_date_args(year, month, day) < 0)
3673 return NULL;
3674 if (check_time_args(hour, minute, second, usecond) < 0)
3675 return NULL;
3676 if (check_tzinfo_subclass(tzinfo) < 0)
3677 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003678 self = new_datetime_ex(year, month, day,
3679 hour, minute, second, usecond,
3680 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003681 }
3682 return self;
3683}
3684
Tim Petersa9bc1682003-01-11 03:39:11 +00003685/* TM_FUNC is the shared type of localtime() and gmtime(). */
3686typedef struct tm *(*TM_FUNC)(const time_t *timer);
3687
3688/* Internal helper.
3689 * Build datetime from a time_t and a distinct count of microseconds.
3690 * Pass localtime or gmtime for f, to control the interpretation of timet.
3691 */
3692static PyObject *
3693datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3694 PyObject *tzinfo)
3695{
3696 struct tm *tm;
3697 PyObject *result = NULL;
3698
3699 tm = f(&timet);
3700 if (tm) {
3701 /* The platform localtime/gmtime may insert leap seconds,
3702 * indicated by tm->tm_sec > 59. We don't care about them,
3703 * except to the extent that passing them on to the datetime
3704 * constructor would raise ValueError for a reason that
3705 * made no sense to the user.
3706 */
3707 if (tm->tm_sec > 59)
3708 tm->tm_sec = 59;
3709 result = PyObject_CallFunction(cls, "iiiiiiiO",
3710 tm->tm_year + 1900,
3711 tm->tm_mon + 1,
3712 tm->tm_mday,
3713 tm->tm_hour,
3714 tm->tm_min,
3715 tm->tm_sec,
3716 us,
3717 tzinfo);
3718 }
3719 else
3720 PyErr_SetString(PyExc_ValueError,
3721 "timestamp out of range for "
3722 "platform localtime()/gmtime() function");
3723 return result;
3724}
3725
3726/* Internal helper.
3727 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3728 * to control the interpretation of the timestamp. Since a double doesn't
3729 * have enough bits to cover a datetime's full range of precision, it's
3730 * better to call datetime_from_timet_and_us provided you have a way
3731 * to get that much precision (e.g., C time() isn't good enough).
3732 */
3733static PyObject *
3734datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3735 PyObject *tzinfo)
3736{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003737 time_t timet;
3738 double fraction;
3739 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003740
Tim Peters1b6f7a92004-06-20 02:50:16 +00003741 timet = _PyTime_DoubleToTimet(timestamp);
3742 if (timet == (time_t)-1 && PyErr_Occurred())
3743 return NULL;
3744 fraction = timestamp - (double)timet;
3745 us = (int)round_to_long(fraction * 1e6);
Guido van Rossum2054ee92007-03-06 15:50:01 +00003746 if (us < 0) {
3747 /* Truncation towards zero is not what we wanted
3748 for negative numbers (Python's mod semantics) */
3749 timet -= 1;
3750 us += 1000000;
3751 }
Georg Brandl6d78a582006-04-28 19:09:24 +00003752 /* If timestamp is less than one microsecond smaller than a
3753 * full second, round up. Otherwise, ValueErrors are raised
3754 * for some floats. */
3755 if (us == 1000000) {
3756 timet += 1;
3757 us = 0;
3758 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003759 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3760}
3761
3762/* Internal helper.
3763 * Build most accurate possible datetime for current time. Pass localtime or
3764 * gmtime for f as appropriate.
3765 */
3766static PyObject *
3767datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3768{
3769#ifdef HAVE_GETTIMEOFDAY
3770 struct timeval t;
3771
3772#ifdef GETTIMEOFDAY_NO_TZ
3773 gettimeofday(&t);
3774#else
3775 gettimeofday(&t, (struct timezone *)NULL);
3776#endif
3777 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3778 tzinfo);
3779
3780#else /* ! HAVE_GETTIMEOFDAY */
3781 /* No flavor of gettimeofday exists on this platform. Python's
3782 * time.time() does a lot of other platform tricks to get the
3783 * best time it can on the platform, and we're not going to do
3784 * better than that (if we could, the better code would belong
3785 * in time.time()!) We're limited by the precision of a double,
3786 * though.
3787 */
3788 PyObject *time;
3789 double dtime;
3790
3791 time = time_time();
3792 if (time == NULL)
3793 return NULL;
3794 dtime = PyFloat_AsDouble(time);
3795 Py_DECREF(time);
3796 if (dtime == -1.0 && PyErr_Occurred())
3797 return NULL;
3798 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3799#endif /* ! HAVE_GETTIMEOFDAY */
3800}
3801
Tim Peters2a799bf2002-12-16 20:18:38 +00003802/* Return best possible local time -- this isn't constrained by the
3803 * precision of a timestamp.
3804 */
3805static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003806datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003807{
Tim Peters10cadce2003-01-23 19:58:02 +00003808 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003809 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003810 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003811
Tim Peters10cadce2003-01-23 19:58:02 +00003812 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3813 &tzinfo))
3814 return NULL;
3815 if (check_tzinfo_subclass(tzinfo) < 0)
3816 return NULL;
3817
3818 self = datetime_best_possible(cls,
3819 tzinfo == Py_None ? localtime : gmtime,
3820 tzinfo);
3821 if (self != NULL && tzinfo != Py_None) {
3822 /* Convert UTC to tzinfo's zone. */
3823 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003824 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003825 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003826 }
3827 return self;
3828}
3829
Tim Petersa9bc1682003-01-11 03:39:11 +00003830/* Return best possible UTC time -- this isn't constrained by the
3831 * precision of a timestamp.
3832 */
3833static PyObject *
3834datetime_utcnow(PyObject *cls, PyObject *dummy)
3835{
3836 return datetime_best_possible(cls, gmtime, Py_None);
3837}
3838
Tim Peters2a799bf2002-12-16 20:18:38 +00003839/* Return new local datetime from timestamp (Python timestamp -- a double). */
3840static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003841datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003842{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003843 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003844 double timestamp;
3845 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003846 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003847
Tim Peters2a44a8d2003-01-23 20:53:10 +00003848 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3849 keywords, &timestamp, &tzinfo))
3850 return NULL;
3851 if (check_tzinfo_subclass(tzinfo) < 0)
3852 return NULL;
3853
3854 self = datetime_from_timestamp(cls,
3855 tzinfo == Py_None ? localtime : gmtime,
3856 timestamp,
3857 tzinfo);
3858 if (self != NULL && tzinfo != Py_None) {
3859 /* Convert UTC to tzinfo's zone. */
3860 PyObject *temp = self;
3861 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3862 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003863 }
3864 return self;
3865}
3866
Tim Petersa9bc1682003-01-11 03:39:11 +00003867/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3868static PyObject *
3869datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3870{
3871 double timestamp;
3872 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003873
Tim Petersa9bc1682003-01-11 03:39:11 +00003874 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3875 result = datetime_from_timestamp(cls, gmtime, timestamp,
3876 Py_None);
3877 return result;
3878}
3879
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003880/* Return new datetime from time.strptime(). */
3881static PyObject *
3882datetime_strptime(PyObject *cls, PyObject *args)
3883{
Skip Montanarofc070d22008-03-15 16:04:45 +00003884 static PyObject *module = NULL;
3885 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003886 const char *string, *format;
3887
3888 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3889 return NULL;
3890
Skip Montanarofc070d22008-03-15 16:04:45 +00003891 if (module == NULL &&
3892 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003893 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003894
Skip Montanarofc070d22008-03-15 16:04:45 +00003895 /* _strptime._strptime returns a two-element tuple. The first
3896 element is a time.struct_time object. The second is the
3897 microseconds (which are not defined for time.struct_time). */
3898 obj = PyObject_CallMethod(module, "_strptime", "ss", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003899 if (obj != NULL) {
3900 int i, good_timetuple = 1;
Skip Montanarofc070d22008-03-15 16:04:45 +00003901 long int ia[7];
3902 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
3903 st = PySequence_GetItem(obj, 0);
3904 frac = PySequence_GetItem(obj, 1);
3905 if (st == NULL || frac == NULL)
3906 good_timetuple = 0;
3907 /* copy y/m/d/h/m/s values out of the
3908 time.struct_time */
3909 if (good_timetuple &&
3910 PySequence_Check(st) &&
3911 PySequence_Size(st) >= 6) {
3912 for (i=0; i < 6; i++) {
3913 PyObject *p = PySequence_GetItem(st, i);
3914 if (p == NULL) {
3915 good_timetuple = 0;
3916 break;
3917 }
3918 if (PyInt_Check(p))
3919 ia[i] = PyInt_AsLong(p);
3920 else
3921 good_timetuple = 0;
3922 Py_DECREF(p);
Thomas Wouters3cfea2d2006-04-14 21:23:42 +00003923 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003924 }
Skip Montanarofc070d22008-03-15 16:04:45 +00003925 else
3926 good_timetuple = 0;
3927 /* follow that up with a little dose of microseconds */
3928 if (PyInt_Check(frac))
3929 ia[6] = PyInt_AsLong(frac);
3930 else
3931 good_timetuple = 0;
3932 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003933 else
3934 good_timetuple = 0;
3935 if (good_timetuple)
Skip Montanarofc070d22008-03-15 16:04:45 +00003936 result = PyObject_CallFunction(cls, "iiiiiii",
3937 ia[0], ia[1], ia[2],
3938 ia[3], ia[4], ia[5],
3939 ia[6]);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003940 else
3941 PyErr_SetString(PyExc_ValueError,
Skip Montanarofc070d22008-03-15 16:04:45 +00003942 "unexpected value from _strptime._strptime");
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003943 }
Skip Montanarofc070d22008-03-15 16:04:45 +00003944 Py_XDECREF(obj);
3945 Py_XDECREF(st);
3946 Py_XDECREF(frac);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003947 return result;
3948}
3949
Tim Petersa9bc1682003-01-11 03:39:11 +00003950/* Return new datetime from date/datetime and time arguments. */
3951static PyObject *
3952datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3953{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003954 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003955 PyObject *date;
3956 PyObject *time;
3957 PyObject *result = NULL;
3958
3959 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3960 &PyDateTime_DateType, &date,
3961 &PyDateTime_TimeType, &time)) {
3962 PyObject *tzinfo = Py_None;
3963
3964 if (HASTZINFO(time))
3965 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3966 result = PyObject_CallFunction(cls, "iiiiiiiO",
3967 GET_YEAR(date),
3968 GET_MONTH(date),
3969 GET_DAY(date),
3970 TIME_GET_HOUR(time),
3971 TIME_GET_MINUTE(time),
3972 TIME_GET_SECOND(time),
3973 TIME_GET_MICROSECOND(time),
3974 tzinfo);
3975 }
3976 return result;
3977}
Tim Peters2a799bf2002-12-16 20:18:38 +00003978
3979/*
3980 * Destructor.
3981 */
3982
3983static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003984datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003985{
Tim Petersa9bc1682003-01-11 03:39:11 +00003986 if (HASTZINFO(self)) {
3987 Py_XDECREF(self->tzinfo);
3988 }
Christian Heimese93237d2007-12-19 02:37:44 +00003989 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003990}
3991
3992/*
3993 * Indirect access to tzinfo methods.
3994 */
3995
Tim Peters2a799bf2002-12-16 20:18:38 +00003996/* These are all METH_NOARGS, so don't need to check the arglist. */
3997static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003998datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3999 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4000 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004001}
4002
4003static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004004datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
4005 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4006 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00004007}
4008
4009static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004010datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
4011 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
4012 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004013}
4014
4015/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004016 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004017 */
4018
Tim Petersa9bc1682003-01-11 03:39:11 +00004019/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4020 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004021 */
4022static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004023add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
4024 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004025{
Tim Petersa9bc1682003-01-11 03:39:11 +00004026 /* Note that the C-level additions can't overflow, because of
4027 * invariant bounds on the member values.
4028 */
4029 int year = GET_YEAR(date);
4030 int month = GET_MONTH(date);
4031 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4032 int hour = DATE_GET_HOUR(date);
4033 int minute = DATE_GET_MINUTE(date);
4034 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4035 int microsecond = DATE_GET_MICROSECOND(date) +
4036 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004037
Tim Petersa9bc1682003-01-11 03:39:11 +00004038 assert(factor == 1 || factor == -1);
4039 if (normalize_datetime(&year, &month, &day,
4040 &hour, &minute, &second, &microsecond) < 0)
4041 return NULL;
4042 else
4043 return new_datetime(year, month, day,
4044 hour, minute, second, microsecond,
4045 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004046}
4047
4048static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004049datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004050{
Tim Petersa9bc1682003-01-11 03:39:11 +00004051 if (PyDateTime_Check(left)) {
4052 /* datetime + ??? */
4053 if (PyDelta_Check(right))
4054 /* datetime + delta */
4055 return add_datetime_timedelta(
4056 (PyDateTime_DateTime *)left,
4057 (PyDateTime_Delta *)right,
4058 1);
4059 }
4060 else if (PyDelta_Check(left)) {
4061 /* delta + datetime */
4062 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4063 (PyDateTime_Delta *) left,
4064 1);
4065 }
4066 Py_INCREF(Py_NotImplemented);
4067 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004068}
4069
4070static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004071datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004072{
4073 PyObject *result = Py_NotImplemented;
4074
4075 if (PyDateTime_Check(left)) {
4076 /* datetime - ??? */
4077 if (PyDateTime_Check(right)) {
4078 /* datetime - datetime */
4079 naivety n1, n2;
4080 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004081 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004082
Tim Peterse39a80c2002-12-30 21:28:52 +00004083 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4084 right, &offset2, &n2,
4085 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00004086 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00004087 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00004088 if (n1 != n2) {
4089 PyErr_SetString(PyExc_TypeError,
4090 "can't subtract offset-naive and "
4091 "offset-aware datetimes");
4092 return NULL;
4093 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004094 delta_d = ymd_to_ord(GET_YEAR(left),
4095 GET_MONTH(left),
4096 GET_DAY(left)) -
4097 ymd_to_ord(GET_YEAR(right),
4098 GET_MONTH(right),
4099 GET_DAY(right));
4100 /* These can't overflow, since the values are
4101 * normalized. At most this gives the number of
4102 * seconds in one day.
4103 */
4104 delta_s = (DATE_GET_HOUR(left) -
4105 DATE_GET_HOUR(right)) * 3600 +
4106 (DATE_GET_MINUTE(left) -
4107 DATE_GET_MINUTE(right)) * 60 +
4108 (DATE_GET_SECOND(left) -
4109 DATE_GET_SECOND(right));
4110 delta_us = DATE_GET_MICROSECOND(left) -
4111 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004112 /* (left - offset1) - (right - offset2) =
4113 * (left - right) + (offset2 - offset1)
4114 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004115 delta_s += (offset2 - offset1) * 60;
4116 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004117 }
4118 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004119 /* datetime - delta */
4120 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004121 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004122 (PyDateTime_Delta *)right,
4123 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004124 }
4125 }
4126
4127 if (result == Py_NotImplemented)
4128 Py_INCREF(result);
4129 return result;
4130}
4131
4132/* Various ways to turn a datetime into a string. */
4133
4134static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004135datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004136{
Tim Petersa9bc1682003-01-11 03:39:11 +00004137 char buffer[1000];
Christian Heimese93237d2007-12-19 02:37:44 +00004138 const char *type_name = Py_TYPE(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004139 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004140
Tim Petersa9bc1682003-01-11 03:39:11 +00004141 if (DATE_GET_MICROSECOND(self)) {
4142 PyOS_snprintf(buffer, sizeof(buffer),
4143 "%s(%d, %d, %d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004144 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004145 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4146 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4147 DATE_GET_SECOND(self),
4148 DATE_GET_MICROSECOND(self));
4149 }
4150 else if (DATE_GET_SECOND(self)) {
4151 PyOS_snprintf(buffer, sizeof(buffer),
4152 "%s(%d, %d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004153 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004154 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4155 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4156 DATE_GET_SECOND(self));
4157 }
4158 else {
4159 PyOS_snprintf(buffer, sizeof(buffer),
4160 "%s(%d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004161 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004162 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4163 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4164 }
4165 baserepr = PyString_FromString(buffer);
4166 if (baserepr == NULL || ! HASTZINFO(self))
4167 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004168 return append_keyword_tzinfo(baserepr, self->tzinfo);
4169}
4170
Tim Petersa9bc1682003-01-11 03:39:11 +00004171static PyObject *
4172datetime_str(PyDateTime_DateTime *self)
4173{
4174 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4175}
Tim Peters2a799bf2002-12-16 20:18:38 +00004176
4177static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004178datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004179{
Tim Petersa9bc1682003-01-11 03:39:11 +00004180 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004181 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004182 char buffer[100];
4183 char *cp;
4184 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004185
Tim Petersa9bc1682003-01-11 03:39:11 +00004186 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4187 &sep))
4188 return NULL;
4189 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4190 assert(cp != NULL);
4191 *cp++ = sep;
4192 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4193 result = PyString_FromString(buffer);
4194 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004195 return result;
4196
4197 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004198 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004199 (PyObject *)self) < 0) {
4200 Py_DECREF(result);
4201 return NULL;
4202 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004203 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004204 return result;
4205}
4206
Tim Petersa9bc1682003-01-11 03:39:11 +00004207static PyObject *
4208datetime_ctime(PyDateTime_DateTime *self)
4209{
4210 return format_ctime((PyDateTime_Date *)self,
4211 DATE_GET_HOUR(self),
4212 DATE_GET_MINUTE(self),
4213 DATE_GET_SECOND(self));
4214}
4215
Tim Peters2a799bf2002-12-16 20:18:38 +00004216/* Miscellaneous methods. */
4217
Tim Petersa9bc1682003-01-11 03:39:11 +00004218/* This is more natural as a tp_compare, but doesn't work then: for whatever
4219 * reason, Python's try_3way_compare ignores tp_compare unless
4220 * PyInstance_Check returns true, but these aren't old-style classes.
4221 */
4222static PyObject *
4223datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
4224{
4225 int diff;
4226 naivety n1, n2;
4227 int offset1, offset2;
4228
4229 if (! PyDateTime_Check(other)) {
Tim Peters528ca532004-09-16 01:30:50 +00004230 /* If other has a "timetuple" attr, that's an advertised
4231 * hook for other classes to ask to get comparison control.
4232 * However, date instances have a timetuple attr, and we
4233 * don't want to allow that comparison. Because datetime
4234 * is a subclass of date, when mixing date and datetime
4235 * in a comparison, Python gives datetime the first shot
4236 * (it's the more specific subtype). So we can stop that
4237 * combination here reliably.
4238 */
4239 if (PyObject_HasAttrString(other, "timetuple") &&
4240 ! PyDate_Check(other)) {
Tim Peters8d81a012003-01-24 22:36:34 +00004241 /* A hook for other kinds of datetime objects. */
4242 Py_INCREF(Py_NotImplemented);
4243 return Py_NotImplemented;
4244 }
Tim Peters07534a62003-02-07 22:50:28 +00004245 if (op == Py_EQ || op == Py_NE) {
4246 PyObject *result = op == Py_EQ ? Py_False : Py_True;
4247 Py_INCREF(result);
4248 return result;
4249 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004250 /* Stop this from falling back to address comparison. */
Tim Peters07534a62003-02-07 22:50:28 +00004251 return cmperror((PyObject *)self, other);
Tim Petersa9bc1682003-01-11 03:39:11 +00004252 }
4253
4254 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
4255 (PyObject *)self,
4256 other, &offset2, &n2,
4257 other) < 0)
4258 return NULL;
4259 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4260 /* If they're both naive, or both aware and have the same offsets,
4261 * we get off cheap. Note that if they're both naive, offset1 ==
4262 * offset2 == 0 at this point.
4263 */
4264 if (n1 == n2 && offset1 == offset2) {
4265 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
4266 _PyDateTime_DATETIME_DATASIZE);
4267 return diff_to_bool(diff, op);
4268 }
4269
4270 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4271 PyDateTime_Delta *delta;
4272
4273 assert(offset1 != offset2); /* else last "if" handled it */
4274 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4275 other);
4276 if (delta == NULL)
4277 return NULL;
4278 diff = GET_TD_DAYS(delta);
4279 if (diff == 0)
4280 diff = GET_TD_SECONDS(delta) |
4281 GET_TD_MICROSECONDS(delta);
4282 Py_DECREF(delta);
4283 return diff_to_bool(diff, op);
4284 }
4285
4286 assert(n1 != n2);
4287 PyErr_SetString(PyExc_TypeError,
4288 "can't compare offset-naive and "
4289 "offset-aware datetimes");
4290 return NULL;
4291}
4292
4293static long
4294datetime_hash(PyDateTime_DateTime *self)
4295{
4296 if (self->hashcode == -1) {
4297 naivety n;
4298 int offset;
4299 PyObject *temp;
4300
4301 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4302 &offset);
4303 assert(n != OFFSET_UNKNOWN);
4304 if (n == OFFSET_ERROR)
4305 return -1;
4306
4307 /* Reduce this to a hash of another object. */
4308 if (n == OFFSET_NAIVE)
4309 temp = PyString_FromStringAndSize(
4310 (char *)self->data,
4311 _PyDateTime_DATETIME_DATASIZE);
4312 else {
4313 int days;
4314 int seconds;
4315
4316 assert(n == OFFSET_AWARE);
4317 assert(HASTZINFO(self));
4318 days = ymd_to_ord(GET_YEAR(self),
4319 GET_MONTH(self),
4320 GET_DAY(self));
4321 seconds = DATE_GET_HOUR(self) * 3600 +
4322 (DATE_GET_MINUTE(self) - offset) * 60 +
4323 DATE_GET_SECOND(self);
4324 temp = new_delta(days,
4325 seconds,
4326 DATE_GET_MICROSECOND(self),
4327 1);
4328 }
4329 if (temp != NULL) {
4330 self->hashcode = PyObject_Hash(temp);
4331 Py_DECREF(temp);
4332 }
4333 }
4334 return self->hashcode;
4335}
Tim Peters2a799bf2002-12-16 20:18:38 +00004336
4337static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004338datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004339{
4340 PyObject *clone;
4341 PyObject *tuple;
4342 int y = GET_YEAR(self);
4343 int m = GET_MONTH(self);
4344 int d = GET_DAY(self);
4345 int hh = DATE_GET_HOUR(self);
4346 int mm = DATE_GET_MINUTE(self);
4347 int ss = DATE_GET_SECOND(self);
4348 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004349 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004350
4351 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004352 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004353 &y, &m, &d, &hh, &mm, &ss, &us,
4354 &tzinfo))
4355 return NULL;
4356 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4357 if (tuple == NULL)
4358 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00004359 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004360 Py_DECREF(tuple);
4361 return clone;
4362}
4363
4364static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004365datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004366{
Tim Peters52dcce22003-01-23 16:36:11 +00004367 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004368 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004369 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004370
Tim Peters80475bb2002-12-25 07:40:55 +00004371 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004372 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004373
Tim Peters52dcce22003-01-23 16:36:11 +00004374 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4375 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004376 return NULL;
4377
Tim Peters52dcce22003-01-23 16:36:11 +00004378 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4379 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004380
Tim Peters52dcce22003-01-23 16:36:11 +00004381 /* Conversion to self's own time zone is a NOP. */
4382 if (self->tzinfo == tzinfo) {
4383 Py_INCREF(self);
4384 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004385 }
Tim Peters521fc152002-12-31 17:36:56 +00004386
Tim Peters52dcce22003-01-23 16:36:11 +00004387 /* Convert self to UTC. */
4388 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4389 if (offset == -1 && PyErr_Occurred())
4390 return NULL;
4391 if (none)
4392 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004393
Tim Peters52dcce22003-01-23 16:36:11 +00004394 y = GET_YEAR(self);
4395 m = GET_MONTH(self);
4396 d = GET_DAY(self);
4397 hh = DATE_GET_HOUR(self);
4398 mm = DATE_GET_MINUTE(self);
4399 ss = DATE_GET_SECOND(self);
4400 us = DATE_GET_MICROSECOND(self);
4401
4402 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004403 if ((mm < 0 || mm >= 60) &&
4404 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004405 return NULL;
4406
4407 /* Attach new tzinfo and let fromutc() do the rest. */
4408 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4409 if (result != NULL) {
4410 PyObject *temp = result;
4411
4412 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4413 Py_DECREF(temp);
4414 }
Tim Petersadf64202003-01-04 06:03:15 +00004415 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004416
Tim Peters52dcce22003-01-23 16:36:11 +00004417NeedAware:
4418 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4419 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004420 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004421}
4422
4423static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004424datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004425{
4426 int dstflag = -1;
4427
Tim Petersa9bc1682003-01-11 03:39:11 +00004428 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004429 int none;
4430
4431 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4432 if (dstflag == -1 && PyErr_Occurred())
4433 return NULL;
4434
4435 if (none)
4436 dstflag = -1;
4437 else if (dstflag != 0)
4438 dstflag = 1;
4439
4440 }
4441 return build_struct_time(GET_YEAR(self),
4442 GET_MONTH(self),
4443 GET_DAY(self),
4444 DATE_GET_HOUR(self),
4445 DATE_GET_MINUTE(self),
4446 DATE_GET_SECOND(self),
4447 dstflag);
4448}
4449
4450static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004451datetime_getdate(PyDateTime_DateTime *self)
4452{
4453 return new_date(GET_YEAR(self),
4454 GET_MONTH(self),
4455 GET_DAY(self));
4456}
4457
4458static PyObject *
4459datetime_gettime(PyDateTime_DateTime *self)
4460{
4461 return new_time(DATE_GET_HOUR(self),
4462 DATE_GET_MINUTE(self),
4463 DATE_GET_SECOND(self),
4464 DATE_GET_MICROSECOND(self),
4465 Py_None);
4466}
4467
4468static PyObject *
4469datetime_gettimetz(PyDateTime_DateTime *self)
4470{
4471 return new_time(DATE_GET_HOUR(self),
4472 DATE_GET_MINUTE(self),
4473 DATE_GET_SECOND(self),
4474 DATE_GET_MICROSECOND(self),
4475 HASTZINFO(self) ? self->tzinfo : Py_None);
4476}
4477
4478static PyObject *
4479datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004480{
4481 int y = GET_YEAR(self);
4482 int m = GET_MONTH(self);
4483 int d = GET_DAY(self);
4484 int hh = DATE_GET_HOUR(self);
4485 int mm = DATE_GET_MINUTE(self);
4486 int ss = DATE_GET_SECOND(self);
4487 int us = 0; /* microseconds are ignored in a timetuple */
4488 int offset = 0;
4489
Tim Petersa9bc1682003-01-11 03:39:11 +00004490 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004491 int none;
4492
4493 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4494 if (offset == -1 && PyErr_Occurred())
4495 return NULL;
4496 }
4497 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4498 * 0 in a UTC timetuple regardless of what dst() says.
4499 */
4500 if (offset) {
4501 /* Subtract offset minutes & normalize. */
4502 int stat;
4503
4504 mm -= offset;
4505 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4506 if (stat < 0) {
4507 /* At the edges, it's possible we overflowed
4508 * beyond MINYEAR or MAXYEAR.
4509 */
4510 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4511 PyErr_Clear();
4512 else
4513 return NULL;
4514 }
4515 }
4516 return build_struct_time(y, m, d, hh, mm, ss, 0);
4517}
4518
Tim Peters371935f2003-02-01 01:52:50 +00004519/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004520
Tim Petersa9bc1682003-01-11 03:39:11 +00004521/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004522 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4523 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004524 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004525 */
4526static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004527datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004528{
4529 PyObject *basestate;
4530 PyObject *result = NULL;
4531
Tim Peters33e0f382003-01-10 02:05:14 +00004532 basestate = PyString_FromStringAndSize((char *)self->data,
4533 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004534 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004535 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004536 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004537 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004538 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004539 Py_DECREF(basestate);
4540 }
4541 return result;
4542}
4543
4544static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004545datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004546{
Christian Heimese93237d2007-12-19 02:37:44 +00004547 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004548}
4549
Tim Petersa9bc1682003-01-11 03:39:11 +00004550static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004551
Tim Peters2a799bf2002-12-16 20:18:38 +00004552 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004553
Tim Petersa9bc1682003-01-11 03:39:11 +00004554 {"now", (PyCFunction)datetime_now,
Neal Norwitza84dcd72007-05-22 07:16:44 +00004555 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004556 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004557
Tim Petersa9bc1682003-01-11 03:39:11 +00004558 {"utcnow", (PyCFunction)datetime_utcnow,
4559 METH_NOARGS | METH_CLASS,
4560 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4561
4562 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Neal Norwitza84dcd72007-05-22 07:16:44 +00004563 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004564 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004565
Tim Petersa9bc1682003-01-11 03:39:11 +00004566 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4567 METH_VARARGS | METH_CLASS,
4568 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4569 "(like time.time()).")},
4570
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004571 {"strptime", (PyCFunction)datetime_strptime,
4572 METH_VARARGS | METH_CLASS,
4573 PyDoc_STR("string, format -> new datetime parsed from a string "
4574 "(like time.strptime()).")},
4575
Tim Petersa9bc1682003-01-11 03:39:11 +00004576 {"combine", (PyCFunction)datetime_combine,
4577 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4578 PyDoc_STR("date, time -> datetime with same date and time fields")},
4579
Tim Peters2a799bf2002-12-16 20:18:38 +00004580 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004581
Tim Petersa9bc1682003-01-11 03:39:11 +00004582 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4583 PyDoc_STR("Return date object with same year, month and day.")},
4584
4585 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4586 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4587
4588 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4589 PyDoc_STR("Return time object with same time and tzinfo.")},
4590
4591 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4592 PyDoc_STR("Return ctime() style string.")},
4593
4594 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004595 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4596
Tim Petersa9bc1682003-01-11 03:39:11 +00004597 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004598 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4599
Neal Norwitza84dcd72007-05-22 07:16:44 +00004600 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004601 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4602 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4603 "sep is used to separate the year from the time, and "
4604 "defaults to 'T'.")},
4605
Tim Petersa9bc1682003-01-11 03:39:11 +00004606 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004607 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4608
Tim Petersa9bc1682003-01-11 03:39:11 +00004609 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004610 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4611
Tim Petersa9bc1682003-01-11 03:39:11 +00004612 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004613 PyDoc_STR("Return self.tzinfo.dst(self).")},
4614
Neal Norwitza84dcd72007-05-22 07:16:44 +00004615 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004616 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004617
Neal Norwitza84dcd72007-05-22 07:16:44 +00004618 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004619 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4620
Guido van Rossum177e41a2003-01-30 22:06:23 +00004621 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4622 PyDoc_STR("__reduce__() -> (cls, state)")},
4623
Tim Peters2a799bf2002-12-16 20:18:38 +00004624 {NULL, NULL}
4625};
4626
Tim Petersa9bc1682003-01-11 03:39:11 +00004627static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004628PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4629\n\
4630The year, month and day arguments are required. tzinfo may be None, or an\n\
4631instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004632
Tim Petersa9bc1682003-01-11 03:39:11 +00004633static PyNumberMethods datetime_as_number = {
4634 datetime_add, /* nb_add */
4635 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004636 0, /* nb_multiply */
4637 0, /* nb_divide */
4638 0, /* nb_remainder */
4639 0, /* nb_divmod */
4640 0, /* nb_power */
4641 0, /* nb_negative */
4642 0, /* nb_positive */
4643 0, /* nb_absolute */
4644 0, /* nb_nonzero */
4645};
4646
Tim Petersa9bc1682003-01-11 03:39:11 +00004647statichere PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004648 PyObject_HEAD_INIT(NULL)
4649 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004650 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004651 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004652 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004653 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004654 0, /* tp_print */
4655 0, /* tp_getattr */
4656 0, /* tp_setattr */
4657 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004658 (reprfunc)datetime_repr, /* tp_repr */
4659 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004660 0, /* tp_as_sequence */
4661 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004662 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004663 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004664 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004665 PyObject_GenericGetAttr, /* tp_getattro */
4666 0, /* tp_setattro */
4667 0, /* tp_as_buffer */
4668 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4669 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004670 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004671 0, /* tp_traverse */
4672 0, /* tp_clear */
Tim Petersa9bc1682003-01-11 03:39:11 +00004673 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004674 0, /* tp_weaklistoffset */
4675 0, /* tp_iter */
4676 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004677 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004678 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004679 datetime_getset, /* tp_getset */
4680 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004681 0, /* tp_dict */
4682 0, /* tp_descr_get */
4683 0, /* tp_descr_set */
4684 0, /* tp_dictoffset */
4685 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004686 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004687 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004688 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004689};
4690
4691/* ---------------------------------------------------------------------------
4692 * Module methods and initialization.
4693 */
4694
4695static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004696 {NULL, NULL}
4697};
4698
Tim Peters9ddf40b2004-06-20 22:41:32 +00004699/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4700 * datetime.h.
4701 */
4702static PyDateTime_CAPI CAPI = {
4703 &PyDateTime_DateType,
4704 &PyDateTime_DateTimeType,
4705 &PyDateTime_TimeType,
4706 &PyDateTime_DeltaType,
4707 &PyDateTime_TZInfoType,
4708 new_date_ex,
4709 new_datetime_ex,
4710 new_time_ex,
4711 new_delta_ex,
4712 datetime_fromtimestamp,
4713 date_fromtimestamp
4714};
4715
4716
Tim Peters2a799bf2002-12-16 20:18:38 +00004717PyMODINIT_FUNC
4718initdatetime(void)
4719{
4720 PyObject *m; /* a module object */
4721 PyObject *d; /* its dict */
4722 PyObject *x;
4723
Tim Peters2a799bf2002-12-16 20:18:38 +00004724 m = Py_InitModule3("datetime", module_methods,
4725 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004726 if (m == NULL)
4727 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004728
4729 if (PyType_Ready(&PyDateTime_DateType) < 0)
4730 return;
4731 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4732 return;
4733 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4734 return;
4735 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4736 return;
4737 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4738 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004739
Tim Peters2a799bf2002-12-16 20:18:38 +00004740 /* timedelta values */
4741 d = PyDateTime_DeltaType.tp_dict;
4742
Tim Peters2a799bf2002-12-16 20:18:38 +00004743 x = new_delta(0, 0, 1, 0);
4744 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4745 return;
4746 Py_DECREF(x);
4747
4748 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4749 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4750 return;
4751 Py_DECREF(x);
4752
4753 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4754 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4755 return;
4756 Py_DECREF(x);
4757
4758 /* date values */
4759 d = PyDateTime_DateType.tp_dict;
4760
4761 x = new_date(1, 1, 1);
4762 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4763 return;
4764 Py_DECREF(x);
4765
4766 x = new_date(MAXYEAR, 12, 31);
4767 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4768 return;
4769 Py_DECREF(x);
4770
4771 x = new_delta(1, 0, 0, 0);
4772 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4773 return;
4774 Py_DECREF(x);
4775
Tim Peters37f39822003-01-10 03:49:02 +00004776 /* time values */
4777 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004778
Tim Peters37f39822003-01-10 03:49:02 +00004779 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004780 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4781 return;
4782 Py_DECREF(x);
4783
Tim Peters37f39822003-01-10 03:49:02 +00004784 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004785 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4786 return;
4787 Py_DECREF(x);
4788
4789 x = new_delta(0, 0, 1, 0);
4790 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4791 return;
4792 Py_DECREF(x);
4793
Tim Petersa9bc1682003-01-11 03:39:11 +00004794 /* datetime values */
4795 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004796
Tim Petersa9bc1682003-01-11 03:39:11 +00004797 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004798 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4799 return;
4800 Py_DECREF(x);
4801
Tim Petersa9bc1682003-01-11 03:39:11 +00004802 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004803 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4804 return;
4805 Py_DECREF(x);
4806
4807 x = new_delta(0, 0, 1, 0);
4808 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4809 return;
4810 Py_DECREF(x);
4811
Tim Peters2a799bf2002-12-16 20:18:38 +00004812 /* module initialization */
4813 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4814 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4815
4816 Py_INCREF(&PyDateTime_DateType);
4817 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4818
Tim Petersa9bc1682003-01-11 03:39:11 +00004819 Py_INCREF(&PyDateTime_DateTimeType);
4820 PyModule_AddObject(m, "datetime",
4821 (PyObject *)&PyDateTime_DateTimeType);
4822
4823 Py_INCREF(&PyDateTime_TimeType);
4824 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4825
Tim Peters2a799bf2002-12-16 20:18:38 +00004826 Py_INCREF(&PyDateTime_DeltaType);
4827 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4828
Tim Peters2a799bf2002-12-16 20:18:38 +00004829 Py_INCREF(&PyDateTime_TZInfoType);
4830 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4831
Tim Peters9ddf40b2004-06-20 22:41:32 +00004832 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4833 NULL);
4834 if (x == NULL)
4835 return;
4836 PyModule_AddObject(m, "datetime_CAPI", x);
4837
Tim Peters2a799bf2002-12-16 20:18:38 +00004838 /* A 4-year cycle has an extra leap day over what we'd get from
4839 * pasting together 4 single years.
4840 */
4841 assert(DI4Y == 4 * 365 + 1);
4842 assert(DI4Y == days_before_year(4+1));
4843
4844 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4845 * get from pasting together 4 100-year cycles.
4846 */
4847 assert(DI400Y == 4 * DI100Y + 1);
4848 assert(DI400Y == days_before_year(400+1));
4849
4850 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4851 * pasting together 25 4-year cycles.
4852 */
4853 assert(DI100Y == 25 * DI4Y - 1);
4854 assert(DI100Y == days_before_year(100+1));
4855
4856 us_per_us = PyInt_FromLong(1);
4857 us_per_ms = PyInt_FromLong(1000);
4858 us_per_second = PyInt_FromLong(1000000);
4859 us_per_minute = PyInt_FromLong(60000000);
4860 seconds_per_day = PyInt_FromLong(24 * 3600);
4861 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4862 us_per_minute == NULL || seconds_per_day == NULL)
4863 return;
4864
4865 /* The rest are too big for 32-bit ints, but even
4866 * us_per_week fits in 40 bits, so doubles should be exact.
4867 */
4868 us_per_hour = PyLong_FromDouble(3600000000.0);
4869 us_per_day = PyLong_FromDouble(86400000000.0);
4870 us_per_week = PyLong_FromDouble(604800000000.0);
4871 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4872 return;
4873}
Tim Petersf3615152003-01-01 21:51:37 +00004874
4875/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004876Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004877 x.n = x stripped of its timezone -- its naive time.
4878 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4879 return None
4880 x.d = x.dst(), and assuming that doesn't raise an exception or
4881 return None
4882 x.s = x's standard offset, x.o - x.d
4883
4884Now some derived rules, where k is a duration (timedelta).
4885
48861. x.o = x.s + x.d
4887 This follows from the definition of x.s.
4888
Tim Petersc5dc4da2003-01-02 17:55:03 +000048892. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004890 This is actually a requirement, an assumption we need to make about
4891 sane tzinfo classes.
4892
48933. The naive UTC time corresponding to x is x.n - x.o.
4894 This is again a requirement for a sane tzinfo class.
4895
48964. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004897 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004898
Tim Petersc5dc4da2003-01-02 17:55:03 +000048995. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004900 Again follows from how arithmetic is defined.
4901
Tim Peters8bb5ad22003-01-24 02:44:45 +00004902Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004903(meaning that the various tzinfo methods exist, and don't blow up or return
4904None when called).
4905
Tim Petersa9bc1682003-01-11 03:39:11 +00004906The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004907x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004908
4909By #3, we want
4910
Tim Peters8bb5ad22003-01-24 02:44:45 +00004911 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004912
4913The algorithm starts by attaching tz to x.n, and calling that y. So
4914x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4915becomes true; in effect, we want to solve [2] for k:
4916
Tim Peters8bb5ad22003-01-24 02:44:45 +00004917 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004918
4919By #1, this is the same as
4920
Tim Peters8bb5ad22003-01-24 02:44:45 +00004921 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004922
4923By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4924Substituting that into [3],
4925
Tim Peters8bb5ad22003-01-24 02:44:45 +00004926 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4927 k - (y+k).s - (y+k).d = 0; rearranging,
4928 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4929 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004930
Tim Peters8bb5ad22003-01-24 02:44:45 +00004931On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4932approximate k by ignoring the (y+k).d term at first. Note that k can't be
4933very large, since all offset-returning methods return a duration of magnitude
4934less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4935be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004936
4937In any case, the new value is
4938
Tim Peters8bb5ad22003-01-24 02:44:45 +00004939 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004940
Tim Peters8bb5ad22003-01-24 02:44:45 +00004941It's helpful to step back at look at [4] from a higher level: it's simply
4942mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004943
4944At this point, if
4945
Tim Peters8bb5ad22003-01-24 02:44:45 +00004946 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004947
4948we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004949at the start of daylight time. Picture US Eastern for concreteness. The wall
4950time 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 +00004951sense then. The docs ask that an Eastern tzinfo class consider such a time to
4952be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4953on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004954the only spelling that makes sense on the local wall clock.
4955
Tim Petersc5dc4da2003-01-02 17:55:03 +00004956In fact, if [5] holds at this point, we do have the standard-time spelling,
4957but that takes a bit of proof. We first prove a stronger result. What's the
4958difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004959
Tim Peters8bb5ad22003-01-24 02:44:45 +00004960 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004961
Tim Petersc5dc4da2003-01-02 17:55:03 +00004962Now
4963 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004964 (y + y.s).n = by #5
4965 y.n + y.s = since y.n = x.n
4966 x.n + y.s = since z and y are have the same tzinfo member,
4967 y.s = z.s by #2
4968 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004969
Tim Petersc5dc4da2003-01-02 17:55:03 +00004970Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004971
Tim Petersc5dc4da2003-01-02 17:55:03 +00004972 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004973 x.n - ((x.n + z.s) - z.o) = expanding
4974 x.n - x.n - z.s + z.o = cancelling
4975 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004976 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004977
Tim Petersc5dc4da2003-01-02 17:55:03 +00004978So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004979
Tim Petersc5dc4da2003-01-02 17:55:03 +00004980If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004981spelling we wanted in the endcase described above. We're done. Contrarily,
4982if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004983
Tim Petersc5dc4da2003-01-02 17:55:03 +00004984If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4985add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004986local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004987
Tim Petersc5dc4da2003-01-02 17:55:03 +00004988Let
Tim Petersf3615152003-01-01 21:51:37 +00004989
Tim Peters4fede1a2003-01-04 00:26:59 +00004990 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004991
Tim Peters4fede1a2003-01-04 00:26:59 +00004992and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004993
Tim Peters8bb5ad22003-01-24 02:44:45 +00004994 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004995
Tim Peters8bb5ad22003-01-24 02:44:45 +00004996If so, we're done. If not, the tzinfo class is insane, according to the
4997assumptions we've made. This also requires a bit of proof. As before, let's
4998compute the difference between the LHS and RHS of [8] (and skipping some of
4999the justifications for the kinds of substitutions we've done several times
5000already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005001
Tim Peters8bb5ad22003-01-24 02:44:45 +00005002 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
5003 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5004 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5005 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5006 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00005007 - z.o + z'.o = #1 twice
5008 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5009 z'.d - z.d
5010
5011So 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 +00005012we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5013return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005014
Tim Peters8bb5ad22003-01-24 02:44:45 +00005015How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5016a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5017would have to change the result dst() returns: we start in DST, and moving
5018a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005019
Tim Peters8bb5ad22003-01-24 02:44:45 +00005020There isn't a sane case where this can happen. The closest it gets is at
5021the end of DST, where there's an hour in UTC with no spelling in a hybrid
5022tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5023that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5024UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5025time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5026clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5027standard time. Since that's what the local clock *does*, we want to map both
5028UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005029in local time, but so it goes -- it's the way the local clock works.
5030
Tim Peters8bb5ad22003-01-24 02:44:45 +00005031When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5032so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5033z' = 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 +00005034(correctly) concludes that z' is not UTC-equivalent to x.
5035
5036Because we know z.d said z was in daylight time (else [5] would have held and
5037we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005038and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005039return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5040but the reasoning doesn't depend on the example -- it depends on there being
5041two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005042z' must be in standard time, and is the spelling we want in this case.
5043
5044Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5045concerned (because it takes z' as being in standard time rather than the
5046daylight time we intend here), but returning it gives the real-life "local
5047clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5048tz.
5049
5050When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5051the 1:MM standard time spelling we want.
5052
5053So how can this break? One of the assumptions must be violated. Two
5054possibilities:
5055
50561) [2] effectively says that y.s is invariant across all y belong to a given
5057 time zone. This isn't true if, for political reasons or continental drift,
5058 a region decides to change its base offset from UTC.
5059
50602) There may be versions of "double daylight" time where the tail end of
5061 the analysis gives up a step too early. I haven't thought about that
5062 enough to say.
5063
5064In any case, it's clear that the default fromutc() is strong enough to handle
5065"almost all" time zones: so long as the standard offset is invariant, it
5066doesn't matter if daylight time transition points change from year to year, or
5067if daylight time is skipped in some years; it doesn't matter how large or
5068small dst() may get within its bounds; and it doesn't even matter if some
5069perverse time zone returns a negative dst()). So a breaking case must be
5070pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005071--------------------------------------------------------------------------- */