blob: d220b563c881d3c78428c308e4bb9a344f2605c2 [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{
1134 PyObject *tzinfo = get_tzinfo_member(object);
1135 PyObject *Zreplacement = PyString_FromString("");
1136 if (Zreplacement == NULL)
1137 return NULL;
1138 if (tzinfo != Py_None && tzinfo != NULL) {
1139 PyObject *temp;
1140 assert(tzinfoarg != NULL);
1141 temp = call_tzname(tzinfo, tzinfoarg);
1142 if (temp == NULL)
1143 goto Error;
1144 if (temp != Py_None) {
1145 assert(PyUnicode_Check(temp));
1146 /* Since the tzname is getting stuffed into the
1147 * format, we have to double any % signs so that
1148 * strftime doesn't treat them as format codes.
1149 */
1150 Py_DECREF(Zreplacement);
1151 Zreplacement = PyObject_CallMethod(temp, "replace",
1152 "ss", "%", "%%");
1153 Py_DECREF(temp);
1154 if (Zreplacement == NULL)
1155 return NULL;
1156 if (PyUnicode_Check(Zreplacement)) {
1157 Zreplacement =
1158 _PyUnicode_AsDefaultEncodedString(
1159 Zreplacement, NULL);
1160 if (Zreplacement == NULL)
1161 return NULL;
Guido van Rossume9fb5152007-08-10 19:26:04 +00001162 Py_INCREF(Zreplacement);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001163 }
1164 if (!PyString_Check(Zreplacement)) {
1165 PyErr_SetString(PyExc_TypeError,
1166 "tzname.replace() did not return a string");
1167 goto Error;
1168 }
1169 }
1170 else
1171 Py_DECREF(temp);
1172 }
1173 return Zreplacement;
1174
1175 Error:
1176 Py_DECREF(Zreplacement);
1177 return NULL;
1178}
1179
Tim Peters2a799bf2002-12-16 20:18:38 +00001180/* I sure don't want to reproduce the strftime code from the time module,
1181 * so this imports the module and calls it. All the hair is due to
1182 * giving special meanings to the %z and %Z format codes via a preprocessing
1183 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001184 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1185 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001186 */
1187static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001188wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1189 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001190{
1191 PyObject *result = NULL; /* guilty until proved innocent */
1192
1193 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1194 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1195
Guido van Rossumbce56a62007-05-10 18:04:33 +00001196 const char *pin;/* pointer to next char in input format */
1197 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001198 char ch; /* next char in input format */
1199
1200 PyObject *newfmt = NULL; /* py string, the output format */
1201 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001202 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001203 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001204 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001205
Guido van Rossumbce56a62007-05-10 18:04:33 +00001206 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001207 int ntoappend; /* # of bytes to append to output buffer */
1208
Tim Peters2a799bf2002-12-16 20:18:38 +00001209 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001210 assert(PyString_Check(format) || PyUnicode_Check(format));
1211
1212 /* Convert the input format to a C string and size */
1213 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1214 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001215
Tim Petersd6844152002-12-22 20:58:42 +00001216 /* Give up if the year is before 1900.
1217 * Python strftime() plays games with the year, and different
1218 * games depending on whether envar PYTHON2K is set. This makes
1219 * years before 1900 a nightmare, even if the platform strftime
1220 * supports them (and not all do).
1221 * We could get a lot farther here by avoiding Python's strftime
1222 * wrapper and calling the C strftime() directly, but that isn't
1223 * an option in the Python implementation of this module.
1224 */
1225 {
1226 long year;
1227 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1228 if (pyyear == NULL) return NULL;
1229 assert(PyInt_Check(pyyear));
1230 year = PyInt_AsLong(pyyear);
1231 Py_DECREF(pyyear);
1232 if (year < 1900) {
1233 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1234 "1900; the datetime strftime() "
1235 "methods require year >= 1900",
1236 year);
1237 return NULL;
1238 }
1239 }
1240
Tim Peters2a799bf2002-12-16 20:18:38 +00001241 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001242 * a new format. Since computing the replacements for those codes
1243 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001244 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001245 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001246 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1247 if (newfmt == NULL) goto Done;
1248 pnew = PyString_AsString(newfmt);
1249 usednew = 0;
1250
Tim Peters2a799bf2002-12-16 20:18:38 +00001251 while ((ch = *pin++) != '\0') {
1252 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001253 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001254 ntoappend = 1;
1255 }
1256 else if ((ch = *pin++) == '\0') {
1257 /* There's a lone trailing %; doesn't make sense. */
1258 PyErr_SetString(PyExc_ValueError, "strftime format "
1259 "ends with raw %");
1260 goto Done;
1261 }
1262 /* A % has been seen and ch is the character after it. */
1263 else if (ch == 'z') {
1264 if (zreplacement == NULL) {
1265 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001266 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001267 PyObject *tzinfo = get_tzinfo_member(object);
1268 zreplacement = PyString_FromString("");
1269 if (zreplacement == NULL) goto Done;
1270 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001271 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001272 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001273 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001274 "",
1275 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001276 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001277 goto Done;
1278 Py_DECREF(zreplacement);
1279 zreplacement = PyString_FromString(buf);
1280 if (zreplacement == NULL) goto Done;
1281 }
1282 }
1283 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001284 ptoappend = PyString_AS_STRING(zreplacement);
1285 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001286 }
1287 else if (ch == 'Z') {
1288 /* format tzname */
1289 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001290 Zreplacement = make_Zreplacement(object,
1291 tzinfoarg);
1292 if (Zreplacement == NULL)
1293 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001294 }
1295 assert(Zreplacement != NULL);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001296 assert(PyString_Check(Zreplacement));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001297 ptoappend = PyString_AS_STRING(Zreplacement);
1298 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001299 }
1300 else {
Tim Peters328fff72002-12-20 01:31:27 +00001301 /* percent followed by neither z nor Z */
1302 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001303 ntoappend = 2;
1304 }
1305
1306 /* Append the ntoappend chars starting at ptoappend to
1307 * the new format.
1308 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001309 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001310 assert(ntoappend >= 0);
1311 if (ntoappend == 0)
1312 continue;
1313 while (usednew + ntoappend > totalnew) {
1314 int bigger = totalnew << 1;
1315 if ((bigger >> 1) != totalnew) { /* overflow */
1316 PyErr_NoMemory();
1317 goto Done;
1318 }
1319 if (_PyString_Resize(&newfmt, bigger) < 0)
1320 goto Done;
1321 totalnew = bigger;
1322 pnew = PyString_AsString(newfmt) + usednew;
1323 }
1324 memcpy(pnew, ptoappend, ntoappend);
1325 pnew += ntoappend;
1326 usednew += ntoappend;
1327 assert(usednew <= totalnew);
1328 } /* end while() */
1329
1330 if (_PyString_Resize(&newfmt, usednew) < 0)
1331 goto Done;
1332 {
1333 PyObject *time = PyImport_ImportModule("time");
1334 if (time == NULL)
1335 goto Done;
1336 result = PyObject_CallMethod(time, "strftime", "OO",
1337 newfmt, timetuple);
1338 Py_DECREF(time);
1339 }
1340 Done:
1341 Py_XDECREF(zreplacement);
1342 Py_XDECREF(Zreplacement);
1343 Py_XDECREF(newfmt);
1344 return result;
1345}
1346
Tim Peters2a799bf2002-12-16 20:18:38 +00001347/* ---------------------------------------------------------------------------
1348 * Wrap functions from the time module. These aren't directly available
1349 * from C. Perhaps they should be.
1350 */
1351
1352/* Call time.time() and return its result (a Python float). */
1353static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001354time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001355{
1356 PyObject *result = NULL;
1357 PyObject *time = PyImport_ImportModule("time");
1358
1359 if (time != NULL) {
1360 result = PyObject_CallMethod(time, "time", "()");
1361 Py_DECREF(time);
1362 }
1363 return result;
1364}
1365
1366/* Build a time.struct_time. The weekday and day number are automatically
1367 * computed from the y,m,d args.
1368 */
1369static PyObject *
1370build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1371{
1372 PyObject *time;
1373 PyObject *result = NULL;
1374
1375 time = PyImport_ImportModule("time");
1376 if (time != NULL) {
1377 result = PyObject_CallMethod(time, "struct_time",
1378 "((iiiiiiiii))",
1379 y, m, d,
1380 hh, mm, ss,
1381 weekday(y, m, d),
1382 days_before_month(y, m) + d,
1383 dstflag);
1384 Py_DECREF(time);
1385 }
1386 return result;
1387}
1388
1389/* ---------------------------------------------------------------------------
1390 * Miscellaneous helpers.
1391 */
1392
Guido van Rossum19960592006-08-24 17:29:38 +00001393/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001394 * The comparisons here all most naturally compute a cmp()-like result.
1395 * This little helper turns that into a bool result for rich comparisons.
1396 */
1397static PyObject *
1398diff_to_bool(int diff, int op)
1399{
1400 PyObject *result;
1401 int istrue;
1402
1403 switch (op) {
1404 case Py_EQ: istrue = diff == 0; break;
1405 case Py_NE: istrue = diff != 0; break;
1406 case Py_LE: istrue = diff <= 0; break;
1407 case Py_GE: istrue = diff >= 0; break;
1408 case Py_LT: istrue = diff < 0; break;
1409 case Py_GT: istrue = diff > 0; break;
1410 default:
1411 assert(! "op unknown");
1412 istrue = 0; /* To shut up compiler */
1413 }
1414 result = istrue ? Py_True : Py_False;
1415 Py_INCREF(result);
1416 return result;
1417}
1418
Tim Peters07534a62003-02-07 22:50:28 +00001419/* Raises a "can't compare" TypeError and returns NULL. */
1420static PyObject *
1421cmperror(PyObject *a, PyObject *b)
1422{
1423 PyErr_Format(PyExc_TypeError,
1424 "can't compare %s to %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001425 Py_Type(a)->tp_name, Py_Type(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001426 return NULL;
1427}
1428
Tim Peters2a799bf2002-12-16 20:18:38 +00001429/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001430 * Cached Python objects; these are set by the module init function.
1431 */
1432
1433/* Conversion factors. */
1434static PyObject *us_per_us = NULL; /* 1 */
1435static PyObject *us_per_ms = NULL; /* 1000 */
1436static PyObject *us_per_second = NULL; /* 1000000 */
1437static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1438static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1439static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1440static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1441static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1442
Tim Peters2a799bf2002-12-16 20:18:38 +00001443/* ---------------------------------------------------------------------------
1444 * Class implementations.
1445 */
1446
1447/*
1448 * PyDateTime_Delta implementation.
1449 */
1450
1451/* Convert a timedelta to a number of us,
1452 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1453 * as a Python int or long.
1454 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1455 * due to ubiquitous overflow possibilities.
1456 */
1457static PyObject *
1458delta_to_microseconds(PyDateTime_Delta *self)
1459{
1460 PyObject *x1 = NULL;
1461 PyObject *x2 = NULL;
1462 PyObject *x3 = NULL;
1463 PyObject *result = NULL;
1464
1465 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1466 if (x1 == NULL)
1467 goto Done;
1468 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1469 if (x2 == NULL)
1470 goto Done;
1471 Py_DECREF(x1);
1472 x1 = NULL;
1473
1474 /* x2 has days in seconds */
1475 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1476 if (x1 == NULL)
1477 goto Done;
1478 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1479 if (x3 == NULL)
1480 goto Done;
1481 Py_DECREF(x1);
1482 Py_DECREF(x2);
1483 x1 = x2 = NULL;
1484
1485 /* x3 has days+seconds in seconds */
1486 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1487 if (x1 == NULL)
1488 goto Done;
1489 Py_DECREF(x3);
1490 x3 = NULL;
1491
1492 /* x1 has days+seconds in us */
1493 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1494 if (x2 == NULL)
1495 goto Done;
1496 result = PyNumber_Add(x1, x2);
1497
1498Done:
1499 Py_XDECREF(x1);
1500 Py_XDECREF(x2);
1501 Py_XDECREF(x3);
1502 return result;
1503}
1504
1505/* Convert a number of us (as a Python int or long) to a timedelta.
1506 */
1507static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001508microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001509{
1510 int us;
1511 int s;
1512 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001513 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001514
1515 PyObject *tuple = NULL;
1516 PyObject *num = NULL;
1517 PyObject *result = NULL;
1518
1519 tuple = PyNumber_Divmod(pyus, us_per_second);
1520 if (tuple == NULL)
1521 goto Done;
1522
1523 num = PyTuple_GetItem(tuple, 1); /* us */
1524 if (num == NULL)
1525 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001526 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001527 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001528 if (temp == -1 && PyErr_Occurred())
1529 goto Done;
1530 assert(0 <= temp && temp < 1000000);
1531 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001532 if (us < 0) {
1533 /* The divisor was positive, so this must be an error. */
1534 assert(PyErr_Occurred());
1535 goto Done;
1536 }
1537
1538 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1539 if (num == NULL)
1540 goto Done;
1541 Py_INCREF(num);
1542 Py_DECREF(tuple);
1543
1544 tuple = PyNumber_Divmod(num, seconds_per_day);
1545 if (tuple == NULL)
1546 goto Done;
1547 Py_DECREF(num);
1548
1549 num = PyTuple_GetItem(tuple, 1); /* seconds */
1550 if (num == NULL)
1551 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001552 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001553 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001554 if (temp == -1 && PyErr_Occurred())
1555 goto Done;
1556 assert(0 <= temp && temp < 24*3600);
1557 s = (int)temp;
1558
Tim Peters2a799bf2002-12-16 20:18:38 +00001559 if (s < 0) {
1560 /* The divisor was positive, so this must be an error. */
1561 assert(PyErr_Occurred());
1562 goto Done;
1563 }
1564
1565 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1566 if (num == NULL)
1567 goto Done;
1568 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001569 temp = PyLong_AsLong(num);
1570 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001571 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001572 d = (int)temp;
1573 if ((long)d != temp) {
1574 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1575 "large to fit in a C int");
1576 goto Done;
1577 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001578 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001579
1580Done:
1581 Py_XDECREF(tuple);
1582 Py_XDECREF(num);
1583 return result;
1584}
1585
Tim Petersb0c854d2003-05-17 15:57:00 +00001586#define microseconds_to_delta(pymicros) \
1587 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1588
Tim Peters2a799bf2002-12-16 20:18:38 +00001589static PyObject *
1590multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1591{
1592 PyObject *pyus_in;
1593 PyObject *pyus_out;
1594 PyObject *result;
1595
1596 pyus_in = delta_to_microseconds(delta);
1597 if (pyus_in == NULL)
1598 return NULL;
1599
1600 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1601 Py_DECREF(pyus_in);
1602 if (pyus_out == NULL)
1603 return NULL;
1604
1605 result = microseconds_to_delta(pyus_out);
1606 Py_DECREF(pyus_out);
1607 return result;
1608}
1609
1610static PyObject *
1611divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1612{
1613 PyObject *pyus_in;
1614 PyObject *pyus_out;
1615 PyObject *result;
1616
1617 pyus_in = delta_to_microseconds(delta);
1618 if (pyus_in == NULL)
1619 return NULL;
1620
1621 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1622 Py_DECREF(pyus_in);
1623 if (pyus_out == NULL)
1624 return NULL;
1625
1626 result = microseconds_to_delta(pyus_out);
1627 Py_DECREF(pyus_out);
1628 return result;
1629}
1630
1631static PyObject *
1632delta_add(PyObject *left, PyObject *right)
1633{
1634 PyObject *result = Py_NotImplemented;
1635
1636 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1637 /* delta + delta */
1638 /* The C-level additions can't overflow because of the
1639 * invariant bounds.
1640 */
1641 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1642 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1643 int microseconds = GET_TD_MICROSECONDS(left) +
1644 GET_TD_MICROSECONDS(right);
1645 result = new_delta(days, seconds, microseconds, 1);
1646 }
1647
1648 if (result == Py_NotImplemented)
1649 Py_INCREF(result);
1650 return result;
1651}
1652
1653static PyObject *
1654delta_negative(PyDateTime_Delta *self)
1655{
1656 return new_delta(-GET_TD_DAYS(self),
1657 -GET_TD_SECONDS(self),
1658 -GET_TD_MICROSECONDS(self),
1659 1);
1660}
1661
1662static PyObject *
1663delta_positive(PyDateTime_Delta *self)
1664{
1665 /* Could optimize this (by returning self) if this isn't a
1666 * subclass -- but who uses unary + ? Approximately nobody.
1667 */
1668 return new_delta(GET_TD_DAYS(self),
1669 GET_TD_SECONDS(self),
1670 GET_TD_MICROSECONDS(self),
1671 0);
1672}
1673
1674static PyObject *
1675delta_abs(PyDateTime_Delta *self)
1676{
1677 PyObject *result;
1678
1679 assert(GET_TD_MICROSECONDS(self) >= 0);
1680 assert(GET_TD_SECONDS(self) >= 0);
1681
1682 if (GET_TD_DAYS(self) < 0)
1683 result = delta_negative(self);
1684 else
1685 result = delta_positive(self);
1686
1687 return result;
1688}
1689
1690static PyObject *
1691delta_subtract(PyObject *left, PyObject *right)
1692{
1693 PyObject *result = Py_NotImplemented;
1694
1695 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1696 /* delta - delta */
1697 PyObject *minus_right = PyNumber_Negative(right);
1698 if (minus_right) {
1699 result = delta_add(left, minus_right);
1700 Py_DECREF(minus_right);
1701 }
1702 else
1703 result = NULL;
1704 }
1705
1706 if (result == Py_NotImplemented)
1707 Py_INCREF(result);
1708 return result;
1709}
1710
Tim Peters2a799bf2002-12-16 20:18:38 +00001711static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001712delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001713{
Tim Petersaa7d8492003-02-08 03:28:59 +00001714 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001715 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001716 if (diff == 0) {
1717 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1718 if (diff == 0)
1719 diff = GET_TD_MICROSECONDS(self) -
1720 GET_TD_MICROSECONDS(other);
1721 }
Guido van Rossum19960592006-08-24 17:29:38 +00001722 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001723 }
Guido van Rossum19960592006-08-24 17:29:38 +00001724 else {
1725 Py_INCREF(Py_NotImplemented);
1726 return Py_NotImplemented;
1727 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001728}
1729
1730static PyObject *delta_getstate(PyDateTime_Delta *self);
1731
1732static long
1733delta_hash(PyDateTime_Delta *self)
1734{
1735 if (self->hashcode == -1) {
1736 PyObject *temp = delta_getstate(self);
1737 if (temp != NULL) {
1738 self->hashcode = PyObject_Hash(temp);
1739 Py_DECREF(temp);
1740 }
1741 }
1742 return self->hashcode;
1743}
1744
1745static PyObject *
1746delta_multiply(PyObject *left, PyObject *right)
1747{
1748 PyObject *result = Py_NotImplemented;
1749
1750 if (PyDelta_Check(left)) {
1751 /* delta * ??? */
1752 if (PyInt_Check(right) || PyLong_Check(right))
1753 result = multiply_int_timedelta(right,
1754 (PyDateTime_Delta *) left);
1755 }
1756 else if (PyInt_Check(left) || PyLong_Check(left))
1757 result = multiply_int_timedelta(left,
1758 (PyDateTime_Delta *) right);
1759
1760 if (result == Py_NotImplemented)
1761 Py_INCREF(result);
1762 return result;
1763}
1764
1765static PyObject *
1766delta_divide(PyObject *left, PyObject *right)
1767{
1768 PyObject *result = Py_NotImplemented;
1769
1770 if (PyDelta_Check(left)) {
1771 /* delta * ??? */
1772 if (PyInt_Check(right) || PyLong_Check(right))
1773 result = divide_timedelta_int(
1774 (PyDateTime_Delta *)left,
1775 right);
1776 }
1777
1778 if (result == Py_NotImplemented)
1779 Py_INCREF(result);
1780 return result;
1781}
1782
1783/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1784 * timedelta constructor. sofar is the # of microseconds accounted for
1785 * so far, and there are factor microseconds per current unit, the number
1786 * of which is given by num. num * factor is added to sofar in a
1787 * numerically careful way, and that's the result. Any fractional
1788 * microseconds left over (this can happen if num is a float type) are
1789 * added into *leftover.
1790 * Note that there are many ways this can give an error (NULL) return.
1791 */
1792static PyObject *
1793accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1794 double *leftover)
1795{
1796 PyObject *prod;
1797 PyObject *sum;
1798
1799 assert(num != NULL);
1800
1801 if (PyInt_Check(num) || PyLong_Check(num)) {
1802 prod = PyNumber_Multiply(num, factor);
1803 if (prod == NULL)
1804 return NULL;
1805 sum = PyNumber_Add(sofar, prod);
1806 Py_DECREF(prod);
1807 return sum;
1808 }
1809
1810 if (PyFloat_Check(num)) {
1811 double dnum;
1812 double fracpart;
1813 double intpart;
1814 PyObject *x;
1815 PyObject *y;
1816
1817 /* The Plan: decompose num into an integer part and a
1818 * fractional part, num = intpart + fracpart.
1819 * Then num * factor ==
1820 * intpart * factor + fracpart * factor
1821 * and the LHS can be computed exactly in long arithmetic.
1822 * The RHS is again broken into an int part and frac part.
1823 * and the frac part is added into *leftover.
1824 */
1825 dnum = PyFloat_AsDouble(num);
1826 if (dnum == -1.0 && PyErr_Occurred())
1827 return NULL;
1828 fracpart = modf(dnum, &intpart);
1829 x = PyLong_FromDouble(intpart);
1830 if (x == NULL)
1831 return NULL;
1832
1833 prod = PyNumber_Multiply(x, factor);
1834 Py_DECREF(x);
1835 if (prod == NULL)
1836 return NULL;
1837
1838 sum = PyNumber_Add(sofar, prod);
1839 Py_DECREF(prod);
1840 if (sum == NULL)
1841 return NULL;
1842
1843 if (fracpart == 0.0)
1844 return sum;
1845 /* So far we've lost no information. Dealing with the
1846 * fractional part requires float arithmetic, and may
1847 * lose a little info.
1848 */
1849 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001850 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001851
1852 dnum *= fracpart;
1853 fracpart = modf(dnum, &intpart);
1854 x = PyLong_FromDouble(intpart);
1855 if (x == NULL) {
1856 Py_DECREF(sum);
1857 return NULL;
1858 }
1859
1860 y = PyNumber_Add(sum, x);
1861 Py_DECREF(sum);
1862 Py_DECREF(x);
1863 *leftover += fracpart;
1864 return y;
1865 }
1866
1867 PyErr_Format(PyExc_TypeError,
1868 "unsupported type for timedelta %s component: %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001869 tag, Py_Type(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001870 return NULL;
1871}
1872
1873static PyObject *
1874delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1875{
1876 PyObject *self = NULL;
1877
1878 /* Argument objects. */
1879 PyObject *day = NULL;
1880 PyObject *second = NULL;
1881 PyObject *us = NULL;
1882 PyObject *ms = NULL;
1883 PyObject *minute = NULL;
1884 PyObject *hour = NULL;
1885 PyObject *week = NULL;
1886
1887 PyObject *x = NULL; /* running sum of microseconds */
1888 PyObject *y = NULL; /* temp sum of microseconds */
1889 double leftover_us = 0.0;
1890
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001891 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001892 "days", "seconds", "microseconds", "milliseconds",
1893 "minutes", "hours", "weeks", NULL
1894 };
1895
1896 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1897 keywords,
1898 &day, &second, &us,
1899 &ms, &minute, &hour, &week) == 0)
1900 goto Done;
1901
1902 x = PyInt_FromLong(0);
1903 if (x == NULL)
1904 goto Done;
1905
1906#define CLEANUP \
1907 Py_DECREF(x); \
1908 x = y; \
1909 if (x == NULL) \
1910 goto Done
1911
1912 if (us) {
1913 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1914 CLEANUP;
1915 }
1916 if (ms) {
1917 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1918 CLEANUP;
1919 }
1920 if (second) {
1921 y = accum("seconds", x, second, us_per_second, &leftover_us);
1922 CLEANUP;
1923 }
1924 if (minute) {
1925 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1926 CLEANUP;
1927 }
1928 if (hour) {
1929 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1930 CLEANUP;
1931 }
1932 if (day) {
1933 y = accum("days", x, day, us_per_day, &leftover_us);
1934 CLEANUP;
1935 }
1936 if (week) {
1937 y = accum("weeks", x, week, us_per_week, &leftover_us);
1938 CLEANUP;
1939 }
1940 if (leftover_us) {
1941 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001942 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001943 if (temp == NULL) {
1944 Py_DECREF(x);
1945 goto Done;
1946 }
1947 y = PyNumber_Add(x, temp);
1948 Py_DECREF(temp);
1949 CLEANUP;
1950 }
1951
Tim Petersb0c854d2003-05-17 15:57:00 +00001952 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001953 Py_DECREF(x);
1954Done:
1955 return self;
1956
1957#undef CLEANUP
1958}
1959
1960static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001961delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001962{
1963 return (GET_TD_DAYS(self) != 0
1964 || GET_TD_SECONDS(self) != 0
1965 || GET_TD_MICROSECONDS(self) != 0);
1966}
1967
1968static PyObject *
1969delta_repr(PyDateTime_Delta *self)
1970{
1971 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001972 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001973 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001974 GET_TD_DAYS(self),
1975 GET_TD_SECONDS(self),
1976 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001977 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001978 return PyUnicode_FromFormat("%s(%d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001979 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001980 GET_TD_DAYS(self),
1981 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001982
Walter Dörwald1ab83302007-05-18 17:15:44 +00001983 return PyUnicode_FromFormat("%s(%d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001984 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001985 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001986}
1987
1988static PyObject *
1989delta_str(PyDateTime_Delta *self)
1990{
Tim Peters2a799bf2002-12-16 20:18:38 +00001991 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00001992 int seconds = GET_TD_SECONDS(self);
1993 int minutes = divmod(seconds, 60, &seconds);
1994 int hours = divmod(minutes, 60, &minutes);
1995 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00001996
1997 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00001998 if (us)
1999 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2000 days, (days == 1 || days == -1) ? "" : "s",
2001 hours, minutes, seconds, us);
2002 else
2003 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2004 days, (days == 1 || days == -1) ? "" : "s",
2005 hours, minutes, seconds);
2006 } else {
2007 if (us)
2008 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2009 hours, minutes, seconds, us);
2010 else
2011 return PyUnicode_FromFormat("%d:%02d:%02d",
2012 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002013 }
2014
Tim Peters2a799bf2002-12-16 20:18:38 +00002015}
2016
Tim Peters371935f2003-02-01 01:52:50 +00002017/* Pickle support, a simple use of __reduce__. */
2018
Tim Petersb57f8f02003-02-01 02:54:15 +00002019/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002020static PyObject *
2021delta_getstate(PyDateTime_Delta *self)
2022{
2023 return Py_BuildValue("iii", GET_TD_DAYS(self),
2024 GET_TD_SECONDS(self),
2025 GET_TD_MICROSECONDS(self));
2026}
2027
Tim Peters2a799bf2002-12-16 20:18:38 +00002028static PyObject *
2029delta_reduce(PyDateTime_Delta* self)
2030{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002031 return Py_BuildValue("ON", Py_Type(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002032}
2033
2034#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2035
2036static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002037
Neal Norwitzdfb80862002-12-19 02:30:56 +00002038 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002039 PyDoc_STR("Number of days.")},
2040
Neal Norwitzdfb80862002-12-19 02:30:56 +00002041 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002042 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2043
Neal Norwitzdfb80862002-12-19 02:30:56 +00002044 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002045 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2046 {NULL}
2047};
2048
2049static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002050 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2051 PyDoc_STR("__reduce__() -> (cls, state)")},
2052
Tim Peters2a799bf2002-12-16 20:18:38 +00002053 {NULL, NULL},
2054};
2055
2056static char delta_doc[] =
2057PyDoc_STR("Difference between two datetime values.");
2058
2059static PyNumberMethods delta_as_number = {
2060 delta_add, /* nb_add */
2061 delta_subtract, /* nb_subtract */
2062 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002063 0, /* nb_remainder */
2064 0, /* nb_divmod */
2065 0, /* nb_power */
2066 (unaryfunc)delta_negative, /* nb_negative */
2067 (unaryfunc)delta_positive, /* nb_positive */
2068 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002069 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002070 0, /*nb_invert*/
2071 0, /*nb_lshift*/
2072 0, /*nb_rshift*/
2073 0, /*nb_and*/
2074 0, /*nb_xor*/
2075 0, /*nb_or*/
2076 0, /*nb_coerce*/
2077 0, /*nb_int*/
2078 0, /*nb_long*/
2079 0, /*nb_float*/
2080 0, /*nb_oct*/
2081 0, /*nb_hex*/
2082 0, /*nb_inplace_add*/
2083 0, /*nb_inplace_subtract*/
2084 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002085 0, /*nb_inplace_remainder*/
2086 0, /*nb_inplace_power*/
2087 0, /*nb_inplace_lshift*/
2088 0, /*nb_inplace_rshift*/
2089 0, /*nb_inplace_and*/
2090 0, /*nb_inplace_xor*/
2091 0, /*nb_inplace_or*/
2092 delta_divide, /* nb_floor_divide */
2093 0, /* nb_true_divide */
2094 0, /* nb_inplace_floor_divide */
2095 0, /* nb_inplace_true_divide */
2096};
2097
2098static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002099 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002100 "datetime.timedelta", /* tp_name */
2101 sizeof(PyDateTime_Delta), /* tp_basicsize */
2102 0, /* tp_itemsize */
2103 0, /* tp_dealloc */
2104 0, /* tp_print */
2105 0, /* tp_getattr */
2106 0, /* tp_setattr */
2107 0, /* tp_compare */
2108 (reprfunc)delta_repr, /* tp_repr */
2109 &delta_as_number, /* tp_as_number */
2110 0, /* tp_as_sequence */
2111 0, /* tp_as_mapping */
2112 (hashfunc)delta_hash, /* tp_hash */
2113 0, /* tp_call */
2114 (reprfunc)delta_str, /* tp_str */
2115 PyObject_GenericGetAttr, /* tp_getattro */
2116 0, /* tp_setattro */
2117 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002118 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002119 delta_doc, /* tp_doc */
2120 0, /* tp_traverse */
2121 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002122 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002123 0, /* tp_weaklistoffset */
2124 0, /* tp_iter */
2125 0, /* tp_iternext */
2126 delta_methods, /* tp_methods */
2127 delta_members, /* tp_members */
2128 0, /* tp_getset */
2129 0, /* tp_base */
2130 0, /* tp_dict */
2131 0, /* tp_descr_get */
2132 0, /* tp_descr_set */
2133 0, /* tp_dictoffset */
2134 0, /* tp_init */
2135 0, /* tp_alloc */
2136 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002137 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002138};
2139
2140/*
2141 * PyDateTime_Date implementation.
2142 */
2143
2144/* Accessor properties. */
2145
2146static PyObject *
2147date_year(PyDateTime_Date *self, void *unused)
2148{
2149 return PyInt_FromLong(GET_YEAR(self));
2150}
2151
2152static PyObject *
2153date_month(PyDateTime_Date *self, void *unused)
2154{
2155 return PyInt_FromLong(GET_MONTH(self));
2156}
2157
2158static PyObject *
2159date_day(PyDateTime_Date *self, void *unused)
2160{
2161 return PyInt_FromLong(GET_DAY(self));
2162}
2163
2164static PyGetSetDef date_getset[] = {
2165 {"year", (getter)date_year},
2166 {"month", (getter)date_month},
2167 {"day", (getter)date_day},
2168 {NULL}
2169};
2170
2171/* Constructors. */
2172
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002173static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002174
Tim Peters2a799bf2002-12-16 20:18:38 +00002175static PyObject *
2176date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2177{
2178 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002179 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002180 int year;
2181 int month;
2182 int day;
2183
Guido van Rossum177e41a2003-01-30 22:06:23 +00002184 /* Check for invocation from pickle with __getstate__ state */
2185 if (PyTuple_GET_SIZE(args) == 1 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002186 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2187 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2188 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002189 {
Tim Peters70533e22003-02-01 04:40:04 +00002190 PyDateTime_Date *me;
2191
Tim Peters604c0132004-06-07 23:04:33 +00002192 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002193 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002194 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002195 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2196 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002197 }
Tim Peters70533e22003-02-01 04:40:04 +00002198 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002199 }
2200
Tim Peters12bf3392002-12-24 05:41:27 +00002201 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002202 &year, &month, &day)) {
2203 if (check_date_args(year, month, day) < 0)
2204 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002205 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002206 }
2207 return self;
2208}
2209
2210/* Return new date from localtime(t). */
2211static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002212date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002213{
2214 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002215 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002216 PyObject *result = NULL;
2217
Tim Peters1b6f7a92004-06-20 02:50:16 +00002218 t = _PyTime_DoubleToTimet(ts);
2219 if (t == (time_t)-1 && PyErr_Occurred())
2220 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002221 tm = localtime(&t);
2222 if (tm)
2223 result = PyObject_CallFunction(cls, "iii",
2224 tm->tm_year + 1900,
2225 tm->tm_mon + 1,
2226 tm->tm_mday);
2227 else
2228 PyErr_SetString(PyExc_ValueError,
2229 "timestamp out of range for "
2230 "platform localtime() function");
2231 return result;
2232}
2233
2234/* Return new date from current time.
2235 * We say this is equivalent to fromtimestamp(time.time()), and the
2236 * only way to be sure of that is to *call* time.time(). That's not
2237 * generally the same as calling C's time.
2238 */
2239static PyObject *
2240date_today(PyObject *cls, PyObject *dummy)
2241{
2242 PyObject *time;
2243 PyObject *result;
2244
2245 time = time_time();
2246 if (time == NULL)
2247 return NULL;
2248
2249 /* Note well: today() is a class method, so this may not call
2250 * date.fromtimestamp. For example, it may call
2251 * datetime.fromtimestamp. That's why we need all the accuracy
2252 * time.time() delivers; if someone were gonzo about optimization,
2253 * date.today() could get away with plain C time().
2254 */
2255 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2256 Py_DECREF(time);
2257 return result;
2258}
2259
2260/* Return new date from given timestamp (Python timestamp -- a double). */
2261static PyObject *
2262date_fromtimestamp(PyObject *cls, PyObject *args)
2263{
2264 double timestamp;
2265 PyObject *result = NULL;
2266
2267 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002268 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002269 return result;
2270}
2271
2272/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2273 * the ordinal is out of range.
2274 */
2275static PyObject *
2276date_fromordinal(PyObject *cls, PyObject *args)
2277{
2278 PyObject *result = NULL;
2279 int ordinal;
2280
2281 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2282 int year;
2283 int month;
2284 int day;
2285
2286 if (ordinal < 1)
2287 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2288 ">= 1");
2289 else {
2290 ord_to_ymd(ordinal, &year, &month, &day);
2291 result = PyObject_CallFunction(cls, "iii",
2292 year, month, day);
2293 }
2294 }
2295 return result;
2296}
2297
2298/*
2299 * Date arithmetic.
2300 */
2301
2302/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2303 * instead.
2304 */
2305static PyObject *
2306add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2307{
2308 PyObject *result = NULL;
2309 int year = GET_YEAR(date);
2310 int month = GET_MONTH(date);
2311 int deltadays = GET_TD_DAYS(delta);
2312 /* C-level overflow is impossible because |deltadays| < 1e9. */
2313 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2314
2315 if (normalize_date(&year, &month, &day) >= 0)
2316 result = new_date(year, month, day);
2317 return result;
2318}
2319
2320static PyObject *
2321date_add(PyObject *left, PyObject *right)
2322{
2323 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2324 Py_INCREF(Py_NotImplemented);
2325 return Py_NotImplemented;
2326 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002327 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002328 /* date + ??? */
2329 if (PyDelta_Check(right))
2330 /* date + delta */
2331 return add_date_timedelta((PyDateTime_Date *) left,
2332 (PyDateTime_Delta *) right,
2333 0);
2334 }
2335 else {
2336 /* ??? + date
2337 * 'right' must be one of us, or we wouldn't have been called
2338 */
2339 if (PyDelta_Check(left))
2340 /* delta + date */
2341 return add_date_timedelta((PyDateTime_Date *) right,
2342 (PyDateTime_Delta *) left,
2343 0);
2344 }
2345 Py_INCREF(Py_NotImplemented);
2346 return Py_NotImplemented;
2347}
2348
2349static PyObject *
2350date_subtract(PyObject *left, PyObject *right)
2351{
2352 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2353 Py_INCREF(Py_NotImplemented);
2354 return Py_NotImplemented;
2355 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002356 if (PyDate_Check(left)) {
2357 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002358 /* date - date */
2359 int left_ord = ymd_to_ord(GET_YEAR(left),
2360 GET_MONTH(left),
2361 GET_DAY(left));
2362 int right_ord = ymd_to_ord(GET_YEAR(right),
2363 GET_MONTH(right),
2364 GET_DAY(right));
2365 return new_delta(left_ord - right_ord, 0, 0, 0);
2366 }
2367 if (PyDelta_Check(right)) {
2368 /* date - delta */
2369 return add_date_timedelta((PyDateTime_Date *) left,
2370 (PyDateTime_Delta *) right,
2371 1);
2372 }
2373 }
2374 Py_INCREF(Py_NotImplemented);
2375 return Py_NotImplemented;
2376}
2377
2378
2379/* Various ways to turn a date into a string. */
2380
2381static PyObject *
2382date_repr(PyDateTime_Date *self)
2383{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002384 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00002385 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002386 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002387}
2388
2389static PyObject *
2390date_isoformat(PyDateTime_Date *self)
2391{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002392 return PyUnicode_FromFormat("%04d-%02d-%02d",
2393 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002394}
2395
Tim Peterse2df5ff2003-05-02 18:39:55 +00002396/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002397static PyObject *
2398date_str(PyDateTime_Date *self)
2399{
2400 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2401}
2402
2403
2404static PyObject *
2405date_ctime(PyDateTime_Date *self)
2406{
2407 return format_ctime(self, 0, 0, 0);
2408}
2409
2410static PyObject *
2411date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2412{
2413 /* This method can be inherited, and needs to call the
2414 * timetuple() method appropriate to self's class.
2415 */
2416 PyObject *result;
2417 PyObject *format;
2418 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002419 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002420
Guido van Rossumbce56a62007-05-10 18:04:33 +00002421 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2422 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002423 return NULL;
2424
2425 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2426 if (tuple == NULL)
2427 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002428 result = wrap_strftime((PyObject *)self, format, tuple,
2429 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002430 Py_DECREF(tuple);
2431 return result;
2432}
2433
2434/* ISO methods. */
2435
2436static PyObject *
2437date_isoweekday(PyDateTime_Date *self)
2438{
2439 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2440
2441 return PyInt_FromLong(dow + 1);
2442}
2443
2444static PyObject *
2445date_isocalendar(PyDateTime_Date *self)
2446{
2447 int year = GET_YEAR(self);
2448 int week1_monday = iso_week1_monday(year);
2449 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2450 int week;
2451 int day;
2452
2453 week = divmod(today - week1_monday, 7, &day);
2454 if (week < 0) {
2455 --year;
2456 week1_monday = iso_week1_monday(year);
2457 week = divmod(today - week1_monday, 7, &day);
2458 }
2459 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2460 ++year;
2461 week = 0;
2462 }
2463 return Py_BuildValue("iii", year, week + 1, day + 1);
2464}
2465
2466/* Miscellaneous methods. */
2467
Tim Peters2a799bf2002-12-16 20:18:38 +00002468static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002469date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002470{
Guido van Rossum19960592006-08-24 17:29:38 +00002471 if (PyDate_Check(other)) {
2472 int diff = memcmp(((PyDateTime_Date *)self)->data,
2473 ((PyDateTime_Date *)other)->data,
2474 _PyDateTime_DATE_DATASIZE);
2475 return diff_to_bool(diff, op);
2476 }
2477 else {
Tim Peters07534a62003-02-07 22:50:28 +00002478 Py_INCREF(Py_NotImplemented);
2479 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002480 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002481}
2482
2483static PyObject *
2484date_timetuple(PyDateTime_Date *self)
2485{
2486 return build_struct_time(GET_YEAR(self),
2487 GET_MONTH(self),
2488 GET_DAY(self),
2489 0, 0, 0, -1);
2490}
2491
Tim Peters12bf3392002-12-24 05:41:27 +00002492static PyObject *
2493date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2494{
2495 PyObject *clone;
2496 PyObject *tuple;
2497 int year = GET_YEAR(self);
2498 int month = GET_MONTH(self);
2499 int day = GET_DAY(self);
2500
2501 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2502 &year, &month, &day))
2503 return NULL;
2504 tuple = Py_BuildValue("iii", year, month, day);
2505 if (tuple == NULL)
2506 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002507 clone = date_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002508 Py_DECREF(tuple);
2509 return clone;
2510}
2511
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002512static PyObject *date_getstate(PyDateTime_Date *self, int hashable);
Tim Peters2a799bf2002-12-16 20:18:38 +00002513
2514static long
2515date_hash(PyDateTime_Date *self)
2516{
2517 if (self->hashcode == -1) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002518 PyObject *temp = date_getstate(self, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002519 if (temp != NULL) {
2520 self->hashcode = PyObject_Hash(temp);
2521 Py_DECREF(temp);
2522 }
2523 }
2524 return self->hashcode;
2525}
2526
2527static PyObject *
2528date_toordinal(PyDateTime_Date *self)
2529{
2530 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2531 GET_DAY(self)));
2532}
2533
2534static PyObject *
2535date_weekday(PyDateTime_Date *self)
2536{
2537 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2538
2539 return PyInt_FromLong(dow);
2540}
2541
Tim Peters371935f2003-02-01 01:52:50 +00002542/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002543
Tim Petersb57f8f02003-02-01 02:54:15 +00002544/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002545static PyObject *
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002546date_getstate(PyDateTime_Date *self, int hashable)
Tim Peters2a799bf2002-12-16 20:18:38 +00002547{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002548 PyObject* field;
2549 if (hashable)
2550 field = PyString_FromStringAndSize(
2551 (char*)self->data, _PyDateTime_DATE_DATASIZE);
2552 else
2553 field = PyBytes_FromStringAndSize(
2554 (char*)self->data, _PyDateTime_DATE_DATASIZE);
2555 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002556}
2557
2558static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002559date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002560{
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00002561 return Py_BuildValue("(ON)", Py_Type(self), date_getstate(self, 0));
Tim Peters2a799bf2002-12-16 20:18:38 +00002562}
2563
2564static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002565
Tim Peters2a799bf2002-12-16 20:18:38 +00002566 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002567
Tim Peters2a799bf2002-12-16 20:18:38 +00002568 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2569 METH_CLASS,
2570 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2571 "time.time()).")},
2572
2573 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2574 METH_CLASS,
2575 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2576 "ordinal.")},
2577
2578 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2579 PyDoc_STR("Current date or datetime: same as "
2580 "self.__class__.fromtimestamp(time.time()).")},
2581
2582 /* Instance methods: */
2583
2584 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2585 PyDoc_STR("Return ctime() style string.")},
2586
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002587 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002588 PyDoc_STR("format -> strftime() style string.")},
2589
2590 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2591 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2592
2593 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2594 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2595 "weekday.")},
2596
2597 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2598 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2599
2600 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2601 PyDoc_STR("Return the day of the week represented by the date.\n"
2602 "Monday == 1 ... Sunday == 7")},
2603
2604 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2605 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2606 "1 is day 1.")},
2607
2608 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2609 PyDoc_STR("Return the day of the week represented by the date.\n"
2610 "Monday == 0 ... Sunday == 6")},
2611
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002612 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002613 PyDoc_STR("Return date with new specified fields.")},
2614
Guido van Rossum177e41a2003-01-30 22:06:23 +00002615 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2616 PyDoc_STR("__reduce__() -> (cls, state)")},
2617
Tim Peters2a799bf2002-12-16 20:18:38 +00002618 {NULL, NULL}
2619};
2620
2621static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002622PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002623
2624static PyNumberMethods date_as_number = {
2625 date_add, /* nb_add */
2626 date_subtract, /* nb_subtract */
2627 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002628 0, /* nb_remainder */
2629 0, /* nb_divmod */
2630 0, /* nb_power */
2631 0, /* nb_negative */
2632 0, /* nb_positive */
2633 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002634 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002635};
2636
2637static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002638 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002639 "datetime.date", /* tp_name */
2640 sizeof(PyDateTime_Date), /* tp_basicsize */
2641 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002642 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002643 0, /* tp_print */
2644 0, /* tp_getattr */
2645 0, /* tp_setattr */
2646 0, /* tp_compare */
2647 (reprfunc)date_repr, /* tp_repr */
2648 &date_as_number, /* tp_as_number */
2649 0, /* tp_as_sequence */
2650 0, /* tp_as_mapping */
2651 (hashfunc)date_hash, /* tp_hash */
2652 0, /* tp_call */
2653 (reprfunc)date_str, /* tp_str */
2654 PyObject_GenericGetAttr, /* tp_getattro */
2655 0, /* tp_setattro */
2656 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002657 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002658 date_doc, /* tp_doc */
2659 0, /* tp_traverse */
2660 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002661 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002662 0, /* tp_weaklistoffset */
2663 0, /* tp_iter */
2664 0, /* tp_iternext */
2665 date_methods, /* tp_methods */
2666 0, /* tp_members */
2667 date_getset, /* tp_getset */
2668 0, /* tp_base */
2669 0, /* tp_dict */
2670 0, /* tp_descr_get */
2671 0, /* tp_descr_set */
2672 0, /* tp_dictoffset */
2673 0, /* tp_init */
2674 0, /* tp_alloc */
2675 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002676 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002677};
2678
2679/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002680 * PyDateTime_TZInfo implementation.
2681 */
2682
2683/* This is a pure abstract base class, so doesn't do anything beyond
2684 * raising NotImplemented exceptions. Real tzinfo classes need
2685 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002686 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002687 * be subclasses of this tzinfo class, which is easy and quick to check).
2688 *
2689 * Note: For reasons having to do with pickling of subclasses, we have
2690 * to allow tzinfo objects to be instantiated. This wasn't an issue
2691 * in the Python implementation (__init__() could raise NotImplementedError
2692 * there without ill effect), but doing so in the C implementation hit a
2693 * brick wall.
2694 */
2695
2696static PyObject *
2697tzinfo_nogo(const char* methodname)
2698{
2699 PyErr_Format(PyExc_NotImplementedError,
2700 "a tzinfo subclass must implement %s()",
2701 methodname);
2702 return NULL;
2703}
2704
2705/* Methods. A subclass must implement these. */
2706
Tim Peters52dcce22003-01-23 16:36:11 +00002707static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002708tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2709{
2710 return tzinfo_nogo("tzname");
2711}
2712
Tim Peters52dcce22003-01-23 16:36:11 +00002713static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002714tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2715{
2716 return tzinfo_nogo("utcoffset");
2717}
2718
Tim Peters52dcce22003-01-23 16:36:11 +00002719static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002720tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2721{
2722 return tzinfo_nogo("dst");
2723}
2724
Tim Peters52dcce22003-01-23 16:36:11 +00002725static PyObject *
2726tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2727{
2728 int y, m, d, hh, mm, ss, us;
2729
2730 PyObject *result;
2731 int off, dst;
2732 int none;
2733 int delta;
2734
2735 if (! PyDateTime_Check(dt)) {
2736 PyErr_SetString(PyExc_TypeError,
2737 "fromutc: argument must be a datetime");
2738 return NULL;
2739 }
2740 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2741 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2742 "is not self");
2743 return NULL;
2744 }
2745
2746 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2747 if (off == -1 && PyErr_Occurred())
2748 return NULL;
2749 if (none) {
2750 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2751 "utcoffset() result required");
2752 return NULL;
2753 }
2754
2755 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2756 if (dst == -1 && PyErr_Occurred())
2757 return NULL;
2758 if (none) {
2759 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2760 "dst() result required");
2761 return NULL;
2762 }
2763
2764 y = GET_YEAR(dt);
2765 m = GET_MONTH(dt);
2766 d = GET_DAY(dt);
2767 hh = DATE_GET_HOUR(dt);
2768 mm = DATE_GET_MINUTE(dt);
2769 ss = DATE_GET_SECOND(dt);
2770 us = DATE_GET_MICROSECOND(dt);
2771
2772 delta = off - dst;
2773 mm += delta;
2774 if ((mm < 0 || mm >= 60) &&
2775 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002776 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002777 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2778 if (result == NULL)
2779 return result;
2780
2781 dst = call_dst(dt->tzinfo, result, &none);
2782 if (dst == -1 && PyErr_Occurred())
2783 goto Fail;
2784 if (none)
2785 goto Inconsistent;
2786 if (dst == 0)
2787 return result;
2788
2789 mm += dst;
2790 if ((mm < 0 || mm >= 60) &&
2791 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2792 goto Fail;
2793 Py_DECREF(result);
2794 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2795 return result;
2796
2797Inconsistent:
2798 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2799 "inconsistent results; cannot convert");
2800
2801 /* fall thru to failure */
2802Fail:
2803 Py_DECREF(result);
2804 return NULL;
2805}
2806
Tim Peters2a799bf2002-12-16 20:18:38 +00002807/*
2808 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002809 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002810 */
2811
Guido van Rossum177e41a2003-01-30 22:06:23 +00002812static PyObject *
2813tzinfo_reduce(PyObject *self)
2814{
2815 PyObject *args, *state, *tmp;
2816 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002817
Guido van Rossum177e41a2003-01-30 22:06:23 +00002818 tmp = PyTuple_New(0);
2819 if (tmp == NULL)
2820 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002821
Guido van Rossum177e41a2003-01-30 22:06:23 +00002822 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2823 if (getinitargs != NULL) {
2824 args = PyObject_CallObject(getinitargs, tmp);
2825 Py_DECREF(getinitargs);
2826 if (args == NULL) {
2827 Py_DECREF(tmp);
2828 return NULL;
2829 }
2830 }
2831 else {
2832 PyErr_Clear();
2833 args = tmp;
2834 Py_INCREF(args);
2835 }
2836
2837 getstate = PyObject_GetAttrString(self, "__getstate__");
2838 if (getstate != NULL) {
2839 state = PyObject_CallObject(getstate, tmp);
2840 Py_DECREF(getstate);
2841 if (state == NULL) {
2842 Py_DECREF(args);
2843 Py_DECREF(tmp);
2844 return NULL;
2845 }
2846 }
2847 else {
2848 PyObject **dictptr;
2849 PyErr_Clear();
2850 state = Py_None;
2851 dictptr = _PyObject_GetDictPtr(self);
2852 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2853 state = *dictptr;
2854 Py_INCREF(state);
2855 }
2856
2857 Py_DECREF(tmp);
2858
2859 if (state == Py_None) {
2860 Py_DECREF(state);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002861 return Py_BuildValue("(ON)", Py_Type(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002862 }
2863 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002864 return Py_BuildValue("(ONN)", Py_Type(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002865}
Tim Peters2a799bf2002-12-16 20:18:38 +00002866
2867static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002868
Tim Peters2a799bf2002-12-16 20:18:38 +00002869 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2870 PyDoc_STR("datetime -> string name of time zone.")},
2871
2872 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2873 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2874 "west of UTC).")},
2875
2876 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2877 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2878
Tim Peters52dcce22003-01-23 16:36:11 +00002879 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2880 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2881
Guido van Rossum177e41a2003-01-30 22:06:23 +00002882 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2883 PyDoc_STR("-> (cls, state)")},
2884
Tim Peters2a799bf2002-12-16 20:18:38 +00002885 {NULL, NULL}
2886};
2887
2888static char tzinfo_doc[] =
2889PyDoc_STR("Abstract base class for time zone info objects.");
2890
Neal Norwitz227b5332006-03-22 09:28:35 +00002891static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002892 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002893 "datetime.tzinfo", /* tp_name */
2894 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2895 0, /* tp_itemsize */
2896 0, /* tp_dealloc */
2897 0, /* tp_print */
2898 0, /* tp_getattr */
2899 0, /* tp_setattr */
2900 0, /* tp_compare */
2901 0, /* tp_repr */
2902 0, /* tp_as_number */
2903 0, /* tp_as_sequence */
2904 0, /* tp_as_mapping */
2905 0, /* tp_hash */
2906 0, /* tp_call */
2907 0, /* tp_str */
2908 PyObject_GenericGetAttr, /* tp_getattro */
2909 0, /* tp_setattro */
2910 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002911 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002912 tzinfo_doc, /* tp_doc */
2913 0, /* tp_traverse */
2914 0, /* tp_clear */
2915 0, /* tp_richcompare */
2916 0, /* tp_weaklistoffset */
2917 0, /* tp_iter */
2918 0, /* tp_iternext */
2919 tzinfo_methods, /* tp_methods */
2920 0, /* tp_members */
2921 0, /* tp_getset */
2922 0, /* tp_base */
2923 0, /* tp_dict */
2924 0, /* tp_descr_get */
2925 0, /* tp_descr_set */
2926 0, /* tp_dictoffset */
2927 0, /* tp_init */
2928 0, /* tp_alloc */
2929 PyType_GenericNew, /* tp_new */
2930 0, /* tp_free */
2931};
2932
2933/*
Tim Peters37f39822003-01-10 03:49:02 +00002934 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002935 */
2936
Tim Peters37f39822003-01-10 03:49:02 +00002937/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002938 */
2939
2940static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002941time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002942{
Tim Peters37f39822003-01-10 03:49:02 +00002943 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002944}
2945
Tim Peters37f39822003-01-10 03:49:02 +00002946static PyObject *
2947time_minute(PyDateTime_Time *self, void *unused)
2948{
2949 return PyInt_FromLong(TIME_GET_MINUTE(self));
2950}
2951
2952/* The name time_second conflicted with some platform header file. */
2953static PyObject *
2954py_time_second(PyDateTime_Time *self, void *unused)
2955{
2956 return PyInt_FromLong(TIME_GET_SECOND(self));
2957}
2958
2959static PyObject *
2960time_microsecond(PyDateTime_Time *self, void *unused)
2961{
2962 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2963}
2964
2965static PyObject *
2966time_tzinfo(PyDateTime_Time *self, void *unused)
2967{
Tim Petersa032d2e2003-01-11 00:15:54 +00002968 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002969 Py_INCREF(result);
2970 return result;
2971}
2972
2973static PyGetSetDef time_getset[] = {
2974 {"hour", (getter)time_hour},
2975 {"minute", (getter)time_minute},
2976 {"second", (getter)py_time_second},
2977 {"microsecond", (getter)time_microsecond},
2978 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00002979 {NULL}
2980};
2981
2982/*
2983 * Constructors.
2984 */
2985
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002986static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00002987 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002988
Tim Peters2a799bf2002-12-16 20:18:38 +00002989static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002990time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00002991{
2992 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002993 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002994 int hour = 0;
2995 int minute = 0;
2996 int second = 0;
2997 int usecond = 0;
2998 PyObject *tzinfo = Py_None;
2999
Guido van Rossum177e41a2003-01-30 22:06:23 +00003000 /* Check for invocation from pickle with __getstate__ state */
3001 if (PyTuple_GET_SIZE(args) >= 1 &&
3002 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003003 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3004 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3005 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003006 {
Tim Peters70533e22003-02-01 04:40:04 +00003007 PyDateTime_Time *me;
3008 char aware;
3009
3010 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003011 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003012 if (check_tzinfo_subclass(tzinfo) < 0) {
3013 PyErr_SetString(PyExc_TypeError, "bad "
3014 "tzinfo state arg");
3015 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003016 }
3017 }
Tim Peters70533e22003-02-01 04:40:04 +00003018 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003019 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003020 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003021 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003022
3023 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3024 me->hashcode = -1;
3025 me->hastzinfo = aware;
3026 if (aware) {
3027 Py_INCREF(tzinfo);
3028 me->tzinfo = tzinfo;
3029 }
3030 }
3031 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003032 }
3033
Tim Peters37f39822003-01-10 03:49:02 +00003034 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003035 &hour, &minute, &second, &usecond,
3036 &tzinfo)) {
3037 if (check_time_args(hour, minute, second, usecond) < 0)
3038 return NULL;
3039 if (check_tzinfo_subclass(tzinfo) < 0)
3040 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003041 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3042 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003043 }
3044 return self;
3045}
3046
3047/*
3048 * Destructor.
3049 */
3050
3051static void
Tim Peters37f39822003-01-10 03:49:02 +00003052time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003053{
Tim Petersa032d2e2003-01-11 00:15:54 +00003054 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003055 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003056 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003057 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003058}
3059
3060/*
Tim Peters855fe882002-12-22 03:43:39 +00003061 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003062 */
3063
Tim Peters2a799bf2002-12-16 20:18:38 +00003064/* These are all METH_NOARGS, so don't need to check the arglist. */
3065static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003066time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003067 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003068 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003069}
3070
3071static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003072time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003073 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003074 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003075}
3076
3077static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003078time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003079 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003080 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003081}
3082
3083/*
Tim Peters37f39822003-01-10 03:49:02 +00003084 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003085 */
3086
3087static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003088time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003089{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003090 const char *type_name = Py_Type(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003091 int h = TIME_GET_HOUR(self);
3092 int m = TIME_GET_MINUTE(self);
3093 int s = TIME_GET_SECOND(self);
3094 int us = TIME_GET_MICROSECOND(self);
3095 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003096
Tim Peters37f39822003-01-10 03:49:02 +00003097 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003098 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3099 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003100 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003101 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3102 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003103 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003104 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003105 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003106 result = append_keyword_tzinfo(result, self->tzinfo);
3107 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003108}
3109
Tim Peters37f39822003-01-10 03:49:02 +00003110static PyObject *
3111time_str(PyDateTime_Time *self)
3112{
3113 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3114}
Tim Peters2a799bf2002-12-16 20:18:38 +00003115
3116static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003117time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003118{
3119 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003120 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003121 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003122
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003123 if (us)
3124 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3125 TIME_GET_HOUR(self),
3126 TIME_GET_MINUTE(self),
3127 TIME_GET_SECOND(self),
3128 us);
3129 else
3130 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3131 TIME_GET_HOUR(self),
3132 TIME_GET_MINUTE(self),
3133 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003134
Tim Petersa032d2e2003-01-11 00:15:54 +00003135 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003136 return result;
3137
3138 /* We need to append the UTC offset. */
3139 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003140 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003141 Py_DECREF(result);
3142 return NULL;
3143 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003144 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003145 return result;
3146}
3147
Tim Peters37f39822003-01-10 03:49:02 +00003148static PyObject *
3149time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3150{
3151 PyObject *result;
3152 PyObject *format;
3153 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003154 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003155
Guido van Rossumbce56a62007-05-10 18:04:33 +00003156 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3157 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003158 return NULL;
3159
3160 /* Python's strftime does insane things with the year part of the
3161 * timetuple. The year is forced to (the otherwise nonsensical)
3162 * 1900 to worm around that.
3163 */
3164 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003165 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003166 TIME_GET_HOUR(self),
3167 TIME_GET_MINUTE(self),
3168 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003169 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003170 if (tuple == NULL)
3171 return NULL;
3172 assert(PyTuple_Size(tuple) == 9);
3173 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3174 Py_DECREF(tuple);
3175 return result;
3176}
Tim Peters2a799bf2002-12-16 20:18:38 +00003177
3178/*
3179 * Miscellaneous methods.
3180 */
3181
Tim Peters37f39822003-01-10 03:49:02 +00003182static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003183time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003184{
3185 int diff;
3186 naivety n1, n2;
3187 int offset1, offset2;
3188
3189 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003190 Py_INCREF(Py_NotImplemented);
3191 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003192 }
Guido van Rossum19960592006-08-24 17:29:38 +00003193 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3194 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003195 return NULL;
3196 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3197 /* If they're both naive, or both aware and have the same offsets,
3198 * we get off cheap. Note that if they're both naive, offset1 ==
3199 * offset2 == 0 at this point.
3200 */
3201 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003202 diff = memcmp(((PyDateTime_Time *)self)->data,
3203 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003204 _PyDateTime_TIME_DATASIZE);
3205 return diff_to_bool(diff, op);
3206 }
3207
3208 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3209 assert(offset1 != offset2); /* else last "if" handled it */
3210 /* Convert everything except microseconds to seconds. These
3211 * can't overflow (no more than the # of seconds in 2 days).
3212 */
3213 offset1 = TIME_GET_HOUR(self) * 3600 +
3214 (TIME_GET_MINUTE(self) - offset1) * 60 +
3215 TIME_GET_SECOND(self);
3216 offset2 = TIME_GET_HOUR(other) * 3600 +
3217 (TIME_GET_MINUTE(other) - offset2) * 60 +
3218 TIME_GET_SECOND(other);
3219 diff = offset1 - offset2;
3220 if (diff == 0)
3221 diff = TIME_GET_MICROSECOND(self) -
3222 TIME_GET_MICROSECOND(other);
3223 return diff_to_bool(diff, op);
3224 }
3225
3226 assert(n1 != n2);
3227 PyErr_SetString(PyExc_TypeError,
3228 "can't compare offset-naive and "
3229 "offset-aware times");
3230 return NULL;
3231}
3232
3233static long
3234time_hash(PyDateTime_Time *self)
3235{
3236 if (self->hashcode == -1) {
3237 naivety n;
3238 int offset;
3239 PyObject *temp;
3240
3241 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3242 assert(n != OFFSET_UNKNOWN);
3243 if (n == OFFSET_ERROR)
3244 return -1;
3245
3246 /* Reduce this to a hash of another object. */
3247 if (offset == 0)
3248 temp = PyString_FromStringAndSize((char *)self->data,
3249 _PyDateTime_TIME_DATASIZE);
3250 else {
3251 int hour;
3252 int minute;
3253
3254 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003255 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003256 hour = divmod(TIME_GET_HOUR(self) * 60 +
3257 TIME_GET_MINUTE(self) - offset,
3258 60,
3259 &minute);
3260 if (0 <= hour && hour < 24)
3261 temp = new_time(hour, minute,
3262 TIME_GET_SECOND(self),
3263 TIME_GET_MICROSECOND(self),
3264 Py_None);
3265 else
3266 temp = Py_BuildValue("iiii",
3267 hour, minute,
3268 TIME_GET_SECOND(self),
3269 TIME_GET_MICROSECOND(self));
3270 }
3271 if (temp != NULL) {
3272 self->hashcode = PyObject_Hash(temp);
3273 Py_DECREF(temp);
3274 }
3275 }
3276 return self->hashcode;
3277}
Tim Peters2a799bf2002-12-16 20:18:38 +00003278
Tim Peters12bf3392002-12-24 05:41:27 +00003279static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003280time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003281{
3282 PyObject *clone;
3283 PyObject *tuple;
3284 int hh = TIME_GET_HOUR(self);
3285 int mm = TIME_GET_MINUTE(self);
3286 int ss = TIME_GET_SECOND(self);
3287 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003288 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003289
3290 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003291 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003292 &hh, &mm, &ss, &us, &tzinfo))
3293 return NULL;
3294 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3295 if (tuple == NULL)
3296 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003297 clone = time_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003298 Py_DECREF(tuple);
3299 return clone;
3300}
3301
Tim Peters2a799bf2002-12-16 20:18:38 +00003302static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003303time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003304{
3305 int offset;
3306 int none;
3307
3308 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3309 /* Since utcoffset is in whole minutes, nothing can
3310 * alter the conclusion that this is nonzero.
3311 */
3312 return 1;
3313 }
3314 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003315 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003316 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003317 if (offset == -1 && PyErr_Occurred())
3318 return -1;
3319 }
3320 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3321}
3322
Tim Peters371935f2003-02-01 01:52:50 +00003323/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003324
Tim Peters33e0f382003-01-10 02:05:14 +00003325/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003326 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3327 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003328 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003329 */
3330static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003331time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003332{
3333 PyObject *basestate;
3334 PyObject *result = NULL;
3335
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003336 basestate = PyBytes_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003337 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003338 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003339 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003340 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003341 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003342 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003343 Py_DECREF(basestate);
3344 }
3345 return result;
3346}
3347
3348static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003349time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003350{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003351 return Py_BuildValue("(ON)", Py_Type(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003352}
3353
Tim Peters37f39822003-01-10 03:49:02 +00003354static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003355
Thomas Wouterscf297e42007-02-23 15:07:44 +00003356 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003357 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3358 "[+HH:MM].")},
3359
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003360 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003361 PyDoc_STR("format -> strftime() style string.")},
3362
3363 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003364 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3365
Tim Peters37f39822003-01-10 03:49:02 +00003366 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003367 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3368
Tim Peters37f39822003-01-10 03:49:02 +00003369 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003370 PyDoc_STR("Return self.tzinfo.dst(self).")},
3371
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003372 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003373 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003374
Guido van Rossum177e41a2003-01-30 22:06:23 +00003375 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3376 PyDoc_STR("__reduce__() -> (cls, state)")},
3377
Tim Peters2a799bf2002-12-16 20:18:38 +00003378 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003379};
3380
Tim Peters37f39822003-01-10 03:49:02 +00003381static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003382PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3383\n\
3384All arguments are optional. tzinfo may be None, or an instance of\n\
3385a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003386
Tim Peters37f39822003-01-10 03:49:02 +00003387static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003388 0, /* nb_add */
3389 0, /* nb_subtract */
3390 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003391 0, /* nb_remainder */
3392 0, /* nb_divmod */
3393 0, /* nb_power */
3394 0, /* nb_negative */
3395 0, /* nb_positive */
3396 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003397 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003398};
3399
Neal Norwitz227b5332006-03-22 09:28:35 +00003400static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003401 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003402 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003403 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003404 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003405 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003406 0, /* tp_print */
3407 0, /* tp_getattr */
3408 0, /* tp_setattr */
3409 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003410 (reprfunc)time_repr, /* tp_repr */
3411 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003412 0, /* tp_as_sequence */
3413 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003414 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003415 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003416 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003417 PyObject_GenericGetAttr, /* tp_getattro */
3418 0, /* tp_setattro */
3419 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003420 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003421 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003422 0, /* tp_traverse */
3423 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003424 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003425 0, /* tp_weaklistoffset */
3426 0, /* tp_iter */
3427 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003428 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003429 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003430 time_getset, /* tp_getset */
3431 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003432 0, /* tp_dict */
3433 0, /* tp_descr_get */
3434 0, /* tp_descr_set */
3435 0, /* tp_dictoffset */
3436 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003437 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003438 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003439 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003440};
3441
3442/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003443 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003444 */
3445
Tim Petersa9bc1682003-01-11 03:39:11 +00003446/* Accessor properties. Properties for day, month, and year are inherited
3447 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003448 */
3449
3450static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003451datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003452{
Tim Petersa9bc1682003-01-11 03:39:11 +00003453 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003454}
3455
Tim Petersa9bc1682003-01-11 03:39:11 +00003456static PyObject *
3457datetime_minute(PyDateTime_DateTime *self, void *unused)
3458{
3459 return PyInt_FromLong(DATE_GET_MINUTE(self));
3460}
3461
3462static PyObject *
3463datetime_second(PyDateTime_DateTime *self, void *unused)
3464{
3465 return PyInt_FromLong(DATE_GET_SECOND(self));
3466}
3467
3468static PyObject *
3469datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3470{
3471 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3472}
3473
3474static PyObject *
3475datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3476{
3477 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3478 Py_INCREF(result);
3479 return result;
3480}
3481
3482static PyGetSetDef datetime_getset[] = {
3483 {"hour", (getter)datetime_hour},
3484 {"minute", (getter)datetime_minute},
3485 {"second", (getter)datetime_second},
3486 {"microsecond", (getter)datetime_microsecond},
3487 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003488 {NULL}
3489};
3490
3491/*
3492 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003493 */
3494
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003495static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003496 "year", "month", "day", "hour", "minute", "second",
3497 "microsecond", "tzinfo", NULL
3498};
3499
Tim Peters2a799bf2002-12-16 20:18:38 +00003500static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003501datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003502{
3503 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003504 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003505 int year;
3506 int month;
3507 int day;
3508 int hour = 0;
3509 int minute = 0;
3510 int second = 0;
3511 int usecond = 0;
3512 PyObject *tzinfo = Py_None;
3513
Guido van Rossum177e41a2003-01-30 22:06:23 +00003514 /* Check for invocation from pickle with __getstate__ state */
3515 if (PyTuple_GET_SIZE(args) >= 1 &&
3516 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003517 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3518 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3519 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003520 {
Tim Peters70533e22003-02-01 04:40:04 +00003521 PyDateTime_DateTime *me;
3522 char aware;
3523
3524 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003525 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003526 if (check_tzinfo_subclass(tzinfo) < 0) {
3527 PyErr_SetString(PyExc_TypeError, "bad "
3528 "tzinfo state arg");
3529 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003530 }
3531 }
Tim Peters70533e22003-02-01 04:40:04 +00003532 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003533 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003534 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003535 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003536
3537 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3538 me->hashcode = -1;
3539 me->hastzinfo = aware;
3540 if (aware) {
3541 Py_INCREF(tzinfo);
3542 me->tzinfo = tzinfo;
3543 }
3544 }
3545 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003546 }
3547
Tim Petersa9bc1682003-01-11 03:39:11 +00003548 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003549 &year, &month, &day, &hour, &minute,
3550 &second, &usecond, &tzinfo)) {
3551 if (check_date_args(year, month, day) < 0)
3552 return NULL;
3553 if (check_time_args(hour, minute, second, usecond) < 0)
3554 return NULL;
3555 if (check_tzinfo_subclass(tzinfo) < 0)
3556 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003557 self = new_datetime_ex(year, month, day,
3558 hour, minute, second, usecond,
3559 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003560 }
3561 return self;
3562}
3563
Tim Petersa9bc1682003-01-11 03:39:11 +00003564/* TM_FUNC is the shared type of localtime() and gmtime(). */
3565typedef struct tm *(*TM_FUNC)(const time_t *timer);
3566
3567/* Internal helper.
3568 * Build datetime from a time_t and a distinct count of microseconds.
3569 * Pass localtime or gmtime for f, to control the interpretation of timet.
3570 */
3571static PyObject *
3572datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3573 PyObject *tzinfo)
3574{
3575 struct tm *tm;
3576 PyObject *result = NULL;
3577
3578 tm = f(&timet);
3579 if (tm) {
3580 /* The platform localtime/gmtime may insert leap seconds,
3581 * indicated by tm->tm_sec > 59. We don't care about them,
3582 * except to the extent that passing them on to the datetime
3583 * constructor would raise ValueError for a reason that
3584 * made no sense to the user.
3585 */
3586 if (tm->tm_sec > 59)
3587 tm->tm_sec = 59;
3588 result = PyObject_CallFunction(cls, "iiiiiiiO",
3589 tm->tm_year + 1900,
3590 tm->tm_mon + 1,
3591 tm->tm_mday,
3592 tm->tm_hour,
3593 tm->tm_min,
3594 tm->tm_sec,
3595 us,
3596 tzinfo);
3597 }
3598 else
3599 PyErr_SetString(PyExc_ValueError,
3600 "timestamp out of range for "
3601 "platform localtime()/gmtime() function");
3602 return result;
3603}
3604
3605/* Internal helper.
3606 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3607 * to control the interpretation of the timestamp. Since a double doesn't
3608 * have enough bits to cover a datetime's full range of precision, it's
3609 * better to call datetime_from_timet_and_us provided you have a way
3610 * to get that much precision (e.g., C time() isn't good enough).
3611 */
3612static PyObject *
3613datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3614 PyObject *tzinfo)
3615{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003616 time_t timet;
3617 double fraction;
3618 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003619
Tim Peters1b6f7a92004-06-20 02:50:16 +00003620 timet = _PyTime_DoubleToTimet(timestamp);
3621 if (timet == (time_t)-1 && PyErr_Occurred())
3622 return NULL;
3623 fraction = timestamp - (double)timet;
3624 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003625 if (us < 0) {
3626 /* Truncation towards zero is not what we wanted
3627 for negative numbers (Python's mod semantics) */
3628 timet -= 1;
3629 us += 1000000;
3630 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003631 /* If timestamp is less than one microsecond smaller than a
3632 * full second, round up. Otherwise, ValueErrors are raised
3633 * for some floats. */
3634 if (us == 1000000) {
3635 timet += 1;
3636 us = 0;
3637 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003638 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3639}
3640
3641/* Internal helper.
3642 * Build most accurate possible datetime for current time. Pass localtime or
3643 * gmtime for f as appropriate.
3644 */
3645static PyObject *
3646datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3647{
3648#ifdef HAVE_GETTIMEOFDAY
3649 struct timeval t;
3650
3651#ifdef GETTIMEOFDAY_NO_TZ
3652 gettimeofday(&t);
3653#else
3654 gettimeofday(&t, (struct timezone *)NULL);
3655#endif
3656 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3657 tzinfo);
3658
3659#else /* ! HAVE_GETTIMEOFDAY */
3660 /* No flavor of gettimeofday exists on this platform. Python's
3661 * time.time() does a lot of other platform tricks to get the
3662 * best time it can on the platform, and we're not going to do
3663 * better than that (if we could, the better code would belong
3664 * in time.time()!) We're limited by the precision of a double,
3665 * though.
3666 */
3667 PyObject *time;
3668 double dtime;
3669
3670 time = time_time();
3671 if (time == NULL)
3672 return NULL;
3673 dtime = PyFloat_AsDouble(time);
3674 Py_DECREF(time);
3675 if (dtime == -1.0 && PyErr_Occurred())
3676 return NULL;
3677 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3678#endif /* ! HAVE_GETTIMEOFDAY */
3679}
3680
Tim Peters2a799bf2002-12-16 20:18:38 +00003681/* Return best possible local time -- this isn't constrained by the
3682 * precision of a timestamp.
3683 */
3684static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003685datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003686{
Tim Peters10cadce2003-01-23 19:58:02 +00003687 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003688 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003689 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003690
Tim Peters10cadce2003-01-23 19:58:02 +00003691 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3692 &tzinfo))
3693 return NULL;
3694 if (check_tzinfo_subclass(tzinfo) < 0)
3695 return NULL;
3696
3697 self = datetime_best_possible(cls,
3698 tzinfo == Py_None ? localtime : gmtime,
3699 tzinfo);
3700 if (self != NULL && tzinfo != Py_None) {
3701 /* Convert UTC to tzinfo's zone. */
3702 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003703 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003704 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003705 }
3706 return self;
3707}
3708
Tim Petersa9bc1682003-01-11 03:39:11 +00003709/* Return best possible UTC time -- this isn't constrained by the
3710 * precision of a timestamp.
3711 */
3712static PyObject *
3713datetime_utcnow(PyObject *cls, PyObject *dummy)
3714{
3715 return datetime_best_possible(cls, gmtime, Py_None);
3716}
3717
Tim Peters2a799bf2002-12-16 20:18:38 +00003718/* Return new local datetime from timestamp (Python timestamp -- a double). */
3719static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003720datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003721{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003722 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003723 double timestamp;
3724 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003725 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003726
Tim Peters2a44a8d2003-01-23 20:53:10 +00003727 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3728 keywords, &timestamp, &tzinfo))
3729 return NULL;
3730 if (check_tzinfo_subclass(tzinfo) < 0)
3731 return NULL;
3732
3733 self = datetime_from_timestamp(cls,
3734 tzinfo == Py_None ? localtime : gmtime,
3735 timestamp,
3736 tzinfo);
3737 if (self != NULL && tzinfo != Py_None) {
3738 /* Convert UTC to tzinfo's zone. */
3739 PyObject *temp = self;
3740 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3741 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003742 }
3743 return self;
3744}
3745
Tim Petersa9bc1682003-01-11 03:39:11 +00003746/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3747static PyObject *
3748datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3749{
3750 double timestamp;
3751 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003752
Tim Petersa9bc1682003-01-11 03:39:11 +00003753 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3754 result = datetime_from_timestamp(cls, gmtime, timestamp,
3755 Py_None);
3756 return result;
3757}
3758
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003759/* Return new datetime from time.strptime(). */
3760static PyObject *
3761datetime_strptime(PyObject *cls, PyObject *args)
3762{
3763 PyObject *result = NULL, *obj, *module;
3764 const char *string, *format;
3765
3766 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3767 return NULL;
3768
3769 if ((module = PyImport_ImportModule("time")) == NULL)
3770 return NULL;
3771 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3772 Py_DECREF(module);
3773
3774 if (obj != NULL) {
3775 int i, good_timetuple = 1;
3776 long int ia[6];
3777 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3778 for (i=0; i < 6; i++) {
3779 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003780 if (p == NULL) {
3781 Py_DECREF(obj);
3782 return NULL;
3783 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003784 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003785 ia[i] = PyInt_AsLong(p);
3786 else
3787 good_timetuple = 0;
3788 Py_DECREF(p);
3789 }
3790 else
3791 good_timetuple = 0;
3792 if (good_timetuple)
3793 result = PyObject_CallFunction(cls, "iiiiii",
3794 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3795 else
3796 PyErr_SetString(PyExc_ValueError,
3797 "unexpected value from time.strptime");
3798 Py_DECREF(obj);
3799 }
3800 return result;
3801}
3802
Tim Petersa9bc1682003-01-11 03:39:11 +00003803/* Return new datetime from date/datetime and time arguments. */
3804static PyObject *
3805datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3806{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003807 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003808 PyObject *date;
3809 PyObject *time;
3810 PyObject *result = NULL;
3811
3812 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3813 &PyDateTime_DateType, &date,
3814 &PyDateTime_TimeType, &time)) {
3815 PyObject *tzinfo = Py_None;
3816
3817 if (HASTZINFO(time))
3818 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3819 result = PyObject_CallFunction(cls, "iiiiiiiO",
3820 GET_YEAR(date),
3821 GET_MONTH(date),
3822 GET_DAY(date),
3823 TIME_GET_HOUR(time),
3824 TIME_GET_MINUTE(time),
3825 TIME_GET_SECOND(time),
3826 TIME_GET_MICROSECOND(time),
3827 tzinfo);
3828 }
3829 return result;
3830}
Tim Peters2a799bf2002-12-16 20:18:38 +00003831
3832/*
3833 * Destructor.
3834 */
3835
3836static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003837datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003838{
Tim Petersa9bc1682003-01-11 03:39:11 +00003839 if (HASTZINFO(self)) {
3840 Py_XDECREF(self->tzinfo);
3841 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003842 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003843}
3844
3845/*
3846 * Indirect access to tzinfo methods.
3847 */
3848
Tim Peters2a799bf2002-12-16 20:18:38 +00003849/* These are all METH_NOARGS, so don't need to check the arglist. */
3850static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003851datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3852 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3853 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003854}
3855
3856static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003857datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3858 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3859 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003860}
3861
3862static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003863datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3864 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3865 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003866}
3867
3868/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003869 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003870 */
3871
Tim Petersa9bc1682003-01-11 03:39:11 +00003872/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3873 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003874 */
3875static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003876add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3877 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003878{
Tim Petersa9bc1682003-01-11 03:39:11 +00003879 /* Note that the C-level additions can't overflow, because of
3880 * invariant bounds on the member values.
3881 */
3882 int year = GET_YEAR(date);
3883 int month = GET_MONTH(date);
3884 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3885 int hour = DATE_GET_HOUR(date);
3886 int minute = DATE_GET_MINUTE(date);
3887 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3888 int microsecond = DATE_GET_MICROSECOND(date) +
3889 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003890
Tim Petersa9bc1682003-01-11 03:39:11 +00003891 assert(factor == 1 || factor == -1);
3892 if (normalize_datetime(&year, &month, &day,
3893 &hour, &minute, &second, &microsecond) < 0)
3894 return NULL;
3895 else
3896 return new_datetime(year, month, day,
3897 hour, minute, second, microsecond,
3898 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003899}
3900
3901static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003902datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003903{
Tim Petersa9bc1682003-01-11 03:39:11 +00003904 if (PyDateTime_Check(left)) {
3905 /* datetime + ??? */
3906 if (PyDelta_Check(right))
3907 /* datetime + delta */
3908 return add_datetime_timedelta(
3909 (PyDateTime_DateTime *)left,
3910 (PyDateTime_Delta *)right,
3911 1);
3912 }
3913 else if (PyDelta_Check(left)) {
3914 /* delta + datetime */
3915 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3916 (PyDateTime_Delta *) left,
3917 1);
3918 }
3919 Py_INCREF(Py_NotImplemented);
3920 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003921}
3922
3923static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003924datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003925{
3926 PyObject *result = Py_NotImplemented;
3927
3928 if (PyDateTime_Check(left)) {
3929 /* datetime - ??? */
3930 if (PyDateTime_Check(right)) {
3931 /* datetime - datetime */
3932 naivety n1, n2;
3933 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003934 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003935
Tim Peterse39a80c2002-12-30 21:28:52 +00003936 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3937 right, &offset2, &n2,
3938 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003939 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003940 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003941 if (n1 != n2) {
3942 PyErr_SetString(PyExc_TypeError,
3943 "can't subtract offset-naive and "
3944 "offset-aware datetimes");
3945 return NULL;
3946 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003947 delta_d = ymd_to_ord(GET_YEAR(left),
3948 GET_MONTH(left),
3949 GET_DAY(left)) -
3950 ymd_to_ord(GET_YEAR(right),
3951 GET_MONTH(right),
3952 GET_DAY(right));
3953 /* These can't overflow, since the values are
3954 * normalized. At most this gives the number of
3955 * seconds in one day.
3956 */
3957 delta_s = (DATE_GET_HOUR(left) -
3958 DATE_GET_HOUR(right)) * 3600 +
3959 (DATE_GET_MINUTE(left) -
3960 DATE_GET_MINUTE(right)) * 60 +
3961 (DATE_GET_SECOND(left) -
3962 DATE_GET_SECOND(right));
3963 delta_us = DATE_GET_MICROSECOND(left) -
3964 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003965 /* (left - offset1) - (right - offset2) =
3966 * (left - right) + (offset2 - offset1)
3967 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003968 delta_s += (offset2 - offset1) * 60;
3969 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003970 }
3971 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003972 /* datetime - delta */
3973 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003974 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00003975 (PyDateTime_Delta *)right,
3976 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003977 }
3978 }
3979
3980 if (result == Py_NotImplemented)
3981 Py_INCREF(result);
3982 return result;
3983}
3984
3985/* Various ways to turn a datetime into a string. */
3986
3987static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003988datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003989{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003990 const char *type_name = Py_Type(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00003991 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00003992
Tim Petersa9bc1682003-01-11 03:39:11 +00003993 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003994 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00003995 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003996 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00003997 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
3998 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
3999 DATE_GET_SECOND(self),
4000 DATE_GET_MICROSECOND(self));
4001 }
4002 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004003 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004004 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004005 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004006 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4007 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4008 DATE_GET_SECOND(self));
4009 }
4010 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004011 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004012 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004013 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004014 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4015 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4016 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004017 if (baserepr == NULL || ! HASTZINFO(self))
4018 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004019 return append_keyword_tzinfo(baserepr, self->tzinfo);
4020}
4021
Tim Petersa9bc1682003-01-11 03:39:11 +00004022static PyObject *
4023datetime_str(PyDateTime_DateTime *self)
4024{
4025 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4026}
Tim Peters2a799bf2002-12-16 20:18:38 +00004027
4028static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004029datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004030{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004031 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004032 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004033 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004034 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004035 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004036
Walter Dörwaldd0941302007-07-01 21:58:22 +00004037 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004038 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004039 if (us)
4040 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4041 GET_YEAR(self), GET_MONTH(self),
4042 GET_DAY(self), (int)sep,
4043 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4044 DATE_GET_SECOND(self), us);
4045 else
4046 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4047 GET_YEAR(self), GET_MONTH(self),
4048 GET_DAY(self), (int)sep,
4049 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4050 DATE_GET_SECOND(self));
4051
4052 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004053 return result;
4054
4055 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004056 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004057 (PyObject *)self) < 0) {
4058 Py_DECREF(result);
4059 return NULL;
4060 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004061 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004062 return result;
4063}
4064
Tim Petersa9bc1682003-01-11 03:39:11 +00004065static PyObject *
4066datetime_ctime(PyDateTime_DateTime *self)
4067{
4068 return format_ctime((PyDateTime_Date *)self,
4069 DATE_GET_HOUR(self),
4070 DATE_GET_MINUTE(self),
4071 DATE_GET_SECOND(self));
4072}
4073
Tim Peters2a799bf2002-12-16 20:18:38 +00004074/* Miscellaneous methods. */
4075
Tim Petersa9bc1682003-01-11 03:39:11 +00004076static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004077datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004078{
4079 int diff;
4080 naivety n1, n2;
4081 int offset1, offset2;
4082
4083 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004084 if (PyDate_Check(other)) {
4085 /* Prevent invocation of date_richcompare. We want to
4086 return NotImplemented here to give the other object
4087 a chance. But since DateTime is a subclass of
4088 Date, if the other object is a Date, it would
4089 compute an ordering based on the date part alone,
4090 and we don't want that. So force unequal or
4091 uncomparable here in that case. */
4092 if (op == Py_EQ)
4093 Py_RETURN_FALSE;
4094 if (op == Py_NE)
4095 Py_RETURN_TRUE;
4096 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004097 }
Guido van Rossum19960592006-08-24 17:29:38 +00004098 Py_INCREF(Py_NotImplemented);
4099 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004100 }
4101
Guido van Rossum19960592006-08-24 17:29:38 +00004102 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4103 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004104 return NULL;
4105 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4106 /* If they're both naive, or both aware and have the same offsets,
4107 * we get off cheap. Note that if they're both naive, offset1 ==
4108 * offset2 == 0 at this point.
4109 */
4110 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004111 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4112 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004113 _PyDateTime_DATETIME_DATASIZE);
4114 return diff_to_bool(diff, op);
4115 }
4116
4117 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4118 PyDateTime_Delta *delta;
4119
4120 assert(offset1 != offset2); /* else last "if" handled it */
4121 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4122 other);
4123 if (delta == NULL)
4124 return NULL;
4125 diff = GET_TD_DAYS(delta);
4126 if (diff == 0)
4127 diff = GET_TD_SECONDS(delta) |
4128 GET_TD_MICROSECONDS(delta);
4129 Py_DECREF(delta);
4130 return diff_to_bool(diff, op);
4131 }
4132
4133 assert(n1 != n2);
4134 PyErr_SetString(PyExc_TypeError,
4135 "can't compare offset-naive and "
4136 "offset-aware datetimes");
4137 return NULL;
4138}
4139
4140static long
4141datetime_hash(PyDateTime_DateTime *self)
4142{
4143 if (self->hashcode == -1) {
4144 naivety n;
4145 int offset;
4146 PyObject *temp;
4147
4148 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4149 &offset);
4150 assert(n != OFFSET_UNKNOWN);
4151 if (n == OFFSET_ERROR)
4152 return -1;
4153
4154 /* Reduce this to a hash of another object. */
4155 if (n == OFFSET_NAIVE)
4156 temp = PyString_FromStringAndSize(
4157 (char *)self->data,
4158 _PyDateTime_DATETIME_DATASIZE);
4159 else {
4160 int days;
4161 int seconds;
4162
4163 assert(n == OFFSET_AWARE);
4164 assert(HASTZINFO(self));
4165 days = ymd_to_ord(GET_YEAR(self),
4166 GET_MONTH(self),
4167 GET_DAY(self));
4168 seconds = DATE_GET_HOUR(self) * 3600 +
4169 (DATE_GET_MINUTE(self) - offset) * 60 +
4170 DATE_GET_SECOND(self);
4171 temp = new_delta(days,
4172 seconds,
4173 DATE_GET_MICROSECOND(self),
4174 1);
4175 }
4176 if (temp != NULL) {
4177 self->hashcode = PyObject_Hash(temp);
4178 Py_DECREF(temp);
4179 }
4180 }
4181 return self->hashcode;
4182}
Tim Peters2a799bf2002-12-16 20:18:38 +00004183
4184static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004185datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004186{
4187 PyObject *clone;
4188 PyObject *tuple;
4189 int y = GET_YEAR(self);
4190 int m = GET_MONTH(self);
4191 int d = GET_DAY(self);
4192 int hh = DATE_GET_HOUR(self);
4193 int mm = DATE_GET_MINUTE(self);
4194 int ss = DATE_GET_SECOND(self);
4195 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004196 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004197
4198 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004199 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004200 &y, &m, &d, &hh, &mm, &ss, &us,
4201 &tzinfo))
4202 return NULL;
4203 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4204 if (tuple == NULL)
4205 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004206 clone = datetime_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004207 Py_DECREF(tuple);
4208 return clone;
4209}
4210
4211static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004212datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004213{
Tim Peters52dcce22003-01-23 16:36:11 +00004214 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004215 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004216 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004217
Tim Peters80475bb2002-12-25 07:40:55 +00004218 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004219 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004220
Tim Peters52dcce22003-01-23 16:36:11 +00004221 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4222 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004223 return NULL;
4224
Tim Peters52dcce22003-01-23 16:36:11 +00004225 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4226 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004227
Tim Peters52dcce22003-01-23 16:36:11 +00004228 /* Conversion to self's own time zone is a NOP. */
4229 if (self->tzinfo == tzinfo) {
4230 Py_INCREF(self);
4231 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004232 }
Tim Peters521fc152002-12-31 17:36:56 +00004233
Tim Peters52dcce22003-01-23 16:36:11 +00004234 /* Convert self to UTC. */
4235 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4236 if (offset == -1 && PyErr_Occurred())
4237 return NULL;
4238 if (none)
4239 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004240
Tim Peters52dcce22003-01-23 16:36:11 +00004241 y = GET_YEAR(self);
4242 m = GET_MONTH(self);
4243 d = GET_DAY(self);
4244 hh = DATE_GET_HOUR(self);
4245 mm = DATE_GET_MINUTE(self);
4246 ss = DATE_GET_SECOND(self);
4247 us = DATE_GET_MICROSECOND(self);
4248
4249 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004250 if ((mm < 0 || mm >= 60) &&
4251 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004252 return NULL;
4253
4254 /* Attach new tzinfo and let fromutc() do the rest. */
4255 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4256 if (result != NULL) {
4257 PyObject *temp = result;
4258
4259 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4260 Py_DECREF(temp);
4261 }
Tim Petersadf64202003-01-04 06:03:15 +00004262 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004263
Tim Peters52dcce22003-01-23 16:36:11 +00004264NeedAware:
4265 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4266 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004267 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004268}
4269
4270static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004271datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004272{
4273 int dstflag = -1;
4274
Tim Petersa9bc1682003-01-11 03:39:11 +00004275 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004276 int none;
4277
4278 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4279 if (dstflag == -1 && PyErr_Occurred())
4280 return NULL;
4281
4282 if (none)
4283 dstflag = -1;
4284 else if (dstflag != 0)
4285 dstflag = 1;
4286
4287 }
4288 return build_struct_time(GET_YEAR(self),
4289 GET_MONTH(self),
4290 GET_DAY(self),
4291 DATE_GET_HOUR(self),
4292 DATE_GET_MINUTE(self),
4293 DATE_GET_SECOND(self),
4294 dstflag);
4295}
4296
4297static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004298datetime_getdate(PyDateTime_DateTime *self)
4299{
4300 return new_date(GET_YEAR(self),
4301 GET_MONTH(self),
4302 GET_DAY(self));
4303}
4304
4305static PyObject *
4306datetime_gettime(PyDateTime_DateTime *self)
4307{
4308 return new_time(DATE_GET_HOUR(self),
4309 DATE_GET_MINUTE(self),
4310 DATE_GET_SECOND(self),
4311 DATE_GET_MICROSECOND(self),
4312 Py_None);
4313}
4314
4315static PyObject *
4316datetime_gettimetz(PyDateTime_DateTime *self)
4317{
4318 return new_time(DATE_GET_HOUR(self),
4319 DATE_GET_MINUTE(self),
4320 DATE_GET_SECOND(self),
4321 DATE_GET_MICROSECOND(self),
4322 HASTZINFO(self) ? self->tzinfo : Py_None);
4323}
4324
4325static PyObject *
4326datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004327{
4328 int y = GET_YEAR(self);
4329 int m = GET_MONTH(self);
4330 int d = GET_DAY(self);
4331 int hh = DATE_GET_HOUR(self);
4332 int mm = DATE_GET_MINUTE(self);
4333 int ss = DATE_GET_SECOND(self);
4334 int us = 0; /* microseconds are ignored in a timetuple */
4335 int offset = 0;
4336
Tim Petersa9bc1682003-01-11 03:39:11 +00004337 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004338 int none;
4339
4340 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4341 if (offset == -1 && PyErr_Occurred())
4342 return NULL;
4343 }
4344 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4345 * 0 in a UTC timetuple regardless of what dst() says.
4346 */
4347 if (offset) {
4348 /* Subtract offset minutes & normalize. */
4349 int stat;
4350
4351 mm -= offset;
4352 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4353 if (stat < 0) {
4354 /* At the edges, it's possible we overflowed
4355 * beyond MINYEAR or MAXYEAR.
4356 */
4357 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4358 PyErr_Clear();
4359 else
4360 return NULL;
4361 }
4362 }
4363 return build_struct_time(y, m, d, hh, mm, ss, 0);
4364}
4365
Tim Peters371935f2003-02-01 01:52:50 +00004366/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004367
Tim Petersa9bc1682003-01-11 03:39:11 +00004368/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004369 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4370 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004371 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004372 */
4373static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004374datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004375{
4376 PyObject *basestate;
4377 PyObject *result = NULL;
4378
Martin v. Löwis10a60b32007-07-18 02:28:27 +00004379 basestate = PyBytes_FromStringAndSize((char *)self->data,
4380 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004381 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004382 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004383 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004384 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004385 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004386 Py_DECREF(basestate);
4387 }
4388 return result;
4389}
4390
4391static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004392datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004393{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004394 return Py_BuildValue("(ON)", Py_Type(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004395}
4396
Tim Petersa9bc1682003-01-11 03:39:11 +00004397static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004398
Tim Peters2a799bf2002-12-16 20:18:38 +00004399 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004400
Tim Petersa9bc1682003-01-11 03:39:11 +00004401 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004402 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004403 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004404
Tim Petersa9bc1682003-01-11 03:39:11 +00004405 {"utcnow", (PyCFunction)datetime_utcnow,
4406 METH_NOARGS | METH_CLASS,
4407 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4408
4409 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004410 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004411 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004412
Tim Petersa9bc1682003-01-11 03:39:11 +00004413 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4414 METH_VARARGS | METH_CLASS,
4415 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4416 "(like time.time()).")},
4417
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004418 {"strptime", (PyCFunction)datetime_strptime,
4419 METH_VARARGS | METH_CLASS,
4420 PyDoc_STR("string, format -> new datetime parsed from a string "
4421 "(like time.strptime()).")},
4422
Tim Petersa9bc1682003-01-11 03:39:11 +00004423 {"combine", (PyCFunction)datetime_combine,
4424 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4425 PyDoc_STR("date, time -> datetime with same date and time fields")},
4426
Tim Peters2a799bf2002-12-16 20:18:38 +00004427 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004428
Tim Petersa9bc1682003-01-11 03:39:11 +00004429 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4430 PyDoc_STR("Return date object with same year, month and day.")},
4431
4432 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4433 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4434
4435 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4436 PyDoc_STR("Return time object with same time and tzinfo.")},
4437
4438 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4439 PyDoc_STR("Return ctime() style string.")},
4440
4441 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004442 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4443
Tim Petersa9bc1682003-01-11 03:39:11 +00004444 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004445 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4446
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004447 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004448 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4449 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4450 "sep is used to separate the year from the time, and "
4451 "defaults to 'T'.")},
4452
Tim Petersa9bc1682003-01-11 03:39:11 +00004453 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004454 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4455
Tim Petersa9bc1682003-01-11 03:39:11 +00004456 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004457 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4458
Tim Petersa9bc1682003-01-11 03:39:11 +00004459 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004460 PyDoc_STR("Return self.tzinfo.dst(self).")},
4461
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004462 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004463 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004464
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004465 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004466 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4467
Guido van Rossum177e41a2003-01-30 22:06:23 +00004468 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4469 PyDoc_STR("__reduce__() -> (cls, state)")},
4470
Tim Peters2a799bf2002-12-16 20:18:38 +00004471 {NULL, NULL}
4472};
4473
Tim Petersa9bc1682003-01-11 03:39:11 +00004474static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004475PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4476\n\
4477The year, month and day arguments are required. tzinfo may be None, or an\n\
4478instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004479
Tim Petersa9bc1682003-01-11 03:39:11 +00004480static PyNumberMethods datetime_as_number = {
4481 datetime_add, /* nb_add */
4482 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004483 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004484 0, /* nb_remainder */
4485 0, /* nb_divmod */
4486 0, /* nb_power */
4487 0, /* nb_negative */
4488 0, /* nb_positive */
4489 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004490 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004491};
4492
Neal Norwitz227b5332006-03-22 09:28:35 +00004493static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004494 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004495 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004496 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004497 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004498 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004499 0, /* tp_print */
4500 0, /* tp_getattr */
4501 0, /* tp_setattr */
4502 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004503 (reprfunc)datetime_repr, /* tp_repr */
4504 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004505 0, /* tp_as_sequence */
4506 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004507 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004508 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004509 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004510 PyObject_GenericGetAttr, /* tp_getattro */
4511 0, /* tp_setattro */
4512 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004513 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004514 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004515 0, /* tp_traverse */
4516 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004517 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004518 0, /* tp_weaklistoffset */
4519 0, /* tp_iter */
4520 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004521 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004522 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004523 datetime_getset, /* tp_getset */
4524 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004525 0, /* tp_dict */
4526 0, /* tp_descr_get */
4527 0, /* tp_descr_set */
4528 0, /* tp_dictoffset */
4529 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004530 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004531 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004532 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004533};
4534
4535/* ---------------------------------------------------------------------------
4536 * Module methods and initialization.
4537 */
4538
4539static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004540 {NULL, NULL}
4541};
4542
Tim Peters9ddf40b2004-06-20 22:41:32 +00004543/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4544 * datetime.h.
4545 */
4546static PyDateTime_CAPI CAPI = {
4547 &PyDateTime_DateType,
4548 &PyDateTime_DateTimeType,
4549 &PyDateTime_TimeType,
4550 &PyDateTime_DeltaType,
4551 &PyDateTime_TZInfoType,
4552 new_date_ex,
4553 new_datetime_ex,
4554 new_time_ex,
4555 new_delta_ex,
4556 datetime_fromtimestamp,
4557 date_fromtimestamp
4558};
4559
4560
Tim Peters2a799bf2002-12-16 20:18:38 +00004561PyMODINIT_FUNC
4562initdatetime(void)
4563{
4564 PyObject *m; /* a module object */
4565 PyObject *d; /* its dict */
4566 PyObject *x;
4567
Tim Peters2a799bf2002-12-16 20:18:38 +00004568 m = Py_InitModule3("datetime", module_methods,
4569 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004570 if (m == NULL)
4571 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004572
4573 if (PyType_Ready(&PyDateTime_DateType) < 0)
4574 return;
4575 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4576 return;
4577 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4578 return;
4579 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4580 return;
4581 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4582 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004583
Tim Peters2a799bf2002-12-16 20:18:38 +00004584 /* timedelta values */
4585 d = PyDateTime_DeltaType.tp_dict;
4586
Tim Peters2a799bf2002-12-16 20:18:38 +00004587 x = new_delta(0, 0, 1, 0);
4588 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4589 return;
4590 Py_DECREF(x);
4591
4592 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4593 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4594 return;
4595 Py_DECREF(x);
4596
4597 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4598 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4599 return;
4600 Py_DECREF(x);
4601
4602 /* date values */
4603 d = PyDateTime_DateType.tp_dict;
4604
4605 x = new_date(1, 1, 1);
4606 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4607 return;
4608 Py_DECREF(x);
4609
4610 x = new_date(MAXYEAR, 12, 31);
4611 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4612 return;
4613 Py_DECREF(x);
4614
4615 x = new_delta(1, 0, 0, 0);
4616 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4617 return;
4618 Py_DECREF(x);
4619
Tim Peters37f39822003-01-10 03:49:02 +00004620 /* time values */
4621 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004622
Tim Peters37f39822003-01-10 03:49:02 +00004623 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004624 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4625 return;
4626 Py_DECREF(x);
4627
Tim Peters37f39822003-01-10 03:49:02 +00004628 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004629 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4630 return;
4631 Py_DECREF(x);
4632
4633 x = new_delta(0, 0, 1, 0);
4634 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4635 return;
4636 Py_DECREF(x);
4637
Tim Petersa9bc1682003-01-11 03:39:11 +00004638 /* datetime values */
4639 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004640
Tim Petersa9bc1682003-01-11 03:39:11 +00004641 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004642 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4643 return;
4644 Py_DECREF(x);
4645
Tim Petersa9bc1682003-01-11 03:39:11 +00004646 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004647 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4648 return;
4649 Py_DECREF(x);
4650
4651 x = new_delta(0, 0, 1, 0);
4652 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4653 return;
4654 Py_DECREF(x);
4655
Tim Peters2a799bf2002-12-16 20:18:38 +00004656 /* module initialization */
4657 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4658 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4659
4660 Py_INCREF(&PyDateTime_DateType);
4661 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4662
Tim Petersa9bc1682003-01-11 03:39:11 +00004663 Py_INCREF(&PyDateTime_DateTimeType);
4664 PyModule_AddObject(m, "datetime",
4665 (PyObject *)&PyDateTime_DateTimeType);
4666
4667 Py_INCREF(&PyDateTime_TimeType);
4668 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4669
Tim Peters2a799bf2002-12-16 20:18:38 +00004670 Py_INCREF(&PyDateTime_DeltaType);
4671 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4672
Tim Peters2a799bf2002-12-16 20:18:38 +00004673 Py_INCREF(&PyDateTime_TZInfoType);
4674 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4675
Tim Peters9ddf40b2004-06-20 22:41:32 +00004676 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4677 NULL);
4678 if (x == NULL)
4679 return;
4680 PyModule_AddObject(m, "datetime_CAPI", x);
4681
Tim Peters2a799bf2002-12-16 20:18:38 +00004682 /* A 4-year cycle has an extra leap day over what we'd get from
4683 * pasting together 4 single years.
4684 */
4685 assert(DI4Y == 4 * 365 + 1);
4686 assert(DI4Y == days_before_year(4+1));
4687
4688 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4689 * get from pasting together 4 100-year cycles.
4690 */
4691 assert(DI400Y == 4 * DI100Y + 1);
4692 assert(DI400Y == days_before_year(400+1));
4693
4694 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4695 * pasting together 25 4-year cycles.
4696 */
4697 assert(DI100Y == 25 * DI4Y - 1);
4698 assert(DI100Y == days_before_year(100+1));
4699
4700 us_per_us = PyInt_FromLong(1);
4701 us_per_ms = PyInt_FromLong(1000);
4702 us_per_second = PyInt_FromLong(1000000);
4703 us_per_minute = PyInt_FromLong(60000000);
4704 seconds_per_day = PyInt_FromLong(24 * 3600);
4705 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4706 us_per_minute == NULL || seconds_per_day == NULL)
4707 return;
4708
4709 /* The rest are too big for 32-bit ints, but even
4710 * us_per_week fits in 40 bits, so doubles should be exact.
4711 */
4712 us_per_hour = PyLong_FromDouble(3600000000.0);
4713 us_per_day = PyLong_FromDouble(86400000000.0);
4714 us_per_week = PyLong_FromDouble(604800000000.0);
4715 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4716 return;
4717}
Tim Petersf3615152003-01-01 21:51:37 +00004718
4719/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004720Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004721 x.n = x stripped of its timezone -- its naive time.
4722 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4723 return None
4724 x.d = x.dst(), and assuming that doesn't raise an exception or
4725 return None
4726 x.s = x's standard offset, x.o - x.d
4727
4728Now some derived rules, where k is a duration (timedelta).
4729
47301. x.o = x.s + x.d
4731 This follows from the definition of x.s.
4732
Tim Petersc5dc4da2003-01-02 17:55:03 +000047332. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004734 This is actually a requirement, an assumption we need to make about
4735 sane tzinfo classes.
4736
47373. The naive UTC time corresponding to x is x.n - x.o.
4738 This is again a requirement for a sane tzinfo class.
4739
47404. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004741 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004742
Tim Petersc5dc4da2003-01-02 17:55:03 +000047435. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004744 Again follows from how arithmetic is defined.
4745
Tim Peters8bb5ad22003-01-24 02:44:45 +00004746Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004747(meaning that the various tzinfo methods exist, and don't blow up or return
4748None when called).
4749
Tim Petersa9bc1682003-01-11 03:39:11 +00004750The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004751x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004752
4753By #3, we want
4754
Tim Peters8bb5ad22003-01-24 02:44:45 +00004755 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004756
4757The algorithm starts by attaching tz to x.n, and calling that y. So
4758x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4759becomes true; in effect, we want to solve [2] for k:
4760
Tim Peters8bb5ad22003-01-24 02:44:45 +00004761 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004762
4763By #1, this is the same as
4764
Tim Peters8bb5ad22003-01-24 02:44:45 +00004765 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004766
4767By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4768Substituting that into [3],
4769
Tim Peters8bb5ad22003-01-24 02:44:45 +00004770 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4771 k - (y+k).s - (y+k).d = 0; rearranging,
4772 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4773 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004774
Tim Peters8bb5ad22003-01-24 02:44:45 +00004775On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4776approximate k by ignoring the (y+k).d term at first. Note that k can't be
4777very large, since all offset-returning methods return a duration of magnitude
4778less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4779be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004780
4781In any case, the new value is
4782
Tim Peters8bb5ad22003-01-24 02:44:45 +00004783 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004784
Tim Peters8bb5ad22003-01-24 02:44:45 +00004785It's helpful to step back at look at [4] from a higher level: it's simply
4786mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004787
4788At this point, if
4789
Tim Peters8bb5ad22003-01-24 02:44:45 +00004790 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004791
4792we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004793at the start of daylight time. Picture US Eastern for concreteness. The wall
4794time 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 +00004795sense then. The docs ask that an Eastern tzinfo class consider such a time to
4796be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4797on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004798the only spelling that makes sense on the local wall clock.
4799
Tim Petersc5dc4da2003-01-02 17:55:03 +00004800In fact, if [5] holds at this point, we do have the standard-time spelling,
4801but that takes a bit of proof. We first prove a stronger result. What's the
4802difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004803
Tim Peters8bb5ad22003-01-24 02:44:45 +00004804 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004805
Tim Petersc5dc4da2003-01-02 17:55:03 +00004806Now
4807 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004808 (y + y.s).n = by #5
4809 y.n + y.s = since y.n = x.n
4810 x.n + y.s = since z and y are have the same tzinfo member,
4811 y.s = z.s by #2
4812 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004813
Tim Petersc5dc4da2003-01-02 17:55:03 +00004814Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004815
Tim Petersc5dc4da2003-01-02 17:55:03 +00004816 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004817 x.n - ((x.n + z.s) - z.o) = expanding
4818 x.n - x.n - z.s + z.o = cancelling
4819 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004820 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004821
Tim Petersc5dc4da2003-01-02 17:55:03 +00004822So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004823
Tim Petersc5dc4da2003-01-02 17:55:03 +00004824If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004825spelling we wanted in the endcase described above. We're done. Contrarily,
4826if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004827
Tim Petersc5dc4da2003-01-02 17:55:03 +00004828If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4829add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004830local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004831
Tim Petersc5dc4da2003-01-02 17:55:03 +00004832Let
Tim Petersf3615152003-01-01 21:51:37 +00004833
Tim Peters4fede1a2003-01-04 00:26:59 +00004834 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004835
Tim Peters4fede1a2003-01-04 00:26:59 +00004836and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004837
Tim Peters8bb5ad22003-01-24 02:44:45 +00004838 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004839
Tim Peters8bb5ad22003-01-24 02:44:45 +00004840If so, we're done. If not, the tzinfo class is insane, according to the
4841assumptions we've made. This also requires a bit of proof. As before, let's
4842compute the difference between the LHS and RHS of [8] (and skipping some of
4843the justifications for the kinds of substitutions we've done several times
4844already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004845
Tim Peters8bb5ad22003-01-24 02:44:45 +00004846 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4847 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4848 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4849 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4850 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004851 - z.o + z'.o = #1 twice
4852 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4853 z'.d - z.d
4854
4855So 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 +00004856we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4857return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004858
Tim Peters8bb5ad22003-01-24 02:44:45 +00004859How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4860a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4861would have to change the result dst() returns: we start in DST, and moving
4862a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004863
Tim Peters8bb5ad22003-01-24 02:44:45 +00004864There isn't a sane case where this can happen. The closest it gets is at
4865the end of DST, where there's an hour in UTC with no spelling in a hybrid
4866tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4867that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4868UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4869time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4870clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4871standard time. Since that's what the local clock *does*, we want to map both
4872UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004873in local time, but so it goes -- it's the way the local clock works.
4874
Tim Peters8bb5ad22003-01-24 02:44:45 +00004875When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4876so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4877z' = 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 +00004878(correctly) concludes that z' is not UTC-equivalent to x.
4879
4880Because we know z.d said z was in daylight time (else [5] would have held and
4881we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004882and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004883return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4884but the reasoning doesn't depend on the example -- it depends on there being
4885two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004886z' must be in standard time, and is the spelling we want in this case.
4887
4888Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4889concerned (because it takes z' as being in standard time rather than the
4890daylight time we intend here), but returning it gives the real-life "local
4891clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4892tz.
4893
4894When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4895the 1:MM standard time spelling we want.
4896
4897So how can this break? One of the assumptions must be violated. Two
4898possibilities:
4899
49001) [2] effectively says that y.s is invariant across all y belong to a given
4901 time zone. This isn't true if, for political reasons or continental drift,
4902 a region decides to change its base offset from UTC.
4903
49042) There may be versions of "double daylight" time where the tail end of
4905 the analysis gives up a step too early. I haven't thought about that
4906 enough to say.
4907
4908In any case, it's clear that the default fromutc() is strong enough to handle
4909"almost all" time zones: so long as the standard offset is invariant, it
4910doesn't matter if daylight time transition points change from year to year, or
4911if daylight time is skipped in some years; it doesn't matter how large or
4912small dst() may get within its bounds; and it doesn't even matter if some
4913perverse time zone returns a negative dst()). So a breaking case must be
4914pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004915--------------------------------------------------------------------------- */