blob: e513910e406b514fbec853d8ad31eefb558c9035 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
28# error "datetime.c requires that C int have at least 32 bits"
29#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
33
34/* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
38 */
39#define MAX_DELTA_DAYS 999999999
40
41/* Rename the long macros in datetime.h to more reasonable short names. */
42#define GET_YEAR PyDateTime_GET_YEAR
43#define GET_MONTH PyDateTime_GET_MONTH
44#define GET_DAY PyDateTime_GET_DAY
45#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
49
50/* Date accessors for date and datetime. */
51#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
55
56/* Date/Time accessors for datetime. */
57#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60#define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
64
65/* Time accessors for time. */
66#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73#define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
77
78/* Delta accessors for timedelta. */
79#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
82
83#define SET_TD_DAYS(o, v) ((o)->days = (v))
84#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
85#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
86
Tim Petersa032d2e2003-01-11 00:15:54 +000087/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
89 */
90#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
91
Tim Peters3f606292004-03-21 23:38:41 +000092/* M is a char or int claiming to be a valid month. The macro is equivalent
93 * to the two-sided Python test
94 * 1 <= M <= 12
95 */
96#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
97
Tim Peters2a799bf2002-12-16 20:18:38 +000098/* Forward declarations. */
99static PyTypeObject PyDateTime_DateType;
100static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000101static PyTypeObject PyDateTime_DeltaType;
102static PyTypeObject PyDateTime_TimeType;
103static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000104
105/* ---------------------------------------------------------------------------
106 * Math utilities.
107 */
108
109/* k = i+j overflows iff k differs in sign from both inputs,
110 * iff k^i has sign bit set and k^j has sign bit set,
111 * iff (k^i)&(k^j) has sign bit set.
112 */
113#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
114 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
115
116/* Compute Python divmod(x, y), returning the quotient and storing the
117 * remainder into *r. The quotient is the floor of x/y, and that's
118 * the real point of this. C will probably truncate instead (C99
119 * requires truncation; C89 left it implementation-defined).
120 * Simplification: we *require* that y > 0 here. That's appropriate
121 * for all the uses made of it. This simplifies the code and makes
122 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
123 * overflow case).
124 */
125static int
126divmod(int x, int y, int *r)
127{
128 int quo;
129
130 assert(y > 0);
131 quo = x / y;
132 *r = x - quo * y;
133 if (*r < 0) {
134 --quo;
135 *r += y;
136 }
137 assert(0 <= *r && *r < y);
138 return quo;
139}
140
Tim Peters5d644dd2003-01-02 16:32:54 +0000141/* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
143 */
144static long
145round_to_long(double x)
146{
147 if (x >= 0.0)
148 x = floor(x + 0.5);
149 else
150 x = ceil(x - 0.5);
151 return (long)x;
152}
153
Tim Peters2a799bf2002-12-16 20:18:38 +0000154/* ---------------------------------------------------------------------------
155 * General calendrical helper functions
156 */
157
158/* For each month ordinal in 1..12, the number of days in that month,
159 * and the number of days before that month in the same year. These
160 * are correct for non-leap years only.
161 */
162static int _days_in_month[] = {
163 0, /* unused; this vector uses 1-based indexing */
164 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
165};
166
167static int _days_before_month[] = {
168 0, /* unused; this vector uses 1-based indexing */
169 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
170};
171
172/* year -> 1 if leap year, else 0. */
173static int
174is_leap(int year)
175{
176 /* Cast year to unsigned. The result is the same either way, but
177 * C can generate faster code for unsigned mod than for signed
178 * mod (especially for % 4 -- a good compiler should just grab
179 * the last 2 bits when the LHS is unsigned).
180 */
181 const unsigned int ayear = (unsigned int)year;
182 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
183}
184
185/* year, month -> number of days in that month in that year */
186static int
187days_in_month(int year, int month)
188{
189 assert(month >= 1);
190 assert(month <= 12);
191 if (month == 2 && is_leap(year))
192 return 29;
193 else
194 return _days_in_month[month];
195}
196
197/* year, month -> number of days in year preceeding first day of month */
198static int
199days_before_month(int year, int month)
200{
201 int days;
202
203 assert(month >= 1);
204 assert(month <= 12);
205 days = _days_before_month[month];
206 if (month > 2 && is_leap(year))
207 ++days;
208 return days;
209}
210
211/* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
213 */
214static int
215days_before_year(int year)
216{
217 int y = year - 1;
218 /* This is incorrect if year <= 0; we really want the floor
219 * here. But so long as MINYEAR is 1, the smallest year this
220 * can see is 0 (this can happen in some normalization endcases),
221 * so we'll just special-case that.
222 */
223 assert (year >= 0);
224 if (y >= 0)
225 return y*365 + y/4 - y/100 + y/400;
226 else {
227 assert(y == -1);
228 return -366;
229 }
230}
231
232/* Number of days in 4, 100, and 400 year cycles. That these have
233 * the correct values is asserted in the module init function.
234 */
235#define DI4Y 1461 /* days_before_year(5); days in 4 years */
236#define DI100Y 36524 /* days_before_year(101); days in 100 years */
237#define DI400Y 146097 /* days_before_year(401); days in 400 years */
238
239/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
240static void
241ord_to_ymd(int ordinal, int *year, int *month, int *day)
242{
243 int n, n1, n4, n100, n400, leapyear, preceding;
244
245 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
246 * leap years repeats exactly every 400 years. The basic strategy is
247 * to find the closest 400-year boundary at or before ordinal, then
248 * work with the offset from that boundary to ordinal. Life is much
249 * clearer if we subtract 1 from ordinal first -- then the values
250 * of ordinal at 400-year boundaries are exactly those divisible
251 * by DI400Y:
252 *
253 * D M Y n n-1
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
257 * ...
258 * 30 Dec 000 -1 -2
259 * 31 Dec 000 0 -1
260 * 1 Jan 001 1 0 400-year boundary
261 * 2 Jan 001 2 1
262 * 3 Jan 001 3 2
263 * ...
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
266 */
267 assert(ordinal >= 1);
268 --ordinal;
269 n400 = ordinal / DI400Y;
270 n = ordinal % DI400Y;
271 *year = n400 * 400 + 1;
272
273 /* Now n is the (non-negative) offset, in days, from January 1 of
274 * year, to the desired date. Now compute how many 100-year cycles
275 * precede n.
276 * Note that it's possible for n100 to equal 4! In that case 4 full
277 * 100-year cycles precede the desired day, which implies the
278 * desired day is December 31 at the end of a 400-year cycle.
279 */
280 n100 = n / DI100Y;
281 n = n % DI100Y;
282
283 /* Now compute how many 4-year cycles precede it. */
284 n4 = n / DI4Y;
285 n = n % DI4Y;
286
287 /* And now how many single years. Again n1 can be 4, and again
288 * meaning that the desired day is December 31 at the end of the
289 * 4-year cycle.
290 */
291 n1 = n / 365;
292 n = n % 365;
293
294 *year += n100 * 100 + n4 * 4 + n1;
295 if (n1 == 4 || n100 == 4) {
296 assert(n == 0);
297 *year -= 1;
298 *month = 12;
299 *day = 31;
300 return;
301 }
302
303 /* Now the year is correct, and n is the offset from January 1. We
304 * find the month via an estimate that's either exact or one too
305 * large.
306 */
307 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
308 assert(leapyear == is_leap(*year));
309 *month = (n + 50) >> 5;
310 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
311 if (preceding > n) {
312 /* estimate is too large */
313 *month -= 1;
314 preceding -= days_in_month(*year, *month);
315 }
316 n -= preceding;
317 assert(0 <= n);
318 assert(n < days_in_month(*year, *month));
319
320 *day = n + 1;
321}
322
323/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
324static int
325ymd_to_ord(int year, int month, int day)
326{
327 return days_before_year(year) + days_before_month(year, month) + day;
328}
329
330/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
331static int
332weekday(int year, int month, int day)
333{
334 return (ymd_to_ord(year, month, day) + 6) % 7;
335}
336
337/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
338 * first calendar week containing a Thursday.
339 */
340static int
341iso_week1_monday(int year)
342{
343 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
344 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
345 int first_weekday = (first_day + 6) % 7;
346 /* ordinal of closest Monday at or before 1/1 */
347 int week1_monday = first_day - first_weekday;
348
349 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
350 week1_monday += 7;
351 return week1_monday;
352}
353
354/* ---------------------------------------------------------------------------
355 * Range checkers.
356 */
357
358/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
360 */
361static int
362check_delta_day_range(int days)
363{
364 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
365 return 0;
366 PyErr_Format(PyExc_OverflowError,
367 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000368 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000369 return -1;
370}
371
372/* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
374 */
375static int
376check_date_args(int year, int month, int day)
377{
378
379 if (year < MINYEAR || year > MAXYEAR) {
380 PyErr_SetString(PyExc_ValueError,
381 "year is out of range");
382 return -1;
383 }
384 if (month < 1 || month > 12) {
385 PyErr_SetString(PyExc_ValueError,
386 "month must be in 1..12");
387 return -1;
388 }
389 if (day < 1 || day > days_in_month(year, month)) {
390 PyErr_SetString(PyExc_ValueError,
391 "day is out of range for month");
392 return -1;
393 }
394 return 0;
395}
396
397/* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_time_args(int h, int m, int s, int us)
402{
403 if (h < 0 || h > 23) {
404 PyErr_SetString(PyExc_ValueError,
405 "hour must be in 0..23");
406 return -1;
407 }
408 if (m < 0 || m > 59) {
409 PyErr_SetString(PyExc_ValueError,
410 "minute must be in 0..59");
411 return -1;
412 }
413 if (s < 0 || s > 59) {
414 PyErr_SetString(PyExc_ValueError,
415 "second must be in 0..59");
416 return -1;
417 }
418 if (us < 0 || us > 999999) {
419 PyErr_SetString(PyExc_ValueError,
420 "microsecond must be in 0..999999");
421 return -1;
422 }
423 return 0;
424}
425
426/* ---------------------------------------------------------------------------
427 * Normalization utilities.
428 */
429
430/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
431 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
432 * at least factor, enough of *lo is converted into "hi" units so that
433 * 0 <= *lo < factor. The input values must be such that int overflow
434 * is impossible.
435 */
436static void
437normalize_pair(int *hi, int *lo, int factor)
438{
439 assert(factor > 0);
440 assert(lo != hi);
441 if (*lo < 0 || *lo >= factor) {
442 const int num_hi = divmod(*lo, factor, lo);
443 const int new_hi = *hi + num_hi;
444 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
445 *hi = new_hi;
446 }
447 assert(0 <= *lo && *lo < factor);
448}
449
450/* Fiddle days (d), seconds (s), and microseconds (us) so that
451 * 0 <= *s < 24*3600
452 * 0 <= *us < 1000000
453 * The input values must be such that the internals don't overflow.
454 * The way this routine is used, we don't get close.
455 */
456static void
457normalize_d_s_us(int *d, int *s, int *us)
458{
459 if (*us < 0 || *us >= 1000000) {
460 normalize_pair(s, us, 1000000);
461 /* |s| can't be bigger than about
462 * |original s| + |original us|/1000000 now.
463 */
464
465 }
466 if (*s < 0 || *s >= 24*3600) {
467 normalize_pair(d, s, 24*3600);
468 /* |d| can't be bigger than about
469 * |original d| +
470 * (|original s| + |original us|/1000000) / (24*3600) now.
471 */
472 }
473 assert(0 <= *s && *s < 24*3600);
474 assert(0 <= *us && *us < 1000000);
475}
476
477/* Fiddle years (y), months (m), and days (d) so that
478 * 1 <= *m <= 12
479 * 1 <= *d <= days_in_month(*y, *m)
480 * The input values must be such that the internals don't overflow.
481 * The way this routine is used, we don't get close.
482 */
483static void
484normalize_y_m_d(int *y, int *m, int *d)
485{
486 int dim; /* # of days in month */
487
488 /* This gets muddy: the proper range for day can't be determined
489 * without knowing the correct month and year, but if day is, e.g.,
490 * plus or minus a million, the current month and year values make
491 * no sense (and may also be out of bounds themselves).
492 * Saying 12 months == 1 year should be non-controversial.
493 */
494 if (*m < 1 || *m > 12) {
495 --*m;
496 normalize_pair(y, m, 12);
497 ++*m;
498 /* |y| can't be bigger than about
499 * |original y| + |original m|/12 now.
500 */
501 }
502 assert(1 <= *m && *m <= 12);
503
504 /* Now only day can be out of bounds (year may also be out of bounds
505 * for a datetime object, but we don't care about that here).
506 * If day is out of bounds, what to do is arguable, but at least the
507 * method here is principled and explainable.
508 */
509 dim = days_in_month(*y, *m);
510 if (*d < 1 || *d > dim) {
511 /* Move day-1 days from the first of the month. First try to
512 * get off cheap if we're only one day out of range
513 * (adjustments for timezone alone can't be worse than that).
514 */
515 if (*d == 0) {
516 --*m;
517 if (*m > 0)
518 *d = days_in_month(*y, *m);
519 else {
520 --*y;
521 *m = 12;
522 *d = 31;
523 }
524 }
525 else if (*d == dim + 1) {
526 /* move forward a day */
527 ++*m;
528 *d = 1;
529 if (*m > 12) {
530 *m = 1;
531 ++*y;
532 }
533 }
534 else {
535 int ordinal = ymd_to_ord(*y, *m, 1) +
536 *d - 1;
537 ord_to_ymd(ordinal, y, m, d);
538 }
539 }
540 assert(*m > 0);
541 assert(*d > 0);
542}
543
544/* Fiddle out-of-bounds months and days so that the result makes some kind
545 * of sense. The parameters are both inputs and outputs. Returns < 0 on
546 * failure, where failure means the adjusted year is out of bounds.
547 */
548static int
549normalize_date(int *year, int *month, int *day)
550{
551 int result;
552
553 normalize_y_m_d(year, month, day);
554 if (MINYEAR <= *year && *year <= MAXYEAR)
555 result = 0;
556 else {
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 result = -1;
560 }
561 return result;
562}
563
564/* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
566 */
567static int
568normalize_datetime(int *year, int *month, int *day,
569 int *hour, int *minute, int *second,
570 int *microsecond)
571{
572 normalize_pair(second, microsecond, 1000000);
573 normalize_pair(minute, second, 60);
574 normalize_pair(hour, minute, 60);
575 normalize_pair(day, hour, 24);
576 return normalize_date(year, month, day);
577}
578
579/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000580 * Basic object allocation: tp_alloc implementations. These allocate
581 * Python objects of the right size and type, and do the Python object-
582 * initialization bit. If there's not enough memory, they return NULL after
583 * setting MemoryError. All data members remain uninitialized trash.
584 *
585 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000586 * member is needed. This is ugly, imprecise, and possibly insecure.
587 * tp_basicsize for the time and datetime types is set to the size of the
588 * struct that has room for the tzinfo member, so subclasses in Python will
589 * allocate enough space for a tzinfo member whether or not one is actually
590 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
591 * part is that PyType_GenericAlloc() (which subclasses in Python end up
592 * using) just happens today to effectively ignore the nitems argument
593 * when tp_itemsize is 0, which it is for these type objects. If that
594 * changes, perhaps the callers of tp_alloc slots in this file should
595 * be changed to force a 0 nitems argument unless the type being allocated
596 * is a base type implemented in this file (so that tp_alloc is time_alloc
597 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000598 */
599
600static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000601time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000602{
603 PyObject *self;
604
605 self = (PyObject *)
606 PyObject_MALLOC(aware ?
607 sizeof(PyDateTime_Time) :
608 sizeof(_PyDateTime_BaseTime));
609 if (self == NULL)
610 return (PyObject *)PyErr_NoMemory();
611 PyObject_INIT(self, type);
612 return self;
613}
614
615static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000616datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000617{
618 PyObject *self;
619
620 self = (PyObject *)
621 PyObject_MALLOC(aware ?
622 sizeof(PyDateTime_DateTime) :
623 sizeof(_PyDateTime_BaseDateTime));
624 if (self == NULL)
625 return (PyObject *)PyErr_NoMemory();
626 PyObject_INIT(self, type);
627 return self;
628}
629
630/* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
633 */
634
635/* For date and datetime. */
636static void
637set_date_fields(PyDateTime_Date *self, int y, int m, int d)
638{
639 self->hashcode = -1;
640 SET_YEAR(self, y);
641 SET_MONTH(self, m);
642 SET_DAY(self, d);
643}
644
645/* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
647 */
648
649/* Create a date instance with no range checking. */
650static PyObject *
651new_date_ex(int year, int month, int day, PyTypeObject *type)
652{
653 PyDateTime_Date *self;
654
655 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
656 if (self != NULL)
657 set_date_fields(self, year, month, day);
658 return (PyObject *) self;
659}
660
661#define new_date(year, month, day) \
662 new_date_ex(year, month, day, &PyDateTime_DateType)
663
664/* Create a datetime instance with no range checking. */
665static PyObject *
666new_datetime_ex(int year, int month, int day, int hour, int minute,
667 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
668{
669 PyDateTime_DateTime *self;
670 char aware = tzinfo != Py_None;
671
672 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
673 if (self != NULL) {
674 self->hastzinfo = aware;
675 set_date_fields((PyDateTime_Date *)self, year, month, day);
676 DATE_SET_HOUR(self, hour);
677 DATE_SET_MINUTE(self, minute);
678 DATE_SET_SECOND(self, second);
679 DATE_SET_MICROSECOND(self, usecond);
680 if (aware) {
681 Py_INCREF(tzinfo);
682 self->tzinfo = tzinfo;
683 }
684 }
685 return (PyObject *)self;
686}
687
688#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
689 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
690 &PyDateTime_DateTimeType)
691
692/* Create a time instance with no range checking. */
693static PyObject *
694new_time_ex(int hour, int minute, int second, int usecond,
695 PyObject *tzinfo, PyTypeObject *type)
696{
697 PyDateTime_Time *self;
698 char aware = tzinfo != Py_None;
699
700 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
701 if (self != NULL) {
702 self->hastzinfo = aware;
703 self->hashcode = -1;
704 TIME_SET_HOUR(self, hour);
705 TIME_SET_MINUTE(self, minute);
706 TIME_SET_SECOND(self, second);
707 TIME_SET_MICROSECOND(self, usecond);
708 if (aware) {
709 Py_INCREF(tzinfo);
710 self->tzinfo = tzinfo;
711 }
712 }
713 return (PyObject *)self;
714}
715
716#define new_time(hh, mm, ss, us, tzinfo) \
717 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
718
719/* Create a timedelta instance. Normalize the members iff normalize is
720 * true. Passing false is a speed optimization, if you know for sure
721 * that seconds and microseconds are already in their proper ranges. In any
722 * case, raises OverflowError and returns NULL if the normalized days is out
723 * of range).
724 */
725static PyObject *
726new_delta_ex(int days, int seconds, int microseconds, int normalize,
727 PyTypeObject *type)
728{
729 PyDateTime_Delta *self;
730
731 if (normalize)
732 normalize_d_s_us(&days, &seconds, &microseconds);
733 assert(0 <= seconds && seconds < 24*3600);
734 assert(0 <= microseconds && microseconds < 1000000);
735
736 if (check_delta_day_range(days) < 0)
737 return NULL;
738
739 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
740 if (self != NULL) {
741 self->hashcode = -1;
742 SET_TD_DAYS(self, days);
743 SET_TD_SECONDS(self, seconds);
744 SET_TD_MICROSECONDS(self, microseconds);
745 }
746 return (PyObject *) self;
747}
748
749#define new_delta(d, s, us, normalize) \
750 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
751
752/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000753 * tzinfo helpers.
754 */
755
Tim Peters855fe882002-12-22 03:43:39 +0000756/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
758 */
759static int
760check_tzinfo_subclass(PyObject *p)
761{
762 if (p == Py_None || PyTZInfo_Check(p))
763 return 0;
764 PyErr_Format(PyExc_TypeError,
765 "tzinfo argument must be None or of a tzinfo subclass, "
766 "not type '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000767 Py_Type(p)->tp_name);
Tim Peters855fe882002-12-22 03:43:39 +0000768 return -1;
769}
770
Tim Petersbad8ff02002-12-30 20:52:32 +0000771/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000772 * If tzinfo is None, returns None.
773 */
774static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000775call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000776{
777 PyObject *result;
778
Tim Petersbad8ff02002-12-30 20:52:32 +0000779 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
784 }
785 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000787 return result;
788}
789
Tim Peters2a799bf2002-12-16 20:18:38 +0000790/* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
793 */
794static PyObject *
795get_tzinfo_member(PyObject *self)
796{
797 PyObject *tzinfo = NULL;
798
Tim Petersa9bc1682003-01-11 03:39:11 +0000799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000801 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
804 return tzinfo;
805}
806
Tim Petersbad8ff02002-12-30 20:52:32 +0000807/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * Else *none is set to 0 and the integer method result is returned.
814 */
815static int
816call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
818{
819 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000820 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000821
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
825
826 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 if (u == NULL)
829 return -1;
830
Tim Peters27362852002-12-23 16:17:39 +0000831 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 result = 0;
833 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000834 }
Tim Peters855fe882002-12-22 03:43:39 +0000835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
842 */
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000851 }
852 }
853 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000854 else {
855 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000856 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000857 "timedelta, not '%s'",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000858 name, Py_Type(u)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 }
860
Tim Peters2a799bf2002-12-16 20:18:38 +0000861 Py_DECREF(u);
862 if (result < -1439 || result > 1439) {
863 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000864 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000865 "-1439 .. 1439",
866 name, result);
867 result = -1;
868 }
Tim Peters397301e2003-01-02 21:28:08 +0000869 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000870}
871
872/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
873 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
874 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000875 * doesn't return None or timedelta, TypeError is raised and this returns -1.
876 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
877 * # of minutes), ValueError is raised and this returns -1. Else *none is
878 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000879 */
880static int
881call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
882{
883 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
884}
885
Tim Petersbad8ff02002-12-30 20:52:32 +0000886/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
887 */
Tim Peters855fe882002-12-22 03:43:39 +0000888static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000889offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000890 PyObject *result;
891
Tim Petersbad8ff02002-12-30 20:52:32 +0000892 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000893 if (tzinfo == Py_None) {
894 result = Py_None;
895 Py_INCREF(result);
896 }
897 else {
898 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000899 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
900 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000901 if (offset < 0 && PyErr_Occurred())
902 return NULL;
903 if (none) {
904 result = Py_None;
905 Py_INCREF(result);
906 }
907 else
908 result = new_delta(0, offset * 60, 0, 1);
909 }
910 return result;
911}
912
Tim Peters2a799bf2002-12-16 20:18:38 +0000913/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If dst()
915 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000916 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000917 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000918 * ValueError is raised and this returns -1. Else *none is set to 0 and
919 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000920 */
921static int
922call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
923{
924 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
925}
926
Tim Petersbad8ff02002-12-30 20:52:32 +0000927/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000928 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000929 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000930 * returns NULL. If the result is a string, we ensure it is a Unicode
931 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000932 */
933static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000934call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000935{
936 PyObject *result;
937
938 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000939 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000940 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000941
Tim Peters855fe882002-12-22 03:43:39 +0000942 if (tzinfo == Py_None) {
943 result = Py_None;
944 Py_INCREF(result);
945 }
946 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000947 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000948
Guido van Rossume3d1d412007-05-23 21:24:35 +0000949 if (result != NULL && result != Py_None) {
Guido van Rossumfd53fd62007-08-24 04:05:13 +0000950 if (!PyUnicode_Check(result)) {
Guido van Rossume3d1d412007-05-23 21:24:35 +0000951 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
952 "return None or a string, not '%s'",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +0000953 Py_Type(result)->tp_name);
Guido van Rossume3d1d412007-05-23 21:24:35 +0000954 Py_DECREF(result);
955 result = NULL;
956 }
957 else if (!PyUnicode_Check(result)) {
958 PyObject *temp = PyUnicode_FromObject(result);
959 Py_DECREF(result);
960 result = temp;
961 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000962 }
963 return result;
964}
965
966typedef enum {
967 /* an exception has been set; the caller should pass it on */
968 OFFSET_ERROR,
969
Tim Petersa9bc1682003-01-11 03:39:11 +0000970 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000971 OFFSET_UNKNOWN,
972
973 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000974 * datetime with !hastzinfo
975 * datetime with None tzinfo,
976 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000977 * time with !hastzinfo
978 * time with None tzinfo,
979 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 */
981 OFFSET_NAIVE,
982
Tim Petersa9bc1682003-01-11 03:39:11 +0000983 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000984 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000985} naivety;
986
Tim Peters14b69412002-12-22 18:10:22 +0000987/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000988 * the "naivety" typedef for details. If the type is aware, *offset is set
989 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000990 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 */
993static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000994classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000995{
996 int none;
997 PyObject *tzinfo;
998
Tim Peterse39a80c2002-12-30 21:28:52 +0000999 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001000 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +00001001 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (tzinfo == Py_None)
1003 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +00001004 if (tzinfo == NULL) {
1005 /* note that a datetime passes the PyDate_Check test */
1006 return (PyTime_Check(op) || PyDate_Check(op)) ?
1007 OFFSET_NAIVE : OFFSET_UNKNOWN;
1008 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001009 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001010 if (*offset == -1 && PyErr_Occurred())
1011 return OFFSET_ERROR;
1012 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1013}
1014
Tim Peters00237032002-12-27 02:21:51 +00001015/* Classify two objects as to whether they're naive or offset-aware.
1016 * This isn't quite the same as calling classify_utcoffset() twice: for
1017 * binary operations (comparison and subtraction), we generally want to
1018 * ignore the tzinfo members if they're identical. This is by design,
1019 * so that results match "naive" expectations when mixing objects from a
1020 * single timezone. So in that case, this sets both offsets to 0 and
1021 * both naiveties to OFFSET_NAIVE.
1022 * The function returns 0 if everything's OK, and -1 on error.
1023 */
1024static int
1025classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001026 PyObject *tzinfoarg1,
1027 PyObject *o2, int *offset2, naivety *n2,
1028 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001029{
1030 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1031 *offset1 = *offset2 = 0;
1032 *n1 = *n2 = OFFSET_NAIVE;
1033 }
1034 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001035 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001036 if (*n1 == OFFSET_ERROR)
1037 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001038 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001039 if (*n2 == OFFSET_ERROR)
1040 return -1;
1041 }
1042 return 0;
1043}
1044
Tim Peters2a799bf2002-12-16 20:18:38 +00001045/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1046 * stuff
1047 * ", tzinfo=" + repr(tzinfo)
1048 * before the closing ")".
1049 */
1050static PyObject *
1051append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1052{
1053 PyObject *temp;
1054
Walter Dörwald1ab83302007-05-18 17:15:44 +00001055 assert(PyUnicode_Check(repr));
Tim Peters2a799bf2002-12-16 20:18:38 +00001056 assert(tzinfo);
1057 if (tzinfo == Py_None)
1058 return repr;
1059 /* Get rid of the trailing ')'. */
Walter Dörwald1ab83302007-05-18 17:15:44 +00001060 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1061 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1062 PyUnicode_GET_SIZE(repr) - 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001063 Py_DECREF(repr);
1064 if (temp == NULL)
1065 return NULL;
Walter Dörwald517bcfe2007-05-23 20:45:05 +00001066 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1067 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00001068 return repr;
1069}
1070
1071/* ---------------------------------------------------------------------------
1072 * String format helpers.
1073 */
1074
1075static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001076format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001077{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001078 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001079 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1080 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001081 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001082 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1083 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1084 };
1085
Tim Peters2a799bf2002-12-16 20:18:38 +00001086 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1087
Walter Dörwald4af32b32007-05-31 16:19:50 +00001088 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1089 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1090 GET_DAY(date), hours, minutes, seconds,
1091 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001092}
1093
1094/* Add an hours & minutes UTC offset string to buf. buf has no more than
1095 * buflen bytes remaining. The UTC offset is gotten by calling
1096 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1097 * *buf, and that's all. Else the returned value is checked for sanity (an
1098 * integer in range), and if that's OK it's converted to an hours & minutes
1099 * string of the form
1100 * sign HH sep MM
1101 * Returns 0 if everything is OK. If the return value from utcoffset() is
1102 * bogus, an appropriate exception is set and -1 is returned.
1103 */
1104static int
Tim Peters328fff72002-12-20 01:31:27 +00001105format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001106 PyObject *tzinfo, PyObject *tzinfoarg)
1107{
1108 int offset;
1109 int hours;
1110 int minutes;
1111 char sign;
1112 int none;
1113
1114 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1115 if (offset == -1 && PyErr_Occurred())
1116 return -1;
1117 if (none) {
1118 *buf = '\0';
1119 return 0;
1120 }
1121 sign = '+';
1122 if (offset < 0) {
1123 sign = '-';
1124 offset = - offset;
1125 }
1126 hours = divmod(offset, 60, &minutes);
1127 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1128 return 0;
1129}
1130
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001131static PyObject *
1132make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1133{
Neal Norwitzaea70e02007-08-12 04:32:26 +00001134 PyObject *temp;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001135 PyObject *tzinfo = get_tzinfo_member(object);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001136 PyObject *Zreplacement = PyBytes_FromStringAndSize("", 0);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001137 if (Zreplacement == NULL)
1138 return NULL;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001139 if (tzinfo == Py_None || tzinfo == NULL)
1140 return Zreplacement;
1141
1142 assert(tzinfoarg != NULL);
1143 temp = call_tzname(tzinfo, tzinfoarg);
1144 if (temp == NULL)
1145 goto Error;
1146 if (temp == Py_None) {
1147 Py_DECREF(temp);
1148 return Zreplacement;
1149 }
1150
1151 assert(PyUnicode_Check(temp));
1152 /* Since the tzname is getting stuffed into the
1153 * format, we have to double any % signs so that
1154 * strftime doesn't treat them as format codes.
1155 */
1156 Py_DECREF(Zreplacement);
1157 Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1158 Py_DECREF(temp);
1159 if (Zreplacement == NULL)
1160 return NULL;
1161 if (PyUnicode_Check(Zreplacement)) {
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001162 PyObject *tmp = PyUnicode_AsUTF8String(Zreplacement);
1163 if (tmp == NULL)
Neal Norwitzaea70e02007-08-12 04:32:26 +00001164 return NULL;
Guido van Rossum06610092007-08-16 21:02:22 +00001165 Py_DECREF(Zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001166 Zreplacement = tmp;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001167 }
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001168 if (!PyBytes_Check(Zreplacement)) {
Neal Norwitzaea70e02007-08-12 04:32:26 +00001169 PyErr_SetString(PyExc_TypeError,
1170 "tzname.replace() did not return a string");
1171 goto Error;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001172 }
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 Rossumfd53fd62007-08-24 04:05:13 +00001210 assert(PyUnicode_Check(format));
1211 /* Convert the input format to a C string and size */
1212 pin = PyUnicode_AsString(format);
1213 if(!pin)
1214 return NULL;
1215 flen = PyUnicode_GetSize(format);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001216
Tim Peters2a799bf2002-12-16 20:18:38 +00001217
Tim Petersd6844152002-12-22 20:58:42 +00001218 /* Give up if the year is before 1900.
1219 * Python strftime() plays games with the year, and different
1220 * games depending on whether envar PYTHON2K is set. This makes
1221 * years before 1900 a nightmare, even if the platform strftime
1222 * supports them (and not all do).
1223 * We could get a lot farther here by avoiding Python's strftime
1224 * wrapper and calling the C strftime() directly, but that isn't
1225 * an option in the Python implementation of this module.
1226 */
1227 {
1228 long year;
1229 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1230 if (pyyear == NULL) return NULL;
1231 assert(PyInt_Check(pyyear));
1232 year = PyInt_AsLong(pyyear);
1233 Py_DECREF(pyyear);
1234 if (year < 1900) {
1235 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1236 "1900; the datetime strftime() "
1237 "methods require year >= 1900",
1238 year);
1239 return NULL;
1240 }
1241 }
1242
Tim Peters2a799bf2002-12-16 20:18:38 +00001243 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001244 * a new format. Since computing the replacements for those codes
1245 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001246 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001247 totalnew = flen + 1; /* realistic if no %z/%Z */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001248 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
Tim Peters2a799bf2002-12-16 20:18:38 +00001249 if (newfmt == NULL) goto Done;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001250 pnew = PyBytes_AsString(newfmt);
Tim Peters2a799bf2002-12-16 20:18:38 +00001251 usednew = 0;
1252
Tim Peters2a799bf2002-12-16 20:18:38 +00001253 while ((ch = *pin++) != '\0') {
1254 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001255 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001256 ntoappend = 1;
1257 }
1258 else if ((ch = *pin++) == '\0') {
1259 /* There's a lone trailing %; doesn't make sense. */
1260 PyErr_SetString(PyExc_ValueError, "strftime format "
1261 "ends with raw %");
1262 goto Done;
1263 }
1264 /* A % has been seen and ch is the character after it. */
1265 else if (ch == 'z') {
1266 if (zreplacement == NULL) {
1267 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001268 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001269 PyObject *tzinfo = get_tzinfo_member(object);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001270 zreplacement = PyBytes_FromStringAndSize("", 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001271 if (zreplacement == NULL) goto Done;
1272 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001273 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001274 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001275 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001276 "",
1277 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001278 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001279 goto Done;
1280 Py_DECREF(zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001281 zreplacement =
1282 PyBytes_FromStringAndSize(buf,
1283 strlen(buf));
1284 if (zreplacement == NULL)
1285 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001286 }
1287 }
1288 assert(zreplacement != NULL);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001289 ptoappend = PyBytes_AS_STRING(zreplacement);
1290 ntoappend = PyBytes_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001291 }
1292 else if (ch == 'Z') {
1293 /* format tzname */
1294 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001295 Zreplacement = make_Zreplacement(object,
1296 tzinfoarg);
1297 if (Zreplacement == NULL)
1298 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001299 }
1300 assert(Zreplacement != NULL);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001301 assert(PyBytes_Check(Zreplacement));
1302 ptoappend = PyBytes_AS_STRING(Zreplacement);
1303 ntoappend = PyBytes_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001304 }
1305 else {
Tim Peters328fff72002-12-20 01:31:27 +00001306 /* percent followed by neither z nor Z */
1307 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001308 ntoappend = 2;
1309 }
1310
1311 /* Append the ntoappend chars starting at ptoappend to
1312 * the new format.
1313 */
Tim Peters2a799bf2002-12-16 20:18:38 +00001314 if (ntoappend == 0)
1315 continue;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001316 assert(ptoappend != NULL);
1317 assert(ntoappend > 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001318 while (usednew + ntoappend > totalnew) {
1319 int bigger = totalnew << 1;
1320 if ((bigger >> 1) != totalnew) { /* overflow */
1321 PyErr_NoMemory();
1322 goto Done;
1323 }
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001324 if (PyBytes_Resize(newfmt, bigger) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001325 goto Done;
1326 totalnew = bigger;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001327 pnew = PyBytes_AsString(newfmt) + usednew;
Tim Peters2a799bf2002-12-16 20:18:38 +00001328 }
1329 memcpy(pnew, ptoappend, ntoappend);
1330 pnew += ntoappend;
1331 usednew += ntoappend;
1332 assert(usednew <= totalnew);
1333 } /* end while() */
1334
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001335 if (PyBytes_Resize(newfmt, usednew) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001336 goto Done;
1337 {
1338 PyObject *time = PyImport_ImportModule("time");
1339 if (time == NULL)
1340 goto Done;
1341 result = PyObject_CallMethod(time, "strftime", "OO",
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001342 PyUnicode_FromString(PyBytes_AS_STRING(newfmt)), timetuple);
Tim Peters2a799bf2002-12-16 20:18:38 +00001343 Py_DECREF(time);
1344 }
1345 Done:
1346 Py_XDECREF(zreplacement);
1347 Py_XDECREF(Zreplacement);
1348 Py_XDECREF(newfmt);
1349 return result;
1350}
1351
Tim Peters2a799bf2002-12-16 20:18:38 +00001352/* ---------------------------------------------------------------------------
1353 * Wrap functions from the time module. These aren't directly available
1354 * from C. Perhaps they should be.
1355 */
1356
1357/* Call time.time() and return its result (a Python float). */
1358static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001359time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001360{
1361 PyObject *result = NULL;
1362 PyObject *time = PyImport_ImportModule("time");
1363
1364 if (time != NULL) {
1365 result = PyObject_CallMethod(time, "time", "()");
1366 Py_DECREF(time);
1367 }
1368 return result;
1369}
1370
1371/* Build a time.struct_time. The weekday and day number are automatically
1372 * computed from the y,m,d args.
1373 */
1374static PyObject *
1375build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1376{
1377 PyObject *time;
1378 PyObject *result = NULL;
1379
1380 time = PyImport_ImportModule("time");
1381 if (time != NULL) {
1382 result = PyObject_CallMethod(time, "struct_time",
1383 "((iiiiiiiii))",
1384 y, m, d,
1385 hh, mm, ss,
1386 weekday(y, m, d),
1387 days_before_month(y, m) + d,
1388 dstflag);
1389 Py_DECREF(time);
1390 }
1391 return result;
1392}
1393
1394/* ---------------------------------------------------------------------------
1395 * Miscellaneous helpers.
1396 */
1397
Guido van Rossum19960592006-08-24 17:29:38 +00001398/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001399 * The comparisons here all most naturally compute a cmp()-like result.
1400 * This little helper turns that into a bool result for rich comparisons.
1401 */
1402static PyObject *
1403diff_to_bool(int diff, int op)
1404{
1405 PyObject *result;
1406 int istrue;
1407
1408 switch (op) {
1409 case Py_EQ: istrue = diff == 0; break;
1410 case Py_NE: istrue = diff != 0; break;
1411 case Py_LE: istrue = diff <= 0; break;
1412 case Py_GE: istrue = diff >= 0; break;
1413 case Py_LT: istrue = diff < 0; break;
1414 case Py_GT: istrue = diff > 0; break;
1415 default:
1416 assert(! "op unknown");
1417 istrue = 0; /* To shut up compiler */
1418 }
1419 result = istrue ? Py_True : Py_False;
1420 Py_INCREF(result);
1421 return result;
1422}
1423
Tim Peters07534a62003-02-07 22:50:28 +00001424/* Raises a "can't compare" TypeError and returns NULL. */
1425static PyObject *
1426cmperror(PyObject *a, PyObject *b)
1427{
1428 PyErr_Format(PyExc_TypeError,
1429 "can't compare %s to %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001430 Py_Type(a)->tp_name, Py_Type(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001431 return NULL;
1432}
1433
Tim Peters2a799bf2002-12-16 20:18:38 +00001434/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001435 * Cached Python objects; these are set by the module init function.
1436 */
1437
1438/* Conversion factors. */
1439static PyObject *us_per_us = NULL; /* 1 */
1440static PyObject *us_per_ms = NULL; /* 1000 */
1441static PyObject *us_per_second = NULL; /* 1000000 */
1442static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1443static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1444static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1445static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1446static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1447
Tim Peters2a799bf2002-12-16 20:18:38 +00001448/* ---------------------------------------------------------------------------
1449 * Class implementations.
1450 */
1451
1452/*
1453 * PyDateTime_Delta implementation.
1454 */
1455
1456/* Convert a timedelta to a number of us,
1457 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1458 * as a Python int or long.
1459 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1460 * due to ubiquitous overflow possibilities.
1461 */
1462static PyObject *
1463delta_to_microseconds(PyDateTime_Delta *self)
1464{
1465 PyObject *x1 = NULL;
1466 PyObject *x2 = NULL;
1467 PyObject *x3 = NULL;
1468 PyObject *result = NULL;
1469
1470 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1471 if (x1 == NULL)
1472 goto Done;
1473 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1474 if (x2 == NULL)
1475 goto Done;
1476 Py_DECREF(x1);
1477 x1 = NULL;
1478
1479 /* x2 has days in seconds */
1480 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1481 if (x1 == NULL)
1482 goto Done;
1483 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1484 if (x3 == NULL)
1485 goto Done;
1486 Py_DECREF(x1);
1487 Py_DECREF(x2);
1488 x1 = x2 = NULL;
1489
1490 /* x3 has days+seconds in seconds */
1491 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1492 if (x1 == NULL)
1493 goto Done;
1494 Py_DECREF(x3);
1495 x3 = NULL;
1496
1497 /* x1 has days+seconds in us */
1498 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1499 if (x2 == NULL)
1500 goto Done;
1501 result = PyNumber_Add(x1, x2);
1502
1503Done:
1504 Py_XDECREF(x1);
1505 Py_XDECREF(x2);
1506 Py_XDECREF(x3);
1507 return result;
1508}
1509
1510/* Convert a number of us (as a Python int or long) to a timedelta.
1511 */
1512static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001513microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001514{
1515 int us;
1516 int s;
1517 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001518 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001519
1520 PyObject *tuple = NULL;
1521 PyObject *num = NULL;
1522 PyObject *result = NULL;
1523
1524 tuple = PyNumber_Divmod(pyus, us_per_second);
1525 if (tuple == NULL)
1526 goto Done;
1527
1528 num = PyTuple_GetItem(tuple, 1); /* us */
1529 if (num == NULL)
1530 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001531 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001532 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001533 if (temp == -1 && PyErr_Occurred())
1534 goto Done;
1535 assert(0 <= temp && temp < 1000000);
1536 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001537 if (us < 0) {
1538 /* The divisor was positive, so this must be an error. */
1539 assert(PyErr_Occurred());
1540 goto Done;
1541 }
1542
1543 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1544 if (num == NULL)
1545 goto Done;
1546 Py_INCREF(num);
1547 Py_DECREF(tuple);
1548
1549 tuple = PyNumber_Divmod(num, seconds_per_day);
1550 if (tuple == NULL)
1551 goto Done;
1552 Py_DECREF(num);
1553
1554 num = PyTuple_GetItem(tuple, 1); /* seconds */
1555 if (num == NULL)
1556 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001557 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001558 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001559 if (temp == -1 && PyErr_Occurred())
1560 goto Done;
1561 assert(0 <= temp && temp < 24*3600);
1562 s = (int)temp;
1563
Tim Peters2a799bf2002-12-16 20:18:38 +00001564 if (s < 0) {
1565 /* The divisor was positive, so this must be an error. */
1566 assert(PyErr_Occurred());
1567 goto Done;
1568 }
1569
1570 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1571 if (num == NULL)
1572 goto Done;
1573 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001574 temp = PyLong_AsLong(num);
1575 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001576 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001577 d = (int)temp;
1578 if ((long)d != temp) {
1579 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1580 "large to fit in a C int");
1581 goto Done;
1582 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001583 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001584
1585Done:
1586 Py_XDECREF(tuple);
1587 Py_XDECREF(num);
1588 return result;
1589}
1590
Tim Petersb0c854d2003-05-17 15:57:00 +00001591#define microseconds_to_delta(pymicros) \
1592 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1593
Tim Peters2a799bf2002-12-16 20:18:38 +00001594static PyObject *
1595multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1596{
1597 PyObject *pyus_in;
1598 PyObject *pyus_out;
1599 PyObject *result;
1600
1601 pyus_in = delta_to_microseconds(delta);
1602 if (pyus_in == NULL)
1603 return NULL;
1604
1605 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1606 Py_DECREF(pyus_in);
1607 if (pyus_out == NULL)
1608 return NULL;
1609
1610 result = microseconds_to_delta(pyus_out);
1611 Py_DECREF(pyus_out);
1612 return result;
1613}
1614
1615static PyObject *
1616divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1617{
1618 PyObject *pyus_in;
1619 PyObject *pyus_out;
1620 PyObject *result;
1621
1622 pyus_in = delta_to_microseconds(delta);
1623 if (pyus_in == NULL)
1624 return NULL;
1625
1626 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1627 Py_DECREF(pyus_in);
1628 if (pyus_out == NULL)
1629 return NULL;
1630
1631 result = microseconds_to_delta(pyus_out);
1632 Py_DECREF(pyus_out);
1633 return result;
1634}
1635
1636static PyObject *
1637delta_add(PyObject *left, PyObject *right)
1638{
1639 PyObject *result = Py_NotImplemented;
1640
1641 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1642 /* delta + delta */
1643 /* The C-level additions can't overflow because of the
1644 * invariant bounds.
1645 */
1646 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1647 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1648 int microseconds = GET_TD_MICROSECONDS(left) +
1649 GET_TD_MICROSECONDS(right);
1650 result = new_delta(days, seconds, microseconds, 1);
1651 }
1652
1653 if (result == Py_NotImplemented)
1654 Py_INCREF(result);
1655 return result;
1656}
1657
1658static PyObject *
1659delta_negative(PyDateTime_Delta *self)
1660{
1661 return new_delta(-GET_TD_DAYS(self),
1662 -GET_TD_SECONDS(self),
1663 -GET_TD_MICROSECONDS(self),
1664 1);
1665}
1666
1667static PyObject *
1668delta_positive(PyDateTime_Delta *self)
1669{
1670 /* Could optimize this (by returning self) if this isn't a
1671 * subclass -- but who uses unary + ? Approximately nobody.
1672 */
1673 return new_delta(GET_TD_DAYS(self),
1674 GET_TD_SECONDS(self),
1675 GET_TD_MICROSECONDS(self),
1676 0);
1677}
1678
1679static PyObject *
1680delta_abs(PyDateTime_Delta *self)
1681{
1682 PyObject *result;
1683
1684 assert(GET_TD_MICROSECONDS(self) >= 0);
1685 assert(GET_TD_SECONDS(self) >= 0);
1686
1687 if (GET_TD_DAYS(self) < 0)
1688 result = delta_negative(self);
1689 else
1690 result = delta_positive(self);
1691
1692 return result;
1693}
1694
1695static PyObject *
1696delta_subtract(PyObject *left, PyObject *right)
1697{
1698 PyObject *result = Py_NotImplemented;
1699
1700 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1701 /* delta - delta */
1702 PyObject *minus_right = PyNumber_Negative(right);
1703 if (minus_right) {
1704 result = delta_add(left, minus_right);
1705 Py_DECREF(minus_right);
1706 }
1707 else
1708 result = NULL;
1709 }
1710
1711 if (result == Py_NotImplemented)
1712 Py_INCREF(result);
1713 return result;
1714}
1715
Tim Peters2a799bf2002-12-16 20:18:38 +00001716static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001717delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001718{
Tim Petersaa7d8492003-02-08 03:28:59 +00001719 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001720 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001721 if (diff == 0) {
1722 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1723 if (diff == 0)
1724 diff = GET_TD_MICROSECONDS(self) -
1725 GET_TD_MICROSECONDS(other);
1726 }
Guido van Rossum19960592006-08-24 17:29:38 +00001727 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001728 }
Guido van Rossum19960592006-08-24 17:29:38 +00001729 else {
1730 Py_INCREF(Py_NotImplemented);
1731 return Py_NotImplemented;
1732 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001733}
1734
1735static PyObject *delta_getstate(PyDateTime_Delta *self);
1736
1737static long
1738delta_hash(PyDateTime_Delta *self)
1739{
1740 if (self->hashcode == -1) {
1741 PyObject *temp = delta_getstate(self);
1742 if (temp != NULL) {
1743 self->hashcode = PyObject_Hash(temp);
1744 Py_DECREF(temp);
1745 }
1746 }
1747 return self->hashcode;
1748}
1749
1750static PyObject *
1751delta_multiply(PyObject *left, PyObject *right)
1752{
1753 PyObject *result = Py_NotImplemented;
1754
1755 if (PyDelta_Check(left)) {
1756 /* delta * ??? */
1757 if (PyInt_Check(right) || PyLong_Check(right))
1758 result = multiply_int_timedelta(right,
1759 (PyDateTime_Delta *) left);
1760 }
1761 else if (PyInt_Check(left) || PyLong_Check(left))
1762 result = multiply_int_timedelta(left,
1763 (PyDateTime_Delta *) right);
1764
1765 if (result == Py_NotImplemented)
1766 Py_INCREF(result);
1767 return result;
1768}
1769
1770static PyObject *
1771delta_divide(PyObject *left, PyObject *right)
1772{
1773 PyObject *result = Py_NotImplemented;
1774
1775 if (PyDelta_Check(left)) {
1776 /* delta * ??? */
1777 if (PyInt_Check(right) || PyLong_Check(right))
1778 result = divide_timedelta_int(
1779 (PyDateTime_Delta *)left,
1780 right);
1781 }
1782
1783 if (result == Py_NotImplemented)
1784 Py_INCREF(result);
1785 return result;
1786}
1787
1788/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1789 * timedelta constructor. sofar is the # of microseconds accounted for
1790 * so far, and there are factor microseconds per current unit, the number
1791 * of which is given by num. num * factor is added to sofar in a
1792 * numerically careful way, and that's the result. Any fractional
1793 * microseconds left over (this can happen if num is a float type) are
1794 * added into *leftover.
1795 * Note that there are many ways this can give an error (NULL) return.
1796 */
1797static PyObject *
1798accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1799 double *leftover)
1800{
1801 PyObject *prod;
1802 PyObject *sum;
1803
1804 assert(num != NULL);
1805
1806 if (PyInt_Check(num) || PyLong_Check(num)) {
1807 prod = PyNumber_Multiply(num, factor);
1808 if (prod == NULL)
1809 return NULL;
1810 sum = PyNumber_Add(sofar, prod);
1811 Py_DECREF(prod);
1812 return sum;
1813 }
1814
1815 if (PyFloat_Check(num)) {
1816 double dnum;
1817 double fracpart;
1818 double intpart;
1819 PyObject *x;
1820 PyObject *y;
1821
1822 /* The Plan: decompose num into an integer part and a
1823 * fractional part, num = intpart + fracpart.
1824 * Then num * factor ==
1825 * intpart * factor + fracpart * factor
1826 * and the LHS can be computed exactly in long arithmetic.
1827 * The RHS is again broken into an int part and frac part.
1828 * and the frac part is added into *leftover.
1829 */
1830 dnum = PyFloat_AsDouble(num);
1831 if (dnum == -1.0 && PyErr_Occurred())
1832 return NULL;
1833 fracpart = modf(dnum, &intpart);
1834 x = PyLong_FromDouble(intpart);
1835 if (x == NULL)
1836 return NULL;
1837
1838 prod = PyNumber_Multiply(x, factor);
1839 Py_DECREF(x);
1840 if (prod == NULL)
1841 return NULL;
1842
1843 sum = PyNumber_Add(sofar, prod);
1844 Py_DECREF(prod);
1845 if (sum == NULL)
1846 return NULL;
1847
1848 if (fracpart == 0.0)
1849 return sum;
1850 /* So far we've lost no information. Dealing with the
1851 * fractional part requires float arithmetic, and may
1852 * lose a little info.
1853 */
1854 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001855 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001856
1857 dnum *= fracpart;
1858 fracpart = modf(dnum, &intpart);
1859 x = PyLong_FromDouble(intpart);
1860 if (x == NULL) {
1861 Py_DECREF(sum);
1862 return NULL;
1863 }
1864
1865 y = PyNumber_Add(sum, x);
1866 Py_DECREF(sum);
1867 Py_DECREF(x);
1868 *leftover += fracpart;
1869 return y;
1870 }
1871
1872 PyErr_Format(PyExc_TypeError,
1873 "unsupported type for timedelta %s component: %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001874 tag, Py_Type(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001875 return NULL;
1876}
1877
1878static PyObject *
1879delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1880{
1881 PyObject *self = NULL;
1882
1883 /* Argument objects. */
1884 PyObject *day = NULL;
1885 PyObject *second = NULL;
1886 PyObject *us = NULL;
1887 PyObject *ms = NULL;
1888 PyObject *minute = NULL;
1889 PyObject *hour = NULL;
1890 PyObject *week = NULL;
1891
1892 PyObject *x = NULL; /* running sum of microseconds */
1893 PyObject *y = NULL; /* temp sum of microseconds */
1894 double leftover_us = 0.0;
1895
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001896 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001897 "days", "seconds", "microseconds", "milliseconds",
1898 "minutes", "hours", "weeks", NULL
1899 };
1900
1901 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1902 keywords,
1903 &day, &second, &us,
1904 &ms, &minute, &hour, &week) == 0)
1905 goto Done;
1906
1907 x = PyInt_FromLong(0);
1908 if (x == NULL)
1909 goto Done;
1910
1911#define CLEANUP \
1912 Py_DECREF(x); \
1913 x = y; \
1914 if (x == NULL) \
1915 goto Done
1916
1917 if (us) {
1918 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1919 CLEANUP;
1920 }
1921 if (ms) {
1922 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1923 CLEANUP;
1924 }
1925 if (second) {
1926 y = accum("seconds", x, second, us_per_second, &leftover_us);
1927 CLEANUP;
1928 }
1929 if (minute) {
1930 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1931 CLEANUP;
1932 }
1933 if (hour) {
1934 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1935 CLEANUP;
1936 }
1937 if (day) {
1938 y = accum("days", x, day, us_per_day, &leftover_us);
1939 CLEANUP;
1940 }
1941 if (week) {
1942 y = accum("weeks", x, week, us_per_week, &leftover_us);
1943 CLEANUP;
1944 }
1945 if (leftover_us) {
1946 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001947 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001948 if (temp == NULL) {
1949 Py_DECREF(x);
1950 goto Done;
1951 }
1952 y = PyNumber_Add(x, temp);
1953 Py_DECREF(temp);
1954 CLEANUP;
1955 }
1956
Tim Petersb0c854d2003-05-17 15:57:00 +00001957 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001958 Py_DECREF(x);
1959Done:
1960 return self;
1961
1962#undef CLEANUP
1963}
1964
1965static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001966delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001967{
1968 return (GET_TD_DAYS(self) != 0
1969 || GET_TD_SECONDS(self) != 0
1970 || GET_TD_MICROSECONDS(self) != 0);
1971}
1972
1973static PyObject *
1974delta_repr(PyDateTime_Delta *self)
1975{
1976 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001977 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001978 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001979 GET_TD_DAYS(self),
1980 GET_TD_SECONDS(self),
1981 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001982 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001983 return PyUnicode_FromFormat("%s(%d, %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),
1986 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001987
Walter Dörwald1ab83302007-05-18 17:15:44 +00001988 return PyUnicode_FromFormat("%s(%d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001989 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001990 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001991}
1992
1993static PyObject *
1994delta_str(PyDateTime_Delta *self)
1995{
Tim Peters2a799bf2002-12-16 20:18:38 +00001996 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00001997 int seconds = GET_TD_SECONDS(self);
1998 int minutes = divmod(seconds, 60, &seconds);
1999 int hours = divmod(minutes, 60, &minutes);
2000 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002001
2002 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002003 if (us)
2004 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2005 days, (days == 1 || days == -1) ? "" : "s",
2006 hours, minutes, seconds, us);
2007 else
2008 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2009 days, (days == 1 || days == -1) ? "" : "s",
2010 hours, minutes, seconds);
2011 } else {
2012 if (us)
2013 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2014 hours, minutes, seconds, us);
2015 else
2016 return PyUnicode_FromFormat("%d:%02d:%02d",
2017 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002018 }
2019
Tim Peters2a799bf2002-12-16 20:18:38 +00002020}
2021
Tim Peters371935f2003-02-01 01:52:50 +00002022/* Pickle support, a simple use of __reduce__. */
2023
Tim Petersb57f8f02003-02-01 02:54:15 +00002024/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002025static PyObject *
2026delta_getstate(PyDateTime_Delta *self)
2027{
2028 return Py_BuildValue("iii", GET_TD_DAYS(self),
2029 GET_TD_SECONDS(self),
2030 GET_TD_MICROSECONDS(self));
2031}
2032
Tim Peters2a799bf2002-12-16 20:18:38 +00002033static PyObject *
2034delta_reduce(PyDateTime_Delta* self)
2035{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002036 return Py_BuildValue("ON", Py_Type(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002037}
2038
2039#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2040
2041static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002042
Neal Norwitzdfb80862002-12-19 02:30:56 +00002043 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002044 PyDoc_STR("Number of days.")},
2045
Neal Norwitzdfb80862002-12-19 02:30:56 +00002046 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002047 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2048
Neal Norwitzdfb80862002-12-19 02:30:56 +00002049 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002050 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2051 {NULL}
2052};
2053
2054static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002055 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2056 PyDoc_STR("__reduce__() -> (cls, state)")},
2057
Tim Peters2a799bf2002-12-16 20:18:38 +00002058 {NULL, NULL},
2059};
2060
2061static char delta_doc[] =
2062PyDoc_STR("Difference between two datetime values.");
2063
2064static PyNumberMethods delta_as_number = {
2065 delta_add, /* nb_add */
2066 delta_subtract, /* nb_subtract */
2067 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002068 0, /* nb_remainder */
2069 0, /* nb_divmod */
2070 0, /* nb_power */
2071 (unaryfunc)delta_negative, /* nb_negative */
2072 (unaryfunc)delta_positive, /* nb_positive */
2073 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002074 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002075 0, /*nb_invert*/
2076 0, /*nb_lshift*/
2077 0, /*nb_rshift*/
2078 0, /*nb_and*/
2079 0, /*nb_xor*/
2080 0, /*nb_or*/
2081 0, /*nb_coerce*/
2082 0, /*nb_int*/
2083 0, /*nb_long*/
2084 0, /*nb_float*/
2085 0, /*nb_oct*/
2086 0, /*nb_hex*/
2087 0, /*nb_inplace_add*/
2088 0, /*nb_inplace_subtract*/
2089 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002090 0, /*nb_inplace_remainder*/
2091 0, /*nb_inplace_power*/
2092 0, /*nb_inplace_lshift*/
2093 0, /*nb_inplace_rshift*/
2094 0, /*nb_inplace_and*/
2095 0, /*nb_inplace_xor*/
2096 0, /*nb_inplace_or*/
2097 delta_divide, /* nb_floor_divide */
2098 0, /* nb_true_divide */
2099 0, /* nb_inplace_floor_divide */
2100 0, /* nb_inplace_true_divide */
2101};
2102
2103static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002104 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002105 "datetime.timedelta", /* tp_name */
2106 sizeof(PyDateTime_Delta), /* tp_basicsize */
2107 0, /* tp_itemsize */
2108 0, /* tp_dealloc */
2109 0, /* tp_print */
2110 0, /* tp_getattr */
2111 0, /* tp_setattr */
2112 0, /* tp_compare */
2113 (reprfunc)delta_repr, /* tp_repr */
2114 &delta_as_number, /* tp_as_number */
2115 0, /* tp_as_sequence */
2116 0, /* tp_as_mapping */
2117 (hashfunc)delta_hash, /* tp_hash */
2118 0, /* tp_call */
2119 (reprfunc)delta_str, /* tp_str */
2120 PyObject_GenericGetAttr, /* tp_getattro */
2121 0, /* tp_setattro */
2122 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002123 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002124 delta_doc, /* tp_doc */
2125 0, /* tp_traverse */
2126 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002127 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002128 0, /* tp_weaklistoffset */
2129 0, /* tp_iter */
2130 0, /* tp_iternext */
2131 delta_methods, /* tp_methods */
2132 delta_members, /* tp_members */
2133 0, /* tp_getset */
2134 0, /* tp_base */
2135 0, /* tp_dict */
2136 0, /* tp_descr_get */
2137 0, /* tp_descr_set */
2138 0, /* tp_dictoffset */
2139 0, /* tp_init */
2140 0, /* tp_alloc */
2141 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002142 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002143};
2144
2145/*
2146 * PyDateTime_Date implementation.
2147 */
2148
2149/* Accessor properties. */
2150
2151static PyObject *
2152date_year(PyDateTime_Date *self, void *unused)
2153{
2154 return PyInt_FromLong(GET_YEAR(self));
2155}
2156
2157static PyObject *
2158date_month(PyDateTime_Date *self, void *unused)
2159{
2160 return PyInt_FromLong(GET_MONTH(self));
2161}
2162
2163static PyObject *
2164date_day(PyDateTime_Date *self, void *unused)
2165{
2166 return PyInt_FromLong(GET_DAY(self));
2167}
2168
2169static PyGetSetDef date_getset[] = {
2170 {"year", (getter)date_year},
2171 {"month", (getter)date_month},
2172 {"day", (getter)date_day},
2173 {NULL}
2174};
2175
2176/* Constructors. */
2177
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002178static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002179
Tim Peters2a799bf2002-12-16 20:18:38 +00002180static PyObject *
2181date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2182{
2183 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002184 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002185 int year;
2186 int month;
2187 int day;
2188
Guido van Rossum177e41a2003-01-30 22:06:23 +00002189 /* Check for invocation from pickle with __getstate__ state */
2190 if (PyTuple_GET_SIZE(args) == 1 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002191 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2192 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2193 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002194 {
Tim Peters70533e22003-02-01 04:40:04 +00002195 PyDateTime_Date *me;
2196
Tim Peters604c0132004-06-07 23:04:33 +00002197 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002198 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002199 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002200 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2201 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002202 }
Tim Peters70533e22003-02-01 04:40:04 +00002203 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002204 }
2205
Tim Peters12bf3392002-12-24 05:41:27 +00002206 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002207 &year, &month, &day)) {
2208 if (check_date_args(year, month, day) < 0)
2209 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002210 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002211 }
2212 return self;
2213}
2214
2215/* Return new date from localtime(t). */
2216static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002217date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002218{
2219 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002220 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002221 PyObject *result = NULL;
2222
Tim Peters1b6f7a92004-06-20 02:50:16 +00002223 t = _PyTime_DoubleToTimet(ts);
2224 if (t == (time_t)-1 && PyErr_Occurred())
2225 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002226 tm = localtime(&t);
2227 if (tm)
2228 result = PyObject_CallFunction(cls, "iii",
2229 tm->tm_year + 1900,
2230 tm->tm_mon + 1,
2231 tm->tm_mday);
2232 else
2233 PyErr_SetString(PyExc_ValueError,
2234 "timestamp out of range for "
2235 "platform localtime() function");
2236 return result;
2237}
2238
2239/* Return new date from current time.
2240 * We say this is equivalent to fromtimestamp(time.time()), and the
2241 * only way to be sure of that is to *call* time.time(). That's not
2242 * generally the same as calling C's time.
2243 */
2244static PyObject *
2245date_today(PyObject *cls, PyObject *dummy)
2246{
2247 PyObject *time;
2248 PyObject *result;
2249
2250 time = time_time();
2251 if (time == NULL)
2252 return NULL;
2253
2254 /* Note well: today() is a class method, so this may not call
2255 * date.fromtimestamp. For example, it may call
2256 * datetime.fromtimestamp. That's why we need all the accuracy
2257 * time.time() delivers; if someone were gonzo about optimization,
2258 * date.today() could get away with plain C time().
2259 */
2260 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2261 Py_DECREF(time);
2262 return result;
2263}
2264
2265/* Return new date from given timestamp (Python timestamp -- a double). */
2266static PyObject *
2267date_fromtimestamp(PyObject *cls, PyObject *args)
2268{
2269 double timestamp;
2270 PyObject *result = NULL;
2271
2272 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002273 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002274 return result;
2275}
2276
2277/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2278 * the ordinal is out of range.
2279 */
2280static PyObject *
2281date_fromordinal(PyObject *cls, PyObject *args)
2282{
2283 PyObject *result = NULL;
2284 int ordinal;
2285
2286 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2287 int year;
2288 int month;
2289 int day;
2290
2291 if (ordinal < 1)
2292 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2293 ">= 1");
2294 else {
2295 ord_to_ymd(ordinal, &year, &month, &day);
2296 result = PyObject_CallFunction(cls, "iii",
2297 year, month, day);
2298 }
2299 }
2300 return result;
2301}
2302
2303/*
2304 * Date arithmetic.
2305 */
2306
2307/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2308 * instead.
2309 */
2310static PyObject *
2311add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2312{
2313 PyObject *result = NULL;
2314 int year = GET_YEAR(date);
2315 int month = GET_MONTH(date);
2316 int deltadays = GET_TD_DAYS(delta);
2317 /* C-level overflow is impossible because |deltadays| < 1e9. */
2318 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2319
2320 if (normalize_date(&year, &month, &day) >= 0)
2321 result = new_date(year, month, day);
2322 return result;
2323}
2324
2325static PyObject *
2326date_add(PyObject *left, PyObject *right)
2327{
2328 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2329 Py_INCREF(Py_NotImplemented);
2330 return Py_NotImplemented;
2331 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002332 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002333 /* date + ??? */
2334 if (PyDelta_Check(right))
2335 /* date + delta */
2336 return add_date_timedelta((PyDateTime_Date *) left,
2337 (PyDateTime_Delta *) right,
2338 0);
2339 }
2340 else {
2341 /* ??? + date
2342 * 'right' must be one of us, or we wouldn't have been called
2343 */
2344 if (PyDelta_Check(left))
2345 /* delta + date */
2346 return add_date_timedelta((PyDateTime_Date *) right,
2347 (PyDateTime_Delta *) left,
2348 0);
2349 }
2350 Py_INCREF(Py_NotImplemented);
2351 return Py_NotImplemented;
2352}
2353
2354static PyObject *
2355date_subtract(PyObject *left, PyObject *right)
2356{
2357 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2358 Py_INCREF(Py_NotImplemented);
2359 return Py_NotImplemented;
2360 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002361 if (PyDate_Check(left)) {
2362 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002363 /* date - date */
2364 int left_ord = ymd_to_ord(GET_YEAR(left),
2365 GET_MONTH(left),
2366 GET_DAY(left));
2367 int right_ord = ymd_to_ord(GET_YEAR(right),
2368 GET_MONTH(right),
2369 GET_DAY(right));
2370 return new_delta(left_ord - right_ord, 0, 0, 0);
2371 }
2372 if (PyDelta_Check(right)) {
2373 /* date - delta */
2374 return add_date_timedelta((PyDateTime_Date *) left,
2375 (PyDateTime_Delta *) right,
2376 1);
2377 }
2378 }
2379 Py_INCREF(Py_NotImplemented);
2380 return Py_NotImplemented;
2381}
2382
2383
2384/* Various ways to turn a date into a string. */
2385
2386static PyObject *
2387date_repr(PyDateTime_Date *self)
2388{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002389 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00002390 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002391 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002392}
2393
2394static PyObject *
2395date_isoformat(PyDateTime_Date *self)
2396{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002397 return PyUnicode_FromFormat("%04d-%02d-%02d",
2398 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002399}
2400
Tim Peterse2df5ff2003-05-02 18:39:55 +00002401/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002402static PyObject *
2403date_str(PyDateTime_Date *self)
2404{
2405 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2406}
2407
2408
2409static PyObject *
2410date_ctime(PyDateTime_Date *self)
2411{
2412 return format_ctime(self, 0, 0, 0);
2413}
2414
2415static PyObject *
2416date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2417{
2418 /* This method can be inherited, and needs to call the
2419 * timetuple() method appropriate to self's class.
2420 */
2421 PyObject *result;
2422 PyObject *format;
2423 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002424 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002425
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002426 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00002427 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002428 return NULL;
2429
2430 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2431 if (tuple == NULL)
2432 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002433 result = wrap_strftime((PyObject *)self, format, tuple,
2434 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002435 Py_DECREF(tuple);
2436 return result;
2437}
2438
2439/* ISO methods. */
2440
2441static PyObject *
2442date_isoweekday(PyDateTime_Date *self)
2443{
2444 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2445
2446 return PyInt_FromLong(dow + 1);
2447}
2448
2449static PyObject *
2450date_isocalendar(PyDateTime_Date *self)
2451{
2452 int year = GET_YEAR(self);
2453 int week1_monday = iso_week1_monday(year);
2454 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2455 int week;
2456 int day;
2457
2458 week = divmod(today - week1_monday, 7, &day);
2459 if (week < 0) {
2460 --year;
2461 week1_monday = iso_week1_monday(year);
2462 week = divmod(today - week1_monday, 7, &day);
2463 }
2464 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2465 ++year;
2466 week = 0;
2467 }
2468 return Py_BuildValue("iii", year, week + 1, day + 1);
2469}
2470
2471/* Miscellaneous methods. */
2472
Tim Peters2a799bf2002-12-16 20:18:38 +00002473static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002474date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002475{
Guido van Rossum19960592006-08-24 17:29:38 +00002476 if (PyDate_Check(other)) {
2477 int diff = memcmp(((PyDateTime_Date *)self)->data,
2478 ((PyDateTime_Date *)other)->data,
2479 _PyDateTime_DATE_DATASIZE);
2480 return diff_to_bool(diff, op);
2481 }
2482 else {
Tim Peters07534a62003-02-07 22:50:28 +00002483 Py_INCREF(Py_NotImplemented);
2484 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002485 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002486}
2487
2488static PyObject *
2489date_timetuple(PyDateTime_Date *self)
2490{
2491 return build_struct_time(GET_YEAR(self),
2492 GET_MONTH(self),
2493 GET_DAY(self),
2494 0, 0, 0, -1);
2495}
2496
Tim Peters12bf3392002-12-24 05:41:27 +00002497static PyObject *
2498date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2499{
2500 PyObject *clone;
2501 PyObject *tuple;
2502 int year = GET_YEAR(self);
2503 int month = GET_MONTH(self);
2504 int day = GET_DAY(self);
2505
2506 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2507 &year, &month, &day))
2508 return NULL;
2509 tuple = Py_BuildValue("iii", year, month, day);
2510 if (tuple == NULL)
2511 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002512 clone = date_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002513 Py_DECREF(tuple);
2514 return clone;
2515}
2516
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002517/*
2518 Borrowed from stringobject.c, originally it was string_hash()
2519*/
2520static long
2521generic_hash(unsigned char *data, int len)
2522{
2523 register unsigned char *p;
2524 register long x;
2525
2526 p = (unsigned char *) data;
2527 x = *p << 7;
2528 while (--len >= 0)
2529 x = (1000003*x) ^ *p++;
2530 x ^= len;
2531 if (x == -1)
2532 x = -2;
2533
2534 return x;
2535}
2536
2537
2538static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002539
2540static long
2541date_hash(PyDateTime_Date *self)
2542{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002543 if (self->hashcode == -1)
2544 self->hashcode = generic_hash(
2545 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
2546
Tim Peters2a799bf2002-12-16 20:18:38 +00002547 return self->hashcode;
2548}
2549
2550static PyObject *
2551date_toordinal(PyDateTime_Date *self)
2552{
2553 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2554 GET_DAY(self)));
2555}
2556
2557static PyObject *
2558date_weekday(PyDateTime_Date *self)
2559{
2560 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2561
2562 return PyInt_FromLong(dow);
2563}
2564
Tim Peters371935f2003-02-01 01:52:50 +00002565/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002566
Tim Petersb57f8f02003-02-01 02:54:15 +00002567/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002568static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002569date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002570{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002571 PyObject* field;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002572 field = PyBytes_FromStringAndSize(
2573 (char*)self->data, _PyDateTime_DATE_DATASIZE);
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002574 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002575}
2576
2577static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002578date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002579{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002580 return Py_BuildValue("(ON)", Py_Type(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002581}
2582
2583static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002584
Tim Peters2a799bf2002-12-16 20:18:38 +00002585 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002586
Tim Peters2a799bf2002-12-16 20:18:38 +00002587 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2588 METH_CLASS,
2589 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2590 "time.time()).")},
2591
2592 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2593 METH_CLASS,
2594 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2595 "ordinal.")},
2596
2597 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2598 PyDoc_STR("Current date or datetime: same as "
2599 "self.__class__.fromtimestamp(time.time()).")},
2600
2601 /* Instance methods: */
2602
2603 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2604 PyDoc_STR("Return ctime() style string.")},
2605
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002606 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002607 PyDoc_STR("format -> strftime() style string.")},
2608
2609 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2610 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2611
2612 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2613 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2614 "weekday.")},
2615
2616 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2617 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2618
2619 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2620 PyDoc_STR("Return the day of the week represented by the date.\n"
2621 "Monday == 1 ... Sunday == 7")},
2622
2623 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2624 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2625 "1 is day 1.")},
2626
2627 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2628 PyDoc_STR("Return the day of the week represented by the date.\n"
2629 "Monday == 0 ... Sunday == 6")},
2630
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002631 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002632 PyDoc_STR("Return date with new specified fields.")},
2633
Guido van Rossum177e41a2003-01-30 22:06:23 +00002634 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2635 PyDoc_STR("__reduce__() -> (cls, state)")},
2636
Tim Peters2a799bf2002-12-16 20:18:38 +00002637 {NULL, NULL}
2638};
2639
2640static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002641PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002642
2643static PyNumberMethods date_as_number = {
2644 date_add, /* nb_add */
2645 date_subtract, /* nb_subtract */
2646 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002647 0, /* nb_remainder */
2648 0, /* nb_divmod */
2649 0, /* nb_power */
2650 0, /* nb_negative */
2651 0, /* nb_positive */
2652 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002653 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002654};
2655
2656static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002657 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002658 "datetime.date", /* tp_name */
2659 sizeof(PyDateTime_Date), /* tp_basicsize */
2660 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002661 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002662 0, /* tp_print */
2663 0, /* tp_getattr */
2664 0, /* tp_setattr */
2665 0, /* tp_compare */
2666 (reprfunc)date_repr, /* tp_repr */
2667 &date_as_number, /* tp_as_number */
2668 0, /* tp_as_sequence */
2669 0, /* tp_as_mapping */
2670 (hashfunc)date_hash, /* tp_hash */
2671 0, /* tp_call */
2672 (reprfunc)date_str, /* tp_str */
2673 PyObject_GenericGetAttr, /* tp_getattro */
2674 0, /* tp_setattro */
2675 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002676 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002677 date_doc, /* tp_doc */
2678 0, /* tp_traverse */
2679 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002680 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002681 0, /* tp_weaklistoffset */
2682 0, /* tp_iter */
2683 0, /* tp_iternext */
2684 date_methods, /* tp_methods */
2685 0, /* tp_members */
2686 date_getset, /* tp_getset */
2687 0, /* tp_base */
2688 0, /* tp_dict */
2689 0, /* tp_descr_get */
2690 0, /* tp_descr_set */
2691 0, /* tp_dictoffset */
2692 0, /* tp_init */
2693 0, /* tp_alloc */
2694 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002695 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002696};
2697
2698/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002699 * PyDateTime_TZInfo implementation.
2700 */
2701
2702/* This is a pure abstract base class, so doesn't do anything beyond
2703 * raising NotImplemented exceptions. Real tzinfo classes need
2704 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002705 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002706 * be subclasses of this tzinfo class, which is easy and quick to check).
2707 *
2708 * Note: For reasons having to do with pickling of subclasses, we have
2709 * to allow tzinfo objects to be instantiated. This wasn't an issue
2710 * in the Python implementation (__init__() could raise NotImplementedError
2711 * there without ill effect), but doing so in the C implementation hit a
2712 * brick wall.
2713 */
2714
2715static PyObject *
2716tzinfo_nogo(const char* methodname)
2717{
2718 PyErr_Format(PyExc_NotImplementedError,
2719 "a tzinfo subclass must implement %s()",
2720 methodname);
2721 return NULL;
2722}
2723
2724/* Methods. A subclass must implement these. */
2725
Tim Peters52dcce22003-01-23 16:36:11 +00002726static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002727tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2728{
2729 return tzinfo_nogo("tzname");
2730}
2731
Tim Peters52dcce22003-01-23 16:36:11 +00002732static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002733tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2734{
2735 return tzinfo_nogo("utcoffset");
2736}
2737
Tim Peters52dcce22003-01-23 16:36:11 +00002738static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002739tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2740{
2741 return tzinfo_nogo("dst");
2742}
2743
Tim Peters52dcce22003-01-23 16:36:11 +00002744static PyObject *
2745tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2746{
2747 int y, m, d, hh, mm, ss, us;
2748
2749 PyObject *result;
2750 int off, dst;
2751 int none;
2752 int delta;
2753
2754 if (! PyDateTime_Check(dt)) {
2755 PyErr_SetString(PyExc_TypeError,
2756 "fromutc: argument must be a datetime");
2757 return NULL;
2758 }
2759 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2760 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2761 "is not self");
2762 return NULL;
2763 }
2764
2765 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2766 if (off == -1 && PyErr_Occurred())
2767 return NULL;
2768 if (none) {
2769 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2770 "utcoffset() result required");
2771 return NULL;
2772 }
2773
2774 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2775 if (dst == -1 && PyErr_Occurred())
2776 return NULL;
2777 if (none) {
2778 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2779 "dst() result required");
2780 return NULL;
2781 }
2782
2783 y = GET_YEAR(dt);
2784 m = GET_MONTH(dt);
2785 d = GET_DAY(dt);
2786 hh = DATE_GET_HOUR(dt);
2787 mm = DATE_GET_MINUTE(dt);
2788 ss = DATE_GET_SECOND(dt);
2789 us = DATE_GET_MICROSECOND(dt);
2790
2791 delta = off - dst;
2792 mm += delta;
2793 if ((mm < 0 || mm >= 60) &&
2794 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002795 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002796 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2797 if (result == NULL)
2798 return result;
2799
2800 dst = call_dst(dt->tzinfo, result, &none);
2801 if (dst == -1 && PyErr_Occurred())
2802 goto Fail;
2803 if (none)
2804 goto Inconsistent;
2805 if (dst == 0)
2806 return result;
2807
2808 mm += dst;
2809 if ((mm < 0 || mm >= 60) &&
2810 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2811 goto Fail;
2812 Py_DECREF(result);
2813 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2814 return result;
2815
2816Inconsistent:
2817 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2818 "inconsistent results; cannot convert");
2819
2820 /* fall thru to failure */
2821Fail:
2822 Py_DECREF(result);
2823 return NULL;
2824}
2825
Tim Peters2a799bf2002-12-16 20:18:38 +00002826/*
2827 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002828 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002829 */
2830
Guido van Rossum177e41a2003-01-30 22:06:23 +00002831static PyObject *
2832tzinfo_reduce(PyObject *self)
2833{
2834 PyObject *args, *state, *tmp;
2835 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002836
Guido van Rossum177e41a2003-01-30 22:06:23 +00002837 tmp = PyTuple_New(0);
2838 if (tmp == NULL)
2839 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002840
Guido van Rossum177e41a2003-01-30 22:06:23 +00002841 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2842 if (getinitargs != NULL) {
2843 args = PyObject_CallObject(getinitargs, tmp);
2844 Py_DECREF(getinitargs);
2845 if (args == NULL) {
2846 Py_DECREF(tmp);
2847 return NULL;
2848 }
2849 }
2850 else {
2851 PyErr_Clear();
2852 args = tmp;
2853 Py_INCREF(args);
2854 }
2855
2856 getstate = PyObject_GetAttrString(self, "__getstate__");
2857 if (getstate != NULL) {
2858 state = PyObject_CallObject(getstate, tmp);
2859 Py_DECREF(getstate);
2860 if (state == NULL) {
2861 Py_DECREF(args);
2862 Py_DECREF(tmp);
2863 return NULL;
2864 }
2865 }
2866 else {
2867 PyObject **dictptr;
2868 PyErr_Clear();
2869 state = Py_None;
2870 dictptr = _PyObject_GetDictPtr(self);
2871 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2872 state = *dictptr;
2873 Py_INCREF(state);
2874 }
2875
2876 Py_DECREF(tmp);
2877
2878 if (state == Py_None) {
2879 Py_DECREF(state);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002880 return Py_BuildValue("(ON)", Py_Type(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002881 }
2882 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002883 return Py_BuildValue("(ONN)", Py_Type(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002884}
Tim Peters2a799bf2002-12-16 20:18:38 +00002885
2886static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002887
Tim Peters2a799bf2002-12-16 20:18:38 +00002888 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2889 PyDoc_STR("datetime -> string name of time zone.")},
2890
2891 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2892 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2893 "west of UTC).")},
2894
2895 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2896 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2897
Tim Peters52dcce22003-01-23 16:36:11 +00002898 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2899 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2900
Guido van Rossum177e41a2003-01-30 22:06:23 +00002901 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2902 PyDoc_STR("-> (cls, state)")},
2903
Tim Peters2a799bf2002-12-16 20:18:38 +00002904 {NULL, NULL}
2905};
2906
2907static char tzinfo_doc[] =
2908PyDoc_STR("Abstract base class for time zone info objects.");
2909
Neal Norwitz227b5332006-03-22 09:28:35 +00002910static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002911 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002912 "datetime.tzinfo", /* tp_name */
2913 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2914 0, /* tp_itemsize */
2915 0, /* tp_dealloc */
2916 0, /* tp_print */
2917 0, /* tp_getattr */
2918 0, /* tp_setattr */
2919 0, /* tp_compare */
2920 0, /* tp_repr */
2921 0, /* tp_as_number */
2922 0, /* tp_as_sequence */
2923 0, /* tp_as_mapping */
2924 0, /* tp_hash */
2925 0, /* tp_call */
2926 0, /* tp_str */
2927 PyObject_GenericGetAttr, /* tp_getattro */
2928 0, /* tp_setattro */
2929 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002930 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002931 tzinfo_doc, /* tp_doc */
2932 0, /* tp_traverse */
2933 0, /* tp_clear */
2934 0, /* tp_richcompare */
2935 0, /* tp_weaklistoffset */
2936 0, /* tp_iter */
2937 0, /* tp_iternext */
2938 tzinfo_methods, /* tp_methods */
2939 0, /* tp_members */
2940 0, /* tp_getset */
2941 0, /* tp_base */
2942 0, /* tp_dict */
2943 0, /* tp_descr_get */
2944 0, /* tp_descr_set */
2945 0, /* tp_dictoffset */
2946 0, /* tp_init */
2947 0, /* tp_alloc */
2948 PyType_GenericNew, /* tp_new */
2949 0, /* tp_free */
2950};
2951
2952/*
Tim Peters37f39822003-01-10 03:49:02 +00002953 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002954 */
2955
Tim Peters37f39822003-01-10 03:49:02 +00002956/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002957 */
2958
2959static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002960time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002961{
Tim Peters37f39822003-01-10 03:49:02 +00002962 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002963}
2964
Tim Peters37f39822003-01-10 03:49:02 +00002965static PyObject *
2966time_minute(PyDateTime_Time *self, void *unused)
2967{
2968 return PyInt_FromLong(TIME_GET_MINUTE(self));
2969}
2970
2971/* The name time_second conflicted with some platform header file. */
2972static PyObject *
2973py_time_second(PyDateTime_Time *self, void *unused)
2974{
2975 return PyInt_FromLong(TIME_GET_SECOND(self));
2976}
2977
2978static PyObject *
2979time_microsecond(PyDateTime_Time *self, void *unused)
2980{
2981 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2982}
2983
2984static PyObject *
2985time_tzinfo(PyDateTime_Time *self, void *unused)
2986{
Tim Petersa032d2e2003-01-11 00:15:54 +00002987 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002988 Py_INCREF(result);
2989 return result;
2990}
2991
2992static PyGetSetDef time_getset[] = {
2993 {"hour", (getter)time_hour},
2994 {"minute", (getter)time_minute},
2995 {"second", (getter)py_time_second},
2996 {"microsecond", (getter)time_microsecond},
2997 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00002998 {NULL}
2999};
3000
3001/*
3002 * Constructors.
3003 */
3004
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003005static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003006 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003007
Tim Peters2a799bf2002-12-16 20:18:38 +00003008static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003009time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003010{
3011 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003012 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003013 int hour = 0;
3014 int minute = 0;
3015 int second = 0;
3016 int usecond = 0;
3017 PyObject *tzinfo = Py_None;
3018
Guido van Rossum177e41a2003-01-30 22:06:23 +00003019 /* Check for invocation from pickle with __getstate__ state */
3020 if (PyTuple_GET_SIZE(args) >= 1 &&
3021 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003022 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3023 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3024 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003025 {
Tim Peters70533e22003-02-01 04:40:04 +00003026 PyDateTime_Time *me;
3027 char aware;
3028
3029 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003030 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003031 if (check_tzinfo_subclass(tzinfo) < 0) {
3032 PyErr_SetString(PyExc_TypeError, "bad "
3033 "tzinfo state arg");
3034 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003035 }
3036 }
Tim Peters70533e22003-02-01 04:40:04 +00003037 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003038 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003039 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003040 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003041
3042 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3043 me->hashcode = -1;
3044 me->hastzinfo = aware;
3045 if (aware) {
3046 Py_INCREF(tzinfo);
3047 me->tzinfo = tzinfo;
3048 }
3049 }
3050 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003051 }
3052
Tim Peters37f39822003-01-10 03:49:02 +00003053 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003054 &hour, &minute, &second, &usecond,
3055 &tzinfo)) {
3056 if (check_time_args(hour, minute, second, usecond) < 0)
3057 return NULL;
3058 if (check_tzinfo_subclass(tzinfo) < 0)
3059 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003060 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3061 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003062 }
3063 return self;
3064}
3065
3066/*
3067 * Destructor.
3068 */
3069
3070static void
Tim Peters37f39822003-01-10 03:49:02 +00003071time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003072{
Tim Petersa032d2e2003-01-11 00:15:54 +00003073 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003074 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003075 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003076 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003077}
3078
3079/*
Tim Peters855fe882002-12-22 03:43:39 +00003080 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003081 */
3082
Tim Peters2a799bf2002-12-16 20:18:38 +00003083/* These are all METH_NOARGS, so don't need to check the arglist. */
3084static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003085time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003086 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003087 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003088}
3089
3090static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003091time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003092 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003093 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003094}
3095
3096static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003097time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003098 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003099 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003100}
3101
3102/*
Tim Peters37f39822003-01-10 03:49:02 +00003103 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003104 */
3105
3106static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003107time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003108{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003109 const char *type_name = Py_Type(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003110 int h = TIME_GET_HOUR(self);
3111 int m = TIME_GET_MINUTE(self);
3112 int s = TIME_GET_SECOND(self);
3113 int us = TIME_GET_MICROSECOND(self);
3114 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003115
Tim Peters37f39822003-01-10 03:49:02 +00003116 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003117 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3118 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003119 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003120 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3121 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003122 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003123 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003124 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003125 result = append_keyword_tzinfo(result, self->tzinfo);
3126 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003127}
3128
Tim Peters37f39822003-01-10 03:49:02 +00003129static PyObject *
3130time_str(PyDateTime_Time *self)
3131{
3132 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3133}
Tim Peters2a799bf2002-12-16 20:18:38 +00003134
3135static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003136time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003137{
3138 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003139 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003140 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003141
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003142 if (us)
3143 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3144 TIME_GET_HOUR(self),
3145 TIME_GET_MINUTE(self),
3146 TIME_GET_SECOND(self),
3147 us);
3148 else
3149 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3150 TIME_GET_HOUR(self),
3151 TIME_GET_MINUTE(self),
3152 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003153
Tim Petersa032d2e2003-01-11 00:15:54 +00003154 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003155 return result;
3156
3157 /* We need to append the UTC offset. */
3158 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003159 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003160 Py_DECREF(result);
3161 return NULL;
3162 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003163 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003164 return result;
3165}
3166
Tim Peters37f39822003-01-10 03:49:02 +00003167static PyObject *
3168time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3169{
3170 PyObject *result;
3171 PyObject *format;
3172 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003173 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003174
Guido van Rossumbce56a62007-05-10 18:04:33 +00003175 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3176 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003177 return NULL;
3178
3179 /* Python's strftime does insane things with the year part of the
3180 * timetuple. The year is forced to (the otherwise nonsensical)
3181 * 1900 to worm around that.
3182 */
3183 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003184 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003185 TIME_GET_HOUR(self),
3186 TIME_GET_MINUTE(self),
3187 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003188 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003189 if (tuple == NULL)
3190 return NULL;
3191 assert(PyTuple_Size(tuple) == 9);
3192 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3193 Py_DECREF(tuple);
3194 return result;
3195}
Tim Peters2a799bf2002-12-16 20:18:38 +00003196
3197/*
3198 * Miscellaneous methods.
3199 */
3200
Tim Peters37f39822003-01-10 03:49:02 +00003201static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003202time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003203{
3204 int diff;
3205 naivety n1, n2;
3206 int offset1, offset2;
3207
3208 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003209 Py_INCREF(Py_NotImplemented);
3210 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003211 }
Guido van Rossum19960592006-08-24 17:29:38 +00003212 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3213 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003214 return NULL;
3215 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3216 /* If they're both naive, or both aware and have the same offsets,
3217 * we get off cheap. Note that if they're both naive, offset1 ==
3218 * offset2 == 0 at this point.
3219 */
3220 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003221 diff = memcmp(((PyDateTime_Time *)self)->data,
3222 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003223 _PyDateTime_TIME_DATASIZE);
3224 return diff_to_bool(diff, op);
3225 }
3226
3227 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3228 assert(offset1 != offset2); /* else last "if" handled it */
3229 /* Convert everything except microseconds to seconds. These
3230 * can't overflow (no more than the # of seconds in 2 days).
3231 */
3232 offset1 = TIME_GET_HOUR(self) * 3600 +
3233 (TIME_GET_MINUTE(self) - offset1) * 60 +
3234 TIME_GET_SECOND(self);
3235 offset2 = TIME_GET_HOUR(other) * 3600 +
3236 (TIME_GET_MINUTE(other) - offset2) * 60 +
3237 TIME_GET_SECOND(other);
3238 diff = offset1 - offset2;
3239 if (diff == 0)
3240 diff = TIME_GET_MICROSECOND(self) -
3241 TIME_GET_MICROSECOND(other);
3242 return diff_to_bool(diff, op);
3243 }
3244
3245 assert(n1 != n2);
3246 PyErr_SetString(PyExc_TypeError,
3247 "can't compare offset-naive and "
3248 "offset-aware times");
3249 return NULL;
3250}
3251
3252static long
3253time_hash(PyDateTime_Time *self)
3254{
3255 if (self->hashcode == -1) {
3256 naivety n;
3257 int offset;
3258 PyObject *temp;
3259
3260 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3261 assert(n != OFFSET_UNKNOWN);
3262 if (n == OFFSET_ERROR)
3263 return -1;
3264
3265 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003266 if (offset == 0) {
3267 self->hashcode = generic_hash(
3268 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3269 return self->hashcode;
3270 }
Tim Peters37f39822003-01-10 03:49:02 +00003271 else {
3272 int hour;
3273 int minute;
3274
3275 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003276 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003277 hour = divmod(TIME_GET_HOUR(self) * 60 +
3278 TIME_GET_MINUTE(self) - offset,
3279 60,
3280 &minute);
3281 if (0 <= hour && hour < 24)
3282 temp = new_time(hour, minute,
3283 TIME_GET_SECOND(self),
3284 TIME_GET_MICROSECOND(self),
3285 Py_None);
3286 else
3287 temp = Py_BuildValue("iiii",
3288 hour, minute,
3289 TIME_GET_SECOND(self),
3290 TIME_GET_MICROSECOND(self));
3291 }
3292 if (temp != NULL) {
3293 self->hashcode = PyObject_Hash(temp);
3294 Py_DECREF(temp);
3295 }
3296 }
3297 return self->hashcode;
3298}
Tim Peters2a799bf2002-12-16 20:18:38 +00003299
Tim Peters12bf3392002-12-24 05:41:27 +00003300static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003301time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003302{
3303 PyObject *clone;
3304 PyObject *tuple;
3305 int hh = TIME_GET_HOUR(self);
3306 int mm = TIME_GET_MINUTE(self);
3307 int ss = TIME_GET_SECOND(self);
3308 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003309 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003310
3311 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003312 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003313 &hh, &mm, &ss, &us, &tzinfo))
3314 return NULL;
3315 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3316 if (tuple == NULL)
3317 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003318 clone = time_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003319 Py_DECREF(tuple);
3320 return clone;
3321}
3322
Tim Peters2a799bf2002-12-16 20:18:38 +00003323static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003324time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003325{
3326 int offset;
3327 int none;
3328
3329 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3330 /* Since utcoffset is in whole minutes, nothing can
3331 * alter the conclusion that this is nonzero.
3332 */
3333 return 1;
3334 }
3335 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003336 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003337 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003338 if (offset == -1 && PyErr_Occurred())
3339 return -1;
3340 }
3341 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3342}
3343
Tim Peters371935f2003-02-01 01:52:50 +00003344/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003345
Tim Peters33e0f382003-01-10 02:05:14 +00003346/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003347 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3348 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003349 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003350 */
3351static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003352time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003353{
3354 PyObject *basestate;
3355 PyObject *result = NULL;
3356
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003357 basestate = PyBytes_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003358 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003359 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003360 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003361 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003362 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003363 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003364 Py_DECREF(basestate);
3365 }
3366 return result;
3367}
3368
3369static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003370time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003371{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003372 return Py_BuildValue("(ON)", Py_Type(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003373}
3374
Tim Peters37f39822003-01-10 03:49:02 +00003375static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003376
Thomas Wouterscf297e42007-02-23 15:07:44 +00003377 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003378 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3379 "[+HH:MM].")},
3380
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003381 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003382 PyDoc_STR("format -> strftime() style string.")},
3383
3384 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003385 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3386
Tim Peters37f39822003-01-10 03:49:02 +00003387 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003388 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3389
Tim Peters37f39822003-01-10 03:49:02 +00003390 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003391 PyDoc_STR("Return self.tzinfo.dst(self).")},
3392
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003393 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003394 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003395
Guido van Rossum177e41a2003-01-30 22:06:23 +00003396 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3397 PyDoc_STR("__reduce__() -> (cls, state)")},
3398
Tim Peters2a799bf2002-12-16 20:18:38 +00003399 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003400};
3401
Tim Peters37f39822003-01-10 03:49:02 +00003402static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003403PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3404\n\
3405All arguments are optional. tzinfo may be None, or an instance of\n\
3406a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003407
Tim Peters37f39822003-01-10 03:49:02 +00003408static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003409 0, /* nb_add */
3410 0, /* nb_subtract */
3411 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003412 0, /* nb_remainder */
3413 0, /* nb_divmod */
3414 0, /* nb_power */
3415 0, /* nb_negative */
3416 0, /* nb_positive */
3417 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003418 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003419};
3420
Neal Norwitz227b5332006-03-22 09:28:35 +00003421static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003422 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003423 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003424 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003425 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003426 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003427 0, /* tp_print */
3428 0, /* tp_getattr */
3429 0, /* tp_setattr */
3430 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003431 (reprfunc)time_repr, /* tp_repr */
3432 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003433 0, /* tp_as_sequence */
3434 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003435 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003436 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003437 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003438 PyObject_GenericGetAttr, /* tp_getattro */
3439 0, /* tp_setattro */
3440 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003441 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003442 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003443 0, /* tp_traverse */
3444 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003445 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003446 0, /* tp_weaklistoffset */
3447 0, /* tp_iter */
3448 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003449 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003450 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003451 time_getset, /* tp_getset */
3452 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003453 0, /* tp_dict */
3454 0, /* tp_descr_get */
3455 0, /* tp_descr_set */
3456 0, /* tp_dictoffset */
3457 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003458 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003459 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003460 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003461};
3462
3463/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003464 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003465 */
3466
Tim Petersa9bc1682003-01-11 03:39:11 +00003467/* Accessor properties. Properties for day, month, and year are inherited
3468 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003469 */
3470
3471static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003472datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003473{
Tim Petersa9bc1682003-01-11 03:39:11 +00003474 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003475}
3476
Tim Petersa9bc1682003-01-11 03:39:11 +00003477static PyObject *
3478datetime_minute(PyDateTime_DateTime *self, void *unused)
3479{
3480 return PyInt_FromLong(DATE_GET_MINUTE(self));
3481}
3482
3483static PyObject *
3484datetime_second(PyDateTime_DateTime *self, void *unused)
3485{
3486 return PyInt_FromLong(DATE_GET_SECOND(self));
3487}
3488
3489static PyObject *
3490datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3491{
3492 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3493}
3494
3495static PyObject *
3496datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3497{
3498 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3499 Py_INCREF(result);
3500 return result;
3501}
3502
3503static PyGetSetDef datetime_getset[] = {
3504 {"hour", (getter)datetime_hour},
3505 {"minute", (getter)datetime_minute},
3506 {"second", (getter)datetime_second},
3507 {"microsecond", (getter)datetime_microsecond},
3508 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003509 {NULL}
3510};
3511
3512/*
3513 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003514 */
3515
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003516static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003517 "year", "month", "day", "hour", "minute", "second",
3518 "microsecond", "tzinfo", NULL
3519};
3520
Tim Peters2a799bf2002-12-16 20:18:38 +00003521static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003522datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003523{
3524 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003525 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003526 int year;
3527 int month;
3528 int day;
3529 int hour = 0;
3530 int minute = 0;
3531 int second = 0;
3532 int usecond = 0;
3533 PyObject *tzinfo = Py_None;
3534
Guido van Rossum177e41a2003-01-30 22:06:23 +00003535 /* Check for invocation from pickle with __getstate__ state */
3536 if (PyTuple_GET_SIZE(args) >= 1 &&
3537 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003538 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3539 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3540 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003541 {
Tim Peters70533e22003-02-01 04:40:04 +00003542 PyDateTime_DateTime *me;
3543 char aware;
3544
3545 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003546 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003547 if (check_tzinfo_subclass(tzinfo) < 0) {
3548 PyErr_SetString(PyExc_TypeError, "bad "
3549 "tzinfo state arg");
3550 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003551 }
3552 }
Tim Peters70533e22003-02-01 04:40:04 +00003553 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003554 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003555 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003556 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003557
3558 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3559 me->hashcode = -1;
3560 me->hastzinfo = aware;
3561 if (aware) {
3562 Py_INCREF(tzinfo);
3563 me->tzinfo = tzinfo;
3564 }
3565 }
3566 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003567 }
3568
Tim Petersa9bc1682003-01-11 03:39:11 +00003569 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003570 &year, &month, &day, &hour, &minute,
3571 &second, &usecond, &tzinfo)) {
3572 if (check_date_args(year, month, day) < 0)
3573 return NULL;
3574 if (check_time_args(hour, minute, second, usecond) < 0)
3575 return NULL;
3576 if (check_tzinfo_subclass(tzinfo) < 0)
3577 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003578 self = new_datetime_ex(year, month, day,
3579 hour, minute, second, usecond,
3580 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003581 }
3582 return self;
3583}
3584
Tim Petersa9bc1682003-01-11 03:39:11 +00003585/* TM_FUNC is the shared type of localtime() and gmtime(). */
3586typedef struct tm *(*TM_FUNC)(const time_t *timer);
3587
3588/* Internal helper.
3589 * Build datetime from a time_t and a distinct count of microseconds.
3590 * Pass localtime or gmtime for f, to control the interpretation of timet.
3591 */
3592static PyObject *
3593datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3594 PyObject *tzinfo)
3595{
3596 struct tm *tm;
3597 PyObject *result = NULL;
3598
3599 tm = f(&timet);
3600 if (tm) {
3601 /* The platform localtime/gmtime may insert leap seconds,
3602 * indicated by tm->tm_sec > 59. We don't care about them,
3603 * except to the extent that passing them on to the datetime
3604 * constructor would raise ValueError for a reason that
3605 * made no sense to the user.
3606 */
3607 if (tm->tm_sec > 59)
3608 tm->tm_sec = 59;
3609 result = PyObject_CallFunction(cls, "iiiiiiiO",
3610 tm->tm_year + 1900,
3611 tm->tm_mon + 1,
3612 tm->tm_mday,
3613 tm->tm_hour,
3614 tm->tm_min,
3615 tm->tm_sec,
3616 us,
3617 tzinfo);
3618 }
3619 else
3620 PyErr_SetString(PyExc_ValueError,
3621 "timestamp out of range for "
3622 "platform localtime()/gmtime() function");
3623 return result;
3624}
3625
3626/* Internal helper.
3627 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3628 * to control the interpretation of the timestamp. Since a double doesn't
3629 * have enough bits to cover a datetime's full range of precision, it's
3630 * better to call datetime_from_timet_and_us provided you have a way
3631 * to get that much precision (e.g., C time() isn't good enough).
3632 */
3633static PyObject *
3634datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3635 PyObject *tzinfo)
3636{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003637 time_t timet;
3638 double fraction;
3639 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003640
Tim Peters1b6f7a92004-06-20 02:50:16 +00003641 timet = _PyTime_DoubleToTimet(timestamp);
3642 if (timet == (time_t)-1 && PyErr_Occurred())
3643 return NULL;
3644 fraction = timestamp - (double)timet;
3645 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003646 if (us < 0) {
3647 /* Truncation towards zero is not what we wanted
3648 for negative numbers (Python's mod semantics) */
3649 timet -= 1;
3650 us += 1000000;
3651 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003652 /* If timestamp is less than one microsecond smaller than a
3653 * full second, round up. Otherwise, ValueErrors are raised
3654 * for some floats. */
3655 if (us == 1000000) {
3656 timet += 1;
3657 us = 0;
3658 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003659 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3660}
3661
3662/* Internal helper.
3663 * Build most accurate possible datetime for current time. Pass localtime or
3664 * gmtime for f as appropriate.
3665 */
3666static PyObject *
3667datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3668{
3669#ifdef HAVE_GETTIMEOFDAY
3670 struct timeval t;
3671
3672#ifdef GETTIMEOFDAY_NO_TZ
3673 gettimeofday(&t);
3674#else
3675 gettimeofday(&t, (struct timezone *)NULL);
3676#endif
3677 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3678 tzinfo);
3679
3680#else /* ! HAVE_GETTIMEOFDAY */
3681 /* No flavor of gettimeofday exists on this platform. Python's
3682 * time.time() does a lot of other platform tricks to get the
3683 * best time it can on the platform, and we're not going to do
3684 * better than that (if we could, the better code would belong
3685 * in time.time()!) We're limited by the precision of a double,
3686 * though.
3687 */
3688 PyObject *time;
3689 double dtime;
3690
3691 time = time_time();
3692 if (time == NULL)
3693 return NULL;
3694 dtime = PyFloat_AsDouble(time);
3695 Py_DECREF(time);
3696 if (dtime == -1.0 && PyErr_Occurred())
3697 return NULL;
3698 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3699#endif /* ! HAVE_GETTIMEOFDAY */
3700}
3701
Tim Peters2a799bf2002-12-16 20:18:38 +00003702/* Return best possible local time -- this isn't constrained by the
3703 * precision of a timestamp.
3704 */
3705static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003706datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003707{
Tim Peters10cadce2003-01-23 19:58:02 +00003708 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003709 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003710 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003711
Tim Peters10cadce2003-01-23 19:58:02 +00003712 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3713 &tzinfo))
3714 return NULL;
3715 if (check_tzinfo_subclass(tzinfo) < 0)
3716 return NULL;
3717
3718 self = datetime_best_possible(cls,
3719 tzinfo == Py_None ? localtime : gmtime,
3720 tzinfo);
3721 if (self != NULL && tzinfo != Py_None) {
3722 /* Convert UTC to tzinfo's zone. */
3723 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003724 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003725 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003726 }
3727 return self;
3728}
3729
Tim Petersa9bc1682003-01-11 03:39:11 +00003730/* Return best possible UTC time -- this isn't constrained by the
3731 * precision of a timestamp.
3732 */
3733static PyObject *
3734datetime_utcnow(PyObject *cls, PyObject *dummy)
3735{
3736 return datetime_best_possible(cls, gmtime, Py_None);
3737}
3738
Tim Peters2a799bf2002-12-16 20:18:38 +00003739/* Return new local datetime from timestamp (Python timestamp -- a double). */
3740static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003741datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003742{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003743 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003744 double timestamp;
3745 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003746 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003747
Tim Peters2a44a8d2003-01-23 20:53:10 +00003748 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3749 keywords, &timestamp, &tzinfo))
3750 return NULL;
3751 if (check_tzinfo_subclass(tzinfo) < 0)
3752 return NULL;
3753
3754 self = datetime_from_timestamp(cls,
3755 tzinfo == Py_None ? localtime : gmtime,
3756 timestamp,
3757 tzinfo);
3758 if (self != NULL && tzinfo != Py_None) {
3759 /* Convert UTC to tzinfo's zone. */
3760 PyObject *temp = self;
3761 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3762 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003763 }
3764 return self;
3765}
3766
Tim Petersa9bc1682003-01-11 03:39:11 +00003767/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3768static PyObject *
3769datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3770{
3771 double timestamp;
3772 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003773
Tim Petersa9bc1682003-01-11 03:39:11 +00003774 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3775 result = datetime_from_timestamp(cls, gmtime, timestamp,
3776 Py_None);
3777 return result;
3778}
3779
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003780/* Return new datetime from time.strptime(). */
3781static PyObject *
3782datetime_strptime(PyObject *cls, PyObject *args)
3783{
3784 PyObject *result = NULL, *obj, *module;
3785 const char *string, *format;
3786
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003787 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003788 return NULL;
3789
3790 if ((module = PyImport_ImportModule("time")) == NULL)
3791 return NULL;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003792 obj = PyObject_CallMethod(module, "strptime", "uu", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003793 Py_DECREF(module);
3794
3795 if (obj != NULL) {
3796 int i, good_timetuple = 1;
3797 long int ia[6];
3798 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3799 for (i=0; i < 6; i++) {
3800 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003801 if (p == NULL) {
3802 Py_DECREF(obj);
3803 return NULL;
3804 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003805 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003806 ia[i] = PyInt_AsLong(p);
3807 else
3808 good_timetuple = 0;
3809 Py_DECREF(p);
3810 }
3811 else
3812 good_timetuple = 0;
3813 if (good_timetuple)
3814 result = PyObject_CallFunction(cls, "iiiiii",
3815 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3816 else
3817 PyErr_SetString(PyExc_ValueError,
3818 "unexpected value from time.strptime");
3819 Py_DECREF(obj);
3820 }
3821 return result;
3822}
3823
Tim Petersa9bc1682003-01-11 03:39:11 +00003824/* Return new datetime from date/datetime and time arguments. */
3825static PyObject *
3826datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3827{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003828 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003829 PyObject *date;
3830 PyObject *time;
3831 PyObject *result = NULL;
3832
3833 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3834 &PyDateTime_DateType, &date,
3835 &PyDateTime_TimeType, &time)) {
3836 PyObject *tzinfo = Py_None;
3837
3838 if (HASTZINFO(time))
3839 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3840 result = PyObject_CallFunction(cls, "iiiiiiiO",
3841 GET_YEAR(date),
3842 GET_MONTH(date),
3843 GET_DAY(date),
3844 TIME_GET_HOUR(time),
3845 TIME_GET_MINUTE(time),
3846 TIME_GET_SECOND(time),
3847 TIME_GET_MICROSECOND(time),
3848 tzinfo);
3849 }
3850 return result;
3851}
Tim Peters2a799bf2002-12-16 20:18:38 +00003852
3853/*
3854 * Destructor.
3855 */
3856
3857static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003858datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003859{
Tim Petersa9bc1682003-01-11 03:39:11 +00003860 if (HASTZINFO(self)) {
3861 Py_XDECREF(self->tzinfo);
3862 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003863 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003864}
3865
3866/*
3867 * Indirect access to tzinfo methods.
3868 */
3869
Tim Peters2a799bf2002-12-16 20:18:38 +00003870/* These are all METH_NOARGS, so don't need to check the arglist. */
3871static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003872datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3873 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3874 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003875}
3876
3877static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003878datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3879 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3880 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003881}
3882
3883static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003884datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3885 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3886 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003887}
3888
3889/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003890 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003891 */
3892
Tim Petersa9bc1682003-01-11 03:39:11 +00003893/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3894 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003895 */
3896static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003897add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3898 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003899{
Tim Petersa9bc1682003-01-11 03:39:11 +00003900 /* Note that the C-level additions can't overflow, because of
3901 * invariant bounds on the member values.
3902 */
3903 int year = GET_YEAR(date);
3904 int month = GET_MONTH(date);
3905 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3906 int hour = DATE_GET_HOUR(date);
3907 int minute = DATE_GET_MINUTE(date);
3908 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3909 int microsecond = DATE_GET_MICROSECOND(date) +
3910 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003911
Tim Petersa9bc1682003-01-11 03:39:11 +00003912 assert(factor == 1 || factor == -1);
3913 if (normalize_datetime(&year, &month, &day,
3914 &hour, &minute, &second, &microsecond) < 0)
3915 return NULL;
3916 else
3917 return new_datetime(year, month, day,
3918 hour, minute, second, microsecond,
3919 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003920}
3921
3922static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003923datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003924{
Tim Petersa9bc1682003-01-11 03:39:11 +00003925 if (PyDateTime_Check(left)) {
3926 /* datetime + ??? */
3927 if (PyDelta_Check(right))
3928 /* datetime + delta */
3929 return add_datetime_timedelta(
3930 (PyDateTime_DateTime *)left,
3931 (PyDateTime_Delta *)right,
3932 1);
3933 }
3934 else if (PyDelta_Check(left)) {
3935 /* delta + datetime */
3936 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3937 (PyDateTime_Delta *) left,
3938 1);
3939 }
3940 Py_INCREF(Py_NotImplemented);
3941 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003942}
3943
3944static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003945datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003946{
3947 PyObject *result = Py_NotImplemented;
3948
3949 if (PyDateTime_Check(left)) {
3950 /* datetime - ??? */
3951 if (PyDateTime_Check(right)) {
3952 /* datetime - datetime */
3953 naivety n1, n2;
3954 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003955 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003956
Tim Peterse39a80c2002-12-30 21:28:52 +00003957 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3958 right, &offset2, &n2,
3959 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003960 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003961 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003962 if (n1 != n2) {
3963 PyErr_SetString(PyExc_TypeError,
3964 "can't subtract offset-naive and "
3965 "offset-aware datetimes");
3966 return NULL;
3967 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003968 delta_d = ymd_to_ord(GET_YEAR(left),
3969 GET_MONTH(left),
3970 GET_DAY(left)) -
3971 ymd_to_ord(GET_YEAR(right),
3972 GET_MONTH(right),
3973 GET_DAY(right));
3974 /* These can't overflow, since the values are
3975 * normalized. At most this gives the number of
3976 * seconds in one day.
3977 */
3978 delta_s = (DATE_GET_HOUR(left) -
3979 DATE_GET_HOUR(right)) * 3600 +
3980 (DATE_GET_MINUTE(left) -
3981 DATE_GET_MINUTE(right)) * 60 +
3982 (DATE_GET_SECOND(left) -
3983 DATE_GET_SECOND(right));
3984 delta_us = DATE_GET_MICROSECOND(left) -
3985 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003986 /* (left - offset1) - (right - offset2) =
3987 * (left - right) + (offset2 - offset1)
3988 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003989 delta_s += (offset2 - offset1) * 60;
3990 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003991 }
3992 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003993 /* datetime - delta */
3994 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003995 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00003996 (PyDateTime_Delta *)right,
3997 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003998 }
3999 }
4000
4001 if (result == Py_NotImplemented)
4002 Py_INCREF(result);
4003 return result;
4004}
4005
4006/* Various ways to turn a datetime into a string. */
4007
4008static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004009datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004010{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004011 const char *type_name = Py_Type(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004012 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004013
Tim Petersa9bc1682003-01-11 03:39:11 +00004014 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004015 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004016 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004017 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004018 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4019 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4020 DATE_GET_SECOND(self),
4021 DATE_GET_MICROSECOND(self));
4022 }
4023 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004024 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004025 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004026 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004027 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4028 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4029 DATE_GET_SECOND(self));
4030 }
4031 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004032 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004033 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004034 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004035 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4036 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4037 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004038 if (baserepr == NULL || ! HASTZINFO(self))
4039 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004040 return append_keyword_tzinfo(baserepr, self->tzinfo);
4041}
4042
Tim Petersa9bc1682003-01-11 03:39:11 +00004043static PyObject *
4044datetime_str(PyDateTime_DateTime *self)
4045{
4046 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4047}
Tim Peters2a799bf2002-12-16 20:18:38 +00004048
4049static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004050datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004051{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004052 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004053 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004054 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004055 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004056 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004057
Walter Dörwaldd0941302007-07-01 21:58:22 +00004058 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004059 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004060 if (us)
4061 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4062 GET_YEAR(self), GET_MONTH(self),
4063 GET_DAY(self), (int)sep,
4064 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4065 DATE_GET_SECOND(self), us);
4066 else
4067 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4068 GET_YEAR(self), GET_MONTH(self),
4069 GET_DAY(self), (int)sep,
4070 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4071 DATE_GET_SECOND(self));
4072
4073 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004074 return result;
4075
4076 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004077 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004078 (PyObject *)self) < 0) {
4079 Py_DECREF(result);
4080 return NULL;
4081 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004082 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004083 return result;
4084}
4085
Tim Petersa9bc1682003-01-11 03:39:11 +00004086static PyObject *
4087datetime_ctime(PyDateTime_DateTime *self)
4088{
4089 return format_ctime((PyDateTime_Date *)self,
4090 DATE_GET_HOUR(self),
4091 DATE_GET_MINUTE(self),
4092 DATE_GET_SECOND(self));
4093}
4094
Tim Peters2a799bf2002-12-16 20:18:38 +00004095/* Miscellaneous methods. */
4096
Tim Petersa9bc1682003-01-11 03:39:11 +00004097static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004098datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004099{
4100 int diff;
4101 naivety n1, n2;
4102 int offset1, offset2;
4103
4104 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004105 if (PyDate_Check(other)) {
4106 /* Prevent invocation of date_richcompare. We want to
4107 return NotImplemented here to give the other object
4108 a chance. But since DateTime is a subclass of
4109 Date, if the other object is a Date, it would
4110 compute an ordering based on the date part alone,
4111 and we don't want that. So force unequal or
4112 uncomparable here in that case. */
4113 if (op == Py_EQ)
4114 Py_RETURN_FALSE;
4115 if (op == Py_NE)
4116 Py_RETURN_TRUE;
4117 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004118 }
Guido van Rossum19960592006-08-24 17:29:38 +00004119 Py_INCREF(Py_NotImplemented);
4120 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004121 }
4122
Guido van Rossum19960592006-08-24 17:29:38 +00004123 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4124 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004125 return NULL;
4126 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4127 /* If they're both naive, or both aware and have the same offsets,
4128 * we get off cheap. Note that if they're both naive, offset1 ==
4129 * offset2 == 0 at this point.
4130 */
4131 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004132 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4133 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004134 _PyDateTime_DATETIME_DATASIZE);
4135 return diff_to_bool(diff, op);
4136 }
4137
4138 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4139 PyDateTime_Delta *delta;
4140
4141 assert(offset1 != offset2); /* else last "if" handled it */
4142 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4143 other);
4144 if (delta == NULL)
4145 return NULL;
4146 diff = GET_TD_DAYS(delta);
4147 if (diff == 0)
4148 diff = GET_TD_SECONDS(delta) |
4149 GET_TD_MICROSECONDS(delta);
4150 Py_DECREF(delta);
4151 return diff_to_bool(diff, op);
4152 }
4153
4154 assert(n1 != n2);
4155 PyErr_SetString(PyExc_TypeError,
4156 "can't compare offset-naive and "
4157 "offset-aware datetimes");
4158 return NULL;
4159}
4160
4161static long
4162datetime_hash(PyDateTime_DateTime *self)
4163{
4164 if (self->hashcode == -1) {
4165 naivety n;
4166 int offset;
4167 PyObject *temp;
4168
4169 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4170 &offset);
4171 assert(n != OFFSET_UNKNOWN);
4172 if (n == OFFSET_ERROR)
4173 return -1;
4174
4175 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00004176 if (n == OFFSET_NAIVE) {
4177 self->hashcode = generic_hash(
4178 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4179 return self->hashcode;
4180 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004181 else {
4182 int days;
4183 int seconds;
4184
4185 assert(n == OFFSET_AWARE);
4186 assert(HASTZINFO(self));
4187 days = ymd_to_ord(GET_YEAR(self),
4188 GET_MONTH(self),
4189 GET_DAY(self));
4190 seconds = DATE_GET_HOUR(self) * 3600 +
4191 (DATE_GET_MINUTE(self) - offset) * 60 +
4192 DATE_GET_SECOND(self);
4193 temp = new_delta(days,
4194 seconds,
4195 DATE_GET_MICROSECOND(self),
4196 1);
4197 }
4198 if (temp != NULL) {
4199 self->hashcode = PyObject_Hash(temp);
4200 Py_DECREF(temp);
4201 }
4202 }
4203 return self->hashcode;
4204}
Tim Peters2a799bf2002-12-16 20:18:38 +00004205
4206static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004207datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004208{
4209 PyObject *clone;
4210 PyObject *tuple;
4211 int y = GET_YEAR(self);
4212 int m = GET_MONTH(self);
4213 int d = GET_DAY(self);
4214 int hh = DATE_GET_HOUR(self);
4215 int mm = DATE_GET_MINUTE(self);
4216 int ss = DATE_GET_SECOND(self);
4217 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004218 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004219
4220 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004221 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004222 &y, &m, &d, &hh, &mm, &ss, &us,
4223 &tzinfo))
4224 return NULL;
4225 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4226 if (tuple == NULL)
4227 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004228 clone = datetime_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004229 Py_DECREF(tuple);
4230 return clone;
4231}
4232
4233static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004234datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004235{
Tim Peters52dcce22003-01-23 16:36:11 +00004236 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004237 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004238 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004239
Tim Peters80475bb2002-12-25 07:40:55 +00004240 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004241 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004242
Tim Peters52dcce22003-01-23 16:36:11 +00004243 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4244 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004245 return NULL;
4246
Tim Peters52dcce22003-01-23 16:36:11 +00004247 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4248 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004249
Tim Peters52dcce22003-01-23 16:36:11 +00004250 /* Conversion to self's own time zone is a NOP. */
4251 if (self->tzinfo == tzinfo) {
4252 Py_INCREF(self);
4253 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004254 }
Tim Peters521fc152002-12-31 17:36:56 +00004255
Tim Peters52dcce22003-01-23 16:36:11 +00004256 /* Convert self to UTC. */
4257 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4258 if (offset == -1 && PyErr_Occurred())
4259 return NULL;
4260 if (none)
4261 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004262
Tim Peters52dcce22003-01-23 16:36:11 +00004263 y = GET_YEAR(self);
4264 m = GET_MONTH(self);
4265 d = GET_DAY(self);
4266 hh = DATE_GET_HOUR(self);
4267 mm = DATE_GET_MINUTE(self);
4268 ss = DATE_GET_SECOND(self);
4269 us = DATE_GET_MICROSECOND(self);
4270
4271 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004272 if ((mm < 0 || mm >= 60) &&
4273 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004274 return NULL;
4275
4276 /* Attach new tzinfo and let fromutc() do the rest. */
4277 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4278 if (result != NULL) {
4279 PyObject *temp = result;
4280
4281 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4282 Py_DECREF(temp);
4283 }
Tim Petersadf64202003-01-04 06:03:15 +00004284 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004285
Tim Peters52dcce22003-01-23 16:36:11 +00004286NeedAware:
4287 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4288 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004289 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004290}
4291
4292static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004293datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004294{
4295 int dstflag = -1;
4296
Tim Petersa9bc1682003-01-11 03:39:11 +00004297 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004298 int none;
4299
4300 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4301 if (dstflag == -1 && PyErr_Occurred())
4302 return NULL;
4303
4304 if (none)
4305 dstflag = -1;
4306 else if (dstflag != 0)
4307 dstflag = 1;
4308
4309 }
4310 return build_struct_time(GET_YEAR(self),
4311 GET_MONTH(self),
4312 GET_DAY(self),
4313 DATE_GET_HOUR(self),
4314 DATE_GET_MINUTE(self),
4315 DATE_GET_SECOND(self),
4316 dstflag);
4317}
4318
4319static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004320datetime_getdate(PyDateTime_DateTime *self)
4321{
4322 return new_date(GET_YEAR(self),
4323 GET_MONTH(self),
4324 GET_DAY(self));
4325}
4326
4327static PyObject *
4328datetime_gettime(PyDateTime_DateTime *self)
4329{
4330 return new_time(DATE_GET_HOUR(self),
4331 DATE_GET_MINUTE(self),
4332 DATE_GET_SECOND(self),
4333 DATE_GET_MICROSECOND(self),
4334 Py_None);
4335}
4336
4337static PyObject *
4338datetime_gettimetz(PyDateTime_DateTime *self)
4339{
4340 return new_time(DATE_GET_HOUR(self),
4341 DATE_GET_MINUTE(self),
4342 DATE_GET_SECOND(self),
4343 DATE_GET_MICROSECOND(self),
4344 HASTZINFO(self) ? self->tzinfo : Py_None);
4345}
4346
4347static PyObject *
4348datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004349{
4350 int y = GET_YEAR(self);
4351 int m = GET_MONTH(self);
4352 int d = GET_DAY(self);
4353 int hh = DATE_GET_HOUR(self);
4354 int mm = DATE_GET_MINUTE(self);
4355 int ss = DATE_GET_SECOND(self);
4356 int us = 0; /* microseconds are ignored in a timetuple */
4357 int offset = 0;
4358
Tim Petersa9bc1682003-01-11 03:39:11 +00004359 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004360 int none;
4361
4362 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4363 if (offset == -1 && PyErr_Occurred())
4364 return NULL;
4365 }
4366 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4367 * 0 in a UTC timetuple regardless of what dst() says.
4368 */
4369 if (offset) {
4370 /* Subtract offset minutes & normalize. */
4371 int stat;
4372
4373 mm -= offset;
4374 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4375 if (stat < 0) {
4376 /* At the edges, it's possible we overflowed
4377 * beyond MINYEAR or MAXYEAR.
4378 */
4379 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4380 PyErr_Clear();
4381 else
4382 return NULL;
4383 }
4384 }
4385 return build_struct_time(y, m, d, hh, mm, ss, 0);
4386}
4387
Tim Peters371935f2003-02-01 01:52:50 +00004388/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004389
Tim Petersa9bc1682003-01-11 03:39:11 +00004390/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004391 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4392 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004393 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004394 */
4395static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004396datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004397{
4398 PyObject *basestate;
4399 PyObject *result = NULL;
4400
Martin v. Löwis10a60b32007-07-18 02:28:27 +00004401 basestate = PyBytes_FromStringAndSize((char *)self->data,
4402 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004403 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004404 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004405 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004406 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004407 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004408 Py_DECREF(basestate);
4409 }
4410 return result;
4411}
4412
4413static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004414datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004415{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004416 return Py_BuildValue("(ON)", Py_Type(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004417}
4418
Tim Petersa9bc1682003-01-11 03:39:11 +00004419static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004420
Tim Peters2a799bf2002-12-16 20:18:38 +00004421 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004422
Tim Petersa9bc1682003-01-11 03:39:11 +00004423 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004424 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004425 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004426
Tim Petersa9bc1682003-01-11 03:39:11 +00004427 {"utcnow", (PyCFunction)datetime_utcnow,
4428 METH_NOARGS | METH_CLASS,
4429 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4430
4431 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004432 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004433 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004434
Tim Petersa9bc1682003-01-11 03:39:11 +00004435 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4436 METH_VARARGS | METH_CLASS,
4437 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4438 "(like time.time()).")},
4439
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004440 {"strptime", (PyCFunction)datetime_strptime,
4441 METH_VARARGS | METH_CLASS,
4442 PyDoc_STR("string, format -> new datetime parsed from a string "
4443 "(like time.strptime()).")},
4444
Tim Petersa9bc1682003-01-11 03:39:11 +00004445 {"combine", (PyCFunction)datetime_combine,
4446 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4447 PyDoc_STR("date, time -> datetime with same date and time fields")},
4448
Tim Peters2a799bf2002-12-16 20:18:38 +00004449 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004450
Tim Petersa9bc1682003-01-11 03:39:11 +00004451 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4452 PyDoc_STR("Return date object with same year, month and day.")},
4453
4454 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4455 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4456
4457 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4458 PyDoc_STR("Return time object with same time and tzinfo.")},
4459
4460 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4461 PyDoc_STR("Return ctime() style string.")},
4462
4463 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004464 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4465
Tim Petersa9bc1682003-01-11 03:39:11 +00004466 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004467 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4468
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004469 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004470 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4471 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4472 "sep is used to separate the year from the time, and "
4473 "defaults to 'T'.")},
4474
Tim Petersa9bc1682003-01-11 03:39:11 +00004475 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004476 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4477
Tim Petersa9bc1682003-01-11 03:39:11 +00004478 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004479 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4480
Tim Petersa9bc1682003-01-11 03:39:11 +00004481 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004482 PyDoc_STR("Return self.tzinfo.dst(self).")},
4483
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004484 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004485 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004486
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004487 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004488 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4489
Guido van Rossum177e41a2003-01-30 22:06:23 +00004490 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4491 PyDoc_STR("__reduce__() -> (cls, state)")},
4492
Tim Peters2a799bf2002-12-16 20:18:38 +00004493 {NULL, NULL}
4494};
4495
Tim Petersa9bc1682003-01-11 03:39:11 +00004496static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004497PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4498\n\
4499The year, month and day arguments are required. tzinfo may be None, or an\n\
4500instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004501
Tim Petersa9bc1682003-01-11 03:39:11 +00004502static PyNumberMethods datetime_as_number = {
4503 datetime_add, /* nb_add */
4504 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004505 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004506 0, /* nb_remainder */
4507 0, /* nb_divmod */
4508 0, /* nb_power */
4509 0, /* nb_negative */
4510 0, /* nb_positive */
4511 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004512 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004513};
4514
Neal Norwitz227b5332006-03-22 09:28:35 +00004515static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004516 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004517 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004518 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004519 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004520 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004521 0, /* tp_print */
4522 0, /* tp_getattr */
4523 0, /* tp_setattr */
4524 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004525 (reprfunc)datetime_repr, /* tp_repr */
4526 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 0, /* tp_as_sequence */
4528 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004529 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004530 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004531 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004532 PyObject_GenericGetAttr, /* tp_getattro */
4533 0, /* tp_setattro */
4534 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004535 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004536 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004537 0, /* tp_traverse */
4538 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004539 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004540 0, /* tp_weaklistoffset */
4541 0, /* tp_iter */
4542 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004543 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004544 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004545 datetime_getset, /* tp_getset */
4546 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004547 0, /* tp_dict */
4548 0, /* tp_descr_get */
4549 0, /* tp_descr_set */
4550 0, /* tp_dictoffset */
4551 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004552 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004553 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004554 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004555};
4556
4557/* ---------------------------------------------------------------------------
4558 * Module methods and initialization.
4559 */
4560
4561static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004562 {NULL, NULL}
4563};
4564
Tim Peters9ddf40b2004-06-20 22:41:32 +00004565/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4566 * datetime.h.
4567 */
4568static PyDateTime_CAPI CAPI = {
4569 &PyDateTime_DateType,
4570 &PyDateTime_DateTimeType,
4571 &PyDateTime_TimeType,
4572 &PyDateTime_DeltaType,
4573 &PyDateTime_TZInfoType,
4574 new_date_ex,
4575 new_datetime_ex,
4576 new_time_ex,
4577 new_delta_ex,
4578 datetime_fromtimestamp,
4579 date_fromtimestamp
4580};
4581
4582
Tim Peters2a799bf2002-12-16 20:18:38 +00004583PyMODINIT_FUNC
4584initdatetime(void)
4585{
4586 PyObject *m; /* a module object */
4587 PyObject *d; /* its dict */
4588 PyObject *x;
4589
Tim Peters2a799bf2002-12-16 20:18:38 +00004590 m = Py_InitModule3("datetime", module_methods,
4591 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004592 if (m == NULL)
4593 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004594
4595 if (PyType_Ready(&PyDateTime_DateType) < 0)
4596 return;
4597 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4598 return;
4599 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4600 return;
4601 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4602 return;
4603 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4604 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004605
Tim Peters2a799bf2002-12-16 20:18:38 +00004606 /* timedelta values */
4607 d = PyDateTime_DeltaType.tp_dict;
4608
Tim Peters2a799bf2002-12-16 20:18:38 +00004609 x = new_delta(0, 0, 1, 0);
4610 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4611 return;
4612 Py_DECREF(x);
4613
4614 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4615 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4616 return;
4617 Py_DECREF(x);
4618
4619 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4620 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4621 return;
4622 Py_DECREF(x);
4623
4624 /* date values */
4625 d = PyDateTime_DateType.tp_dict;
4626
4627 x = new_date(1, 1, 1);
4628 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4629 return;
4630 Py_DECREF(x);
4631
4632 x = new_date(MAXYEAR, 12, 31);
4633 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4634 return;
4635 Py_DECREF(x);
4636
4637 x = new_delta(1, 0, 0, 0);
4638 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4639 return;
4640 Py_DECREF(x);
4641
Tim Peters37f39822003-01-10 03:49:02 +00004642 /* time values */
4643 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004644
Tim Peters37f39822003-01-10 03:49:02 +00004645 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004646 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4647 return;
4648 Py_DECREF(x);
4649
Tim Peters37f39822003-01-10 03:49:02 +00004650 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004651 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4652 return;
4653 Py_DECREF(x);
4654
4655 x = new_delta(0, 0, 1, 0);
4656 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4657 return;
4658 Py_DECREF(x);
4659
Tim Petersa9bc1682003-01-11 03:39:11 +00004660 /* datetime values */
4661 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004662
Tim Petersa9bc1682003-01-11 03:39:11 +00004663 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004664 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4665 return;
4666 Py_DECREF(x);
4667
Tim Petersa9bc1682003-01-11 03:39:11 +00004668 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004669 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4670 return;
4671 Py_DECREF(x);
4672
4673 x = new_delta(0, 0, 1, 0);
4674 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4675 return;
4676 Py_DECREF(x);
4677
Tim Peters2a799bf2002-12-16 20:18:38 +00004678 /* module initialization */
4679 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4680 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4681
4682 Py_INCREF(&PyDateTime_DateType);
4683 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4684
Tim Petersa9bc1682003-01-11 03:39:11 +00004685 Py_INCREF(&PyDateTime_DateTimeType);
4686 PyModule_AddObject(m, "datetime",
4687 (PyObject *)&PyDateTime_DateTimeType);
4688
4689 Py_INCREF(&PyDateTime_TimeType);
4690 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4691
Tim Peters2a799bf2002-12-16 20:18:38 +00004692 Py_INCREF(&PyDateTime_DeltaType);
4693 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4694
Tim Peters2a799bf2002-12-16 20:18:38 +00004695 Py_INCREF(&PyDateTime_TZInfoType);
4696 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4697
Tim Peters9ddf40b2004-06-20 22:41:32 +00004698 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4699 NULL);
4700 if (x == NULL)
4701 return;
4702 PyModule_AddObject(m, "datetime_CAPI", x);
4703
Tim Peters2a799bf2002-12-16 20:18:38 +00004704 /* A 4-year cycle has an extra leap day over what we'd get from
4705 * pasting together 4 single years.
4706 */
4707 assert(DI4Y == 4 * 365 + 1);
4708 assert(DI4Y == days_before_year(4+1));
4709
4710 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4711 * get from pasting together 4 100-year cycles.
4712 */
4713 assert(DI400Y == 4 * DI100Y + 1);
4714 assert(DI400Y == days_before_year(400+1));
4715
4716 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4717 * pasting together 25 4-year cycles.
4718 */
4719 assert(DI100Y == 25 * DI4Y - 1);
4720 assert(DI100Y == days_before_year(100+1));
4721
4722 us_per_us = PyInt_FromLong(1);
4723 us_per_ms = PyInt_FromLong(1000);
4724 us_per_second = PyInt_FromLong(1000000);
4725 us_per_minute = PyInt_FromLong(60000000);
4726 seconds_per_day = PyInt_FromLong(24 * 3600);
4727 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4728 us_per_minute == NULL || seconds_per_day == NULL)
4729 return;
4730
4731 /* The rest are too big for 32-bit ints, but even
4732 * us_per_week fits in 40 bits, so doubles should be exact.
4733 */
4734 us_per_hour = PyLong_FromDouble(3600000000.0);
4735 us_per_day = PyLong_FromDouble(86400000000.0);
4736 us_per_week = PyLong_FromDouble(604800000000.0);
4737 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4738 return;
4739}
Tim Petersf3615152003-01-01 21:51:37 +00004740
4741/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004742Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004743 x.n = x stripped of its timezone -- its naive time.
4744 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4745 return None
4746 x.d = x.dst(), and assuming that doesn't raise an exception or
4747 return None
4748 x.s = x's standard offset, x.o - x.d
4749
4750Now some derived rules, where k is a duration (timedelta).
4751
47521. x.o = x.s + x.d
4753 This follows from the definition of x.s.
4754
Tim Petersc5dc4da2003-01-02 17:55:03 +000047552. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004756 This is actually a requirement, an assumption we need to make about
4757 sane tzinfo classes.
4758
47593. The naive UTC time corresponding to x is x.n - x.o.
4760 This is again a requirement for a sane tzinfo class.
4761
47624. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004763 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004764
Tim Petersc5dc4da2003-01-02 17:55:03 +000047655. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004766 Again follows from how arithmetic is defined.
4767
Tim Peters8bb5ad22003-01-24 02:44:45 +00004768Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004769(meaning that the various tzinfo methods exist, and don't blow up or return
4770None when called).
4771
Tim Petersa9bc1682003-01-11 03:39:11 +00004772The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004773x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004774
4775By #3, we want
4776
Tim Peters8bb5ad22003-01-24 02:44:45 +00004777 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004778
4779The algorithm starts by attaching tz to x.n, and calling that y. So
4780x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4781becomes true; in effect, we want to solve [2] for k:
4782
Tim Peters8bb5ad22003-01-24 02:44:45 +00004783 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004784
4785By #1, this is the same as
4786
Tim Peters8bb5ad22003-01-24 02:44:45 +00004787 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004788
4789By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4790Substituting that into [3],
4791
Tim Peters8bb5ad22003-01-24 02:44:45 +00004792 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4793 k - (y+k).s - (y+k).d = 0; rearranging,
4794 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4795 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004796
Tim Peters8bb5ad22003-01-24 02:44:45 +00004797On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4798approximate k by ignoring the (y+k).d term at first. Note that k can't be
4799very large, since all offset-returning methods return a duration of magnitude
4800less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4801be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004802
4803In any case, the new value is
4804
Tim Peters8bb5ad22003-01-24 02:44:45 +00004805 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004806
Tim Peters8bb5ad22003-01-24 02:44:45 +00004807It's helpful to step back at look at [4] from a higher level: it's simply
4808mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004809
4810At this point, if
4811
Tim Peters8bb5ad22003-01-24 02:44:45 +00004812 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004813
4814we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004815at the start of daylight time. Picture US Eastern for concreteness. The wall
4816time 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 +00004817sense then. The docs ask that an Eastern tzinfo class consider such a time to
4818be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4819on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004820the only spelling that makes sense on the local wall clock.
4821
Tim Petersc5dc4da2003-01-02 17:55:03 +00004822In fact, if [5] holds at this point, we do have the standard-time spelling,
4823but that takes a bit of proof. We first prove a stronger result. What's the
4824difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004825
Tim Peters8bb5ad22003-01-24 02:44:45 +00004826 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004827
Tim Petersc5dc4da2003-01-02 17:55:03 +00004828Now
4829 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004830 (y + y.s).n = by #5
4831 y.n + y.s = since y.n = x.n
4832 x.n + y.s = since z and y are have the same tzinfo member,
4833 y.s = z.s by #2
4834 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004835
Tim Petersc5dc4da2003-01-02 17:55:03 +00004836Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004837
Tim Petersc5dc4da2003-01-02 17:55:03 +00004838 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004839 x.n - ((x.n + z.s) - z.o) = expanding
4840 x.n - x.n - z.s + z.o = cancelling
4841 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004842 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004843
Tim Petersc5dc4da2003-01-02 17:55:03 +00004844So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004845
Tim Petersc5dc4da2003-01-02 17:55:03 +00004846If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004847spelling we wanted in the endcase described above. We're done. Contrarily,
4848if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004849
Tim Petersc5dc4da2003-01-02 17:55:03 +00004850If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4851add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004852local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004853
Tim Petersc5dc4da2003-01-02 17:55:03 +00004854Let
Tim Petersf3615152003-01-01 21:51:37 +00004855
Tim Peters4fede1a2003-01-04 00:26:59 +00004856 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004857
Tim Peters4fede1a2003-01-04 00:26:59 +00004858and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004859
Tim Peters8bb5ad22003-01-24 02:44:45 +00004860 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004861
Tim Peters8bb5ad22003-01-24 02:44:45 +00004862If so, we're done. If not, the tzinfo class is insane, according to the
4863assumptions we've made. This also requires a bit of proof. As before, let's
4864compute the difference between the LHS and RHS of [8] (and skipping some of
4865the justifications for the kinds of substitutions we've done several times
4866already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004867
Tim Peters8bb5ad22003-01-24 02:44:45 +00004868 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4869 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4870 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4871 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4872 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004873 - z.o + z'.o = #1 twice
4874 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4875 z'.d - z.d
4876
4877So 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 +00004878we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4879return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004880
Tim Peters8bb5ad22003-01-24 02:44:45 +00004881How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4882a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4883would have to change the result dst() returns: we start in DST, and moving
4884a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004885
Tim Peters8bb5ad22003-01-24 02:44:45 +00004886There isn't a sane case where this can happen. The closest it gets is at
4887the end of DST, where there's an hour in UTC with no spelling in a hybrid
4888tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4889that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4890UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4891time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4892clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4893standard time. Since that's what the local clock *does*, we want to map both
4894UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004895in local time, but so it goes -- it's the way the local clock works.
4896
Tim Peters8bb5ad22003-01-24 02:44:45 +00004897When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4898so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4899z' = 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 +00004900(correctly) concludes that z' is not UTC-equivalent to x.
4901
4902Because we know z.d said z was in daylight time (else [5] would have held and
4903we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004904and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004905return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4906but the reasoning doesn't depend on the example -- it depends on there being
4907two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004908z' must be in standard time, and is the spelling we want in this case.
4909
4910Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4911concerned (because it takes z' as being in standard time rather than the
4912daylight time we intend here), but returning it gives the real-life "local
4913clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4914tz.
4915
4916When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4917the 1:MM standard time spelling we want.
4918
4919So how can this break? One of the assumptions must be violated. Two
4920possibilities:
4921
49221) [2] effectively says that y.s is invariant across all y belong to a given
4923 time zone. This isn't true if, for political reasons or continental drift,
4924 a region decides to change its base offset from UTC.
4925
49262) There may be versions of "double daylight" time where the tail end of
4927 the analysis gives up a step too early. I haven't thought about that
4928 enough to say.
4929
4930In any case, it's clear that the default fromutc() is strong enough to handle
4931"almost all" time zones: so long as the standard offset is invariant, it
4932doesn't matter if daylight time transition points change from year to year, or
4933if daylight time is skipped in some years; it doesn't matter how large or
4934small dst() may get within its bounds; and it doesn't even matter if some
4935perverse time zone returns a negative dst()). So a breaking case must be
4936pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004937--------------------------------------------------------------------------- */