blob: 8b860e7a7737e267f4a78578a325a627a4dceeec [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
28# error "datetime.c requires that C int have at least 32 bits"
29#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
33
34/* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
38 */
39#define MAX_DELTA_DAYS 999999999
40
41/* Rename the long macros in datetime.h to more reasonable short names. */
42#define GET_YEAR PyDateTime_GET_YEAR
43#define GET_MONTH PyDateTime_GET_MONTH
44#define GET_DAY PyDateTime_GET_DAY
45#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
49
50/* Date accessors for date and datetime. */
51#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
55
56/* Date/Time accessors for datetime. */
57#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60#define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
64
65/* Time accessors for time. */
66#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73#define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
77
78/* Delta accessors for timedelta. */
79#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
82
83#define SET_TD_DAYS(o, v) ((o)->days = (v))
84#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
85#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
86
Tim Petersa032d2e2003-01-11 00:15:54 +000087/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
89 */
90#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
91
Tim Peters3f606292004-03-21 23:38:41 +000092/* M is a char or int claiming to be a valid month. The macro is equivalent
93 * to the two-sided Python test
94 * 1 <= M <= 12
95 */
96#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
97
Tim Peters2a799bf2002-12-16 20:18:38 +000098/* Forward declarations. */
99static PyTypeObject PyDateTime_DateType;
100static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000101static PyTypeObject PyDateTime_DeltaType;
102static PyTypeObject PyDateTime_TimeType;
103static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000104
105/* ---------------------------------------------------------------------------
106 * Math utilities.
107 */
108
109/* k = i+j overflows iff k differs in sign from both inputs,
110 * iff k^i has sign bit set and k^j has sign bit set,
111 * iff (k^i)&(k^j) has sign bit set.
112 */
113#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
114 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
115
116/* Compute Python divmod(x, y), returning the quotient and storing the
117 * remainder into *r. The quotient is the floor of x/y, and that's
118 * the real point of this. C will probably truncate instead (C99
119 * requires truncation; C89 left it implementation-defined).
120 * Simplification: we *require* that y > 0 here. That's appropriate
121 * for all the uses made of it. This simplifies the code and makes
122 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
123 * overflow case).
124 */
125static int
126divmod(int x, int y, int *r)
127{
128 int quo;
129
130 assert(y > 0);
131 quo = x / y;
132 *r = x - quo * y;
133 if (*r < 0) {
134 --quo;
135 *r += y;
136 }
137 assert(0 <= *r && *r < y);
138 return quo;
139}
140
Tim Peters5d644dd2003-01-02 16:32:54 +0000141/* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
143 */
144static long
145round_to_long(double x)
146{
147 if (x >= 0.0)
148 x = floor(x + 0.5);
149 else
150 x = ceil(x - 0.5);
151 return (long)x;
152}
153
Tim Peters2a799bf2002-12-16 20:18:38 +0000154/* ---------------------------------------------------------------------------
155 * General calendrical helper functions
156 */
157
158/* For each month ordinal in 1..12, the number of days in that month,
159 * and the number of days before that month in the same year. These
160 * are correct for non-leap years only.
161 */
162static int _days_in_month[] = {
163 0, /* unused; this vector uses 1-based indexing */
164 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
165};
166
167static int _days_before_month[] = {
168 0, /* unused; this vector uses 1-based indexing */
169 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
170};
171
172/* year -> 1 if leap year, else 0. */
173static int
174is_leap(int year)
175{
176 /* Cast year to unsigned. The result is the same either way, but
177 * C can generate faster code for unsigned mod than for signed
178 * mod (especially for % 4 -- a good compiler should just grab
179 * the last 2 bits when the LHS is unsigned).
180 */
181 const unsigned int ayear = (unsigned int)year;
182 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
183}
184
185/* year, month -> number of days in that month in that year */
186static int
187days_in_month(int year, int month)
188{
189 assert(month >= 1);
190 assert(month <= 12);
191 if (month == 2 && is_leap(year))
192 return 29;
193 else
194 return _days_in_month[month];
195}
196
197/* year, month -> number of days in year preceeding first day of month */
198static int
199days_before_month(int year, int month)
200{
201 int days;
202
203 assert(month >= 1);
204 assert(month <= 12);
205 days = _days_before_month[month];
206 if (month > 2 && is_leap(year))
207 ++days;
208 return days;
209}
210
211/* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
213 */
214static int
215days_before_year(int year)
216{
217 int y = year - 1;
218 /* This is incorrect if year <= 0; we really want the floor
219 * here. But so long as MINYEAR is 1, the smallest year this
220 * can see is 0 (this can happen in some normalization endcases),
221 * so we'll just special-case that.
222 */
223 assert (year >= 0);
224 if (y >= 0)
225 return y*365 + y/4 - y/100 + y/400;
226 else {
227 assert(y == -1);
228 return -366;
229 }
230}
231
232/* Number of days in 4, 100, and 400 year cycles. That these have
233 * the correct values is asserted in the module init function.
234 */
235#define DI4Y 1461 /* days_before_year(5); days in 4 years */
236#define DI100Y 36524 /* days_before_year(101); days in 100 years */
237#define DI400Y 146097 /* days_before_year(401); days in 400 years */
238
239/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
240static void
241ord_to_ymd(int ordinal, int *year, int *month, int *day)
242{
243 int n, n1, n4, n100, n400, leapyear, preceding;
244
245 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
246 * leap years repeats exactly every 400 years. The basic strategy is
247 * to find the closest 400-year boundary at or before ordinal, then
248 * work with the offset from that boundary to ordinal. Life is much
249 * clearer if we subtract 1 from ordinal first -- then the values
250 * of ordinal at 400-year boundaries are exactly those divisible
251 * by DI400Y:
252 *
253 * D M Y n n-1
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
257 * ...
258 * 30 Dec 000 -1 -2
259 * 31 Dec 000 0 -1
260 * 1 Jan 001 1 0 400-year boundary
261 * 2 Jan 001 2 1
262 * 3 Jan 001 3 2
263 * ...
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
266 */
267 assert(ordinal >= 1);
268 --ordinal;
269 n400 = ordinal / DI400Y;
270 n = ordinal % DI400Y;
271 *year = n400 * 400 + 1;
272
273 /* Now n is the (non-negative) offset, in days, from January 1 of
274 * year, to the desired date. Now compute how many 100-year cycles
275 * precede n.
276 * Note that it's possible for n100 to equal 4! In that case 4 full
277 * 100-year cycles precede the desired day, which implies the
278 * desired day is December 31 at the end of a 400-year cycle.
279 */
280 n100 = n / DI100Y;
281 n = n % DI100Y;
282
283 /* Now compute how many 4-year cycles precede it. */
284 n4 = n / DI4Y;
285 n = n % DI4Y;
286
287 /* And now how many single years. Again n1 can be 4, and again
288 * meaning that the desired day is December 31 at the end of the
289 * 4-year cycle.
290 */
291 n1 = n / 365;
292 n = n % 365;
293
294 *year += n100 * 100 + n4 * 4 + n1;
295 if (n1 == 4 || n100 == 4) {
296 assert(n == 0);
297 *year -= 1;
298 *month = 12;
299 *day = 31;
300 return;
301 }
302
303 /* Now the year is correct, and n is the offset from January 1. We
304 * find the month via an estimate that's either exact or one too
305 * large.
306 */
307 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
308 assert(leapyear == is_leap(*year));
309 *month = (n + 50) >> 5;
310 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
311 if (preceding > n) {
312 /* estimate is too large */
313 *month -= 1;
314 preceding -= days_in_month(*year, *month);
315 }
316 n -= preceding;
317 assert(0 <= n);
318 assert(n < days_in_month(*year, *month));
319
320 *day = n + 1;
321}
322
323/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
324static int
325ymd_to_ord(int year, int month, int day)
326{
327 return days_before_year(year) + days_before_month(year, month) + day;
328}
329
330/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
331static int
332weekday(int year, int month, int day)
333{
334 return (ymd_to_ord(year, month, day) + 6) % 7;
335}
336
337/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
338 * first calendar week containing a Thursday.
339 */
340static int
341iso_week1_monday(int year)
342{
343 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
344 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
345 int first_weekday = (first_day + 6) % 7;
346 /* ordinal of closest Monday at or before 1/1 */
347 int week1_monday = first_day - first_weekday;
348
349 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
350 week1_monday += 7;
351 return week1_monday;
352}
353
354/* ---------------------------------------------------------------------------
355 * Range checkers.
356 */
357
358/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
360 */
361static int
362check_delta_day_range(int days)
363{
364 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
365 return 0;
366 PyErr_Format(PyExc_OverflowError,
367 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000368 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000369 return -1;
370}
371
372/* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
374 */
375static int
376check_date_args(int year, int month, int day)
377{
378
379 if (year < MINYEAR || year > MAXYEAR) {
380 PyErr_SetString(PyExc_ValueError,
381 "year is out of range");
382 return -1;
383 }
384 if (month < 1 || month > 12) {
385 PyErr_SetString(PyExc_ValueError,
386 "month must be in 1..12");
387 return -1;
388 }
389 if (day < 1 || day > days_in_month(year, month)) {
390 PyErr_SetString(PyExc_ValueError,
391 "day is out of range for month");
392 return -1;
393 }
394 return 0;
395}
396
397/* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_time_args(int h, int m, int s, int us)
402{
403 if (h < 0 || h > 23) {
404 PyErr_SetString(PyExc_ValueError,
405 "hour must be in 0..23");
406 return -1;
407 }
408 if (m < 0 || m > 59) {
409 PyErr_SetString(PyExc_ValueError,
410 "minute must be in 0..59");
411 return -1;
412 }
413 if (s < 0 || s > 59) {
414 PyErr_SetString(PyExc_ValueError,
415 "second must be in 0..59");
416 return -1;
417 }
418 if (us < 0 || us > 999999) {
419 PyErr_SetString(PyExc_ValueError,
420 "microsecond must be in 0..999999");
421 return -1;
422 }
423 return 0;
424}
425
426/* ---------------------------------------------------------------------------
427 * Normalization utilities.
428 */
429
430/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
431 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
432 * at least factor, enough of *lo is converted into "hi" units so that
433 * 0 <= *lo < factor. The input values must be such that int overflow
434 * is impossible.
435 */
436static void
437normalize_pair(int *hi, int *lo, int factor)
438{
439 assert(factor > 0);
440 assert(lo != hi);
441 if (*lo < 0 || *lo >= factor) {
442 const int num_hi = divmod(*lo, factor, lo);
443 const int new_hi = *hi + num_hi;
444 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
445 *hi = new_hi;
446 }
447 assert(0 <= *lo && *lo < factor);
448}
449
450/* Fiddle days (d), seconds (s), and microseconds (us) so that
451 * 0 <= *s < 24*3600
452 * 0 <= *us < 1000000
453 * The input values must be such that the internals don't overflow.
454 * The way this routine is used, we don't get close.
455 */
456static void
457normalize_d_s_us(int *d, int *s, int *us)
458{
459 if (*us < 0 || *us >= 1000000) {
460 normalize_pair(s, us, 1000000);
461 /* |s| can't be bigger than about
462 * |original s| + |original us|/1000000 now.
463 */
464
465 }
466 if (*s < 0 || *s >= 24*3600) {
467 normalize_pair(d, s, 24*3600);
468 /* |d| can't be bigger than about
469 * |original d| +
470 * (|original s| + |original us|/1000000) / (24*3600) now.
471 */
472 }
473 assert(0 <= *s && *s < 24*3600);
474 assert(0 <= *us && *us < 1000000);
475}
476
477/* Fiddle years (y), months (m), and days (d) so that
478 * 1 <= *m <= 12
479 * 1 <= *d <= days_in_month(*y, *m)
480 * The input values must be such that the internals don't overflow.
481 * The way this routine is used, we don't get close.
482 */
483static void
484normalize_y_m_d(int *y, int *m, int *d)
485{
486 int dim; /* # of days in month */
487
488 /* This gets muddy: the proper range for day can't be determined
489 * without knowing the correct month and year, but if day is, e.g.,
490 * plus or minus a million, the current month and year values make
491 * no sense (and may also be out of bounds themselves).
492 * Saying 12 months == 1 year should be non-controversial.
493 */
494 if (*m < 1 || *m > 12) {
495 --*m;
496 normalize_pair(y, m, 12);
497 ++*m;
498 /* |y| can't be bigger than about
499 * |original y| + |original m|/12 now.
500 */
501 }
502 assert(1 <= *m && *m <= 12);
503
504 /* Now only day can be out of bounds (year may also be out of bounds
505 * for a datetime object, but we don't care about that here).
506 * If day is out of bounds, what to do is arguable, but at least the
507 * method here is principled and explainable.
508 */
509 dim = days_in_month(*y, *m);
510 if (*d < 1 || *d > dim) {
511 /* Move day-1 days from the first of the month. First try to
512 * get off cheap if we're only one day out of range
513 * (adjustments for timezone alone can't be worse than that).
514 */
515 if (*d == 0) {
516 --*m;
517 if (*m > 0)
518 *d = days_in_month(*y, *m);
519 else {
520 --*y;
521 *m = 12;
522 *d = 31;
523 }
524 }
525 else if (*d == dim + 1) {
526 /* move forward a day */
527 ++*m;
528 *d = 1;
529 if (*m > 12) {
530 *m = 1;
531 ++*y;
532 }
533 }
534 else {
535 int ordinal = ymd_to_ord(*y, *m, 1) +
536 *d - 1;
537 ord_to_ymd(ordinal, y, m, d);
538 }
539 }
540 assert(*m > 0);
541 assert(*d > 0);
542}
543
544/* Fiddle out-of-bounds months and days so that the result makes some kind
545 * of sense. The parameters are both inputs and outputs. Returns < 0 on
546 * failure, where failure means the adjusted year is out of bounds.
547 */
548static int
549normalize_date(int *year, int *month, int *day)
550{
551 int result;
552
553 normalize_y_m_d(year, month, day);
554 if (MINYEAR <= *year && *year <= MAXYEAR)
555 result = 0;
556 else {
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 result = -1;
560 }
561 return result;
562}
563
564/* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
566 */
567static int
568normalize_datetime(int *year, int *month, int *day,
569 int *hour, int *minute, int *second,
570 int *microsecond)
571{
572 normalize_pair(second, microsecond, 1000000);
573 normalize_pair(minute, second, 60);
574 normalize_pair(hour, minute, 60);
575 normalize_pair(day, hour, 24);
576 return normalize_date(year, month, day);
577}
578
579/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000580 * Basic object allocation: tp_alloc implementations. These allocate
581 * Python objects of the right size and type, and do the Python object-
582 * initialization bit. If there's not enough memory, they return NULL after
583 * setting MemoryError. All data members remain uninitialized trash.
584 *
585 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000586 * member is needed. This is ugly, imprecise, and possibly insecure.
587 * tp_basicsize for the time and datetime types is set to the size of the
588 * struct that has room for the tzinfo member, so subclasses in Python will
589 * allocate enough space for a tzinfo member whether or not one is actually
590 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
591 * part is that PyType_GenericAlloc() (which subclasses in Python end up
592 * using) just happens today to effectively ignore the nitems argument
593 * when tp_itemsize is 0, which it is for these type objects. If that
594 * changes, perhaps the callers of tp_alloc slots in this file should
595 * be changed to force a 0 nitems argument unless the type being allocated
596 * is a base type implemented in this file (so that tp_alloc is time_alloc
597 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000598 */
599
600static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000601time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000602{
603 PyObject *self;
604
605 self = (PyObject *)
606 PyObject_MALLOC(aware ?
607 sizeof(PyDateTime_Time) :
608 sizeof(_PyDateTime_BaseTime));
609 if (self == NULL)
610 return (PyObject *)PyErr_NoMemory();
611 PyObject_INIT(self, type);
612 return self;
613}
614
615static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000616datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000617{
618 PyObject *self;
619
620 self = (PyObject *)
621 PyObject_MALLOC(aware ?
622 sizeof(PyDateTime_DateTime) :
623 sizeof(_PyDateTime_BaseDateTime));
624 if (self == NULL)
625 return (PyObject *)PyErr_NoMemory();
626 PyObject_INIT(self, type);
627 return self;
628}
629
630/* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
633 */
634
635/* For date and datetime. */
636static void
637set_date_fields(PyDateTime_Date *self, int y, int m, int d)
638{
639 self->hashcode = -1;
640 SET_YEAR(self, y);
641 SET_MONTH(self, m);
642 SET_DAY(self, d);
643}
644
645/* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
647 */
648
649/* Create a date instance with no range checking. */
650static PyObject *
651new_date_ex(int year, int month, int day, PyTypeObject *type)
652{
653 PyDateTime_Date *self;
654
655 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
656 if (self != NULL)
657 set_date_fields(self, year, month, day);
658 return (PyObject *) self;
659}
660
661#define new_date(year, month, day) \
662 new_date_ex(year, month, day, &PyDateTime_DateType)
663
664/* Create a datetime instance with no range checking. */
665static PyObject *
666new_datetime_ex(int year, int month, int day, int hour, int minute,
667 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
668{
669 PyDateTime_DateTime *self;
670 char aware = tzinfo != Py_None;
671
672 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
673 if (self != NULL) {
674 self->hastzinfo = aware;
675 set_date_fields((PyDateTime_Date *)self, year, month, day);
676 DATE_SET_HOUR(self, hour);
677 DATE_SET_MINUTE(self, minute);
678 DATE_SET_SECOND(self, second);
679 DATE_SET_MICROSECOND(self, usecond);
680 if (aware) {
681 Py_INCREF(tzinfo);
682 self->tzinfo = tzinfo;
683 }
684 }
685 return (PyObject *)self;
686}
687
688#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
689 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
690 &PyDateTime_DateTimeType)
691
692/* Create a time instance with no range checking. */
693static PyObject *
694new_time_ex(int hour, int minute, int second, int usecond,
695 PyObject *tzinfo, PyTypeObject *type)
696{
697 PyDateTime_Time *self;
698 char aware = tzinfo != Py_None;
699
700 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
701 if (self != NULL) {
702 self->hastzinfo = aware;
703 self->hashcode = -1;
704 TIME_SET_HOUR(self, hour);
705 TIME_SET_MINUTE(self, minute);
706 TIME_SET_SECOND(self, second);
707 TIME_SET_MICROSECOND(self, usecond);
708 if (aware) {
709 Py_INCREF(tzinfo);
710 self->tzinfo = tzinfo;
711 }
712 }
713 return (PyObject *)self;
714}
715
716#define new_time(hh, mm, ss, us, tzinfo) \
717 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
718
719/* Create a timedelta instance. Normalize the members iff normalize is
720 * true. Passing false is a speed optimization, if you know for sure
721 * that seconds and microseconds are already in their proper ranges. In any
722 * case, raises OverflowError and returns NULL if the normalized days is out
723 * of range).
724 */
725static PyObject *
726new_delta_ex(int days, int seconds, int microseconds, int normalize,
727 PyTypeObject *type)
728{
729 PyDateTime_Delta *self;
730
731 if (normalize)
732 normalize_d_s_us(&days, &seconds, &microseconds);
733 assert(0 <= seconds && seconds < 24*3600);
734 assert(0 <= microseconds && microseconds < 1000000);
735
736 if (check_delta_day_range(days) < 0)
737 return NULL;
738
739 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
740 if (self != NULL) {
741 self->hashcode = -1;
742 SET_TD_DAYS(self, days);
743 SET_TD_SECONDS(self, seconds);
744 SET_TD_MICROSECONDS(self, microseconds);
745 }
746 return (PyObject *) self;
747}
748
749#define new_delta(d, s, us, normalize) \
750 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
751
752/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000753 * tzinfo helpers.
754 */
755
Tim Peters855fe882002-12-22 03:43:39 +0000756/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
758 */
759static int
760check_tzinfo_subclass(PyObject *p)
761{
762 if (p == Py_None || PyTZInfo_Check(p))
763 return 0;
764 PyErr_Format(PyExc_TypeError,
765 "tzinfo argument must be None or of a tzinfo subclass, "
766 "not type '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000767 Py_Type(p)->tp_name);
Tim Peters855fe882002-12-22 03:43:39 +0000768 return -1;
769}
770
Tim Petersbad8ff02002-12-30 20:52:32 +0000771/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000772 * If tzinfo is None, returns None.
773 */
774static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000775call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000776{
777 PyObject *result;
778
Tim Petersbad8ff02002-12-30 20:52:32 +0000779 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
784 }
785 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000787 return result;
788}
789
Tim Peters2a799bf2002-12-16 20:18:38 +0000790/* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
793 */
794static PyObject *
795get_tzinfo_member(PyObject *self)
796{
797 PyObject *tzinfo = NULL;
798
Tim Petersa9bc1682003-01-11 03:39:11 +0000799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000801 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
804 return tzinfo;
805}
806
Tim Petersbad8ff02002-12-30 20:52:32 +0000807/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * Else *none is set to 0 and the integer method result is returned.
814 */
815static int
816call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
818{
819 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000820 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000821
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
825
826 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 if (u == NULL)
829 return -1;
830
Tim Peters27362852002-12-23 16:17:39 +0000831 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 result = 0;
833 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000834 }
Tim Peters855fe882002-12-22 03:43:39 +0000835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
842 */
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000851 }
852 }
853 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000854 else {
855 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000856 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000857 "timedelta, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000858 name, Py_Type(u)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 }
860
Tim Peters2a799bf2002-12-16 20:18:38 +0000861 Py_DECREF(u);
862 if (result < -1439 || result > 1439) {
863 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000864 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000865 "-1439 .. 1439",
866 name, result);
867 result = -1;
868 }
Tim Peters397301e2003-01-02 21:28:08 +0000869 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000870}
871
872/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
873 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
874 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000875 * doesn't return None or timedelta, TypeError is raised and this returns -1.
876 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
877 * # of minutes), ValueError is raised and this returns -1. Else *none is
878 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000879 */
880static int
881call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
882{
883 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
884}
885
Tim Petersbad8ff02002-12-30 20:52:32 +0000886/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
887 */
Tim Peters855fe882002-12-22 03:43:39 +0000888static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000889offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000890 PyObject *result;
891
Tim Petersbad8ff02002-12-30 20:52:32 +0000892 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000893 if (tzinfo == Py_None) {
894 result = Py_None;
895 Py_INCREF(result);
896 }
897 else {
898 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000899 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
900 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000901 if (offset < 0 && PyErr_Occurred())
902 return NULL;
903 if (none) {
904 result = Py_None;
905 Py_INCREF(result);
906 }
907 else
908 result = new_delta(0, offset * 60, 0, 1);
909 }
910 return result;
911}
912
Tim Peters2a799bf2002-12-16 20:18:38 +0000913/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If dst()
915 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000916 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000917 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000918 * ValueError is raised and this returns -1. Else *none is set to 0 and
919 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000920 */
921static int
922call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
923{
924 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
925}
926
Tim Petersbad8ff02002-12-30 20:52:32 +0000927/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000928 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000929 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000930 * returns NULL. If the result is a string, we ensure it is a Unicode
931 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000932 */
933static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000934call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000935{
936 PyObject *result;
937
938 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000939 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000940 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000941
Tim Peters855fe882002-12-22 03:43:39 +0000942 if (tzinfo == Py_None) {
943 result = Py_None;
944 Py_INCREF(result);
945 }
946 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000947 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000948
Guido van Rossume3d1d412007-05-23 21:24:35 +0000949 if (result != NULL && result != Py_None) {
950 if (!PyString_Check(result) && !PyUnicode_Check(result)) {
951 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
952 "return None or a string, not '%s'",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +0000953 Py_Type(result)->tp_name);
Guido van Rossume3d1d412007-05-23 21:24:35 +0000954 Py_DECREF(result);
955 result = NULL;
956 }
957 else if (!PyUnicode_Check(result)) {
958 PyObject *temp = PyUnicode_FromObject(result);
959 Py_DECREF(result);
960 result = temp;
961 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000962 }
963 return result;
964}
965
966typedef enum {
967 /* an exception has been set; the caller should pass it on */
968 OFFSET_ERROR,
969
Tim Petersa9bc1682003-01-11 03:39:11 +0000970 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000971 OFFSET_UNKNOWN,
972
973 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000974 * datetime with !hastzinfo
975 * datetime with None tzinfo,
976 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000977 * time with !hastzinfo
978 * time with None tzinfo,
979 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 */
981 OFFSET_NAIVE,
982
Tim Petersa9bc1682003-01-11 03:39:11 +0000983 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000984 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000985} naivety;
986
Tim Peters14b69412002-12-22 18:10:22 +0000987/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000988 * the "naivety" typedef for details. If the type is aware, *offset is set
989 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000990 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 */
993static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000994classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000995{
996 int none;
997 PyObject *tzinfo;
998
Tim Peterse39a80c2002-12-30 21:28:52 +0000999 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001000 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +00001001 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (tzinfo == Py_None)
1003 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +00001004 if (tzinfo == NULL) {
1005 /* note that a datetime passes the PyDate_Check test */
1006 return (PyTime_Check(op) || PyDate_Check(op)) ?
1007 OFFSET_NAIVE : OFFSET_UNKNOWN;
1008 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001009 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001010 if (*offset == -1 && PyErr_Occurred())
1011 return OFFSET_ERROR;
1012 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1013}
1014
Tim Peters00237032002-12-27 02:21:51 +00001015/* Classify two objects as to whether they're naive or offset-aware.
1016 * This isn't quite the same as calling classify_utcoffset() twice: for
1017 * binary operations (comparison and subtraction), we generally want to
1018 * ignore the tzinfo members if they're identical. This is by design,
1019 * so that results match "naive" expectations when mixing objects from a
1020 * single timezone. So in that case, this sets both offsets to 0 and
1021 * both naiveties to OFFSET_NAIVE.
1022 * The function returns 0 if everything's OK, and -1 on error.
1023 */
1024static int
1025classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001026 PyObject *tzinfoarg1,
1027 PyObject *o2, int *offset2, naivety *n2,
1028 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001029{
1030 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1031 *offset1 = *offset2 = 0;
1032 *n1 = *n2 = OFFSET_NAIVE;
1033 }
1034 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001035 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001036 if (*n1 == OFFSET_ERROR)
1037 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001038 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001039 if (*n2 == OFFSET_ERROR)
1040 return -1;
1041 }
1042 return 0;
1043}
1044
Tim Peters2a799bf2002-12-16 20:18:38 +00001045/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1046 * stuff
1047 * ", tzinfo=" + repr(tzinfo)
1048 * before the closing ")".
1049 */
1050static PyObject *
1051append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1052{
1053 PyObject *temp;
1054
Walter Dörwald1ab83302007-05-18 17:15:44 +00001055 assert(PyUnicode_Check(repr));
Tim Peters2a799bf2002-12-16 20:18:38 +00001056 assert(tzinfo);
1057 if (tzinfo == Py_None)
1058 return repr;
1059 /* Get rid of the trailing ')'. */
Walter Dörwald1ab83302007-05-18 17:15:44 +00001060 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1061 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1062 PyUnicode_GET_SIZE(repr) - 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001063 Py_DECREF(repr);
1064 if (temp == NULL)
1065 return NULL;
Walter Dörwald517bcfe2007-05-23 20:45:05 +00001066 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1067 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00001068 return repr;
1069}
1070
1071/* ---------------------------------------------------------------------------
1072 * String format helpers.
1073 */
1074
1075static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001076format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001077{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001078 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001079 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1080 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001081 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001082 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1083 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1084 };
1085
Tim Peters2a799bf2002-12-16 20:18:38 +00001086 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1087
Walter Dörwald4af32b32007-05-31 16:19:50 +00001088 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1089 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1090 GET_DAY(date), hours, minutes, seconds,
1091 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001092}
1093
1094/* Add an hours & minutes UTC offset string to buf. buf has no more than
1095 * buflen bytes remaining. The UTC offset is gotten by calling
1096 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1097 * *buf, and that's all. Else the returned value is checked for sanity (an
1098 * integer in range), and if that's OK it's converted to an hours & minutes
1099 * string of the form
1100 * sign HH sep MM
1101 * Returns 0 if everything is OK. If the return value from utcoffset() is
1102 * bogus, an appropriate exception is set and -1 is returned.
1103 */
1104static int
Tim Peters328fff72002-12-20 01:31:27 +00001105format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001106 PyObject *tzinfo, PyObject *tzinfoarg)
1107{
1108 int offset;
1109 int hours;
1110 int minutes;
1111 char sign;
1112 int none;
1113
1114 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1115 if (offset == -1 && PyErr_Occurred())
1116 return -1;
1117 if (none) {
1118 *buf = '\0';
1119 return 0;
1120 }
1121 sign = '+';
1122 if (offset < 0) {
1123 sign = '-';
1124 offset = - offset;
1125 }
1126 hours = divmod(offset, 60, &minutes);
1127 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1128 return 0;
1129}
1130
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001131static PyObject *
1132make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1133{
Neal Norwitzaea70e02007-08-12 04:32:26 +00001134 PyObject *temp;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001135 PyObject *tzinfo = get_tzinfo_member(object);
1136 PyObject *Zreplacement = PyString_FromString("");
1137 if (Zreplacement == NULL)
1138 return NULL;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001139 if (tzinfo == Py_None || tzinfo == NULL)
1140 return Zreplacement;
1141
1142 assert(tzinfoarg != NULL);
1143 temp = call_tzname(tzinfo, tzinfoarg);
1144 if (temp == NULL)
1145 goto Error;
1146 if (temp == Py_None) {
1147 Py_DECREF(temp);
1148 return Zreplacement;
1149 }
1150
1151 assert(PyUnicode_Check(temp));
1152 /* Since the tzname is getting stuffed into the
1153 * format, we have to double any % signs so that
1154 * strftime doesn't treat them as format codes.
1155 */
1156 Py_DECREF(Zreplacement);
1157 Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1158 Py_DECREF(temp);
1159 if (Zreplacement == NULL)
1160 return NULL;
1161 if (PyUnicode_Check(Zreplacement)) {
Neal Norwitzaea70e02007-08-12 04:32:26 +00001162 PyObject *Zreplacement2 =
1163 _PyUnicode_AsDefaultEncodedString(Zreplacement, NULL);
1164 if (Zreplacement2 == NULL)
1165 return NULL;
1166 Py_INCREF(Zreplacement2);
Guido van Rossum06610092007-08-16 21:02:22 +00001167 Py_DECREF(Zreplacement);
Neal Norwitzaea70e02007-08-12 04:32:26 +00001168 Zreplacement = Zreplacement2;
1169 }
1170 if (!PyString_Check(Zreplacement)) {
1171 PyErr_SetString(PyExc_TypeError,
1172 "tzname.replace() did not return a string");
1173 goto Error;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001174 }
1175 return Zreplacement;
1176
1177 Error:
1178 Py_DECREF(Zreplacement);
1179 return NULL;
1180}
1181
Tim Peters2a799bf2002-12-16 20:18:38 +00001182/* I sure don't want to reproduce the strftime code from the time module,
1183 * so this imports the module and calls it. All the hair is due to
1184 * giving special meanings to the %z and %Z format codes via a preprocessing
1185 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001186 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1187 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001188 */
1189static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001190wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1191 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001192{
1193 PyObject *result = NULL; /* guilty until proved innocent */
1194
1195 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1196 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1197
Guido van Rossumbce56a62007-05-10 18:04:33 +00001198 const char *pin;/* pointer to next char in input format */
1199 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001200 char ch; /* next char in input format */
1201
1202 PyObject *newfmt = NULL; /* py string, the output format */
1203 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001204 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001205 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001206 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001207
Guido van Rossumbce56a62007-05-10 18:04:33 +00001208 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001209 int ntoappend; /* # of bytes to append to output buffer */
1210
Tim Peters2a799bf2002-12-16 20:18:38 +00001211 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001212 assert(PyString_Check(format) || PyUnicode_Check(format));
1213
1214 /* Convert the input format to a C string and size */
1215 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1216 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001217
Tim Petersd6844152002-12-22 20:58:42 +00001218 /* Give up if the year is before 1900.
1219 * Python strftime() plays games with the year, and different
1220 * games depending on whether envar PYTHON2K is set. This makes
1221 * years before 1900 a nightmare, even if the platform strftime
1222 * supports them (and not all do).
1223 * We could get a lot farther here by avoiding Python's strftime
1224 * wrapper and calling the C strftime() directly, but that isn't
1225 * an option in the Python implementation of this module.
1226 */
1227 {
1228 long year;
1229 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1230 if (pyyear == NULL) return NULL;
1231 assert(PyInt_Check(pyyear));
1232 year = PyInt_AsLong(pyyear);
1233 Py_DECREF(pyyear);
1234 if (year < 1900) {
1235 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1236 "1900; the datetime strftime() "
1237 "methods require year >= 1900",
1238 year);
1239 return NULL;
1240 }
1241 }
1242
Tim Peters2a799bf2002-12-16 20:18:38 +00001243 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001244 * a new format. Since computing the replacements for those codes
1245 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001246 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001247 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001248 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1249 if (newfmt == NULL) goto Done;
1250 pnew = PyString_AsString(newfmt);
1251 usednew = 0;
1252
Tim Peters2a799bf2002-12-16 20:18:38 +00001253 while ((ch = *pin++) != '\0') {
1254 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001255 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001256 ntoappend = 1;
1257 }
1258 else if ((ch = *pin++) == '\0') {
1259 /* There's a lone trailing %; doesn't make sense. */
1260 PyErr_SetString(PyExc_ValueError, "strftime format "
1261 "ends with raw %");
1262 goto Done;
1263 }
1264 /* A % has been seen and ch is the character after it. */
1265 else if (ch == 'z') {
1266 if (zreplacement == NULL) {
1267 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001268 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001269 PyObject *tzinfo = get_tzinfo_member(object);
1270 zreplacement = PyString_FromString("");
1271 if (zreplacement == NULL) goto Done;
1272 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001273 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001274 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001275 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001276 "",
1277 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001278 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001279 goto Done;
1280 Py_DECREF(zreplacement);
1281 zreplacement = PyString_FromString(buf);
1282 if (zreplacement == NULL) goto Done;
1283 }
1284 }
1285 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001286 ptoappend = PyString_AS_STRING(zreplacement);
1287 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001288 }
1289 else if (ch == 'Z') {
1290 /* format tzname */
1291 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001292 Zreplacement = make_Zreplacement(object,
1293 tzinfoarg);
1294 if (Zreplacement == NULL)
1295 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001296 }
1297 assert(Zreplacement != NULL);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001298 assert(PyString_Check(Zreplacement));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001299 ptoappend = PyString_AS_STRING(Zreplacement);
1300 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001301 }
1302 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 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 {
1335 PyObject *time = PyImport_ImportModule("time");
1336 if (time == NULL)
1337 goto Done;
1338 result = PyObject_CallMethod(time, "strftime", "OO",
1339 newfmt, timetuple);
1340 Py_DECREF(time);
1341 }
1342 Done:
1343 Py_XDECREF(zreplacement);
1344 Py_XDECREF(Zreplacement);
1345 Py_XDECREF(newfmt);
1346 return result;
1347}
1348
Tim Peters2a799bf2002-12-16 20:18:38 +00001349/* ---------------------------------------------------------------------------
1350 * Wrap functions from the time module. These aren't directly available
1351 * from C. Perhaps they should be.
1352 */
1353
1354/* Call time.time() and return its result (a Python float). */
1355static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001356time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001357{
1358 PyObject *result = NULL;
1359 PyObject *time = PyImport_ImportModule("time");
1360
1361 if (time != NULL) {
1362 result = PyObject_CallMethod(time, "time", "()");
1363 Py_DECREF(time);
1364 }
1365 return result;
1366}
1367
1368/* Build a time.struct_time. The weekday and day number are automatically
1369 * computed from the y,m,d args.
1370 */
1371static PyObject *
1372build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1373{
1374 PyObject *time;
1375 PyObject *result = NULL;
1376
1377 time = PyImport_ImportModule("time");
1378 if (time != NULL) {
1379 result = PyObject_CallMethod(time, "struct_time",
1380 "((iiiiiiiii))",
1381 y, m, d,
1382 hh, mm, ss,
1383 weekday(y, m, d),
1384 days_before_month(y, m) + d,
1385 dstflag);
1386 Py_DECREF(time);
1387 }
1388 return result;
1389}
1390
1391/* ---------------------------------------------------------------------------
1392 * Miscellaneous helpers.
1393 */
1394
Guido van Rossum19960592006-08-24 17:29:38 +00001395/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001396 * The comparisons here all most naturally compute a cmp()-like result.
1397 * This little helper turns that into a bool result for rich comparisons.
1398 */
1399static PyObject *
1400diff_to_bool(int diff, int op)
1401{
1402 PyObject *result;
1403 int istrue;
1404
1405 switch (op) {
1406 case Py_EQ: istrue = diff == 0; break;
1407 case Py_NE: istrue = diff != 0; break;
1408 case Py_LE: istrue = diff <= 0; break;
1409 case Py_GE: istrue = diff >= 0; break;
1410 case Py_LT: istrue = diff < 0; break;
1411 case Py_GT: istrue = diff > 0; break;
1412 default:
1413 assert(! "op unknown");
1414 istrue = 0; /* To shut up compiler */
1415 }
1416 result = istrue ? Py_True : Py_False;
1417 Py_INCREF(result);
1418 return result;
1419}
1420
Tim Peters07534a62003-02-07 22:50:28 +00001421/* Raises a "can't compare" TypeError and returns NULL. */
1422static PyObject *
1423cmperror(PyObject *a, PyObject *b)
1424{
1425 PyErr_Format(PyExc_TypeError,
1426 "can't compare %s to %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001427 Py_Type(a)->tp_name, Py_Type(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001428 return NULL;
1429}
1430
Tim Peters2a799bf2002-12-16 20:18:38 +00001431/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001432 * Cached Python objects; these are set by the module init function.
1433 */
1434
1435/* Conversion factors. */
1436static PyObject *us_per_us = NULL; /* 1 */
1437static PyObject *us_per_ms = NULL; /* 1000 */
1438static PyObject *us_per_second = NULL; /* 1000000 */
1439static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1440static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1441static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1442static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1443static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1444
Tim Peters2a799bf2002-12-16 20:18:38 +00001445/* ---------------------------------------------------------------------------
1446 * Class implementations.
1447 */
1448
1449/*
1450 * PyDateTime_Delta implementation.
1451 */
1452
1453/* Convert a timedelta to a number of us,
1454 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1455 * as a Python int or long.
1456 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1457 * due to ubiquitous overflow possibilities.
1458 */
1459static PyObject *
1460delta_to_microseconds(PyDateTime_Delta *self)
1461{
1462 PyObject *x1 = NULL;
1463 PyObject *x2 = NULL;
1464 PyObject *x3 = NULL;
1465 PyObject *result = NULL;
1466
1467 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1468 if (x1 == NULL)
1469 goto Done;
1470 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1471 if (x2 == NULL)
1472 goto Done;
1473 Py_DECREF(x1);
1474 x1 = NULL;
1475
1476 /* x2 has days in seconds */
1477 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1478 if (x1 == NULL)
1479 goto Done;
1480 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1481 if (x3 == NULL)
1482 goto Done;
1483 Py_DECREF(x1);
1484 Py_DECREF(x2);
1485 x1 = x2 = NULL;
1486
1487 /* x3 has days+seconds in seconds */
1488 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1489 if (x1 == NULL)
1490 goto Done;
1491 Py_DECREF(x3);
1492 x3 = NULL;
1493
1494 /* x1 has days+seconds in us */
1495 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1496 if (x2 == NULL)
1497 goto Done;
1498 result = PyNumber_Add(x1, x2);
1499
1500Done:
1501 Py_XDECREF(x1);
1502 Py_XDECREF(x2);
1503 Py_XDECREF(x3);
1504 return result;
1505}
1506
1507/* Convert a number of us (as a Python int or long) to a timedelta.
1508 */
1509static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001510microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001511{
1512 int us;
1513 int s;
1514 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001515 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001516
1517 PyObject *tuple = NULL;
1518 PyObject *num = NULL;
1519 PyObject *result = NULL;
1520
1521 tuple = PyNumber_Divmod(pyus, us_per_second);
1522 if (tuple == NULL)
1523 goto Done;
1524
1525 num = PyTuple_GetItem(tuple, 1); /* us */
1526 if (num == NULL)
1527 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001528 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001529 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001530 if (temp == -1 && PyErr_Occurred())
1531 goto Done;
1532 assert(0 <= temp && temp < 1000000);
1533 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001534 if (us < 0) {
1535 /* The divisor was positive, so this must be an error. */
1536 assert(PyErr_Occurred());
1537 goto Done;
1538 }
1539
1540 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1541 if (num == NULL)
1542 goto Done;
1543 Py_INCREF(num);
1544 Py_DECREF(tuple);
1545
1546 tuple = PyNumber_Divmod(num, seconds_per_day);
1547 if (tuple == NULL)
1548 goto Done;
1549 Py_DECREF(num);
1550
1551 num = PyTuple_GetItem(tuple, 1); /* seconds */
1552 if (num == NULL)
1553 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001554 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001555 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001556 if (temp == -1 && PyErr_Occurred())
1557 goto Done;
1558 assert(0 <= temp && temp < 24*3600);
1559 s = (int)temp;
1560
Tim Peters2a799bf2002-12-16 20:18:38 +00001561 if (s < 0) {
1562 /* The divisor was positive, so this must be an error. */
1563 assert(PyErr_Occurred());
1564 goto Done;
1565 }
1566
1567 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1568 if (num == NULL)
1569 goto Done;
1570 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001571 temp = PyLong_AsLong(num);
1572 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001573 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001574 d = (int)temp;
1575 if ((long)d != temp) {
1576 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1577 "large to fit in a C int");
1578 goto Done;
1579 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001580 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001581
1582Done:
1583 Py_XDECREF(tuple);
1584 Py_XDECREF(num);
1585 return result;
1586}
1587
Tim Petersb0c854d2003-05-17 15:57:00 +00001588#define microseconds_to_delta(pymicros) \
1589 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1590
Tim Peters2a799bf2002-12-16 20:18:38 +00001591static PyObject *
1592multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1593{
1594 PyObject *pyus_in;
1595 PyObject *pyus_out;
1596 PyObject *result;
1597
1598 pyus_in = delta_to_microseconds(delta);
1599 if (pyus_in == NULL)
1600 return NULL;
1601
1602 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1603 Py_DECREF(pyus_in);
1604 if (pyus_out == NULL)
1605 return NULL;
1606
1607 result = microseconds_to_delta(pyus_out);
1608 Py_DECREF(pyus_out);
1609 return result;
1610}
1611
1612static PyObject *
1613divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1614{
1615 PyObject *pyus_in;
1616 PyObject *pyus_out;
1617 PyObject *result;
1618
1619 pyus_in = delta_to_microseconds(delta);
1620 if (pyus_in == NULL)
1621 return NULL;
1622
1623 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1624 Py_DECREF(pyus_in);
1625 if (pyus_out == NULL)
1626 return NULL;
1627
1628 result = microseconds_to_delta(pyus_out);
1629 Py_DECREF(pyus_out);
1630 return result;
1631}
1632
1633static PyObject *
1634delta_add(PyObject *left, PyObject *right)
1635{
1636 PyObject *result = Py_NotImplemented;
1637
1638 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1639 /* delta + delta */
1640 /* The C-level additions can't overflow because of the
1641 * invariant bounds.
1642 */
1643 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1644 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1645 int microseconds = GET_TD_MICROSECONDS(left) +
1646 GET_TD_MICROSECONDS(right);
1647 result = new_delta(days, seconds, microseconds, 1);
1648 }
1649
1650 if (result == Py_NotImplemented)
1651 Py_INCREF(result);
1652 return result;
1653}
1654
1655static PyObject *
1656delta_negative(PyDateTime_Delta *self)
1657{
1658 return new_delta(-GET_TD_DAYS(self),
1659 -GET_TD_SECONDS(self),
1660 -GET_TD_MICROSECONDS(self),
1661 1);
1662}
1663
1664static PyObject *
1665delta_positive(PyDateTime_Delta *self)
1666{
1667 /* Could optimize this (by returning self) if this isn't a
1668 * subclass -- but who uses unary + ? Approximately nobody.
1669 */
1670 return new_delta(GET_TD_DAYS(self),
1671 GET_TD_SECONDS(self),
1672 GET_TD_MICROSECONDS(self),
1673 0);
1674}
1675
1676static PyObject *
1677delta_abs(PyDateTime_Delta *self)
1678{
1679 PyObject *result;
1680
1681 assert(GET_TD_MICROSECONDS(self) >= 0);
1682 assert(GET_TD_SECONDS(self) >= 0);
1683
1684 if (GET_TD_DAYS(self) < 0)
1685 result = delta_negative(self);
1686 else
1687 result = delta_positive(self);
1688
1689 return result;
1690}
1691
1692static PyObject *
1693delta_subtract(PyObject *left, PyObject *right)
1694{
1695 PyObject *result = Py_NotImplemented;
1696
1697 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1698 /* delta - delta */
1699 PyObject *minus_right = PyNumber_Negative(right);
1700 if (minus_right) {
1701 result = delta_add(left, minus_right);
1702 Py_DECREF(minus_right);
1703 }
1704 else
1705 result = NULL;
1706 }
1707
1708 if (result == Py_NotImplemented)
1709 Py_INCREF(result);
1710 return result;
1711}
1712
Tim Peters2a799bf2002-12-16 20:18:38 +00001713static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001714delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001715{
Tim Petersaa7d8492003-02-08 03:28:59 +00001716 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001717 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001718 if (diff == 0) {
1719 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1720 if (diff == 0)
1721 diff = GET_TD_MICROSECONDS(self) -
1722 GET_TD_MICROSECONDS(other);
1723 }
Guido van Rossum19960592006-08-24 17:29:38 +00001724 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001725 }
Guido van Rossum19960592006-08-24 17:29:38 +00001726 else {
1727 Py_INCREF(Py_NotImplemented);
1728 return Py_NotImplemented;
1729 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001730}
1731
1732static PyObject *delta_getstate(PyDateTime_Delta *self);
1733
1734static long
1735delta_hash(PyDateTime_Delta *self)
1736{
1737 if (self->hashcode == -1) {
1738 PyObject *temp = delta_getstate(self);
1739 if (temp != NULL) {
1740 self->hashcode = PyObject_Hash(temp);
1741 Py_DECREF(temp);
1742 }
1743 }
1744 return self->hashcode;
1745}
1746
1747static PyObject *
1748delta_multiply(PyObject *left, PyObject *right)
1749{
1750 PyObject *result = Py_NotImplemented;
1751
1752 if (PyDelta_Check(left)) {
1753 /* delta * ??? */
1754 if (PyInt_Check(right) || PyLong_Check(right))
1755 result = multiply_int_timedelta(right,
1756 (PyDateTime_Delta *) left);
1757 }
1758 else if (PyInt_Check(left) || PyLong_Check(left))
1759 result = multiply_int_timedelta(left,
1760 (PyDateTime_Delta *) right);
1761
1762 if (result == Py_NotImplemented)
1763 Py_INCREF(result);
1764 return result;
1765}
1766
1767static PyObject *
1768delta_divide(PyObject *left, PyObject *right)
1769{
1770 PyObject *result = Py_NotImplemented;
1771
1772 if (PyDelta_Check(left)) {
1773 /* delta * ??? */
1774 if (PyInt_Check(right) || PyLong_Check(right))
1775 result = divide_timedelta_int(
1776 (PyDateTime_Delta *)left,
1777 right);
1778 }
1779
1780 if (result == Py_NotImplemented)
1781 Py_INCREF(result);
1782 return result;
1783}
1784
1785/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1786 * timedelta constructor. sofar is the # of microseconds accounted for
1787 * so far, and there are factor microseconds per current unit, the number
1788 * of which is given by num. num * factor is added to sofar in a
1789 * numerically careful way, and that's the result. Any fractional
1790 * microseconds left over (this can happen if num is a float type) are
1791 * added into *leftover.
1792 * Note that there are many ways this can give an error (NULL) return.
1793 */
1794static PyObject *
1795accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1796 double *leftover)
1797{
1798 PyObject *prod;
1799 PyObject *sum;
1800
1801 assert(num != NULL);
1802
1803 if (PyInt_Check(num) || PyLong_Check(num)) {
1804 prod = PyNumber_Multiply(num, factor);
1805 if (prod == NULL)
1806 return NULL;
1807 sum = PyNumber_Add(sofar, prod);
1808 Py_DECREF(prod);
1809 return sum;
1810 }
1811
1812 if (PyFloat_Check(num)) {
1813 double dnum;
1814 double fracpart;
1815 double intpart;
1816 PyObject *x;
1817 PyObject *y;
1818
1819 /* The Plan: decompose num into an integer part and a
1820 * fractional part, num = intpart + fracpart.
1821 * Then num * factor ==
1822 * intpart * factor + fracpart * factor
1823 * and the LHS can be computed exactly in long arithmetic.
1824 * The RHS is again broken into an int part and frac part.
1825 * and the frac part is added into *leftover.
1826 */
1827 dnum = PyFloat_AsDouble(num);
1828 if (dnum == -1.0 && PyErr_Occurred())
1829 return NULL;
1830 fracpart = modf(dnum, &intpart);
1831 x = PyLong_FromDouble(intpart);
1832 if (x == NULL)
1833 return NULL;
1834
1835 prod = PyNumber_Multiply(x, factor);
1836 Py_DECREF(x);
1837 if (prod == NULL)
1838 return NULL;
1839
1840 sum = PyNumber_Add(sofar, prod);
1841 Py_DECREF(prod);
1842 if (sum == NULL)
1843 return NULL;
1844
1845 if (fracpart == 0.0)
1846 return sum;
1847 /* So far we've lost no information. Dealing with the
1848 * fractional part requires float arithmetic, and may
1849 * lose a little info.
1850 */
1851 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001852 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001853
1854 dnum *= fracpart;
1855 fracpart = modf(dnum, &intpart);
1856 x = PyLong_FromDouble(intpart);
1857 if (x == NULL) {
1858 Py_DECREF(sum);
1859 return NULL;
1860 }
1861
1862 y = PyNumber_Add(sum, x);
1863 Py_DECREF(sum);
1864 Py_DECREF(x);
1865 *leftover += fracpart;
1866 return y;
1867 }
1868
1869 PyErr_Format(PyExc_TypeError,
1870 "unsupported type for timedelta %s component: %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001871 tag, Py_Type(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001872 return NULL;
1873}
1874
1875static PyObject *
1876delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1877{
1878 PyObject *self = NULL;
1879
1880 /* Argument objects. */
1881 PyObject *day = NULL;
1882 PyObject *second = NULL;
1883 PyObject *us = NULL;
1884 PyObject *ms = NULL;
1885 PyObject *minute = NULL;
1886 PyObject *hour = NULL;
1887 PyObject *week = NULL;
1888
1889 PyObject *x = NULL; /* running sum of microseconds */
1890 PyObject *y = NULL; /* temp sum of microseconds */
1891 double leftover_us = 0.0;
1892
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001893 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001894 "days", "seconds", "microseconds", "milliseconds",
1895 "minutes", "hours", "weeks", NULL
1896 };
1897
1898 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1899 keywords,
1900 &day, &second, &us,
1901 &ms, &minute, &hour, &week) == 0)
1902 goto Done;
1903
1904 x = PyInt_FromLong(0);
1905 if (x == NULL)
1906 goto Done;
1907
1908#define CLEANUP \
1909 Py_DECREF(x); \
1910 x = y; \
1911 if (x == NULL) \
1912 goto Done
1913
1914 if (us) {
1915 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1916 CLEANUP;
1917 }
1918 if (ms) {
1919 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1920 CLEANUP;
1921 }
1922 if (second) {
1923 y = accum("seconds", x, second, us_per_second, &leftover_us);
1924 CLEANUP;
1925 }
1926 if (minute) {
1927 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1928 CLEANUP;
1929 }
1930 if (hour) {
1931 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1932 CLEANUP;
1933 }
1934 if (day) {
1935 y = accum("days", x, day, us_per_day, &leftover_us);
1936 CLEANUP;
1937 }
1938 if (week) {
1939 y = accum("weeks", x, week, us_per_week, &leftover_us);
1940 CLEANUP;
1941 }
1942 if (leftover_us) {
1943 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001944 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001945 if (temp == NULL) {
1946 Py_DECREF(x);
1947 goto Done;
1948 }
1949 y = PyNumber_Add(x, temp);
1950 Py_DECREF(temp);
1951 CLEANUP;
1952 }
1953
Tim Petersb0c854d2003-05-17 15:57:00 +00001954 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001955 Py_DECREF(x);
1956Done:
1957 return self;
1958
1959#undef CLEANUP
1960}
1961
1962static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001963delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001964{
1965 return (GET_TD_DAYS(self) != 0
1966 || GET_TD_SECONDS(self) != 0
1967 || GET_TD_MICROSECONDS(self) != 0);
1968}
1969
1970static PyObject *
1971delta_repr(PyDateTime_Delta *self)
1972{
1973 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001974 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001975 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001976 GET_TD_DAYS(self),
1977 GET_TD_SECONDS(self),
1978 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001979 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001980 return PyUnicode_FromFormat("%s(%d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001981 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001982 GET_TD_DAYS(self),
1983 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001984
Walter Dörwald1ab83302007-05-18 17:15:44 +00001985 return PyUnicode_FromFormat("%s(%d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001986 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001987 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001988}
1989
1990static PyObject *
1991delta_str(PyDateTime_Delta *self)
1992{
Tim Peters2a799bf2002-12-16 20:18:38 +00001993 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00001994 int seconds = GET_TD_SECONDS(self);
1995 int minutes = divmod(seconds, 60, &seconds);
1996 int hours = divmod(minutes, 60, &minutes);
1997 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001998
1999 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002000 if (us)
2001 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2002 days, (days == 1 || days == -1) ? "" : "s",
2003 hours, minutes, seconds, us);
2004 else
2005 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2006 days, (days == 1 || days == -1) ? "" : "s",
2007 hours, minutes, seconds);
2008 } else {
2009 if (us)
2010 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2011 hours, minutes, seconds, us);
2012 else
2013 return PyUnicode_FromFormat("%d:%02d:%02d",
2014 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002015 }
2016
Tim Peters2a799bf2002-12-16 20:18:38 +00002017}
2018
Tim Peters371935f2003-02-01 01:52:50 +00002019/* Pickle support, a simple use of __reduce__. */
2020
Tim Petersb57f8f02003-02-01 02:54:15 +00002021/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002022static PyObject *
2023delta_getstate(PyDateTime_Delta *self)
2024{
2025 return Py_BuildValue("iii", GET_TD_DAYS(self),
2026 GET_TD_SECONDS(self),
2027 GET_TD_MICROSECONDS(self));
2028}
2029
Tim Peters2a799bf2002-12-16 20:18:38 +00002030static PyObject *
2031delta_reduce(PyDateTime_Delta* self)
2032{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002033 return Py_BuildValue("ON", Py_Type(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002034}
2035
2036#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2037
2038static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002039
Neal Norwitzdfb80862002-12-19 02:30:56 +00002040 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002041 PyDoc_STR("Number of days.")},
2042
Neal Norwitzdfb80862002-12-19 02:30:56 +00002043 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002044 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2045
Neal Norwitzdfb80862002-12-19 02:30:56 +00002046 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002047 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2048 {NULL}
2049};
2050
2051static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002052 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2053 PyDoc_STR("__reduce__() -> (cls, state)")},
2054
Tim Peters2a799bf2002-12-16 20:18:38 +00002055 {NULL, NULL},
2056};
2057
2058static char delta_doc[] =
2059PyDoc_STR("Difference between two datetime values.");
2060
2061static PyNumberMethods delta_as_number = {
2062 delta_add, /* nb_add */
2063 delta_subtract, /* nb_subtract */
2064 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002065 0, /* nb_remainder */
2066 0, /* nb_divmod */
2067 0, /* nb_power */
2068 (unaryfunc)delta_negative, /* nb_negative */
2069 (unaryfunc)delta_positive, /* nb_positive */
2070 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002071 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002072 0, /*nb_invert*/
2073 0, /*nb_lshift*/
2074 0, /*nb_rshift*/
2075 0, /*nb_and*/
2076 0, /*nb_xor*/
2077 0, /*nb_or*/
2078 0, /*nb_coerce*/
2079 0, /*nb_int*/
2080 0, /*nb_long*/
2081 0, /*nb_float*/
2082 0, /*nb_oct*/
2083 0, /*nb_hex*/
2084 0, /*nb_inplace_add*/
2085 0, /*nb_inplace_subtract*/
2086 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002087 0, /*nb_inplace_remainder*/
2088 0, /*nb_inplace_power*/
2089 0, /*nb_inplace_lshift*/
2090 0, /*nb_inplace_rshift*/
2091 0, /*nb_inplace_and*/
2092 0, /*nb_inplace_xor*/
2093 0, /*nb_inplace_or*/
2094 delta_divide, /* nb_floor_divide */
2095 0, /* nb_true_divide */
2096 0, /* nb_inplace_floor_divide */
2097 0, /* nb_inplace_true_divide */
2098};
2099
2100static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002101 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002102 "datetime.timedelta", /* tp_name */
2103 sizeof(PyDateTime_Delta), /* tp_basicsize */
2104 0, /* tp_itemsize */
2105 0, /* tp_dealloc */
2106 0, /* tp_print */
2107 0, /* tp_getattr */
2108 0, /* tp_setattr */
2109 0, /* tp_compare */
2110 (reprfunc)delta_repr, /* tp_repr */
2111 &delta_as_number, /* tp_as_number */
2112 0, /* tp_as_sequence */
2113 0, /* tp_as_mapping */
2114 (hashfunc)delta_hash, /* tp_hash */
2115 0, /* tp_call */
2116 (reprfunc)delta_str, /* tp_str */
2117 PyObject_GenericGetAttr, /* tp_getattro */
2118 0, /* tp_setattro */
2119 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002120 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002121 delta_doc, /* tp_doc */
2122 0, /* tp_traverse */
2123 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002124 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002125 0, /* tp_weaklistoffset */
2126 0, /* tp_iter */
2127 0, /* tp_iternext */
2128 delta_methods, /* tp_methods */
2129 delta_members, /* tp_members */
2130 0, /* tp_getset */
2131 0, /* tp_base */
2132 0, /* tp_dict */
2133 0, /* tp_descr_get */
2134 0, /* tp_descr_set */
2135 0, /* tp_dictoffset */
2136 0, /* tp_init */
2137 0, /* tp_alloc */
2138 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002139 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002140};
2141
2142/*
2143 * PyDateTime_Date implementation.
2144 */
2145
2146/* Accessor properties. */
2147
2148static PyObject *
2149date_year(PyDateTime_Date *self, void *unused)
2150{
2151 return PyInt_FromLong(GET_YEAR(self));
2152}
2153
2154static PyObject *
2155date_month(PyDateTime_Date *self, void *unused)
2156{
2157 return PyInt_FromLong(GET_MONTH(self));
2158}
2159
2160static PyObject *
2161date_day(PyDateTime_Date *self, void *unused)
2162{
2163 return PyInt_FromLong(GET_DAY(self));
2164}
2165
2166static PyGetSetDef date_getset[] = {
2167 {"year", (getter)date_year},
2168 {"month", (getter)date_month},
2169 {"day", (getter)date_day},
2170 {NULL}
2171};
2172
2173/* Constructors. */
2174
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002175static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002176
Tim Peters2a799bf2002-12-16 20:18:38 +00002177static PyObject *
2178date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2179{
2180 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002181 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002182 int year;
2183 int month;
2184 int day;
2185
Guido van Rossum177e41a2003-01-30 22:06:23 +00002186 /* Check for invocation from pickle with __getstate__ state */
2187 if (PyTuple_GET_SIZE(args) == 1 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002188 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2189 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2190 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002191 {
Tim Peters70533e22003-02-01 04:40:04 +00002192 PyDateTime_Date *me;
2193
Tim Peters604c0132004-06-07 23:04:33 +00002194 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002195 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002196 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002197 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2198 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002199 }
Tim Peters70533e22003-02-01 04:40:04 +00002200 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002201 }
2202
Tim Peters12bf3392002-12-24 05:41:27 +00002203 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002204 &year, &month, &day)) {
2205 if (check_date_args(year, month, day) < 0)
2206 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002207 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002208 }
2209 return self;
2210}
2211
2212/* Return new date from localtime(t). */
2213static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002214date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002215{
2216 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002217 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002218 PyObject *result = NULL;
2219
Tim Peters1b6f7a92004-06-20 02:50:16 +00002220 t = _PyTime_DoubleToTimet(ts);
2221 if (t == (time_t)-1 && PyErr_Occurred())
2222 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002223 tm = localtime(&t);
2224 if (tm)
2225 result = PyObject_CallFunction(cls, "iii",
2226 tm->tm_year + 1900,
2227 tm->tm_mon + 1,
2228 tm->tm_mday);
2229 else
2230 PyErr_SetString(PyExc_ValueError,
2231 "timestamp out of range for "
2232 "platform localtime() function");
2233 return result;
2234}
2235
2236/* Return new date from current time.
2237 * We say this is equivalent to fromtimestamp(time.time()), and the
2238 * only way to be sure of that is to *call* time.time(). That's not
2239 * generally the same as calling C's time.
2240 */
2241static PyObject *
2242date_today(PyObject *cls, PyObject *dummy)
2243{
2244 PyObject *time;
2245 PyObject *result;
2246
2247 time = time_time();
2248 if (time == NULL)
2249 return NULL;
2250
2251 /* Note well: today() is a class method, so this may not call
2252 * date.fromtimestamp. For example, it may call
2253 * datetime.fromtimestamp. That's why we need all the accuracy
2254 * time.time() delivers; if someone were gonzo about optimization,
2255 * date.today() could get away with plain C time().
2256 */
2257 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2258 Py_DECREF(time);
2259 return result;
2260}
2261
2262/* Return new date from given timestamp (Python timestamp -- a double). */
2263static PyObject *
2264date_fromtimestamp(PyObject *cls, PyObject *args)
2265{
2266 double timestamp;
2267 PyObject *result = NULL;
2268
2269 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002270 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002271 return result;
2272}
2273
2274/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2275 * the ordinal is out of range.
2276 */
2277static PyObject *
2278date_fromordinal(PyObject *cls, PyObject *args)
2279{
2280 PyObject *result = NULL;
2281 int ordinal;
2282
2283 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2284 int year;
2285 int month;
2286 int day;
2287
2288 if (ordinal < 1)
2289 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2290 ">= 1");
2291 else {
2292 ord_to_ymd(ordinal, &year, &month, &day);
2293 result = PyObject_CallFunction(cls, "iii",
2294 year, month, day);
2295 }
2296 }
2297 return result;
2298}
2299
2300/*
2301 * Date arithmetic.
2302 */
2303
2304/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2305 * instead.
2306 */
2307static PyObject *
2308add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2309{
2310 PyObject *result = NULL;
2311 int year = GET_YEAR(date);
2312 int month = GET_MONTH(date);
2313 int deltadays = GET_TD_DAYS(delta);
2314 /* C-level overflow is impossible because |deltadays| < 1e9. */
2315 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2316
2317 if (normalize_date(&year, &month, &day) >= 0)
2318 result = new_date(year, month, day);
2319 return result;
2320}
2321
2322static PyObject *
2323date_add(PyObject *left, PyObject *right)
2324{
2325 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2326 Py_INCREF(Py_NotImplemented);
2327 return Py_NotImplemented;
2328 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002329 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002330 /* date + ??? */
2331 if (PyDelta_Check(right))
2332 /* date + delta */
2333 return add_date_timedelta((PyDateTime_Date *) left,
2334 (PyDateTime_Delta *) right,
2335 0);
2336 }
2337 else {
2338 /* ??? + date
2339 * 'right' must be one of us, or we wouldn't have been called
2340 */
2341 if (PyDelta_Check(left))
2342 /* delta + date */
2343 return add_date_timedelta((PyDateTime_Date *) right,
2344 (PyDateTime_Delta *) left,
2345 0);
2346 }
2347 Py_INCREF(Py_NotImplemented);
2348 return Py_NotImplemented;
2349}
2350
2351static PyObject *
2352date_subtract(PyObject *left, PyObject *right)
2353{
2354 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2355 Py_INCREF(Py_NotImplemented);
2356 return Py_NotImplemented;
2357 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002358 if (PyDate_Check(left)) {
2359 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002360 /* date - date */
2361 int left_ord = ymd_to_ord(GET_YEAR(left),
2362 GET_MONTH(left),
2363 GET_DAY(left));
2364 int right_ord = ymd_to_ord(GET_YEAR(right),
2365 GET_MONTH(right),
2366 GET_DAY(right));
2367 return new_delta(left_ord - right_ord, 0, 0, 0);
2368 }
2369 if (PyDelta_Check(right)) {
2370 /* date - delta */
2371 return add_date_timedelta((PyDateTime_Date *) left,
2372 (PyDateTime_Delta *) right,
2373 1);
2374 }
2375 }
2376 Py_INCREF(Py_NotImplemented);
2377 return Py_NotImplemented;
2378}
2379
2380
2381/* Various ways to turn a date into a string. */
2382
2383static PyObject *
2384date_repr(PyDateTime_Date *self)
2385{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002386 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00002387 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002388 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002389}
2390
2391static PyObject *
2392date_isoformat(PyDateTime_Date *self)
2393{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002394 return PyUnicode_FromFormat("%04d-%02d-%02d",
2395 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002396}
2397
Tim Peterse2df5ff2003-05-02 18:39:55 +00002398/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002399static PyObject *
2400date_str(PyDateTime_Date *self)
2401{
2402 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2403}
2404
2405
2406static PyObject *
2407date_ctime(PyDateTime_Date *self)
2408{
2409 return format_ctime(self, 0, 0, 0);
2410}
2411
2412static PyObject *
2413date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2414{
2415 /* This method can be inherited, and needs to call the
2416 * timetuple() method appropriate to self's class.
2417 */
2418 PyObject *result;
2419 PyObject *format;
2420 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002421 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002422
Guido van Rossumbce56a62007-05-10 18:04:33 +00002423 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2424 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002425 return NULL;
2426
2427 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2428 if (tuple == NULL)
2429 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002430 result = wrap_strftime((PyObject *)self, format, tuple,
2431 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002432 Py_DECREF(tuple);
2433 return result;
2434}
2435
2436/* ISO methods. */
2437
2438static PyObject *
2439date_isoweekday(PyDateTime_Date *self)
2440{
2441 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2442
2443 return PyInt_FromLong(dow + 1);
2444}
2445
2446static PyObject *
2447date_isocalendar(PyDateTime_Date *self)
2448{
2449 int year = GET_YEAR(self);
2450 int week1_monday = iso_week1_monday(year);
2451 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2452 int week;
2453 int day;
2454
2455 week = divmod(today - week1_monday, 7, &day);
2456 if (week < 0) {
2457 --year;
2458 week1_monday = iso_week1_monday(year);
2459 week = divmod(today - week1_monday, 7, &day);
2460 }
2461 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2462 ++year;
2463 week = 0;
2464 }
2465 return Py_BuildValue("iii", year, week + 1, day + 1);
2466}
2467
2468/* Miscellaneous methods. */
2469
Tim Peters2a799bf2002-12-16 20:18:38 +00002470static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002471date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002472{
Guido van Rossum19960592006-08-24 17:29:38 +00002473 if (PyDate_Check(other)) {
2474 int diff = memcmp(((PyDateTime_Date *)self)->data,
2475 ((PyDateTime_Date *)other)->data,
2476 _PyDateTime_DATE_DATASIZE);
2477 return diff_to_bool(diff, op);
2478 }
2479 else {
Tim Peters07534a62003-02-07 22:50:28 +00002480 Py_INCREF(Py_NotImplemented);
2481 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002482 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002483}
2484
2485static PyObject *
2486date_timetuple(PyDateTime_Date *self)
2487{
2488 return build_struct_time(GET_YEAR(self),
2489 GET_MONTH(self),
2490 GET_DAY(self),
2491 0, 0, 0, -1);
2492}
2493
Tim Peters12bf3392002-12-24 05:41:27 +00002494static PyObject *
2495date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2496{
2497 PyObject *clone;
2498 PyObject *tuple;
2499 int year = GET_YEAR(self);
2500 int month = GET_MONTH(self);
2501 int day = GET_DAY(self);
2502
2503 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2504 &year, &month, &day))
2505 return NULL;
2506 tuple = Py_BuildValue("iii", year, month, day);
2507 if (tuple == NULL)
2508 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002509 clone = date_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002510 Py_DECREF(tuple);
2511 return clone;
2512}
2513
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002514static PyObject *date_getstate(PyDateTime_Date *self, int hashable);
Tim Peters2a799bf2002-12-16 20:18:38 +00002515
2516static long
2517date_hash(PyDateTime_Date *self)
2518{
2519 if (self->hashcode == -1) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002520 PyObject *temp = date_getstate(self, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002521 if (temp != NULL) {
2522 self->hashcode = PyObject_Hash(temp);
2523 Py_DECREF(temp);
2524 }
2525 }
2526 return self->hashcode;
2527}
2528
2529static PyObject *
2530date_toordinal(PyDateTime_Date *self)
2531{
2532 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2533 GET_DAY(self)));
2534}
2535
2536static PyObject *
2537date_weekday(PyDateTime_Date *self)
2538{
2539 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2540
2541 return PyInt_FromLong(dow);
2542}
2543
Tim Peters371935f2003-02-01 01:52:50 +00002544/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002545
Tim Petersb57f8f02003-02-01 02:54:15 +00002546/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002547static PyObject *
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002548date_getstate(PyDateTime_Date *self, int hashable)
Tim Peters2a799bf2002-12-16 20:18:38 +00002549{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002550 PyObject* field;
2551 if (hashable)
2552 field = PyString_FromStringAndSize(
2553 (char*)self->data, _PyDateTime_DATE_DATASIZE);
2554 else
2555 field = PyBytes_FromStringAndSize(
2556 (char*)self->data, _PyDateTime_DATE_DATASIZE);
2557 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002558}
2559
2560static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002561date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002562{
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00002563 return Py_BuildValue("(ON)", Py_Type(self), date_getstate(self, 0));
Tim Peters2a799bf2002-12-16 20:18:38 +00002564}
2565
2566static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002567
Tim Peters2a799bf2002-12-16 20:18:38 +00002568 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002569
Tim Peters2a799bf2002-12-16 20:18:38 +00002570 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2571 METH_CLASS,
2572 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2573 "time.time()).")},
2574
2575 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2576 METH_CLASS,
2577 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2578 "ordinal.")},
2579
2580 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2581 PyDoc_STR("Current date or datetime: same as "
2582 "self.__class__.fromtimestamp(time.time()).")},
2583
2584 /* Instance methods: */
2585
2586 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2587 PyDoc_STR("Return ctime() style string.")},
2588
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002589 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002590 PyDoc_STR("format -> strftime() style string.")},
2591
2592 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2593 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2594
2595 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2596 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2597 "weekday.")},
2598
2599 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2600 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2601
2602 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2603 PyDoc_STR("Return the day of the week represented by the date.\n"
2604 "Monday == 1 ... Sunday == 7")},
2605
2606 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2607 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2608 "1 is day 1.")},
2609
2610 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2611 PyDoc_STR("Return the day of the week represented by the date.\n"
2612 "Monday == 0 ... Sunday == 6")},
2613
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002614 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002615 PyDoc_STR("Return date with new specified fields.")},
2616
Guido van Rossum177e41a2003-01-30 22:06:23 +00002617 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2618 PyDoc_STR("__reduce__() -> (cls, state)")},
2619
Tim Peters2a799bf2002-12-16 20:18:38 +00002620 {NULL, NULL}
2621};
2622
2623static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002624PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002625
2626static PyNumberMethods date_as_number = {
2627 date_add, /* nb_add */
2628 date_subtract, /* nb_subtract */
2629 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002630 0, /* nb_remainder */
2631 0, /* nb_divmod */
2632 0, /* nb_power */
2633 0, /* nb_negative */
2634 0, /* nb_positive */
2635 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002636 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002637};
2638
2639static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002640 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002641 "datetime.date", /* tp_name */
2642 sizeof(PyDateTime_Date), /* tp_basicsize */
2643 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002644 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002645 0, /* tp_print */
2646 0, /* tp_getattr */
2647 0, /* tp_setattr */
2648 0, /* tp_compare */
2649 (reprfunc)date_repr, /* tp_repr */
2650 &date_as_number, /* tp_as_number */
2651 0, /* tp_as_sequence */
2652 0, /* tp_as_mapping */
2653 (hashfunc)date_hash, /* tp_hash */
2654 0, /* tp_call */
2655 (reprfunc)date_str, /* tp_str */
2656 PyObject_GenericGetAttr, /* tp_getattro */
2657 0, /* tp_setattro */
2658 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002659 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002660 date_doc, /* tp_doc */
2661 0, /* tp_traverse */
2662 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002663 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002664 0, /* tp_weaklistoffset */
2665 0, /* tp_iter */
2666 0, /* tp_iternext */
2667 date_methods, /* tp_methods */
2668 0, /* tp_members */
2669 date_getset, /* tp_getset */
2670 0, /* tp_base */
2671 0, /* tp_dict */
2672 0, /* tp_descr_get */
2673 0, /* tp_descr_set */
2674 0, /* tp_dictoffset */
2675 0, /* tp_init */
2676 0, /* tp_alloc */
2677 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002678 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002679};
2680
2681/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002682 * PyDateTime_TZInfo implementation.
2683 */
2684
2685/* This is a pure abstract base class, so doesn't do anything beyond
2686 * raising NotImplemented exceptions. Real tzinfo classes need
2687 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002688 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002689 * be subclasses of this tzinfo class, which is easy and quick to check).
2690 *
2691 * Note: For reasons having to do with pickling of subclasses, we have
2692 * to allow tzinfo objects to be instantiated. This wasn't an issue
2693 * in the Python implementation (__init__() could raise NotImplementedError
2694 * there without ill effect), but doing so in the C implementation hit a
2695 * brick wall.
2696 */
2697
2698static PyObject *
2699tzinfo_nogo(const char* methodname)
2700{
2701 PyErr_Format(PyExc_NotImplementedError,
2702 "a tzinfo subclass must implement %s()",
2703 methodname);
2704 return NULL;
2705}
2706
2707/* Methods. A subclass must implement these. */
2708
Tim Peters52dcce22003-01-23 16:36:11 +00002709static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002710tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2711{
2712 return tzinfo_nogo("tzname");
2713}
2714
Tim Peters52dcce22003-01-23 16:36:11 +00002715static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002716tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2717{
2718 return tzinfo_nogo("utcoffset");
2719}
2720
Tim Peters52dcce22003-01-23 16:36:11 +00002721static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002722tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2723{
2724 return tzinfo_nogo("dst");
2725}
2726
Tim Peters52dcce22003-01-23 16:36:11 +00002727static PyObject *
2728tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2729{
2730 int y, m, d, hh, mm, ss, us;
2731
2732 PyObject *result;
2733 int off, dst;
2734 int none;
2735 int delta;
2736
2737 if (! PyDateTime_Check(dt)) {
2738 PyErr_SetString(PyExc_TypeError,
2739 "fromutc: argument must be a datetime");
2740 return NULL;
2741 }
2742 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2743 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2744 "is not self");
2745 return NULL;
2746 }
2747
2748 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2749 if (off == -1 && PyErr_Occurred())
2750 return NULL;
2751 if (none) {
2752 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2753 "utcoffset() result required");
2754 return NULL;
2755 }
2756
2757 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2758 if (dst == -1 && PyErr_Occurred())
2759 return NULL;
2760 if (none) {
2761 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2762 "dst() result required");
2763 return NULL;
2764 }
2765
2766 y = GET_YEAR(dt);
2767 m = GET_MONTH(dt);
2768 d = GET_DAY(dt);
2769 hh = DATE_GET_HOUR(dt);
2770 mm = DATE_GET_MINUTE(dt);
2771 ss = DATE_GET_SECOND(dt);
2772 us = DATE_GET_MICROSECOND(dt);
2773
2774 delta = off - dst;
2775 mm += delta;
2776 if ((mm < 0 || mm >= 60) &&
2777 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002778 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002779 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2780 if (result == NULL)
2781 return result;
2782
2783 dst = call_dst(dt->tzinfo, result, &none);
2784 if (dst == -1 && PyErr_Occurred())
2785 goto Fail;
2786 if (none)
2787 goto Inconsistent;
2788 if (dst == 0)
2789 return result;
2790
2791 mm += dst;
2792 if ((mm < 0 || mm >= 60) &&
2793 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2794 goto Fail;
2795 Py_DECREF(result);
2796 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2797 return result;
2798
2799Inconsistent:
2800 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2801 "inconsistent results; cannot convert");
2802
2803 /* fall thru to failure */
2804Fail:
2805 Py_DECREF(result);
2806 return NULL;
2807}
2808
Tim Peters2a799bf2002-12-16 20:18:38 +00002809/*
2810 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002811 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002812 */
2813
Guido van Rossum177e41a2003-01-30 22:06:23 +00002814static PyObject *
2815tzinfo_reduce(PyObject *self)
2816{
2817 PyObject *args, *state, *tmp;
2818 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002819
Guido van Rossum177e41a2003-01-30 22:06:23 +00002820 tmp = PyTuple_New(0);
2821 if (tmp == NULL)
2822 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002823
Guido van Rossum177e41a2003-01-30 22:06:23 +00002824 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2825 if (getinitargs != NULL) {
2826 args = PyObject_CallObject(getinitargs, tmp);
2827 Py_DECREF(getinitargs);
2828 if (args == NULL) {
2829 Py_DECREF(tmp);
2830 return NULL;
2831 }
2832 }
2833 else {
2834 PyErr_Clear();
2835 args = tmp;
2836 Py_INCREF(args);
2837 }
2838
2839 getstate = PyObject_GetAttrString(self, "__getstate__");
2840 if (getstate != NULL) {
2841 state = PyObject_CallObject(getstate, tmp);
2842 Py_DECREF(getstate);
2843 if (state == NULL) {
2844 Py_DECREF(args);
2845 Py_DECREF(tmp);
2846 return NULL;
2847 }
2848 }
2849 else {
2850 PyObject **dictptr;
2851 PyErr_Clear();
2852 state = Py_None;
2853 dictptr = _PyObject_GetDictPtr(self);
2854 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2855 state = *dictptr;
2856 Py_INCREF(state);
2857 }
2858
2859 Py_DECREF(tmp);
2860
2861 if (state == Py_None) {
2862 Py_DECREF(state);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002863 return Py_BuildValue("(ON)", Py_Type(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002864 }
2865 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002866 return Py_BuildValue("(ONN)", Py_Type(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002867}
Tim Peters2a799bf2002-12-16 20:18:38 +00002868
2869static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002870
Tim Peters2a799bf2002-12-16 20:18:38 +00002871 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2872 PyDoc_STR("datetime -> string name of time zone.")},
2873
2874 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2875 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2876 "west of UTC).")},
2877
2878 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2879 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2880
Tim Peters52dcce22003-01-23 16:36:11 +00002881 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2882 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2883
Guido van Rossum177e41a2003-01-30 22:06:23 +00002884 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2885 PyDoc_STR("-> (cls, state)")},
2886
Tim Peters2a799bf2002-12-16 20:18:38 +00002887 {NULL, NULL}
2888};
2889
2890static char tzinfo_doc[] =
2891PyDoc_STR("Abstract base class for time zone info objects.");
2892
Neal Norwitz227b5332006-03-22 09:28:35 +00002893static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002894 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002895 "datetime.tzinfo", /* tp_name */
2896 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2897 0, /* tp_itemsize */
2898 0, /* tp_dealloc */
2899 0, /* tp_print */
2900 0, /* tp_getattr */
2901 0, /* tp_setattr */
2902 0, /* tp_compare */
2903 0, /* tp_repr */
2904 0, /* tp_as_number */
2905 0, /* tp_as_sequence */
2906 0, /* tp_as_mapping */
2907 0, /* tp_hash */
2908 0, /* tp_call */
2909 0, /* tp_str */
2910 PyObject_GenericGetAttr, /* tp_getattro */
2911 0, /* tp_setattro */
2912 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002914 tzinfo_doc, /* tp_doc */
2915 0, /* tp_traverse */
2916 0, /* tp_clear */
2917 0, /* tp_richcompare */
2918 0, /* tp_weaklistoffset */
2919 0, /* tp_iter */
2920 0, /* tp_iternext */
2921 tzinfo_methods, /* tp_methods */
2922 0, /* tp_members */
2923 0, /* tp_getset */
2924 0, /* tp_base */
2925 0, /* tp_dict */
2926 0, /* tp_descr_get */
2927 0, /* tp_descr_set */
2928 0, /* tp_dictoffset */
2929 0, /* tp_init */
2930 0, /* tp_alloc */
2931 PyType_GenericNew, /* tp_new */
2932 0, /* tp_free */
2933};
2934
2935/*
Tim Peters37f39822003-01-10 03:49:02 +00002936 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002937 */
2938
Tim Peters37f39822003-01-10 03:49:02 +00002939/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002940 */
2941
2942static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002943time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002944{
Tim Peters37f39822003-01-10 03:49:02 +00002945 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002946}
2947
Tim Peters37f39822003-01-10 03:49:02 +00002948static PyObject *
2949time_minute(PyDateTime_Time *self, void *unused)
2950{
2951 return PyInt_FromLong(TIME_GET_MINUTE(self));
2952}
2953
2954/* The name time_second conflicted with some platform header file. */
2955static PyObject *
2956py_time_second(PyDateTime_Time *self, void *unused)
2957{
2958 return PyInt_FromLong(TIME_GET_SECOND(self));
2959}
2960
2961static PyObject *
2962time_microsecond(PyDateTime_Time *self, void *unused)
2963{
2964 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2965}
2966
2967static PyObject *
2968time_tzinfo(PyDateTime_Time *self, void *unused)
2969{
Tim Petersa032d2e2003-01-11 00:15:54 +00002970 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002971 Py_INCREF(result);
2972 return result;
2973}
2974
2975static PyGetSetDef time_getset[] = {
2976 {"hour", (getter)time_hour},
2977 {"minute", (getter)time_minute},
2978 {"second", (getter)py_time_second},
2979 {"microsecond", (getter)time_microsecond},
2980 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00002981 {NULL}
2982};
2983
2984/*
2985 * Constructors.
2986 */
2987
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002988static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00002989 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002990
Tim Peters2a799bf2002-12-16 20:18:38 +00002991static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002992time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00002993{
2994 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002995 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002996 int hour = 0;
2997 int minute = 0;
2998 int second = 0;
2999 int usecond = 0;
3000 PyObject *tzinfo = Py_None;
3001
Guido van Rossum177e41a2003-01-30 22:06:23 +00003002 /* Check for invocation from pickle with __getstate__ state */
3003 if (PyTuple_GET_SIZE(args) >= 1 &&
3004 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003005 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3006 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3007 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003008 {
Tim Peters70533e22003-02-01 04:40:04 +00003009 PyDateTime_Time *me;
3010 char aware;
3011
3012 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003013 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003014 if (check_tzinfo_subclass(tzinfo) < 0) {
3015 PyErr_SetString(PyExc_TypeError, "bad "
3016 "tzinfo state arg");
3017 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003018 }
3019 }
Tim Peters70533e22003-02-01 04:40:04 +00003020 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003021 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003022 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003023 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003024
3025 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3026 me->hashcode = -1;
3027 me->hastzinfo = aware;
3028 if (aware) {
3029 Py_INCREF(tzinfo);
3030 me->tzinfo = tzinfo;
3031 }
3032 }
3033 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003034 }
3035
Tim Peters37f39822003-01-10 03:49:02 +00003036 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003037 &hour, &minute, &second, &usecond,
3038 &tzinfo)) {
3039 if (check_time_args(hour, minute, second, usecond) < 0)
3040 return NULL;
3041 if (check_tzinfo_subclass(tzinfo) < 0)
3042 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003043 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3044 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003045 }
3046 return self;
3047}
3048
3049/*
3050 * Destructor.
3051 */
3052
3053static void
Tim Peters37f39822003-01-10 03:49:02 +00003054time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003055{
Tim Petersa032d2e2003-01-11 00:15:54 +00003056 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003057 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003058 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003059 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003060}
3061
3062/*
Tim Peters855fe882002-12-22 03:43:39 +00003063 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003064 */
3065
Tim Peters2a799bf2002-12-16 20:18:38 +00003066/* These are all METH_NOARGS, so don't need to check the arglist. */
3067static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003068time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003069 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003070 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003071}
3072
3073static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003074time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003075 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003076 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003077}
3078
3079static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003080time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003081 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003082 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003083}
3084
3085/*
Tim Peters37f39822003-01-10 03:49:02 +00003086 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003087 */
3088
3089static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003090time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003091{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003092 const char *type_name = Py_Type(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003093 int h = TIME_GET_HOUR(self);
3094 int m = TIME_GET_MINUTE(self);
3095 int s = TIME_GET_SECOND(self);
3096 int us = TIME_GET_MICROSECOND(self);
3097 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003098
Tim Peters37f39822003-01-10 03:49:02 +00003099 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003100 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3101 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003102 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003103 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3104 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003105 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003106 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003107 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003108 result = append_keyword_tzinfo(result, self->tzinfo);
3109 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003110}
3111
Tim Peters37f39822003-01-10 03:49:02 +00003112static PyObject *
3113time_str(PyDateTime_Time *self)
3114{
3115 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3116}
Tim Peters2a799bf2002-12-16 20:18:38 +00003117
3118static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003119time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003120{
3121 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003122 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003123 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003124
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003125 if (us)
3126 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3127 TIME_GET_HOUR(self),
3128 TIME_GET_MINUTE(self),
3129 TIME_GET_SECOND(self),
3130 us);
3131 else
3132 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3133 TIME_GET_HOUR(self),
3134 TIME_GET_MINUTE(self),
3135 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003136
Tim Petersa032d2e2003-01-11 00:15:54 +00003137 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003138 return result;
3139
3140 /* We need to append the UTC offset. */
3141 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003142 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003143 Py_DECREF(result);
3144 return NULL;
3145 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003146 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003147 return result;
3148}
3149
Tim Peters37f39822003-01-10 03:49:02 +00003150static PyObject *
3151time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3152{
3153 PyObject *result;
3154 PyObject *format;
3155 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003156 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003157
Guido van Rossumbce56a62007-05-10 18:04:33 +00003158 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3159 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003160 return NULL;
3161
3162 /* Python's strftime does insane things with the year part of the
3163 * timetuple. The year is forced to (the otherwise nonsensical)
3164 * 1900 to worm around that.
3165 */
3166 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003167 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003168 TIME_GET_HOUR(self),
3169 TIME_GET_MINUTE(self),
3170 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003171 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003172 if (tuple == NULL)
3173 return NULL;
3174 assert(PyTuple_Size(tuple) == 9);
3175 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3176 Py_DECREF(tuple);
3177 return result;
3178}
Tim Peters2a799bf2002-12-16 20:18:38 +00003179
3180/*
3181 * Miscellaneous methods.
3182 */
3183
Tim Peters37f39822003-01-10 03:49:02 +00003184static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003185time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003186{
3187 int diff;
3188 naivety n1, n2;
3189 int offset1, offset2;
3190
3191 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003192 Py_INCREF(Py_NotImplemented);
3193 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003194 }
Guido van Rossum19960592006-08-24 17:29:38 +00003195 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3196 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003197 return NULL;
3198 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3199 /* If they're both naive, or both aware and have the same offsets,
3200 * we get off cheap. Note that if they're both naive, offset1 ==
3201 * offset2 == 0 at this point.
3202 */
3203 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003204 diff = memcmp(((PyDateTime_Time *)self)->data,
3205 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003206 _PyDateTime_TIME_DATASIZE);
3207 return diff_to_bool(diff, op);
3208 }
3209
3210 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3211 assert(offset1 != offset2); /* else last "if" handled it */
3212 /* Convert everything except microseconds to seconds. These
3213 * can't overflow (no more than the # of seconds in 2 days).
3214 */
3215 offset1 = TIME_GET_HOUR(self) * 3600 +
3216 (TIME_GET_MINUTE(self) - offset1) * 60 +
3217 TIME_GET_SECOND(self);
3218 offset2 = TIME_GET_HOUR(other) * 3600 +
3219 (TIME_GET_MINUTE(other) - offset2) * 60 +
3220 TIME_GET_SECOND(other);
3221 diff = offset1 - offset2;
3222 if (diff == 0)
3223 diff = TIME_GET_MICROSECOND(self) -
3224 TIME_GET_MICROSECOND(other);
3225 return diff_to_bool(diff, op);
3226 }
3227
3228 assert(n1 != n2);
3229 PyErr_SetString(PyExc_TypeError,
3230 "can't compare offset-naive and "
3231 "offset-aware times");
3232 return NULL;
3233}
3234
3235static long
3236time_hash(PyDateTime_Time *self)
3237{
3238 if (self->hashcode == -1) {
3239 naivety n;
3240 int offset;
3241 PyObject *temp;
3242
3243 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3244 assert(n != OFFSET_UNKNOWN);
3245 if (n == OFFSET_ERROR)
3246 return -1;
3247
3248 /* Reduce this to a hash of another object. */
3249 if (offset == 0)
3250 temp = PyString_FromStringAndSize((char *)self->data,
3251 _PyDateTime_TIME_DATASIZE);
3252 else {
3253 int hour;
3254 int minute;
3255
3256 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003257 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003258 hour = divmod(TIME_GET_HOUR(self) * 60 +
3259 TIME_GET_MINUTE(self) - offset,
3260 60,
3261 &minute);
3262 if (0 <= hour && hour < 24)
3263 temp = new_time(hour, minute,
3264 TIME_GET_SECOND(self),
3265 TIME_GET_MICROSECOND(self),
3266 Py_None);
3267 else
3268 temp = Py_BuildValue("iiii",
3269 hour, minute,
3270 TIME_GET_SECOND(self),
3271 TIME_GET_MICROSECOND(self));
3272 }
3273 if (temp != NULL) {
3274 self->hashcode = PyObject_Hash(temp);
3275 Py_DECREF(temp);
3276 }
3277 }
3278 return self->hashcode;
3279}
Tim Peters2a799bf2002-12-16 20:18:38 +00003280
Tim Peters12bf3392002-12-24 05:41:27 +00003281static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003282time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003283{
3284 PyObject *clone;
3285 PyObject *tuple;
3286 int hh = TIME_GET_HOUR(self);
3287 int mm = TIME_GET_MINUTE(self);
3288 int ss = TIME_GET_SECOND(self);
3289 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003290 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003291
3292 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003293 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003294 &hh, &mm, &ss, &us, &tzinfo))
3295 return NULL;
3296 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3297 if (tuple == NULL)
3298 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003299 clone = time_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003300 Py_DECREF(tuple);
3301 return clone;
3302}
3303
Tim Peters2a799bf2002-12-16 20:18:38 +00003304static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003305time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003306{
3307 int offset;
3308 int none;
3309
3310 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3311 /* Since utcoffset is in whole minutes, nothing can
3312 * alter the conclusion that this is nonzero.
3313 */
3314 return 1;
3315 }
3316 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003317 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003318 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003319 if (offset == -1 && PyErr_Occurred())
3320 return -1;
3321 }
3322 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3323}
3324
Tim Peters371935f2003-02-01 01:52:50 +00003325/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003326
Tim Peters33e0f382003-01-10 02:05:14 +00003327/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003328 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3329 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003330 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003331 */
3332static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003333time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003334{
3335 PyObject *basestate;
3336 PyObject *result = NULL;
3337
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003338 basestate = PyBytes_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003339 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003340 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003341 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003342 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003343 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003344 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003345 Py_DECREF(basestate);
3346 }
3347 return result;
3348}
3349
3350static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003351time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003352{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003353 return Py_BuildValue("(ON)", Py_Type(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003354}
3355
Tim Peters37f39822003-01-10 03:49:02 +00003356static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003357
Thomas Wouterscf297e42007-02-23 15:07:44 +00003358 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003359 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3360 "[+HH:MM].")},
3361
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003362 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003363 PyDoc_STR("format -> strftime() style string.")},
3364
3365 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003366 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3367
Tim Peters37f39822003-01-10 03:49:02 +00003368 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003369 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3370
Tim Peters37f39822003-01-10 03:49:02 +00003371 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003372 PyDoc_STR("Return self.tzinfo.dst(self).")},
3373
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003374 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003375 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003376
Guido van Rossum177e41a2003-01-30 22:06:23 +00003377 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3378 PyDoc_STR("__reduce__() -> (cls, state)")},
3379
Tim Peters2a799bf2002-12-16 20:18:38 +00003380 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003381};
3382
Tim Peters37f39822003-01-10 03:49:02 +00003383static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003384PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3385\n\
3386All arguments are optional. tzinfo may be None, or an instance of\n\
3387a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003388
Tim Peters37f39822003-01-10 03:49:02 +00003389static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003390 0, /* nb_add */
3391 0, /* nb_subtract */
3392 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003393 0, /* nb_remainder */
3394 0, /* nb_divmod */
3395 0, /* nb_power */
3396 0, /* nb_negative */
3397 0, /* nb_positive */
3398 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003399 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003400};
3401
Neal Norwitz227b5332006-03-22 09:28:35 +00003402static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003403 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003404 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003405 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003406 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003407 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003408 0, /* tp_print */
3409 0, /* tp_getattr */
3410 0, /* tp_setattr */
3411 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003412 (reprfunc)time_repr, /* tp_repr */
3413 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003414 0, /* tp_as_sequence */
3415 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003416 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003417 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003418 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003419 PyObject_GenericGetAttr, /* tp_getattro */
3420 0, /* tp_setattro */
3421 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003422 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003423 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003424 0, /* tp_traverse */
3425 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003426 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003427 0, /* tp_weaklistoffset */
3428 0, /* tp_iter */
3429 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003430 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003431 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003432 time_getset, /* tp_getset */
3433 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003434 0, /* tp_dict */
3435 0, /* tp_descr_get */
3436 0, /* tp_descr_set */
3437 0, /* tp_dictoffset */
3438 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003439 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003440 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003441 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003442};
3443
3444/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003445 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003446 */
3447
Tim Petersa9bc1682003-01-11 03:39:11 +00003448/* Accessor properties. Properties for day, month, and year are inherited
3449 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003450 */
3451
3452static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003453datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003454{
Tim Petersa9bc1682003-01-11 03:39:11 +00003455 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003456}
3457
Tim Petersa9bc1682003-01-11 03:39:11 +00003458static PyObject *
3459datetime_minute(PyDateTime_DateTime *self, void *unused)
3460{
3461 return PyInt_FromLong(DATE_GET_MINUTE(self));
3462}
3463
3464static PyObject *
3465datetime_second(PyDateTime_DateTime *self, void *unused)
3466{
3467 return PyInt_FromLong(DATE_GET_SECOND(self));
3468}
3469
3470static PyObject *
3471datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3472{
3473 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3474}
3475
3476static PyObject *
3477datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3478{
3479 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3480 Py_INCREF(result);
3481 return result;
3482}
3483
3484static PyGetSetDef datetime_getset[] = {
3485 {"hour", (getter)datetime_hour},
3486 {"minute", (getter)datetime_minute},
3487 {"second", (getter)datetime_second},
3488 {"microsecond", (getter)datetime_microsecond},
3489 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003490 {NULL}
3491};
3492
3493/*
3494 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003495 */
3496
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003497static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003498 "year", "month", "day", "hour", "minute", "second",
3499 "microsecond", "tzinfo", NULL
3500};
3501
Tim Peters2a799bf2002-12-16 20:18:38 +00003502static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003503datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003504{
3505 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003506 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003507 int year;
3508 int month;
3509 int day;
3510 int hour = 0;
3511 int minute = 0;
3512 int second = 0;
3513 int usecond = 0;
3514 PyObject *tzinfo = Py_None;
3515
Guido van Rossum177e41a2003-01-30 22:06:23 +00003516 /* Check for invocation from pickle with __getstate__ state */
3517 if (PyTuple_GET_SIZE(args) >= 1 &&
3518 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003519 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3520 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3521 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003522 {
Tim Peters70533e22003-02-01 04:40:04 +00003523 PyDateTime_DateTime *me;
3524 char aware;
3525
3526 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003527 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003528 if (check_tzinfo_subclass(tzinfo) < 0) {
3529 PyErr_SetString(PyExc_TypeError, "bad "
3530 "tzinfo state arg");
3531 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003532 }
3533 }
Tim Peters70533e22003-02-01 04:40:04 +00003534 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003535 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003536 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003537 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003538
3539 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3540 me->hashcode = -1;
3541 me->hastzinfo = aware;
3542 if (aware) {
3543 Py_INCREF(tzinfo);
3544 me->tzinfo = tzinfo;
3545 }
3546 }
3547 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003548 }
3549
Tim Petersa9bc1682003-01-11 03:39:11 +00003550 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003551 &year, &month, &day, &hour, &minute,
3552 &second, &usecond, &tzinfo)) {
3553 if (check_date_args(year, month, day) < 0)
3554 return NULL;
3555 if (check_time_args(hour, minute, second, usecond) < 0)
3556 return NULL;
3557 if (check_tzinfo_subclass(tzinfo) < 0)
3558 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003559 self = new_datetime_ex(year, month, day,
3560 hour, minute, second, usecond,
3561 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003562 }
3563 return self;
3564}
3565
Tim Petersa9bc1682003-01-11 03:39:11 +00003566/* TM_FUNC is the shared type of localtime() and gmtime(). */
3567typedef struct tm *(*TM_FUNC)(const time_t *timer);
3568
3569/* Internal helper.
3570 * Build datetime from a time_t and a distinct count of microseconds.
3571 * Pass localtime or gmtime for f, to control the interpretation of timet.
3572 */
3573static PyObject *
3574datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3575 PyObject *tzinfo)
3576{
3577 struct tm *tm;
3578 PyObject *result = NULL;
3579
3580 tm = f(&timet);
3581 if (tm) {
3582 /* The platform localtime/gmtime may insert leap seconds,
3583 * indicated by tm->tm_sec > 59. We don't care about them,
3584 * except to the extent that passing them on to the datetime
3585 * constructor would raise ValueError for a reason that
3586 * made no sense to the user.
3587 */
3588 if (tm->tm_sec > 59)
3589 tm->tm_sec = 59;
3590 result = PyObject_CallFunction(cls, "iiiiiiiO",
3591 tm->tm_year + 1900,
3592 tm->tm_mon + 1,
3593 tm->tm_mday,
3594 tm->tm_hour,
3595 tm->tm_min,
3596 tm->tm_sec,
3597 us,
3598 tzinfo);
3599 }
3600 else
3601 PyErr_SetString(PyExc_ValueError,
3602 "timestamp out of range for "
3603 "platform localtime()/gmtime() function");
3604 return result;
3605}
3606
3607/* Internal helper.
3608 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3609 * to control the interpretation of the timestamp. Since a double doesn't
3610 * have enough bits to cover a datetime's full range of precision, it's
3611 * better to call datetime_from_timet_and_us provided you have a way
3612 * to get that much precision (e.g., C time() isn't good enough).
3613 */
3614static PyObject *
3615datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3616 PyObject *tzinfo)
3617{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003618 time_t timet;
3619 double fraction;
3620 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003621
Tim Peters1b6f7a92004-06-20 02:50:16 +00003622 timet = _PyTime_DoubleToTimet(timestamp);
3623 if (timet == (time_t)-1 && PyErr_Occurred())
3624 return NULL;
3625 fraction = timestamp - (double)timet;
3626 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003627 if (us < 0) {
3628 /* Truncation towards zero is not what we wanted
3629 for negative numbers (Python's mod semantics) */
3630 timet -= 1;
3631 us += 1000000;
3632 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003633 /* If timestamp is less than one microsecond smaller than a
3634 * full second, round up. Otherwise, ValueErrors are raised
3635 * for some floats. */
3636 if (us == 1000000) {
3637 timet += 1;
3638 us = 0;
3639 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003640 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3641}
3642
3643/* Internal helper.
3644 * Build most accurate possible datetime for current time. Pass localtime or
3645 * gmtime for f as appropriate.
3646 */
3647static PyObject *
3648datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3649{
3650#ifdef HAVE_GETTIMEOFDAY
3651 struct timeval t;
3652
3653#ifdef GETTIMEOFDAY_NO_TZ
3654 gettimeofday(&t);
3655#else
3656 gettimeofday(&t, (struct timezone *)NULL);
3657#endif
3658 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3659 tzinfo);
3660
3661#else /* ! HAVE_GETTIMEOFDAY */
3662 /* No flavor of gettimeofday exists on this platform. Python's
3663 * time.time() does a lot of other platform tricks to get the
3664 * best time it can on the platform, and we're not going to do
3665 * better than that (if we could, the better code would belong
3666 * in time.time()!) We're limited by the precision of a double,
3667 * though.
3668 */
3669 PyObject *time;
3670 double dtime;
3671
3672 time = time_time();
3673 if (time == NULL)
3674 return NULL;
3675 dtime = PyFloat_AsDouble(time);
3676 Py_DECREF(time);
3677 if (dtime == -1.0 && PyErr_Occurred())
3678 return NULL;
3679 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3680#endif /* ! HAVE_GETTIMEOFDAY */
3681}
3682
Tim Peters2a799bf2002-12-16 20:18:38 +00003683/* Return best possible local time -- this isn't constrained by the
3684 * precision of a timestamp.
3685 */
3686static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003687datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003688{
Tim Peters10cadce2003-01-23 19:58:02 +00003689 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003690 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003691 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003692
Tim Peters10cadce2003-01-23 19:58:02 +00003693 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3694 &tzinfo))
3695 return NULL;
3696 if (check_tzinfo_subclass(tzinfo) < 0)
3697 return NULL;
3698
3699 self = datetime_best_possible(cls,
3700 tzinfo == Py_None ? localtime : gmtime,
3701 tzinfo);
3702 if (self != NULL && tzinfo != Py_None) {
3703 /* Convert UTC to tzinfo's zone. */
3704 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003705 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003706 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003707 }
3708 return self;
3709}
3710
Tim Petersa9bc1682003-01-11 03:39:11 +00003711/* Return best possible UTC time -- this isn't constrained by the
3712 * precision of a timestamp.
3713 */
3714static PyObject *
3715datetime_utcnow(PyObject *cls, PyObject *dummy)
3716{
3717 return datetime_best_possible(cls, gmtime, Py_None);
3718}
3719
Tim Peters2a799bf2002-12-16 20:18:38 +00003720/* Return new local datetime from timestamp (Python timestamp -- a double). */
3721static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003722datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003723{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003724 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003725 double timestamp;
3726 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003727 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003728
Tim Peters2a44a8d2003-01-23 20:53:10 +00003729 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3730 keywords, &timestamp, &tzinfo))
3731 return NULL;
3732 if (check_tzinfo_subclass(tzinfo) < 0)
3733 return NULL;
3734
3735 self = datetime_from_timestamp(cls,
3736 tzinfo == Py_None ? localtime : gmtime,
3737 timestamp,
3738 tzinfo);
3739 if (self != NULL && tzinfo != Py_None) {
3740 /* Convert UTC to tzinfo's zone. */
3741 PyObject *temp = self;
3742 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3743 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003744 }
3745 return self;
3746}
3747
Tim Petersa9bc1682003-01-11 03:39:11 +00003748/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3749static PyObject *
3750datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3751{
3752 double timestamp;
3753 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003754
Tim Petersa9bc1682003-01-11 03:39:11 +00003755 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3756 result = datetime_from_timestamp(cls, gmtime, timestamp,
3757 Py_None);
3758 return result;
3759}
3760
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003761/* Return new datetime from time.strptime(). */
3762static PyObject *
3763datetime_strptime(PyObject *cls, PyObject *args)
3764{
3765 PyObject *result = NULL, *obj, *module;
3766 const char *string, *format;
3767
3768 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3769 return NULL;
3770
3771 if ((module = PyImport_ImportModule("time")) == NULL)
3772 return NULL;
3773 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3774 Py_DECREF(module);
3775
3776 if (obj != NULL) {
3777 int i, good_timetuple = 1;
3778 long int ia[6];
3779 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3780 for (i=0; i < 6; i++) {
3781 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003782 if (p == NULL) {
3783 Py_DECREF(obj);
3784 return NULL;
3785 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003786 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003787 ia[i] = PyInt_AsLong(p);
3788 else
3789 good_timetuple = 0;
3790 Py_DECREF(p);
3791 }
3792 else
3793 good_timetuple = 0;
3794 if (good_timetuple)
3795 result = PyObject_CallFunction(cls, "iiiiii",
3796 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3797 else
3798 PyErr_SetString(PyExc_ValueError,
3799 "unexpected value from time.strptime");
3800 Py_DECREF(obj);
3801 }
3802 return result;
3803}
3804
Tim Petersa9bc1682003-01-11 03:39:11 +00003805/* Return new datetime from date/datetime and time arguments. */
3806static PyObject *
3807datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3808{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003809 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003810 PyObject *date;
3811 PyObject *time;
3812 PyObject *result = NULL;
3813
3814 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3815 &PyDateTime_DateType, &date,
3816 &PyDateTime_TimeType, &time)) {
3817 PyObject *tzinfo = Py_None;
3818
3819 if (HASTZINFO(time))
3820 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3821 result = PyObject_CallFunction(cls, "iiiiiiiO",
3822 GET_YEAR(date),
3823 GET_MONTH(date),
3824 GET_DAY(date),
3825 TIME_GET_HOUR(time),
3826 TIME_GET_MINUTE(time),
3827 TIME_GET_SECOND(time),
3828 TIME_GET_MICROSECOND(time),
3829 tzinfo);
3830 }
3831 return result;
3832}
Tim Peters2a799bf2002-12-16 20:18:38 +00003833
3834/*
3835 * Destructor.
3836 */
3837
3838static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003839datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003840{
Tim Petersa9bc1682003-01-11 03:39:11 +00003841 if (HASTZINFO(self)) {
3842 Py_XDECREF(self->tzinfo);
3843 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003844 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003845}
3846
3847/*
3848 * Indirect access to tzinfo methods.
3849 */
3850
Tim Peters2a799bf2002-12-16 20:18:38 +00003851/* These are all METH_NOARGS, so don't need to check the arglist. */
3852static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003853datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3854 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3855 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003856}
3857
3858static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003859datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3860 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3861 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003862}
3863
3864static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003865datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3866 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3867 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003868}
3869
3870/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003871 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003872 */
3873
Tim Petersa9bc1682003-01-11 03:39:11 +00003874/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3875 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003876 */
3877static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003878add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3879 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003880{
Tim Petersa9bc1682003-01-11 03:39:11 +00003881 /* Note that the C-level additions can't overflow, because of
3882 * invariant bounds on the member values.
3883 */
3884 int year = GET_YEAR(date);
3885 int month = GET_MONTH(date);
3886 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3887 int hour = DATE_GET_HOUR(date);
3888 int minute = DATE_GET_MINUTE(date);
3889 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3890 int microsecond = DATE_GET_MICROSECOND(date) +
3891 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003892
Tim Petersa9bc1682003-01-11 03:39:11 +00003893 assert(factor == 1 || factor == -1);
3894 if (normalize_datetime(&year, &month, &day,
3895 &hour, &minute, &second, &microsecond) < 0)
3896 return NULL;
3897 else
3898 return new_datetime(year, month, day,
3899 hour, minute, second, microsecond,
3900 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003901}
3902
3903static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003904datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003905{
Tim Petersa9bc1682003-01-11 03:39:11 +00003906 if (PyDateTime_Check(left)) {
3907 /* datetime + ??? */
3908 if (PyDelta_Check(right))
3909 /* datetime + delta */
3910 return add_datetime_timedelta(
3911 (PyDateTime_DateTime *)left,
3912 (PyDateTime_Delta *)right,
3913 1);
3914 }
3915 else if (PyDelta_Check(left)) {
3916 /* delta + datetime */
3917 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3918 (PyDateTime_Delta *) left,
3919 1);
3920 }
3921 Py_INCREF(Py_NotImplemented);
3922 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003923}
3924
3925static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003926datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003927{
3928 PyObject *result = Py_NotImplemented;
3929
3930 if (PyDateTime_Check(left)) {
3931 /* datetime - ??? */
3932 if (PyDateTime_Check(right)) {
3933 /* datetime - datetime */
3934 naivety n1, n2;
3935 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003936 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003937
Tim Peterse39a80c2002-12-30 21:28:52 +00003938 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3939 right, &offset2, &n2,
3940 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003941 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003942 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003943 if (n1 != n2) {
3944 PyErr_SetString(PyExc_TypeError,
3945 "can't subtract offset-naive and "
3946 "offset-aware datetimes");
3947 return NULL;
3948 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003949 delta_d = ymd_to_ord(GET_YEAR(left),
3950 GET_MONTH(left),
3951 GET_DAY(left)) -
3952 ymd_to_ord(GET_YEAR(right),
3953 GET_MONTH(right),
3954 GET_DAY(right));
3955 /* These can't overflow, since the values are
3956 * normalized. At most this gives the number of
3957 * seconds in one day.
3958 */
3959 delta_s = (DATE_GET_HOUR(left) -
3960 DATE_GET_HOUR(right)) * 3600 +
3961 (DATE_GET_MINUTE(left) -
3962 DATE_GET_MINUTE(right)) * 60 +
3963 (DATE_GET_SECOND(left) -
3964 DATE_GET_SECOND(right));
3965 delta_us = DATE_GET_MICROSECOND(left) -
3966 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003967 /* (left - offset1) - (right - offset2) =
3968 * (left - right) + (offset2 - offset1)
3969 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003970 delta_s += (offset2 - offset1) * 60;
3971 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003972 }
3973 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003974 /* datetime - delta */
3975 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003976 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00003977 (PyDateTime_Delta *)right,
3978 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003979 }
3980 }
3981
3982 if (result == Py_NotImplemented)
3983 Py_INCREF(result);
3984 return result;
3985}
3986
3987/* Various ways to turn a datetime into a string. */
3988
3989static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003990datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003991{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003992 const char *type_name = Py_Type(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00003993 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00003994
Tim Petersa9bc1682003-01-11 03:39:11 +00003995 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003996 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00003997 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003998 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00003999 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4000 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4001 DATE_GET_SECOND(self),
4002 DATE_GET_MICROSECOND(self));
4003 }
4004 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004005 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004006 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004007 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004008 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4009 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4010 DATE_GET_SECOND(self));
4011 }
4012 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004013 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004014 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004015 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004016 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4017 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4018 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004019 if (baserepr == NULL || ! HASTZINFO(self))
4020 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004021 return append_keyword_tzinfo(baserepr, self->tzinfo);
4022}
4023
Tim Petersa9bc1682003-01-11 03:39:11 +00004024static PyObject *
4025datetime_str(PyDateTime_DateTime *self)
4026{
4027 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4028}
Tim Peters2a799bf2002-12-16 20:18:38 +00004029
4030static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004031datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004032{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004033 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004034 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004035 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004036 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004037 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004038
Walter Dörwaldd0941302007-07-01 21:58:22 +00004039 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004040 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004041 if (us)
4042 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4043 GET_YEAR(self), GET_MONTH(self),
4044 GET_DAY(self), (int)sep,
4045 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4046 DATE_GET_SECOND(self), us);
4047 else
4048 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4049 GET_YEAR(self), GET_MONTH(self),
4050 GET_DAY(self), (int)sep,
4051 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4052 DATE_GET_SECOND(self));
4053
4054 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004055 return result;
4056
4057 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004058 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004059 (PyObject *)self) < 0) {
4060 Py_DECREF(result);
4061 return NULL;
4062 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004063 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004064 return result;
4065}
4066
Tim Petersa9bc1682003-01-11 03:39:11 +00004067static PyObject *
4068datetime_ctime(PyDateTime_DateTime *self)
4069{
4070 return format_ctime((PyDateTime_Date *)self,
4071 DATE_GET_HOUR(self),
4072 DATE_GET_MINUTE(self),
4073 DATE_GET_SECOND(self));
4074}
4075
Tim Peters2a799bf2002-12-16 20:18:38 +00004076/* Miscellaneous methods. */
4077
Tim Petersa9bc1682003-01-11 03:39:11 +00004078static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004079datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004080{
4081 int diff;
4082 naivety n1, n2;
4083 int offset1, offset2;
4084
4085 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004086 if (PyDate_Check(other)) {
4087 /* Prevent invocation of date_richcompare. We want to
4088 return NotImplemented here to give the other object
4089 a chance. But since DateTime is a subclass of
4090 Date, if the other object is a Date, it would
4091 compute an ordering based on the date part alone,
4092 and we don't want that. So force unequal or
4093 uncomparable here in that case. */
4094 if (op == Py_EQ)
4095 Py_RETURN_FALSE;
4096 if (op == Py_NE)
4097 Py_RETURN_TRUE;
4098 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004099 }
Guido van Rossum19960592006-08-24 17:29:38 +00004100 Py_INCREF(Py_NotImplemented);
4101 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004102 }
4103
Guido van Rossum19960592006-08-24 17:29:38 +00004104 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4105 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004106 return NULL;
4107 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4108 /* If they're both naive, or both aware and have the same offsets,
4109 * we get off cheap. Note that if they're both naive, offset1 ==
4110 * offset2 == 0 at this point.
4111 */
4112 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004113 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4114 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004115 _PyDateTime_DATETIME_DATASIZE);
4116 return diff_to_bool(diff, op);
4117 }
4118
4119 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4120 PyDateTime_Delta *delta;
4121
4122 assert(offset1 != offset2); /* else last "if" handled it */
4123 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4124 other);
4125 if (delta == NULL)
4126 return NULL;
4127 diff = GET_TD_DAYS(delta);
4128 if (diff == 0)
4129 diff = GET_TD_SECONDS(delta) |
4130 GET_TD_MICROSECONDS(delta);
4131 Py_DECREF(delta);
4132 return diff_to_bool(diff, op);
4133 }
4134
4135 assert(n1 != n2);
4136 PyErr_SetString(PyExc_TypeError,
4137 "can't compare offset-naive and "
4138 "offset-aware datetimes");
4139 return NULL;
4140}
4141
4142static long
4143datetime_hash(PyDateTime_DateTime *self)
4144{
4145 if (self->hashcode == -1) {
4146 naivety n;
4147 int offset;
4148 PyObject *temp;
4149
4150 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4151 &offset);
4152 assert(n != OFFSET_UNKNOWN);
4153 if (n == OFFSET_ERROR)
4154 return -1;
4155
4156 /* Reduce this to a hash of another object. */
4157 if (n == OFFSET_NAIVE)
4158 temp = PyString_FromStringAndSize(
4159 (char *)self->data,
4160 _PyDateTime_DATETIME_DATASIZE);
4161 else {
4162 int days;
4163 int seconds;
4164
4165 assert(n == OFFSET_AWARE);
4166 assert(HASTZINFO(self));
4167 days = ymd_to_ord(GET_YEAR(self),
4168 GET_MONTH(self),
4169 GET_DAY(self));
4170 seconds = DATE_GET_HOUR(self) * 3600 +
4171 (DATE_GET_MINUTE(self) - offset) * 60 +
4172 DATE_GET_SECOND(self);
4173 temp = new_delta(days,
4174 seconds,
4175 DATE_GET_MICROSECOND(self),
4176 1);
4177 }
4178 if (temp != NULL) {
4179 self->hashcode = PyObject_Hash(temp);
4180 Py_DECREF(temp);
4181 }
4182 }
4183 return self->hashcode;
4184}
Tim Peters2a799bf2002-12-16 20:18:38 +00004185
4186static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004187datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004188{
4189 PyObject *clone;
4190 PyObject *tuple;
4191 int y = GET_YEAR(self);
4192 int m = GET_MONTH(self);
4193 int d = GET_DAY(self);
4194 int hh = DATE_GET_HOUR(self);
4195 int mm = DATE_GET_MINUTE(self);
4196 int ss = DATE_GET_SECOND(self);
4197 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004198 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004199
4200 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004201 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004202 &y, &m, &d, &hh, &mm, &ss, &us,
4203 &tzinfo))
4204 return NULL;
4205 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4206 if (tuple == NULL)
4207 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004208 clone = datetime_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004209 Py_DECREF(tuple);
4210 return clone;
4211}
4212
4213static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004214datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004215{
Tim Peters52dcce22003-01-23 16:36:11 +00004216 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004217 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004218 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004219
Tim Peters80475bb2002-12-25 07:40:55 +00004220 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004221 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004222
Tim Peters52dcce22003-01-23 16:36:11 +00004223 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4224 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004225 return NULL;
4226
Tim Peters52dcce22003-01-23 16:36:11 +00004227 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4228 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004229
Tim Peters52dcce22003-01-23 16:36:11 +00004230 /* Conversion to self's own time zone is a NOP. */
4231 if (self->tzinfo == tzinfo) {
4232 Py_INCREF(self);
4233 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004234 }
Tim Peters521fc152002-12-31 17:36:56 +00004235
Tim Peters52dcce22003-01-23 16:36:11 +00004236 /* Convert self to UTC. */
4237 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4238 if (offset == -1 && PyErr_Occurred())
4239 return NULL;
4240 if (none)
4241 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004242
Tim Peters52dcce22003-01-23 16:36:11 +00004243 y = GET_YEAR(self);
4244 m = GET_MONTH(self);
4245 d = GET_DAY(self);
4246 hh = DATE_GET_HOUR(self);
4247 mm = DATE_GET_MINUTE(self);
4248 ss = DATE_GET_SECOND(self);
4249 us = DATE_GET_MICROSECOND(self);
4250
4251 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004252 if ((mm < 0 || mm >= 60) &&
4253 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004254 return NULL;
4255
4256 /* Attach new tzinfo and let fromutc() do the rest. */
4257 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4258 if (result != NULL) {
4259 PyObject *temp = result;
4260
4261 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4262 Py_DECREF(temp);
4263 }
Tim Petersadf64202003-01-04 06:03:15 +00004264 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004265
Tim Peters52dcce22003-01-23 16:36:11 +00004266NeedAware:
4267 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4268 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004269 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004270}
4271
4272static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004273datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004274{
4275 int dstflag = -1;
4276
Tim Petersa9bc1682003-01-11 03:39:11 +00004277 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004278 int none;
4279
4280 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4281 if (dstflag == -1 && PyErr_Occurred())
4282 return NULL;
4283
4284 if (none)
4285 dstflag = -1;
4286 else if (dstflag != 0)
4287 dstflag = 1;
4288
4289 }
4290 return build_struct_time(GET_YEAR(self),
4291 GET_MONTH(self),
4292 GET_DAY(self),
4293 DATE_GET_HOUR(self),
4294 DATE_GET_MINUTE(self),
4295 DATE_GET_SECOND(self),
4296 dstflag);
4297}
4298
4299static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004300datetime_getdate(PyDateTime_DateTime *self)
4301{
4302 return new_date(GET_YEAR(self),
4303 GET_MONTH(self),
4304 GET_DAY(self));
4305}
4306
4307static PyObject *
4308datetime_gettime(PyDateTime_DateTime *self)
4309{
4310 return new_time(DATE_GET_HOUR(self),
4311 DATE_GET_MINUTE(self),
4312 DATE_GET_SECOND(self),
4313 DATE_GET_MICROSECOND(self),
4314 Py_None);
4315}
4316
4317static PyObject *
4318datetime_gettimetz(PyDateTime_DateTime *self)
4319{
4320 return new_time(DATE_GET_HOUR(self),
4321 DATE_GET_MINUTE(self),
4322 DATE_GET_SECOND(self),
4323 DATE_GET_MICROSECOND(self),
4324 HASTZINFO(self) ? self->tzinfo : Py_None);
4325}
4326
4327static PyObject *
4328datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004329{
4330 int y = GET_YEAR(self);
4331 int m = GET_MONTH(self);
4332 int d = GET_DAY(self);
4333 int hh = DATE_GET_HOUR(self);
4334 int mm = DATE_GET_MINUTE(self);
4335 int ss = DATE_GET_SECOND(self);
4336 int us = 0; /* microseconds are ignored in a timetuple */
4337 int offset = 0;
4338
Tim Petersa9bc1682003-01-11 03:39:11 +00004339 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004340 int none;
4341
4342 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4343 if (offset == -1 && PyErr_Occurred())
4344 return NULL;
4345 }
4346 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4347 * 0 in a UTC timetuple regardless of what dst() says.
4348 */
4349 if (offset) {
4350 /* Subtract offset minutes & normalize. */
4351 int stat;
4352
4353 mm -= offset;
4354 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4355 if (stat < 0) {
4356 /* At the edges, it's possible we overflowed
4357 * beyond MINYEAR or MAXYEAR.
4358 */
4359 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4360 PyErr_Clear();
4361 else
4362 return NULL;
4363 }
4364 }
4365 return build_struct_time(y, m, d, hh, mm, ss, 0);
4366}
4367
Tim Peters371935f2003-02-01 01:52:50 +00004368/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004369
Tim Petersa9bc1682003-01-11 03:39:11 +00004370/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004371 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4372 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004373 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004374 */
4375static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004376datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004377{
4378 PyObject *basestate;
4379 PyObject *result = NULL;
4380
Martin v. Löwis10a60b32007-07-18 02:28:27 +00004381 basestate = PyBytes_FromStringAndSize((char *)self->data,
4382 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004383 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004384 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004385 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004386 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004387 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004388 Py_DECREF(basestate);
4389 }
4390 return result;
4391}
4392
4393static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004394datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004395{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004396 return Py_BuildValue("(ON)", Py_Type(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004397}
4398
Tim Petersa9bc1682003-01-11 03:39:11 +00004399static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004400
Tim Peters2a799bf2002-12-16 20:18:38 +00004401 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004402
Tim Petersa9bc1682003-01-11 03:39:11 +00004403 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004404 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004405 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004406
Tim Petersa9bc1682003-01-11 03:39:11 +00004407 {"utcnow", (PyCFunction)datetime_utcnow,
4408 METH_NOARGS | METH_CLASS,
4409 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4410
4411 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004412 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004413 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004414
Tim Petersa9bc1682003-01-11 03:39:11 +00004415 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4416 METH_VARARGS | METH_CLASS,
4417 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4418 "(like time.time()).")},
4419
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004420 {"strptime", (PyCFunction)datetime_strptime,
4421 METH_VARARGS | METH_CLASS,
4422 PyDoc_STR("string, format -> new datetime parsed from a string "
4423 "(like time.strptime()).")},
4424
Tim Petersa9bc1682003-01-11 03:39:11 +00004425 {"combine", (PyCFunction)datetime_combine,
4426 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4427 PyDoc_STR("date, time -> datetime with same date and time fields")},
4428
Tim Peters2a799bf2002-12-16 20:18:38 +00004429 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004430
Tim Petersa9bc1682003-01-11 03:39:11 +00004431 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4432 PyDoc_STR("Return date object with same year, month and day.")},
4433
4434 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4435 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4436
4437 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4438 PyDoc_STR("Return time object with same time and tzinfo.")},
4439
4440 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4441 PyDoc_STR("Return ctime() style string.")},
4442
4443 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004444 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4445
Tim Petersa9bc1682003-01-11 03:39:11 +00004446 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004447 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4448
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004449 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004450 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4451 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4452 "sep is used to separate the year from the time, and "
4453 "defaults to 'T'.")},
4454
Tim Petersa9bc1682003-01-11 03:39:11 +00004455 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004456 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4457
Tim Petersa9bc1682003-01-11 03:39:11 +00004458 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004459 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4460
Tim Petersa9bc1682003-01-11 03:39:11 +00004461 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004462 PyDoc_STR("Return self.tzinfo.dst(self).")},
4463
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004464 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004465 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004466
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004467 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004468 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4469
Guido van Rossum177e41a2003-01-30 22:06:23 +00004470 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4471 PyDoc_STR("__reduce__() -> (cls, state)")},
4472
Tim Peters2a799bf2002-12-16 20:18:38 +00004473 {NULL, NULL}
4474};
4475
Tim Petersa9bc1682003-01-11 03:39:11 +00004476static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004477PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4478\n\
4479The year, month and day arguments are required. tzinfo may be None, or an\n\
4480instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004481
Tim Petersa9bc1682003-01-11 03:39:11 +00004482static PyNumberMethods datetime_as_number = {
4483 datetime_add, /* nb_add */
4484 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004485 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004486 0, /* nb_remainder */
4487 0, /* nb_divmod */
4488 0, /* nb_power */
4489 0, /* nb_negative */
4490 0, /* nb_positive */
4491 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004492 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004493};
4494
Neal Norwitz227b5332006-03-22 09:28:35 +00004495static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004496 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004497 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004498 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004499 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004500 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004501 0, /* tp_print */
4502 0, /* tp_getattr */
4503 0, /* tp_setattr */
4504 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004505 (reprfunc)datetime_repr, /* tp_repr */
4506 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004507 0, /* tp_as_sequence */
4508 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004509 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004510 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004511 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004512 PyObject_GenericGetAttr, /* tp_getattro */
4513 0, /* tp_setattro */
4514 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004515 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004516 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004517 0, /* tp_traverse */
4518 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004519 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004520 0, /* tp_weaklistoffset */
4521 0, /* tp_iter */
4522 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004523 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004524 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004525 datetime_getset, /* tp_getset */
4526 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 0, /* tp_dict */
4528 0, /* tp_descr_get */
4529 0, /* tp_descr_set */
4530 0, /* tp_dictoffset */
4531 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004532 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004533 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004534 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004535};
4536
4537/* ---------------------------------------------------------------------------
4538 * Module methods and initialization.
4539 */
4540
4541static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004542 {NULL, NULL}
4543};
4544
Tim Peters9ddf40b2004-06-20 22:41:32 +00004545/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4546 * datetime.h.
4547 */
4548static PyDateTime_CAPI CAPI = {
4549 &PyDateTime_DateType,
4550 &PyDateTime_DateTimeType,
4551 &PyDateTime_TimeType,
4552 &PyDateTime_DeltaType,
4553 &PyDateTime_TZInfoType,
4554 new_date_ex,
4555 new_datetime_ex,
4556 new_time_ex,
4557 new_delta_ex,
4558 datetime_fromtimestamp,
4559 date_fromtimestamp
4560};
4561
4562
Tim Peters2a799bf2002-12-16 20:18:38 +00004563PyMODINIT_FUNC
4564initdatetime(void)
4565{
4566 PyObject *m; /* a module object */
4567 PyObject *d; /* its dict */
4568 PyObject *x;
4569
Tim Peters2a799bf2002-12-16 20:18:38 +00004570 m = Py_InitModule3("datetime", module_methods,
4571 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004572 if (m == NULL)
4573 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004574
4575 if (PyType_Ready(&PyDateTime_DateType) < 0)
4576 return;
4577 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4578 return;
4579 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4580 return;
4581 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4582 return;
4583 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4584 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004585
Tim Peters2a799bf2002-12-16 20:18:38 +00004586 /* timedelta values */
4587 d = PyDateTime_DeltaType.tp_dict;
4588
Tim Peters2a799bf2002-12-16 20:18:38 +00004589 x = new_delta(0, 0, 1, 0);
4590 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4591 return;
4592 Py_DECREF(x);
4593
4594 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4595 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4596 return;
4597 Py_DECREF(x);
4598
4599 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4600 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4601 return;
4602 Py_DECREF(x);
4603
4604 /* date values */
4605 d = PyDateTime_DateType.tp_dict;
4606
4607 x = new_date(1, 1, 1);
4608 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4609 return;
4610 Py_DECREF(x);
4611
4612 x = new_date(MAXYEAR, 12, 31);
4613 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4614 return;
4615 Py_DECREF(x);
4616
4617 x = new_delta(1, 0, 0, 0);
4618 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4619 return;
4620 Py_DECREF(x);
4621
Tim Peters37f39822003-01-10 03:49:02 +00004622 /* time values */
4623 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004624
Tim Peters37f39822003-01-10 03:49:02 +00004625 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004626 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4627 return;
4628 Py_DECREF(x);
4629
Tim Peters37f39822003-01-10 03:49:02 +00004630 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004631 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4632 return;
4633 Py_DECREF(x);
4634
4635 x = new_delta(0, 0, 1, 0);
4636 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4637 return;
4638 Py_DECREF(x);
4639
Tim Petersa9bc1682003-01-11 03:39:11 +00004640 /* datetime values */
4641 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004642
Tim Petersa9bc1682003-01-11 03:39:11 +00004643 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004644 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4645 return;
4646 Py_DECREF(x);
4647
Tim Petersa9bc1682003-01-11 03:39:11 +00004648 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004649 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4650 return;
4651 Py_DECREF(x);
4652
4653 x = new_delta(0, 0, 1, 0);
4654 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4655 return;
4656 Py_DECREF(x);
4657
Tim Peters2a799bf2002-12-16 20:18:38 +00004658 /* module initialization */
4659 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4660 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4661
4662 Py_INCREF(&PyDateTime_DateType);
4663 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4664
Tim Petersa9bc1682003-01-11 03:39:11 +00004665 Py_INCREF(&PyDateTime_DateTimeType);
4666 PyModule_AddObject(m, "datetime",
4667 (PyObject *)&PyDateTime_DateTimeType);
4668
4669 Py_INCREF(&PyDateTime_TimeType);
4670 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4671
Tim Peters2a799bf2002-12-16 20:18:38 +00004672 Py_INCREF(&PyDateTime_DeltaType);
4673 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4674
Tim Peters2a799bf2002-12-16 20:18:38 +00004675 Py_INCREF(&PyDateTime_TZInfoType);
4676 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4677
Tim Peters9ddf40b2004-06-20 22:41:32 +00004678 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4679 NULL);
4680 if (x == NULL)
4681 return;
4682 PyModule_AddObject(m, "datetime_CAPI", x);
4683
Tim Peters2a799bf2002-12-16 20:18:38 +00004684 /* A 4-year cycle has an extra leap day over what we'd get from
4685 * pasting together 4 single years.
4686 */
4687 assert(DI4Y == 4 * 365 + 1);
4688 assert(DI4Y == days_before_year(4+1));
4689
4690 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4691 * get from pasting together 4 100-year cycles.
4692 */
4693 assert(DI400Y == 4 * DI100Y + 1);
4694 assert(DI400Y == days_before_year(400+1));
4695
4696 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4697 * pasting together 25 4-year cycles.
4698 */
4699 assert(DI100Y == 25 * DI4Y - 1);
4700 assert(DI100Y == days_before_year(100+1));
4701
4702 us_per_us = PyInt_FromLong(1);
4703 us_per_ms = PyInt_FromLong(1000);
4704 us_per_second = PyInt_FromLong(1000000);
4705 us_per_minute = PyInt_FromLong(60000000);
4706 seconds_per_day = PyInt_FromLong(24 * 3600);
4707 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4708 us_per_minute == NULL || seconds_per_day == NULL)
4709 return;
4710
4711 /* The rest are too big for 32-bit ints, but even
4712 * us_per_week fits in 40 bits, so doubles should be exact.
4713 */
4714 us_per_hour = PyLong_FromDouble(3600000000.0);
4715 us_per_day = PyLong_FromDouble(86400000000.0);
4716 us_per_week = PyLong_FromDouble(604800000000.0);
4717 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4718 return;
4719}
Tim Petersf3615152003-01-01 21:51:37 +00004720
4721/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004722Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004723 x.n = x stripped of its timezone -- its naive time.
4724 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4725 return None
4726 x.d = x.dst(), and assuming that doesn't raise an exception or
4727 return None
4728 x.s = x's standard offset, x.o - x.d
4729
4730Now some derived rules, where k is a duration (timedelta).
4731
47321. x.o = x.s + x.d
4733 This follows from the definition of x.s.
4734
Tim Petersc5dc4da2003-01-02 17:55:03 +000047352. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004736 This is actually a requirement, an assumption we need to make about
4737 sane tzinfo classes.
4738
47393. The naive UTC time corresponding to x is x.n - x.o.
4740 This is again a requirement for a sane tzinfo class.
4741
47424. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004743 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004744
Tim Petersc5dc4da2003-01-02 17:55:03 +000047455. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004746 Again follows from how arithmetic is defined.
4747
Tim Peters8bb5ad22003-01-24 02:44:45 +00004748Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004749(meaning that the various tzinfo methods exist, and don't blow up or return
4750None when called).
4751
Tim Petersa9bc1682003-01-11 03:39:11 +00004752The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004753x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004754
4755By #3, we want
4756
Tim Peters8bb5ad22003-01-24 02:44:45 +00004757 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004758
4759The algorithm starts by attaching tz to x.n, and calling that y. So
4760x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4761becomes true; in effect, we want to solve [2] for k:
4762
Tim Peters8bb5ad22003-01-24 02:44:45 +00004763 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004764
4765By #1, this is the same as
4766
Tim Peters8bb5ad22003-01-24 02:44:45 +00004767 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004768
4769By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4770Substituting that into [3],
4771
Tim Peters8bb5ad22003-01-24 02:44:45 +00004772 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4773 k - (y+k).s - (y+k).d = 0; rearranging,
4774 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4775 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004776
Tim Peters8bb5ad22003-01-24 02:44:45 +00004777On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4778approximate k by ignoring the (y+k).d term at first. Note that k can't be
4779very large, since all offset-returning methods return a duration of magnitude
4780less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4781be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004782
4783In any case, the new value is
4784
Tim Peters8bb5ad22003-01-24 02:44:45 +00004785 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004786
Tim Peters8bb5ad22003-01-24 02:44:45 +00004787It's helpful to step back at look at [4] from a higher level: it's simply
4788mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004789
4790At this point, if
4791
Tim Peters8bb5ad22003-01-24 02:44:45 +00004792 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004793
4794we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004795at the start of daylight time. Picture US Eastern for concreteness. The wall
4796time 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 +00004797sense then. The docs ask that an Eastern tzinfo class consider such a time to
4798be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4799on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004800the only spelling that makes sense on the local wall clock.
4801
Tim Petersc5dc4da2003-01-02 17:55:03 +00004802In fact, if [5] holds at this point, we do have the standard-time spelling,
4803but that takes a bit of proof. We first prove a stronger result. What's the
4804difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004805
Tim Peters8bb5ad22003-01-24 02:44:45 +00004806 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004807
Tim Petersc5dc4da2003-01-02 17:55:03 +00004808Now
4809 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004810 (y + y.s).n = by #5
4811 y.n + y.s = since y.n = x.n
4812 x.n + y.s = since z and y are have the same tzinfo member,
4813 y.s = z.s by #2
4814 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004815
Tim Petersc5dc4da2003-01-02 17:55:03 +00004816Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004817
Tim Petersc5dc4da2003-01-02 17:55:03 +00004818 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004819 x.n - ((x.n + z.s) - z.o) = expanding
4820 x.n - x.n - z.s + z.o = cancelling
4821 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004822 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004823
Tim Petersc5dc4da2003-01-02 17:55:03 +00004824So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004825
Tim Petersc5dc4da2003-01-02 17:55:03 +00004826If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004827spelling we wanted in the endcase described above. We're done. Contrarily,
4828if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004829
Tim Petersc5dc4da2003-01-02 17:55:03 +00004830If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4831add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004832local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004833
Tim Petersc5dc4da2003-01-02 17:55:03 +00004834Let
Tim Petersf3615152003-01-01 21:51:37 +00004835
Tim Peters4fede1a2003-01-04 00:26:59 +00004836 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004837
Tim Peters4fede1a2003-01-04 00:26:59 +00004838and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004839
Tim Peters8bb5ad22003-01-24 02:44:45 +00004840 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004841
Tim Peters8bb5ad22003-01-24 02:44:45 +00004842If so, we're done. If not, the tzinfo class is insane, according to the
4843assumptions we've made. This also requires a bit of proof. As before, let's
4844compute the difference between the LHS and RHS of [8] (and skipping some of
4845the justifications for the kinds of substitutions we've done several times
4846already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004847
Tim Peters8bb5ad22003-01-24 02:44:45 +00004848 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4849 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4850 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4851 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4852 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004853 - z.o + z'.o = #1 twice
4854 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4855 z'.d - z.d
4856
4857So 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 +00004858we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4859return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004860
Tim Peters8bb5ad22003-01-24 02:44:45 +00004861How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4862a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4863would have to change the result dst() returns: we start in DST, and moving
4864a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004865
Tim Peters8bb5ad22003-01-24 02:44:45 +00004866There isn't a sane case where this can happen. The closest it gets is at
4867the end of DST, where there's an hour in UTC with no spelling in a hybrid
4868tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4869that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4870UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4871time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4872clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4873standard time. Since that's what the local clock *does*, we want to map both
4874UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004875in local time, but so it goes -- it's the way the local clock works.
4876
Tim Peters8bb5ad22003-01-24 02:44:45 +00004877When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4878so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4879z' = 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 +00004880(correctly) concludes that z' is not UTC-equivalent to x.
4881
4882Because we know z.d said z was in daylight time (else [5] would have held and
4883we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004884and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004885return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4886but the reasoning doesn't depend on the example -- it depends on there being
4887two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004888z' must be in standard time, and is the spelling we want in this case.
4889
4890Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4891concerned (because it takes z' as being in standard time rather than the
4892daylight time we intend here), but returning it gives the real-life "local
4893clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4894tz.
4895
4896When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4897the 1:MM standard time spelling we want.
4898
4899So how can this break? One of the assumptions must be violated. Two
4900possibilities:
4901
49021) [2] effectively says that y.s is invariant across all y belong to a given
4903 time zone. This isn't true if, for political reasons or continental drift,
4904 a region decides to change its base offset from UTC.
4905
49062) There may be versions of "double daylight" time where the tail end of
4907 the analysis gives up a step too early. I haven't thought about that
4908 enough to say.
4909
4910In any case, it's clear that the default fromutc() is strong enough to handle
4911"almost all" time zones: so long as the standard offset is invariant, it
4912doesn't matter if daylight time transition points change from year to year, or
4913if daylight time is skipped in some years; it doesn't matter how large or
4914small dst() may get within its bounds; and it doesn't even matter if some
4915perverse time zone returns a negative dst()). So a breaking case must be
4916pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004917--------------------------------------------------------------------------- */