blob: b48385f4544f960b36fb46818f543c5f94a4d0b1 [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);
Neal Norwitz908c8712007-08-27 04:58:38 +00001163 Py_DECREF(Zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001164 if (tmp == NULL)
Neal Norwitzaea70e02007-08-12 04:32:26 +00001165 return NULL;
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));
Neal Norwitz908c8712007-08-27 04:58:38 +00001211 /* 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);
Tim Peters2a799bf2002-12-16 20:18:38 +00001216
Tim Petersd6844152002-12-22 20:58:42 +00001217 /* Give up if the year is before 1900.
1218 * Python strftime() plays games with the year, and different
1219 * games depending on whether envar PYTHON2K is set. This makes
1220 * years before 1900 a nightmare, even if the platform strftime
1221 * supports them (and not all do).
1222 * We could get a lot farther here by avoiding Python's strftime
1223 * wrapper and calling the C strftime() directly, but that isn't
1224 * an option in the Python implementation of this module.
1225 */
1226 {
1227 long year;
1228 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1229 if (pyyear == NULL) return NULL;
1230 assert(PyInt_Check(pyyear));
1231 year = PyInt_AsLong(pyyear);
1232 Py_DECREF(pyyear);
1233 if (year < 1900) {
1234 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1235 "1900; the datetime strftime() "
1236 "methods require year >= 1900",
1237 year);
1238 return NULL;
1239 }
1240 }
1241
Tim Peters2a799bf2002-12-16 20:18:38 +00001242 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001243 * a new format. Since computing the replacements for those codes
1244 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001245 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001246 totalnew = flen + 1; /* realistic if no %z/%Z */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001247 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
Tim Peters2a799bf2002-12-16 20:18:38 +00001248 if (newfmt == NULL) goto Done;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001249 pnew = PyBytes_AsString(newfmt);
Tim Peters2a799bf2002-12-16 20:18:38 +00001250 usednew = 0;
1251
Tim Peters2a799bf2002-12-16 20:18:38 +00001252 while ((ch = *pin++) != '\0') {
1253 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001254 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001255 ntoappend = 1;
1256 }
1257 else if ((ch = *pin++) == '\0') {
1258 /* There's a lone trailing %; doesn't make sense. */
1259 PyErr_SetString(PyExc_ValueError, "strftime format "
1260 "ends with raw %");
1261 goto Done;
1262 }
1263 /* A % has been seen and ch is the character after it. */
1264 else if (ch == 'z') {
1265 if (zreplacement == NULL) {
1266 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001267 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001268 PyObject *tzinfo = get_tzinfo_member(object);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001269 zreplacement = PyBytes_FromStringAndSize("", 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001270 if (zreplacement == NULL) goto Done;
1271 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001272 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001273 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001274 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001275 "",
1276 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001277 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001278 goto Done;
1279 Py_DECREF(zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001280 zreplacement =
1281 PyBytes_FromStringAndSize(buf,
1282 strlen(buf));
1283 if (zreplacement == NULL)
1284 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001285 }
1286 }
1287 assert(zreplacement != NULL);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001288 ptoappend = PyBytes_AS_STRING(zreplacement);
1289 ntoappend = PyBytes_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001290 }
1291 else if (ch == 'Z') {
1292 /* format tzname */
1293 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001294 Zreplacement = make_Zreplacement(object,
1295 tzinfoarg);
1296 if (Zreplacement == NULL)
1297 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001298 }
1299 assert(Zreplacement != NULL);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001300 assert(PyBytes_Check(Zreplacement));
1301 ptoappend = PyBytes_AS_STRING(Zreplacement);
1302 ntoappend = PyBytes_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001303 }
1304 else {
Tim Peters328fff72002-12-20 01:31:27 +00001305 /* percent followed by neither z nor Z */
1306 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001307 ntoappend = 2;
1308 }
1309
1310 /* Append the ntoappend chars starting at ptoappend to
1311 * the new format.
1312 */
Tim Peters2a799bf2002-12-16 20:18:38 +00001313 if (ntoappend == 0)
1314 continue;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001315 assert(ptoappend != NULL);
1316 assert(ntoappend > 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001317 while (usednew + ntoappend > totalnew) {
1318 int bigger = totalnew << 1;
1319 if ((bigger >> 1) != totalnew) { /* overflow */
1320 PyErr_NoMemory();
1321 goto Done;
1322 }
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001323 if (PyBytes_Resize(newfmt, bigger) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001324 goto Done;
1325 totalnew = bigger;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001326 pnew = PyBytes_AsString(newfmt) + usednew;
Tim Peters2a799bf2002-12-16 20:18:38 +00001327 }
1328 memcpy(pnew, ptoappend, ntoappend);
1329 pnew += ntoappend;
1330 usednew += ntoappend;
1331 assert(usednew <= totalnew);
1332 } /* end while() */
1333
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001334 if (PyBytes_Resize(newfmt, usednew) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001335 goto Done;
1336 {
Neal Norwitz908c8712007-08-27 04:58:38 +00001337 PyObject *format;
Tim Peters2a799bf2002-12-16 20:18:38 +00001338 PyObject *time = PyImport_ImportModule("time");
1339 if (time == NULL)
1340 goto Done;
Neal Norwitz908c8712007-08-27 04:58:38 +00001341 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
1342 if (format != NULL) {
1343 result = PyObject_CallMethod(time, "strftime", "OO",
1344 format, timetuple);
1345 Py_DECREF(format);
1346 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001347 Py_DECREF(time);
1348 }
1349 Done:
1350 Py_XDECREF(zreplacement);
1351 Py_XDECREF(Zreplacement);
1352 Py_XDECREF(newfmt);
1353 return result;
1354}
1355
Tim Peters2a799bf2002-12-16 20:18:38 +00001356/* ---------------------------------------------------------------------------
1357 * Wrap functions from the time module. These aren't directly available
1358 * from C. Perhaps they should be.
1359 */
1360
1361/* Call time.time() and return its result (a Python float). */
1362static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001363time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001364{
1365 PyObject *result = NULL;
1366 PyObject *time = PyImport_ImportModule("time");
1367
1368 if (time != NULL) {
1369 result = PyObject_CallMethod(time, "time", "()");
1370 Py_DECREF(time);
1371 }
1372 return result;
1373}
1374
1375/* Build a time.struct_time. The weekday and day number are automatically
1376 * computed from the y,m,d args.
1377 */
1378static PyObject *
1379build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1380{
1381 PyObject *time;
1382 PyObject *result = NULL;
1383
1384 time = PyImport_ImportModule("time");
1385 if (time != NULL) {
1386 result = PyObject_CallMethod(time, "struct_time",
1387 "((iiiiiiiii))",
1388 y, m, d,
1389 hh, mm, ss,
1390 weekday(y, m, d),
1391 days_before_month(y, m) + d,
1392 dstflag);
1393 Py_DECREF(time);
1394 }
1395 return result;
1396}
1397
1398/* ---------------------------------------------------------------------------
1399 * Miscellaneous helpers.
1400 */
1401
Guido van Rossum19960592006-08-24 17:29:38 +00001402/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001403 * The comparisons here all most naturally compute a cmp()-like result.
1404 * This little helper turns that into a bool result for rich comparisons.
1405 */
1406static PyObject *
1407diff_to_bool(int diff, int op)
1408{
1409 PyObject *result;
1410 int istrue;
1411
1412 switch (op) {
1413 case Py_EQ: istrue = diff == 0; break;
1414 case Py_NE: istrue = diff != 0; break;
1415 case Py_LE: istrue = diff <= 0; break;
1416 case Py_GE: istrue = diff >= 0; break;
1417 case Py_LT: istrue = diff < 0; break;
1418 case Py_GT: istrue = diff > 0; break;
1419 default:
1420 assert(! "op unknown");
1421 istrue = 0; /* To shut up compiler */
1422 }
1423 result = istrue ? Py_True : Py_False;
1424 Py_INCREF(result);
1425 return result;
1426}
1427
Tim Peters07534a62003-02-07 22:50:28 +00001428/* Raises a "can't compare" TypeError and returns NULL. */
1429static PyObject *
1430cmperror(PyObject *a, PyObject *b)
1431{
1432 PyErr_Format(PyExc_TypeError,
1433 "can't compare %s to %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001434 Py_Type(a)->tp_name, Py_Type(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001435 return NULL;
1436}
1437
Tim Peters2a799bf2002-12-16 20:18:38 +00001438/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001439 * Cached Python objects; these are set by the module init function.
1440 */
1441
1442/* Conversion factors. */
1443static PyObject *us_per_us = NULL; /* 1 */
1444static PyObject *us_per_ms = NULL; /* 1000 */
1445static PyObject *us_per_second = NULL; /* 1000000 */
1446static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1447static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1448static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1449static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1450static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1451
Tim Peters2a799bf2002-12-16 20:18:38 +00001452/* ---------------------------------------------------------------------------
1453 * Class implementations.
1454 */
1455
1456/*
1457 * PyDateTime_Delta implementation.
1458 */
1459
1460/* Convert a timedelta to a number of us,
1461 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1462 * as a Python int or long.
1463 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1464 * due to ubiquitous overflow possibilities.
1465 */
1466static PyObject *
1467delta_to_microseconds(PyDateTime_Delta *self)
1468{
1469 PyObject *x1 = NULL;
1470 PyObject *x2 = NULL;
1471 PyObject *x3 = NULL;
1472 PyObject *result = NULL;
1473
1474 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1475 if (x1 == NULL)
1476 goto Done;
1477 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1478 if (x2 == NULL)
1479 goto Done;
1480 Py_DECREF(x1);
1481 x1 = NULL;
1482
1483 /* x2 has days in seconds */
1484 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1485 if (x1 == NULL)
1486 goto Done;
1487 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1488 if (x3 == NULL)
1489 goto Done;
1490 Py_DECREF(x1);
1491 Py_DECREF(x2);
1492 x1 = x2 = NULL;
1493
1494 /* x3 has days+seconds in seconds */
1495 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1496 if (x1 == NULL)
1497 goto Done;
1498 Py_DECREF(x3);
1499 x3 = NULL;
1500
1501 /* x1 has days+seconds in us */
1502 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1503 if (x2 == NULL)
1504 goto Done;
1505 result = PyNumber_Add(x1, x2);
1506
1507Done:
1508 Py_XDECREF(x1);
1509 Py_XDECREF(x2);
1510 Py_XDECREF(x3);
1511 return result;
1512}
1513
1514/* Convert a number of us (as a Python int or long) to a timedelta.
1515 */
1516static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001517microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001518{
1519 int us;
1520 int s;
1521 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001522 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001523
1524 PyObject *tuple = NULL;
1525 PyObject *num = NULL;
1526 PyObject *result = NULL;
1527
1528 tuple = PyNumber_Divmod(pyus, us_per_second);
1529 if (tuple == NULL)
1530 goto Done;
1531
1532 num = PyTuple_GetItem(tuple, 1); /* us */
1533 if (num == NULL)
1534 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001535 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001536 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001537 if (temp == -1 && PyErr_Occurred())
1538 goto Done;
1539 assert(0 <= temp && temp < 1000000);
1540 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001541 if (us < 0) {
1542 /* The divisor was positive, so this must be an error. */
1543 assert(PyErr_Occurred());
1544 goto Done;
1545 }
1546
1547 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1548 if (num == NULL)
1549 goto Done;
1550 Py_INCREF(num);
1551 Py_DECREF(tuple);
1552
1553 tuple = PyNumber_Divmod(num, seconds_per_day);
1554 if (tuple == NULL)
1555 goto Done;
1556 Py_DECREF(num);
1557
1558 num = PyTuple_GetItem(tuple, 1); /* seconds */
1559 if (num == NULL)
1560 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001561 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001562 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001563 if (temp == -1 && PyErr_Occurred())
1564 goto Done;
1565 assert(0 <= temp && temp < 24*3600);
1566 s = (int)temp;
1567
Tim Peters2a799bf2002-12-16 20:18:38 +00001568 if (s < 0) {
1569 /* The divisor was positive, so this must be an error. */
1570 assert(PyErr_Occurred());
1571 goto Done;
1572 }
1573
1574 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1575 if (num == NULL)
1576 goto Done;
1577 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001578 temp = PyLong_AsLong(num);
1579 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001580 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001581 d = (int)temp;
1582 if ((long)d != temp) {
1583 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1584 "large to fit in a C int");
1585 goto Done;
1586 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001587 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001588
1589Done:
1590 Py_XDECREF(tuple);
1591 Py_XDECREF(num);
1592 return result;
1593}
1594
Tim Petersb0c854d2003-05-17 15:57:00 +00001595#define microseconds_to_delta(pymicros) \
1596 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1597
Tim Peters2a799bf2002-12-16 20:18:38 +00001598static PyObject *
1599multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1600{
1601 PyObject *pyus_in;
1602 PyObject *pyus_out;
1603 PyObject *result;
1604
1605 pyus_in = delta_to_microseconds(delta);
1606 if (pyus_in == NULL)
1607 return NULL;
1608
1609 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1610 Py_DECREF(pyus_in);
1611 if (pyus_out == NULL)
1612 return NULL;
1613
1614 result = microseconds_to_delta(pyus_out);
1615 Py_DECREF(pyus_out);
1616 return result;
1617}
1618
1619static PyObject *
1620divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1621{
1622 PyObject *pyus_in;
1623 PyObject *pyus_out;
1624 PyObject *result;
1625
1626 pyus_in = delta_to_microseconds(delta);
1627 if (pyus_in == NULL)
1628 return NULL;
1629
1630 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1631 Py_DECREF(pyus_in);
1632 if (pyus_out == NULL)
1633 return NULL;
1634
1635 result = microseconds_to_delta(pyus_out);
1636 Py_DECREF(pyus_out);
1637 return result;
1638}
1639
1640static PyObject *
1641delta_add(PyObject *left, PyObject *right)
1642{
1643 PyObject *result = Py_NotImplemented;
1644
1645 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1646 /* delta + delta */
1647 /* The C-level additions can't overflow because of the
1648 * invariant bounds.
1649 */
1650 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1651 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1652 int microseconds = GET_TD_MICROSECONDS(left) +
1653 GET_TD_MICROSECONDS(right);
1654 result = new_delta(days, seconds, microseconds, 1);
1655 }
1656
1657 if (result == Py_NotImplemented)
1658 Py_INCREF(result);
1659 return result;
1660}
1661
1662static PyObject *
1663delta_negative(PyDateTime_Delta *self)
1664{
1665 return new_delta(-GET_TD_DAYS(self),
1666 -GET_TD_SECONDS(self),
1667 -GET_TD_MICROSECONDS(self),
1668 1);
1669}
1670
1671static PyObject *
1672delta_positive(PyDateTime_Delta *self)
1673{
1674 /* Could optimize this (by returning self) if this isn't a
1675 * subclass -- but who uses unary + ? Approximately nobody.
1676 */
1677 return new_delta(GET_TD_DAYS(self),
1678 GET_TD_SECONDS(self),
1679 GET_TD_MICROSECONDS(self),
1680 0);
1681}
1682
1683static PyObject *
1684delta_abs(PyDateTime_Delta *self)
1685{
1686 PyObject *result;
1687
1688 assert(GET_TD_MICROSECONDS(self) >= 0);
1689 assert(GET_TD_SECONDS(self) >= 0);
1690
1691 if (GET_TD_DAYS(self) < 0)
1692 result = delta_negative(self);
1693 else
1694 result = delta_positive(self);
1695
1696 return result;
1697}
1698
1699static PyObject *
1700delta_subtract(PyObject *left, PyObject *right)
1701{
1702 PyObject *result = Py_NotImplemented;
1703
1704 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1705 /* delta - delta */
1706 PyObject *minus_right = PyNumber_Negative(right);
1707 if (minus_right) {
1708 result = delta_add(left, minus_right);
1709 Py_DECREF(minus_right);
1710 }
1711 else
1712 result = NULL;
1713 }
1714
1715 if (result == Py_NotImplemented)
1716 Py_INCREF(result);
1717 return result;
1718}
1719
Tim Peters2a799bf2002-12-16 20:18:38 +00001720static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001721delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001722{
Tim Petersaa7d8492003-02-08 03:28:59 +00001723 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001724 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001725 if (diff == 0) {
1726 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1727 if (diff == 0)
1728 diff = GET_TD_MICROSECONDS(self) -
1729 GET_TD_MICROSECONDS(other);
1730 }
Guido van Rossum19960592006-08-24 17:29:38 +00001731 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001732 }
Guido van Rossum19960592006-08-24 17:29:38 +00001733 else {
1734 Py_INCREF(Py_NotImplemented);
1735 return Py_NotImplemented;
1736 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001737}
1738
1739static PyObject *delta_getstate(PyDateTime_Delta *self);
1740
1741static long
1742delta_hash(PyDateTime_Delta *self)
1743{
1744 if (self->hashcode == -1) {
1745 PyObject *temp = delta_getstate(self);
1746 if (temp != NULL) {
1747 self->hashcode = PyObject_Hash(temp);
1748 Py_DECREF(temp);
1749 }
1750 }
1751 return self->hashcode;
1752}
1753
1754static PyObject *
1755delta_multiply(PyObject *left, PyObject *right)
1756{
1757 PyObject *result = Py_NotImplemented;
1758
1759 if (PyDelta_Check(left)) {
1760 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001761 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001762 result = multiply_int_timedelta(right,
1763 (PyDateTime_Delta *) left);
1764 }
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001765 else if (PyLong_Check(left))
Tim Peters2a799bf2002-12-16 20:18:38 +00001766 result = multiply_int_timedelta(left,
1767 (PyDateTime_Delta *) right);
1768
1769 if (result == Py_NotImplemented)
1770 Py_INCREF(result);
1771 return result;
1772}
1773
1774static PyObject *
1775delta_divide(PyObject *left, PyObject *right)
1776{
1777 PyObject *result = Py_NotImplemented;
1778
1779 if (PyDelta_Check(left)) {
1780 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001781 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001782 result = divide_timedelta_int(
1783 (PyDateTime_Delta *)left,
1784 right);
1785 }
1786
1787 if (result == Py_NotImplemented)
1788 Py_INCREF(result);
1789 return result;
1790}
1791
1792/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1793 * timedelta constructor. sofar is the # of microseconds accounted for
1794 * so far, and there are factor microseconds per current unit, the number
1795 * of which is given by num. num * factor is added to sofar in a
1796 * numerically careful way, and that's the result. Any fractional
1797 * microseconds left over (this can happen if num is a float type) are
1798 * added into *leftover.
1799 * Note that there are many ways this can give an error (NULL) return.
1800 */
1801static PyObject *
1802accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1803 double *leftover)
1804{
1805 PyObject *prod;
1806 PyObject *sum;
1807
1808 assert(num != NULL);
1809
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001810 if (PyLong_Check(num)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00001811 prod = PyNumber_Multiply(num, factor);
1812 if (prod == NULL)
1813 return NULL;
1814 sum = PyNumber_Add(sofar, prod);
1815 Py_DECREF(prod);
1816 return sum;
1817 }
1818
1819 if (PyFloat_Check(num)) {
1820 double dnum;
1821 double fracpart;
1822 double intpart;
1823 PyObject *x;
1824 PyObject *y;
1825
1826 /* The Plan: decompose num into an integer part and a
1827 * fractional part, num = intpart + fracpart.
1828 * Then num * factor ==
1829 * intpart * factor + fracpart * factor
1830 * and the LHS can be computed exactly in long arithmetic.
1831 * The RHS is again broken into an int part and frac part.
1832 * and the frac part is added into *leftover.
1833 */
1834 dnum = PyFloat_AsDouble(num);
1835 if (dnum == -1.0 && PyErr_Occurred())
1836 return NULL;
1837 fracpart = modf(dnum, &intpart);
1838 x = PyLong_FromDouble(intpart);
1839 if (x == NULL)
1840 return NULL;
1841
1842 prod = PyNumber_Multiply(x, factor);
1843 Py_DECREF(x);
1844 if (prod == NULL)
1845 return NULL;
1846
1847 sum = PyNumber_Add(sofar, prod);
1848 Py_DECREF(prod);
1849 if (sum == NULL)
1850 return NULL;
1851
1852 if (fracpart == 0.0)
1853 return sum;
1854 /* So far we've lost no information. Dealing with the
1855 * fractional part requires float arithmetic, and may
1856 * lose a little info.
1857 */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001858 assert(PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001859 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001860
1861 dnum *= fracpart;
1862 fracpart = modf(dnum, &intpart);
1863 x = PyLong_FromDouble(intpart);
1864 if (x == NULL) {
1865 Py_DECREF(sum);
1866 return NULL;
1867 }
1868
1869 y = PyNumber_Add(sum, x);
1870 Py_DECREF(sum);
1871 Py_DECREF(x);
1872 *leftover += fracpart;
1873 return y;
1874 }
1875
1876 PyErr_Format(PyExc_TypeError,
1877 "unsupported type for timedelta %s component: %s",
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001878 tag, Py_Type(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001879 return NULL;
1880}
1881
1882static PyObject *
1883delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1884{
1885 PyObject *self = NULL;
1886
1887 /* Argument objects. */
1888 PyObject *day = NULL;
1889 PyObject *second = NULL;
1890 PyObject *us = NULL;
1891 PyObject *ms = NULL;
1892 PyObject *minute = NULL;
1893 PyObject *hour = NULL;
1894 PyObject *week = NULL;
1895
1896 PyObject *x = NULL; /* running sum of microseconds */
1897 PyObject *y = NULL; /* temp sum of microseconds */
1898 double leftover_us = 0.0;
1899
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001900 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001901 "days", "seconds", "microseconds", "milliseconds",
1902 "minutes", "hours", "weeks", NULL
1903 };
1904
1905 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1906 keywords,
1907 &day, &second, &us,
1908 &ms, &minute, &hour, &week) == 0)
1909 goto Done;
1910
1911 x = PyInt_FromLong(0);
1912 if (x == NULL)
1913 goto Done;
1914
1915#define CLEANUP \
1916 Py_DECREF(x); \
1917 x = y; \
1918 if (x == NULL) \
1919 goto Done
1920
1921 if (us) {
1922 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1923 CLEANUP;
1924 }
1925 if (ms) {
1926 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1927 CLEANUP;
1928 }
1929 if (second) {
1930 y = accum("seconds", x, second, us_per_second, &leftover_us);
1931 CLEANUP;
1932 }
1933 if (minute) {
1934 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1935 CLEANUP;
1936 }
1937 if (hour) {
1938 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1939 CLEANUP;
1940 }
1941 if (day) {
1942 y = accum("days", x, day, us_per_day, &leftover_us);
1943 CLEANUP;
1944 }
1945 if (week) {
1946 y = accum("weeks", x, week, us_per_week, &leftover_us);
1947 CLEANUP;
1948 }
1949 if (leftover_us) {
1950 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001951 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001952 if (temp == NULL) {
1953 Py_DECREF(x);
1954 goto Done;
1955 }
1956 y = PyNumber_Add(x, temp);
1957 Py_DECREF(temp);
1958 CLEANUP;
1959 }
1960
Tim Petersb0c854d2003-05-17 15:57:00 +00001961 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001962 Py_DECREF(x);
1963Done:
1964 return self;
1965
1966#undef CLEANUP
1967}
1968
1969static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001970delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001971{
1972 return (GET_TD_DAYS(self) != 0
1973 || GET_TD_SECONDS(self) != 0
1974 || GET_TD_MICROSECONDS(self) != 0);
1975}
1976
1977static PyObject *
1978delta_repr(PyDateTime_Delta *self)
1979{
1980 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001981 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001982 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001983 GET_TD_DAYS(self),
1984 GET_TD_SECONDS(self),
1985 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001986 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001987 return PyUnicode_FromFormat("%s(%d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001988 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001989 GET_TD_DAYS(self),
1990 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001991
Walter Dörwald1ab83302007-05-18 17:15:44 +00001992 return PyUnicode_FromFormat("%s(%d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00001993 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001994 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001995}
1996
1997static PyObject *
1998delta_str(PyDateTime_Delta *self)
1999{
Tim Peters2a799bf2002-12-16 20:18:38 +00002000 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002001 int seconds = GET_TD_SECONDS(self);
2002 int minutes = divmod(seconds, 60, &seconds);
2003 int hours = divmod(minutes, 60, &minutes);
2004 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002005
2006 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002007 if (us)
2008 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2009 days, (days == 1 || days == -1) ? "" : "s",
2010 hours, minutes, seconds, us);
2011 else
2012 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2013 days, (days == 1 || days == -1) ? "" : "s",
2014 hours, minutes, seconds);
2015 } else {
2016 if (us)
2017 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2018 hours, minutes, seconds, us);
2019 else
2020 return PyUnicode_FromFormat("%d:%02d:%02d",
2021 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002022 }
2023
Tim Peters2a799bf2002-12-16 20:18:38 +00002024}
2025
Tim Peters371935f2003-02-01 01:52:50 +00002026/* Pickle support, a simple use of __reduce__. */
2027
Tim Petersb57f8f02003-02-01 02:54:15 +00002028/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002029static PyObject *
2030delta_getstate(PyDateTime_Delta *self)
2031{
2032 return Py_BuildValue("iii", GET_TD_DAYS(self),
2033 GET_TD_SECONDS(self),
2034 GET_TD_MICROSECONDS(self));
2035}
2036
Tim Peters2a799bf2002-12-16 20:18:38 +00002037static PyObject *
2038delta_reduce(PyDateTime_Delta* self)
2039{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002040 return Py_BuildValue("ON", Py_Type(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002041}
2042
2043#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2044
2045static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002046
Neal Norwitzdfb80862002-12-19 02:30:56 +00002047 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002048 PyDoc_STR("Number of days.")},
2049
Neal Norwitzdfb80862002-12-19 02:30:56 +00002050 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002051 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2052
Neal Norwitzdfb80862002-12-19 02:30:56 +00002053 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002054 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2055 {NULL}
2056};
2057
2058static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002059 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2060 PyDoc_STR("__reduce__() -> (cls, state)")},
2061
Tim Peters2a799bf2002-12-16 20:18:38 +00002062 {NULL, NULL},
2063};
2064
2065static char delta_doc[] =
2066PyDoc_STR("Difference between two datetime values.");
2067
2068static PyNumberMethods delta_as_number = {
2069 delta_add, /* nb_add */
2070 delta_subtract, /* nb_subtract */
2071 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002072 0, /* nb_remainder */
2073 0, /* nb_divmod */
2074 0, /* nb_power */
2075 (unaryfunc)delta_negative, /* nb_negative */
2076 (unaryfunc)delta_positive, /* nb_positive */
2077 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002078 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002079 0, /*nb_invert*/
2080 0, /*nb_lshift*/
2081 0, /*nb_rshift*/
2082 0, /*nb_and*/
2083 0, /*nb_xor*/
2084 0, /*nb_or*/
2085 0, /*nb_coerce*/
2086 0, /*nb_int*/
2087 0, /*nb_long*/
2088 0, /*nb_float*/
2089 0, /*nb_oct*/
2090 0, /*nb_hex*/
2091 0, /*nb_inplace_add*/
2092 0, /*nb_inplace_subtract*/
2093 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002094 0, /*nb_inplace_remainder*/
2095 0, /*nb_inplace_power*/
2096 0, /*nb_inplace_lshift*/
2097 0, /*nb_inplace_rshift*/
2098 0, /*nb_inplace_and*/
2099 0, /*nb_inplace_xor*/
2100 0, /*nb_inplace_or*/
2101 delta_divide, /* nb_floor_divide */
2102 0, /* nb_true_divide */
2103 0, /* nb_inplace_floor_divide */
2104 0, /* nb_inplace_true_divide */
2105};
2106
2107static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002108 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002109 "datetime.timedelta", /* tp_name */
2110 sizeof(PyDateTime_Delta), /* tp_basicsize */
2111 0, /* tp_itemsize */
2112 0, /* tp_dealloc */
2113 0, /* tp_print */
2114 0, /* tp_getattr */
2115 0, /* tp_setattr */
2116 0, /* tp_compare */
2117 (reprfunc)delta_repr, /* tp_repr */
2118 &delta_as_number, /* tp_as_number */
2119 0, /* tp_as_sequence */
2120 0, /* tp_as_mapping */
2121 (hashfunc)delta_hash, /* tp_hash */
2122 0, /* tp_call */
2123 (reprfunc)delta_str, /* tp_str */
2124 PyObject_GenericGetAttr, /* tp_getattro */
2125 0, /* tp_setattro */
2126 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002127 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002128 delta_doc, /* tp_doc */
2129 0, /* tp_traverse */
2130 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002131 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002132 0, /* tp_weaklistoffset */
2133 0, /* tp_iter */
2134 0, /* tp_iternext */
2135 delta_methods, /* tp_methods */
2136 delta_members, /* tp_members */
2137 0, /* tp_getset */
2138 0, /* tp_base */
2139 0, /* tp_dict */
2140 0, /* tp_descr_get */
2141 0, /* tp_descr_set */
2142 0, /* tp_dictoffset */
2143 0, /* tp_init */
2144 0, /* tp_alloc */
2145 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002146 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002147};
2148
2149/*
2150 * PyDateTime_Date implementation.
2151 */
2152
2153/* Accessor properties. */
2154
2155static PyObject *
2156date_year(PyDateTime_Date *self, void *unused)
2157{
2158 return PyInt_FromLong(GET_YEAR(self));
2159}
2160
2161static PyObject *
2162date_month(PyDateTime_Date *self, void *unused)
2163{
2164 return PyInt_FromLong(GET_MONTH(self));
2165}
2166
2167static PyObject *
2168date_day(PyDateTime_Date *self, void *unused)
2169{
2170 return PyInt_FromLong(GET_DAY(self));
2171}
2172
2173static PyGetSetDef date_getset[] = {
2174 {"year", (getter)date_year},
2175 {"month", (getter)date_month},
2176 {"day", (getter)date_day},
2177 {NULL}
2178};
2179
2180/* Constructors. */
2181
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002182static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002183
Tim Peters2a799bf2002-12-16 20:18:38 +00002184static PyObject *
2185date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2186{
2187 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002188 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002189 int year;
2190 int month;
2191 int day;
2192
Guido van Rossum177e41a2003-01-30 22:06:23 +00002193 /* Check for invocation from pickle with __getstate__ state */
2194 if (PyTuple_GET_SIZE(args) == 1 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002195 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2196 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2197 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002198 {
Tim Peters70533e22003-02-01 04:40:04 +00002199 PyDateTime_Date *me;
2200
Tim Peters604c0132004-06-07 23:04:33 +00002201 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002202 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002203 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002204 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2205 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002206 }
Tim Peters70533e22003-02-01 04:40:04 +00002207 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002208 }
2209
Tim Peters12bf3392002-12-24 05:41:27 +00002210 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002211 &year, &month, &day)) {
2212 if (check_date_args(year, month, day) < 0)
2213 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002214 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002215 }
2216 return self;
2217}
2218
2219/* Return new date from localtime(t). */
2220static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002221date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002222{
2223 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002224 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002225 PyObject *result = NULL;
2226
Tim Peters1b6f7a92004-06-20 02:50:16 +00002227 t = _PyTime_DoubleToTimet(ts);
2228 if (t == (time_t)-1 && PyErr_Occurred())
2229 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002230 tm = localtime(&t);
2231 if (tm)
2232 result = PyObject_CallFunction(cls, "iii",
2233 tm->tm_year + 1900,
2234 tm->tm_mon + 1,
2235 tm->tm_mday);
2236 else
2237 PyErr_SetString(PyExc_ValueError,
2238 "timestamp out of range for "
2239 "platform localtime() function");
2240 return result;
2241}
2242
2243/* Return new date from current time.
2244 * We say this is equivalent to fromtimestamp(time.time()), and the
2245 * only way to be sure of that is to *call* time.time(). That's not
2246 * generally the same as calling C's time.
2247 */
2248static PyObject *
2249date_today(PyObject *cls, PyObject *dummy)
2250{
2251 PyObject *time;
2252 PyObject *result;
2253
2254 time = time_time();
2255 if (time == NULL)
2256 return NULL;
2257
2258 /* Note well: today() is a class method, so this may not call
2259 * date.fromtimestamp. For example, it may call
2260 * datetime.fromtimestamp. That's why we need all the accuracy
2261 * time.time() delivers; if someone were gonzo about optimization,
2262 * date.today() could get away with plain C time().
2263 */
2264 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2265 Py_DECREF(time);
2266 return result;
2267}
2268
2269/* Return new date from given timestamp (Python timestamp -- a double). */
2270static PyObject *
2271date_fromtimestamp(PyObject *cls, PyObject *args)
2272{
2273 double timestamp;
2274 PyObject *result = NULL;
2275
2276 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002277 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002278 return result;
2279}
2280
2281/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2282 * the ordinal is out of range.
2283 */
2284static PyObject *
2285date_fromordinal(PyObject *cls, PyObject *args)
2286{
2287 PyObject *result = NULL;
2288 int ordinal;
2289
2290 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2291 int year;
2292 int month;
2293 int day;
2294
2295 if (ordinal < 1)
2296 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2297 ">= 1");
2298 else {
2299 ord_to_ymd(ordinal, &year, &month, &day);
2300 result = PyObject_CallFunction(cls, "iii",
2301 year, month, day);
2302 }
2303 }
2304 return result;
2305}
2306
2307/*
2308 * Date arithmetic.
2309 */
2310
2311/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2312 * instead.
2313 */
2314static PyObject *
2315add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2316{
2317 PyObject *result = NULL;
2318 int year = GET_YEAR(date);
2319 int month = GET_MONTH(date);
2320 int deltadays = GET_TD_DAYS(delta);
2321 /* C-level overflow is impossible because |deltadays| < 1e9. */
2322 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2323
2324 if (normalize_date(&year, &month, &day) >= 0)
2325 result = new_date(year, month, day);
2326 return result;
2327}
2328
2329static PyObject *
2330date_add(PyObject *left, PyObject *right)
2331{
2332 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2333 Py_INCREF(Py_NotImplemented);
2334 return Py_NotImplemented;
2335 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002336 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002337 /* date + ??? */
2338 if (PyDelta_Check(right))
2339 /* date + delta */
2340 return add_date_timedelta((PyDateTime_Date *) left,
2341 (PyDateTime_Delta *) right,
2342 0);
2343 }
2344 else {
2345 /* ??? + date
2346 * 'right' must be one of us, or we wouldn't have been called
2347 */
2348 if (PyDelta_Check(left))
2349 /* delta + date */
2350 return add_date_timedelta((PyDateTime_Date *) right,
2351 (PyDateTime_Delta *) left,
2352 0);
2353 }
2354 Py_INCREF(Py_NotImplemented);
2355 return Py_NotImplemented;
2356}
2357
2358static PyObject *
2359date_subtract(PyObject *left, PyObject *right)
2360{
2361 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2362 Py_INCREF(Py_NotImplemented);
2363 return Py_NotImplemented;
2364 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002365 if (PyDate_Check(left)) {
2366 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002367 /* date - date */
2368 int left_ord = ymd_to_ord(GET_YEAR(left),
2369 GET_MONTH(left),
2370 GET_DAY(left));
2371 int right_ord = ymd_to_ord(GET_YEAR(right),
2372 GET_MONTH(right),
2373 GET_DAY(right));
2374 return new_delta(left_ord - right_ord, 0, 0, 0);
2375 }
2376 if (PyDelta_Check(right)) {
2377 /* date - delta */
2378 return add_date_timedelta((PyDateTime_Date *) left,
2379 (PyDateTime_Delta *) right,
2380 1);
2381 }
2382 }
2383 Py_INCREF(Py_NotImplemented);
2384 return Py_NotImplemented;
2385}
2386
2387
2388/* Various ways to turn a date into a string. */
2389
2390static PyObject *
2391date_repr(PyDateTime_Date *self)
2392{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002393 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Martin v. Löwis5d7428b2007-07-21 18:47:48 +00002394 Py_Type(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002395 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002396}
2397
2398static PyObject *
2399date_isoformat(PyDateTime_Date *self)
2400{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002401 return PyUnicode_FromFormat("%04d-%02d-%02d",
2402 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002403}
2404
Tim Peterse2df5ff2003-05-02 18:39:55 +00002405/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002406static PyObject *
2407date_str(PyDateTime_Date *self)
2408{
2409 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2410}
2411
2412
2413static PyObject *
2414date_ctime(PyDateTime_Date *self)
2415{
2416 return format_ctime(self, 0, 0, 0);
2417}
2418
2419static PyObject *
2420date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2421{
2422 /* This method can be inherited, and needs to call the
2423 * timetuple() method appropriate to self's class.
2424 */
2425 PyObject *result;
2426 PyObject *format;
2427 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002428 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002429
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002430 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00002431 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002432 return NULL;
2433
2434 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2435 if (tuple == NULL)
2436 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002437 result = wrap_strftime((PyObject *)self, format, tuple,
2438 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002439 Py_DECREF(tuple);
2440 return result;
2441}
2442
Eric Smith1ba31142007-09-11 18:06:02 +00002443static PyObject *
2444date_format(PyDateTime_Date *self, PyObject *args)
2445{
2446 PyObject *format;
2447
2448 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2449 return NULL;
2450
2451 /* if the format is zero length, return str(self) */
2452 if (PyUnicode_GetSize(format) == 0)
2453 return PyObject_Unicode((PyObject *)self);
2454
2455 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
2456}
2457
Tim Peters2a799bf2002-12-16 20:18:38 +00002458/* ISO methods. */
2459
2460static PyObject *
2461date_isoweekday(PyDateTime_Date *self)
2462{
2463 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2464
2465 return PyInt_FromLong(dow + 1);
2466}
2467
2468static PyObject *
2469date_isocalendar(PyDateTime_Date *self)
2470{
2471 int year = GET_YEAR(self);
2472 int week1_monday = iso_week1_monday(year);
2473 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2474 int week;
2475 int day;
2476
2477 week = divmod(today - week1_monday, 7, &day);
2478 if (week < 0) {
2479 --year;
2480 week1_monday = iso_week1_monday(year);
2481 week = divmod(today - week1_monday, 7, &day);
2482 }
2483 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2484 ++year;
2485 week = 0;
2486 }
2487 return Py_BuildValue("iii", year, week + 1, day + 1);
2488}
2489
2490/* Miscellaneous methods. */
2491
Tim Peters2a799bf2002-12-16 20:18:38 +00002492static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002493date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002494{
Guido van Rossum19960592006-08-24 17:29:38 +00002495 if (PyDate_Check(other)) {
2496 int diff = memcmp(((PyDateTime_Date *)self)->data,
2497 ((PyDateTime_Date *)other)->data,
2498 _PyDateTime_DATE_DATASIZE);
2499 return diff_to_bool(diff, op);
2500 }
2501 else {
Tim Peters07534a62003-02-07 22:50:28 +00002502 Py_INCREF(Py_NotImplemented);
2503 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002504 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002505}
2506
2507static PyObject *
2508date_timetuple(PyDateTime_Date *self)
2509{
2510 return build_struct_time(GET_YEAR(self),
2511 GET_MONTH(self),
2512 GET_DAY(self),
2513 0, 0, 0, -1);
2514}
2515
Tim Peters12bf3392002-12-24 05:41:27 +00002516static PyObject *
2517date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2518{
2519 PyObject *clone;
2520 PyObject *tuple;
2521 int year = GET_YEAR(self);
2522 int month = GET_MONTH(self);
2523 int day = GET_DAY(self);
2524
2525 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2526 &year, &month, &day))
2527 return NULL;
2528 tuple = Py_BuildValue("iii", year, month, day);
2529 if (tuple == NULL)
2530 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002531 clone = date_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002532 Py_DECREF(tuple);
2533 return clone;
2534}
2535
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002536/*
2537 Borrowed from stringobject.c, originally it was string_hash()
2538*/
2539static long
2540generic_hash(unsigned char *data, int len)
2541{
2542 register unsigned char *p;
2543 register long x;
2544
2545 p = (unsigned char *) data;
2546 x = *p << 7;
2547 while (--len >= 0)
2548 x = (1000003*x) ^ *p++;
2549 x ^= len;
2550 if (x == -1)
2551 x = -2;
2552
2553 return x;
2554}
2555
2556
2557static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002558
2559static long
2560date_hash(PyDateTime_Date *self)
2561{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002562 if (self->hashcode == -1)
2563 self->hashcode = generic_hash(
2564 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
2565
Tim Peters2a799bf2002-12-16 20:18:38 +00002566 return self->hashcode;
2567}
2568
2569static PyObject *
2570date_toordinal(PyDateTime_Date *self)
2571{
2572 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2573 GET_DAY(self)));
2574}
2575
2576static PyObject *
2577date_weekday(PyDateTime_Date *self)
2578{
2579 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2580
2581 return PyInt_FromLong(dow);
2582}
2583
Tim Peters371935f2003-02-01 01:52:50 +00002584/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002585
Tim Petersb57f8f02003-02-01 02:54:15 +00002586/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002587static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002588date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002589{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002590 PyObject* field;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002591 field = PyBytes_FromStringAndSize(
2592 (char*)self->data, _PyDateTime_DATE_DATASIZE);
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002593 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002594}
2595
2596static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002597date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002598{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002599 return Py_BuildValue("(ON)", Py_Type(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002600}
2601
2602static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002603
Tim Peters2a799bf2002-12-16 20:18:38 +00002604 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002605
Tim Peters2a799bf2002-12-16 20:18:38 +00002606 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2607 METH_CLASS,
2608 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2609 "time.time()).")},
2610
2611 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2612 METH_CLASS,
2613 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2614 "ordinal.")},
2615
2616 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2617 PyDoc_STR("Current date or datetime: same as "
2618 "self.__class__.fromtimestamp(time.time()).")},
2619
2620 /* Instance methods: */
2621
2622 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2623 PyDoc_STR("Return ctime() style string.")},
2624
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002625 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002626 PyDoc_STR("format -> strftime() style string.")},
2627
Eric Smith1ba31142007-09-11 18:06:02 +00002628 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2629 PyDoc_STR("Formats self with strftime.")},
2630
Tim Peters2a799bf2002-12-16 20:18:38 +00002631 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2632 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2633
2634 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2635 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2636 "weekday.")},
2637
2638 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2639 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2640
2641 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2642 PyDoc_STR("Return the day of the week represented by the date.\n"
2643 "Monday == 1 ... Sunday == 7")},
2644
2645 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2646 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2647 "1 is day 1.")},
2648
2649 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2650 PyDoc_STR("Return the day of the week represented by the date.\n"
2651 "Monday == 0 ... Sunday == 6")},
2652
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002653 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002654 PyDoc_STR("Return date with new specified fields.")},
2655
Guido van Rossum177e41a2003-01-30 22:06:23 +00002656 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2657 PyDoc_STR("__reduce__() -> (cls, state)")},
2658
Tim Peters2a799bf2002-12-16 20:18:38 +00002659 {NULL, NULL}
2660};
2661
2662static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002663PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002664
2665static PyNumberMethods date_as_number = {
2666 date_add, /* nb_add */
2667 date_subtract, /* nb_subtract */
2668 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002669 0, /* nb_remainder */
2670 0, /* nb_divmod */
2671 0, /* nb_power */
2672 0, /* nb_negative */
2673 0, /* nb_positive */
2674 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002675 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002676};
2677
2678static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002679 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002680 "datetime.date", /* tp_name */
2681 sizeof(PyDateTime_Date), /* tp_basicsize */
2682 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002683 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002684 0, /* tp_print */
2685 0, /* tp_getattr */
2686 0, /* tp_setattr */
2687 0, /* tp_compare */
2688 (reprfunc)date_repr, /* tp_repr */
2689 &date_as_number, /* tp_as_number */
2690 0, /* tp_as_sequence */
2691 0, /* tp_as_mapping */
2692 (hashfunc)date_hash, /* tp_hash */
2693 0, /* tp_call */
2694 (reprfunc)date_str, /* tp_str */
2695 PyObject_GenericGetAttr, /* tp_getattro */
2696 0, /* tp_setattro */
2697 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002698 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002699 date_doc, /* tp_doc */
2700 0, /* tp_traverse */
2701 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002702 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002703 0, /* tp_weaklistoffset */
2704 0, /* tp_iter */
2705 0, /* tp_iternext */
2706 date_methods, /* tp_methods */
2707 0, /* tp_members */
2708 date_getset, /* tp_getset */
2709 0, /* tp_base */
2710 0, /* tp_dict */
2711 0, /* tp_descr_get */
2712 0, /* tp_descr_set */
2713 0, /* tp_dictoffset */
2714 0, /* tp_init */
2715 0, /* tp_alloc */
2716 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002717 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002718};
2719
2720/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002721 * PyDateTime_TZInfo implementation.
2722 */
2723
2724/* This is a pure abstract base class, so doesn't do anything beyond
2725 * raising NotImplemented exceptions. Real tzinfo classes need
2726 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002727 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002728 * be subclasses of this tzinfo class, which is easy and quick to check).
2729 *
2730 * Note: For reasons having to do with pickling of subclasses, we have
2731 * to allow tzinfo objects to be instantiated. This wasn't an issue
2732 * in the Python implementation (__init__() could raise NotImplementedError
2733 * there without ill effect), but doing so in the C implementation hit a
2734 * brick wall.
2735 */
2736
2737static PyObject *
2738tzinfo_nogo(const char* methodname)
2739{
2740 PyErr_Format(PyExc_NotImplementedError,
2741 "a tzinfo subclass must implement %s()",
2742 methodname);
2743 return NULL;
2744}
2745
2746/* Methods. A subclass must implement these. */
2747
Tim Peters52dcce22003-01-23 16:36:11 +00002748static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002749tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2750{
2751 return tzinfo_nogo("tzname");
2752}
2753
Tim Peters52dcce22003-01-23 16:36:11 +00002754static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002755tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2756{
2757 return tzinfo_nogo("utcoffset");
2758}
2759
Tim Peters52dcce22003-01-23 16:36:11 +00002760static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002761tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2762{
2763 return tzinfo_nogo("dst");
2764}
2765
Tim Peters52dcce22003-01-23 16:36:11 +00002766static PyObject *
2767tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2768{
2769 int y, m, d, hh, mm, ss, us;
2770
2771 PyObject *result;
2772 int off, dst;
2773 int none;
2774 int delta;
2775
2776 if (! PyDateTime_Check(dt)) {
2777 PyErr_SetString(PyExc_TypeError,
2778 "fromutc: argument must be a datetime");
2779 return NULL;
2780 }
2781 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2782 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2783 "is not self");
2784 return NULL;
2785 }
2786
2787 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2788 if (off == -1 && PyErr_Occurred())
2789 return NULL;
2790 if (none) {
2791 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2792 "utcoffset() result required");
2793 return NULL;
2794 }
2795
2796 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2797 if (dst == -1 && PyErr_Occurred())
2798 return NULL;
2799 if (none) {
2800 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2801 "dst() result required");
2802 return NULL;
2803 }
2804
2805 y = GET_YEAR(dt);
2806 m = GET_MONTH(dt);
2807 d = GET_DAY(dt);
2808 hh = DATE_GET_HOUR(dt);
2809 mm = DATE_GET_MINUTE(dt);
2810 ss = DATE_GET_SECOND(dt);
2811 us = DATE_GET_MICROSECOND(dt);
2812
2813 delta = off - dst;
2814 mm += delta;
2815 if ((mm < 0 || mm >= 60) &&
2816 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002817 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002818 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2819 if (result == NULL)
2820 return result;
2821
2822 dst = call_dst(dt->tzinfo, result, &none);
2823 if (dst == -1 && PyErr_Occurred())
2824 goto Fail;
2825 if (none)
2826 goto Inconsistent;
2827 if (dst == 0)
2828 return result;
2829
2830 mm += dst;
2831 if ((mm < 0 || mm >= 60) &&
2832 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2833 goto Fail;
2834 Py_DECREF(result);
2835 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2836 return result;
2837
2838Inconsistent:
2839 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2840 "inconsistent results; cannot convert");
2841
2842 /* fall thru to failure */
2843Fail:
2844 Py_DECREF(result);
2845 return NULL;
2846}
2847
Tim Peters2a799bf2002-12-16 20:18:38 +00002848/*
2849 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002850 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002851 */
2852
Guido van Rossum177e41a2003-01-30 22:06:23 +00002853static PyObject *
2854tzinfo_reduce(PyObject *self)
2855{
2856 PyObject *args, *state, *tmp;
2857 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002858
Guido van Rossum177e41a2003-01-30 22:06:23 +00002859 tmp = PyTuple_New(0);
2860 if (tmp == NULL)
2861 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002862
Guido van Rossum177e41a2003-01-30 22:06:23 +00002863 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2864 if (getinitargs != NULL) {
2865 args = PyObject_CallObject(getinitargs, tmp);
2866 Py_DECREF(getinitargs);
2867 if (args == NULL) {
2868 Py_DECREF(tmp);
2869 return NULL;
2870 }
2871 }
2872 else {
2873 PyErr_Clear();
2874 args = tmp;
2875 Py_INCREF(args);
2876 }
2877
2878 getstate = PyObject_GetAttrString(self, "__getstate__");
2879 if (getstate != NULL) {
2880 state = PyObject_CallObject(getstate, tmp);
2881 Py_DECREF(getstate);
2882 if (state == NULL) {
2883 Py_DECREF(args);
2884 Py_DECREF(tmp);
2885 return NULL;
2886 }
2887 }
2888 else {
2889 PyObject **dictptr;
2890 PyErr_Clear();
2891 state = Py_None;
2892 dictptr = _PyObject_GetDictPtr(self);
2893 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2894 state = *dictptr;
2895 Py_INCREF(state);
2896 }
2897
2898 Py_DECREF(tmp);
2899
2900 if (state == Py_None) {
2901 Py_DECREF(state);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002902 return Py_BuildValue("(ON)", Py_Type(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002903 }
2904 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002905 return Py_BuildValue("(ONN)", Py_Type(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002906}
Tim Peters2a799bf2002-12-16 20:18:38 +00002907
2908static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002909
Tim Peters2a799bf2002-12-16 20:18:38 +00002910 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2911 PyDoc_STR("datetime -> string name of time zone.")},
2912
2913 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2914 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2915 "west of UTC).")},
2916
2917 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2918 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2919
Tim Peters52dcce22003-01-23 16:36:11 +00002920 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2921 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2922
Guido van Rossum177e41a2003-01-30 22:06:23 +00002923 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2924 PyDoc_STR("-> (cls, state)")},
2925
Tim Peters2a799bf2002-12-16 20:18:38 +00002926 {NULL, NULL}
2927};
2928
2929static char tzinfo_doc[] =
2930PyDoc_STR("Abstract base class for time zone info objects.");
2931
Neal Norwitz227b5332006-03-22 09:28:35 +00002932static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002933 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002934 "datetime.tzinfo", /* tp_name */
2935 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2936 0, /* tp_itemsize */
2937 0, /* tp_dealloc */
2938 0, /* tp_print */
2939 0, /* tp_getattr */
2940 0, /* tp_setattr */
2941 0, /* tp_compare */
2942 0, /* tp_repr */
2943 0, /* tp_as_number */
2944 0, /* tp_as_sequence */
2945 0, /* tp_as_mapping */
2946 0, /* tp_hash */
2947 0, /* tp_call */
2948 0, /* tp_str */
2949 PyObject_GenericGetAttr, /* tp_getattro */
2950 0, /* tp_setattro */
2951 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002952 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002953 tzinfo_doc, /* tp_doc */
2954 0, /* tp_traverse */
2955 0, /* tp_clear */
2956 0, /* tp_richcompare */
2957 0, /* tp_weaklistoffset */
2958 0, /* tp_iter */
2959 0, /* tp_iternext */
2960 tzinfo_methods, /* tp_methods */
2961 0, /* tp_members */
2962 0, /* tp_getset */
2963 0, /* tp_base */
2964 0, /* tp_dict */
2965 0, /* tp_descr_get */
2966 0, /* tp_descr_set */
2967 0, /* tp_dictoffset */
2968 0, /* tp_init */
2969 0, /* tp_alloc */
2970 PyType_GenericNew, /* tp_new */
2971 0, /* tp_free */
2972};
2973
2974/*
Tim Peters37f39822003-01-10 03:49:02 +00002975 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002976 */
2977
Tim Peters37f39822003-01-10 03:49:02 +00002978/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002979 */
2980
2981static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002982time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002983{
Tim Peters37f39822003-01-10 03:49:02 +00002984 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002985}
2986
Tim Peters37f39822003-01-10 03:49:02 +00002987static PyObject *
2988time_minute(PyDateTime_Time *self, void *unused)
2989{
2990 return PyInt_FromLong(TIME_GET_MINUTE(self));
2991}
2992
2993/* The name time_second conflicted with some platform header file. */
2994static PyObject *
2995py_time_second(PyDateTime_Time *self, void *unused)
2996{
2997 return PyInt_FromLong(TIME_GET_SECOND(self));
2998}
2999
3000static PyObject *
3001time_microsecond(PyDateTime_Time *self, void *unused)
3002{
3003 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3004}
3005
3006static PyObject *
3007time_tzinfo(PyDateTime_Time *self, void *unused)
3008{
Tim Petersa032d2e2003-01-11 00:15:54 +00003009 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003010 Py_INCREF(result);
3011 return result;
3012}
3013
3014static PyGetSetDef time_getset[] = {
3015 {"hour", (getter)time_hour},
3016 {"minute", (getter)time_minute},
3017 {"second", (getter)py_time_second},
3018 {"microsecond", (getter)time_microsecond},
3019 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003020 {NULL}
3021};
3022
3023/*
3024 * Constructors.
3025 */
3026
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003027static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003028 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003029
Tim Peters2a799bf2002-12-16 20:18:38 +00003030static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003031time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003032{
3033 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003034 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003035 int hour = 0;
3036 int minute = 0;
3037 int second = 0;
3038 int usecond = 0;
3039 PyObject *tzinfo = Py_None;
3040
Guido van Rossum177e41a2003-01-30 22:06:23 +00003041 /* Check for invocation from pickle with __getstate__ state */
3042 if (PyTuple_GET_SIZE(args) >= 1 &&
3043 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003044 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3045 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3046 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003047 {
Tim Peters70533e22003-02-01 04:40:04 +00003048 PyDateTime_Time *me;
3049 char aware;
3050
3051 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003052 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003053 if (check_tzinfo_subclass(tzinfo) < 0) {
3054 PyErr_SetString(PyExc_TypeError, "bad "
3055 "tzinfo state arg");
3056 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003057 }
3058 }
Tim Peters70533e22003-02-01 04:40:04 +00003059 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003060 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003061 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003062 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003063
3064 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3065 me->hashcode = -1;
3066 me->hastzinfo = aware;
3067 if (aware) {
3068 Py_INCREF(tzinfo);
3069 me->tzinfo = tzinfo;
3070 }
3071 }
3072 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003073 }
3074
Tim Peters37f39822003-01-10 03:49:02 +00003075 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003076 &hour, &minute, &second, &usecond,
3077 &tzinfo)) {
3078 if (check_time_args(hour, minute, second, usecond) < 0)
3079 return NULL;
3080 if (check_tzinfo_subclass(tzinfo) < 0)
3081 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003082 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3083 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003084 }
3085 return self;
3086}
3087
3088/*
3089 * Destructor.
3090 */
3091
3092static void
Tim Peters37f39822003-01-10 03:49:02 +00003093time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003094{
Tim Petersa032d2e2003-01-11 00:15:54 +00003095 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003096 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003097 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003098 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003099}
3100
3101/*
Tim Peters855fe882002-12-22 03:43:39 +00003102 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003103 */
3104
Tim Peters2a799bf2002-12-16 20:18:38 +00003105/* These are all METH_NOARGS, so don't need to check the arglist. */
3106static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003107time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003108 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003109 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003110}
3111
3112static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003113time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003114 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003115 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003116}
3117
3118static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003119time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003120 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003121 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003122}
3123
3124/*
Tim Peters37f39822003-01-10 03:49:02 +00003125 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003126 */
3127
3128static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003129time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003130{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003131 const char *type_name = Py_Type(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003132 int h = TIME_GET_HOUR(self);
3133 int m = TIME_GET_MINUTE(self);
3134 int s = TIME_GET_SECOND(self);
3135 int us = TIME_GET_MICROSECOND(self);
3136 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003137
Tim Peters37f39822003-01-10 03:49:02 +00003138 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003139 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3140 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003141 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003142 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3143 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003144 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003145 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003146 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003147 result = append_keyword_tzinfo(result, self->tzinfo);
3148 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003149}
3150
Tim Peters37f39822003-01-10 03:49:02 +00003151static PyObject *
3152time_str(PyDateTime_Time *self)
3153{
3154 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3155}
Tim Peters2a799bf2002-12-16 20:18:38 +00003156
3157static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003158time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003159{
3160 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003161 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003162 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003163
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003164 if (us)
3165 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3166 TIME_GET_HOUR(self),
3167 TIME_GET_MINUTE(self),
3168 TIME_GET_SECOND(self),
3169 us);
3170 else
3171 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3172 TIME_GET_HOUR(self),
3173 TIME_GET_MINUTE(self),
3174 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003175
Tim Petersa032d2e2003-01-11 00:15:54 +00003176 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003177 return result;
3178
3179 /* We need to append the UTC offset. */
3180 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003181 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003182 Py_DECREF(result);
3183 return NULL;
3184 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003185 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003186 return result;
3187}
3188
Tim Peters37f39822003-01-10 03:49:02 +00003189static PyObject *
3190time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3191{
3192 PyObject *result;
3193 PyObject *format;
3194 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003195 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003196
Guido van Rossumbce56a62007-05-10 18:04:33 +00003197 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3198 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003199 return NULL;
3200
3201 /* Python's strftime does insane things with the year part of the
3202 * timetuple. The year is forced to (the otherwise nonsensical)
3203 * 1900 to worm around that.
3204 */
3205 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003206 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003207 TIME_GET_HOUR(self),
3208 TIME_GET_MINUTE(self),
3209 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003210 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003211 if (tuple == NULL)
3212 return NULL;
3213 assert(PyTuple_Size(tuple) == 9);
3214 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3215 Py_DECREF(tuple);
3216 return result;
3217}
Tim Peters2a799bf2002-12-16 20:18:38 +00003218
Eric Smith1ba31142007-09-11 18:06:02 +00003219static PyObject *
3220time_format(PyDateTime_Time *self, PyObject *args)
3221{
3222 PyObject *format;
3223
3224 if (!PyArg_ParseTuple(args, "U:__format__", &format))
3225 return NULL;
3226
3227 /* if the format is zero length, return str(self) */
3228 if (PyUnicode_GetSize(format) == 0)
3229 return PyObject_Unicode((PyObject *)self);
3230
3231 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
3232}
3233
Tim Peters2a799bf2002-12-16 20:18:38 +00003234/*
3235 * Miscellaneous methods.
3236 */
3237
Tim Peters37f39822003-01-10 03:49:02 +00003238static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003239time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003240{
3241 int diff;
3242 naivety n1, n2;
3243 int offset1, offset2;
3244
3245 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003246 Py_INCREF(Py_NotImplemented);
3247 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003248 }
Guido van Rossum19960592006-08-24 17:29:38 +00003249 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3250 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003251 return NULL;
3252 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3253 /* If they're both naive, or both aware and have the same offsets,
3254 * we get off cheap. Note that if they're both naive, offset1 ==
3255 * offset2 == 0 at this point.
3256 */
3257 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003258 diff = memcmp(((PyDateTime_Time *)self)->data,
3259 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003260 _PyDateTime_TIME_DATASIZE);
3261 return diff_to_bool(diff, op);
3262 }
3263
3264 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3265 assert(offset1 != offset2); /* else last "if" handled it */
3266 /* Convert everything except microseconds to seconds. These
3267 * can't overflow (no more than the # of seconds in 2 days).
3268 */
3269 offset1 = TIME_GET_HOUR(self) * 3600 +
3270 (TIME_GET_MINUTE(self) - offset1) * 60 +
3271 TIME_GET_SECOND(self);
3272 offset2 = TIME_GET_HOUR(other) * 3600 +
3273 (TIME_GET_MINUTE(other) - offset2) * 60 +
3274 TIME_GET_SECOND(other);
3275 diff = offset1 - offset2;
3276 if (diff == 0)
3277 diff = TIME_GET_MICROSECOND(self) -
3278 TIME_GET_MICROSECOND(other);
3279 return diff_to_bool(diff, op);
3280 }
3281
3282 assert(n1 != n2);
3283 PyErr_SetString(PyExc_TypeError,
3284 "can't compare offset-naive and "
3285 "offset-aware times");
3286 return NULL;
3287}
3288
3289static long
3290time_hash(PyDateTime_Time *self)
3291{
3292 if (self->hashcode == -1) {
3293 naivety n;
3294 int offset;
3295 PyObject *temp;
3296
3297 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3298 assert(n != OFFSET_UNKNOWN);
3299 if (n == OFFSET_ERROR)
3300 return -1;
3301
3302 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003303 if (offset == 0) {
3304 self->hashcode = generic_hash(
3305 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3306 return self->hashcode;
3307 }
Tim Peters37f39822003-01-10 03:49:02 +00003308 else {
3309 int hour;
3310 int minute;
3311
3312 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003313 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003314 hour = divmod(TIME_GET_HOUR(self) * 60 +
3315 TIME_GET_MINUTE(self) - offset,
3316 60,
3317 &minute);
3318 if (0 <= hour && hour < 24)
3319 temp = new_time(hour, minute,
3320 TIME_GET_SECOND(self),
3321 TIME_GET_MICROSECOND(self),
3322 Py_None);
3323 else
3324 temp = Py_BuildValue("iiii",
3325 hour, minute,
3326 TIME_GET_SECOND(self),
3327 TIME_GET_MICROSECOND(self));
3328 }
3329 if (temp != NULL) {
3330 self->hashcode = PyObject_Hash(temp);
3331 Py_DECREF(temp);
3332 }
3333 }
3334 return self->hashcode;
3335}
Tim Peters2a799bf2002-12-16 20:18:38 +00003336
Tim Peters12bf3392002-12-24 05:41:27 +00003337static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003338time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003339{
3340 PyObject *clone;
3341 PyObject *tuple;
3342 int hh = TIME_GET_HOUR(self);
3343 int mm = TIME_GET_MINUTE(self);
3344 int ss = TIME_GET_SECOND(self);
3345 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003346 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003347
3348 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003349 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003350 &hh, &mm, &ss, &us, &tzinfo))
3351 return NULL;
3352 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3353 if (tuple == NULL)
3354 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003355 clone = time_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003356 Py_DECREF(tuple);
3357 return clone;
3358}
3359
Tim Peters2a799bf2002-12-16 20:18:38 +00003360static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003361time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003362{
3363 int offset;
3364 int none;
3365
3366 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3367 /* Since utcoffset is in whole minutes, nothing can
3368 * alter the conclusion that this is nonzero.
3369 */
3370 return 1;
3371 }
3372 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003373 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003374 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003375 if (offset == -1 && PyErr_Occurred())
3376 return -1;
3377 }
3378 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3379}
3380
Tim Peters371935f2003-02-01 01:52:50 +00003381/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003382
Tim Peters33e0f382003-01-10 02:05:14 +00003383/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003384 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3385 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003386 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003387 */
3388static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003389time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003390{
3391 PyObject *basestate;
3392 PyObject *result = NULL;
3393
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003394 basestate = PyBytes_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003395 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003396 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003397 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003398 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003399 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003400 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003401 Py_DECREF(basestate);
3402 }
3403 return result;
3404}
3405
3406static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003407time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003408{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003409 return Py_BuildValue("(ON)", Py_Type(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003410}
3411
Tim Peters37f39822003-01-10 03:49:02 +00003412static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003413
Thomas Wouterscf297e42007-02-23 15:07:44 +00003414 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003415 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3416 "[+HH:MM].")},
3417
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003418 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003419 PyDoc_STR("format -> strftime() style string.")},
3420
Eric Smith1ba31142007-09-11 18:06:02 +00003421 {"__format__", (PyCFunction)time_format, METH_VARARGS,
3422 PyDoc_STR("Formats self with strftime.")},
3423
Tim Peters37f39822003-01-10 03:49:02 +00003424 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003425 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3426
Tim Peters37f39822003-01-10 03:49:02 +00003427 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3429
Tim Peters37f39822003-01-10 03:49:02 +00003430 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003431 PyDoc_STR("Return self.tzinfo.dst(self).")},
3432
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003433 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003434 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003435
Guido van Rossum177e41a2003-01-30 22:06:23 +00003436 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3437 PyDoc_STR("__reduce__() -> (cls, state)")},
3438
Tim Peters2a799bf2002-12-16 20:18:38 +00003439 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003440};
3441
Tim Peters37f39822003-01-10 03:49:02 +00003442static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003443PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3444\n\
3445All arguments are optional. tzinfo may be None, or an instance of\n\
3446a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003447
Tim Peters37f39822003-01-10 03:49:02 +00003448static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003449 0, /* nb_add */
3450 0, /* nb_subtract */
3451 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003452 0, /* nb_remainder */
3453 0, /* nb_divmod */
3454 0, /* nb_power */
3455 0, /* nb_negative */
3456 0, /* nb_positive */
3457 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003458 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003459};
3460
Neal Norwitz227b5332006-03-22 09:28:35 +00003461static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003462 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003463 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003464 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003465 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003466 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003467 0, /* tp_print */
3468 0, /* tp_getattr */
3469 0, /* tp_setattr */
3470 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003471 (reprfunc)time_repr, /* tp_repr */
3472 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003473 0, /* tp_as_sequence */
3474 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003475 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003476 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003477 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003478 PyObject_GenericGetAttr, /* tp_getattro */
3479 0, /* tp_setattro */
3480 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003481 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003482 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003483 0, /* tp_traverse */
3484 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003485 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003486 0, /* tp_weaklistoffset */
3487 0, /* tp_iter */
3488 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003489 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003490 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003491 time_getset, /* tp_getset */
3492 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003493 0, /* tp_dict */
3494 0, /* tp_descr_get */
3495 0, /* tp_descr_set */
3496 0, /* tp_dictoffset */
3497 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003498 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003499 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003500 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003501};
3502
3503/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003504 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003505 */
3506
Tim Petersa9bc1682003-01-11 03:39:11 +00003507/* Accessor properties. Properties for day, month, and year are inherited
3508 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003509 */
3510
3511static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003512datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003513{
Tim Petersa9bc1682003-01-11 03:39:11 +00003514 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003515}
3516
Tim Petersa9bc1682003-01-11 03:39:11 +00003517static PyObject *
3518datetime_minute(PyDateTime_DateTime *self, void *unused)
3519{
3520 return PyInt_FromLong(DATE_GET_MINUTE(self));
3521}
3522
3523static PyObject *
3524datetime_second(PyDateTime_DateTime *self, void *unused)
3525{
3526 return PyInt_FromLong(DATE_GET_SECOND(self));
3527}
3528
3529static PyObject *
3530datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3531{
3532 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3533}
3534
3535static PyObject *
3536datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3537{
3538 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3539 Py_INCREF(result);
3540 return result;
3541}
3542
3543static PyGetSetDef datetime_getset[] = {
3544 {"hour", (getter)datetime_hour},
3545 {"minute", (getter)datetime_minute},
3546 {"second", (getter)datetime_second},
3547 {"microsecond", (getter)datetime_microsecond},
3548 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003549 {NULL}
3550};
3551
3552/*
3553 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003554 */
3555
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003556static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003557 "year", "month", "day", "hour", "minute", "second",
3558 "microsecond", "tzinfo", NULL
3559};
3560
Tim Peters2a799bf2002-12-16 20:18:38 +00003561static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003562datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003563{
3564 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003565 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003566 int year;
3567 int month;
3568 int day;
3569 int hour = 0;
3570 int minute = 0;
3571 int second = 0;
3572 int usecond = 0;
3573 PyObject *tzinfo = Py_None;
3574
Guido van Rossum177e41a2003-01-30 22:06:23 +00003575 /* Check for invocation from pickle with __getstate__ state */
3576 if (PyTuple_GET_SIZE(args) >= 1 &&
3577 PyTuple_GET_SIZE(args) <= 2 &&
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003578 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3579 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3580 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003581 {
Tim Peters70533e22003-02-01 04:40:04 +00003582 PyDateTime_DateTime *me;
3583 char aware;
3584
3585 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003586 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003587 if (check_tzinfo_subclass(tzinfo) < 0) {
3588 PyErr_SetString(PyExc_TypeError, "bad "
3589 "tzinfo state arg");
3590 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003591 }
3592 }
Tim Peters70533e22003-02-01 04:40:04 +00003593 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003594 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003595 if (me != NULL) {
Martin v. Löwis10a60b32007-07-18 02:28:27 +00003596 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003597
3598 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3599 me->hashcode = -1;
3600 me->hastzinfo = aware;
3601 if (aware) {
3602 Py_INCREF(tzinfo);
3603 me->tzinfo = tzinfo;
3604 }
3605 }
3606 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003607 }
3608
Tim Petersa9bc1682003-01-11 03:39:11 +00003609 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003610 &year, &month, &day, &hour, &minute,
3611 &second, &usecond, &tzinfo)) {
3612 if (check_date_args(year, month, day) < 0)
3613 return NULL;
3614 if (check_time_args(hour, minute, second, usecond) < 0)
3615 return NULL;
3616 if (check_tzinfo_subclass(tzinfo) < 0)
3617 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003618 self = new_datetime_ex(year, month, day,
3619 hour, minute, second, usecond,
3620 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003621 }
3622 return self;
3623}
3624
Tim Petersa9bc1682003-01-11 03:39:11 +00003625/* TM_FUNC is the shared type of localtime() and gmtime(). */
3626typedef struct tm *(*TM_FUNC)(const time_t *timer);
3627
3628/* Internal helper.
3629 * Build datetime from a time_t and a distinct count of microseconds.
3630 * Pass localtime or gmtime for f, to control the interpretation of timet.
3631 */
3632static PyObject *
3633datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3634 PyObject *tzinfo)
3635{
3636 struct tm *tm;
3637 PyObject *result = NULL;
3638
3639 tm = f(&timet);
3640 if (tm) {
3641 /* The platform localtime/gmtime may insert leap seconds,
3642 * indicated by tm->tm_sec > 59. We don't care about them,
3643 * except to the extent that passing them on to the datetime
3644 * constructor would raise ValueError for a reason that
3645 * made no sense to the user.
3646 */
3647 if (tm->tm_sec > 59)
3648 tm->tm_sec = 59;
3649 result = PyObject_CallFunction(cls, "iiiiiiiO",
3650 tm->tm_year + 1900,
3651 tm->tm_mon + 1,
3652 tm->tm_mday,
3653 tm->tm_hour,
3654 tm->tm_min,
3655 tm->tm_sec,
3656 us,
3657 tzinfo);
3658 }
3659 else
3660 PyErr_SetString(PyExc_ValueError,
3661 "timestamp out of range for "
3662 "platform localtime()/gmtime() function");
3663 return result;
3664}
3665
3666/* Internal helper.
3667 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3668 * to control the interpretation of the timestamp. Since a double doesn't
3669 * have enough bits to cover a datetime's full range of precision, it's
3670 * better to call datetime_from_timet_and_us provided you have a way
3671 * to get that much precision (e.g., C time() isn't good enough).
3672 */
3673static PyObject *
3674datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3675 PyObject *tzinfo)
3676{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003677 time_t timet;
3678 double fraction;
3679 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003680
Tim Peters1b6f7a92004-06-20 02:50:16 +00003681 timet = _PyTime_DoubleToTimet(timestamp);
3682 if (timet == (time_t)-1 && PyErr_Occurred())
3683 return NULL;
3684 fraction = timestamp - (double)timet;
3685 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003686 if (us < 0) {
3687 /* Truncation towards zero is not what we wanted
3688 for negative numbers (Python's mod semantics) */
3689 timet -= 1;
3690 us += 1000000;
3691 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003692 /* If timestamp is less than one microsecond smaller than a
3693 * full second, round up. Otherwise, ValueErrors are raised
3694 * for some floats. */
3695 if (us == 1000000) {
3696 timet += 1;
3697 us = 0;
3698 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003699 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3700}
3701
3702/* Internal helper.
3703 * Build most accurate possible datetime for current time. Pass localtime or
3704 * gmtime for f as appropriate.
3705 */
3706static PyObject *
3707datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3708{
3709#ifdef HAVE_GETTIMEOFDAY
3710 struct timeval t;
3711
3712#ifdef GETTIMEOFDAY_NO_TZ
3713 gettimeofday(&t);
3714#else
3715 gettimeofday(&t, (struct timezone *)NULL);
3716#endif
3717 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3718 tzinfo);
3719
3720#else /* ! HAVE_GETTIMEOFDAY */
3721 /* No flavor of gettimeofday exists on this platform. Python's
3722 * time.time() does a lot of other platform tricks to get the
3723 * best time it can on the platform, and we're not going to do
3724 * better than that (if we could, the better code would belong
3725 * in time.time()!) We're limited by the precision of a double,
3726 * though.
3727 */
3728 PyObject *time;
3729 double dtime;
3730
3731 time = time_time();
3732 if (time == NULL)
3733 return NULL;
3734 dtime = PyFloat_AsDouble(time);
3735 Py_DECREF(time);
3736 if (dtime == -1.0 && PyErr_Occurred())
3737 return NULL;
3738 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3739#endif /* ! HAVE_GETTIMEOFDAY */
3740}
3741
Tim Peters2a799bf2002-12-16 20:18:38 +00003742/* Return best possible local time -- this isn't constrained by the
3743 * precision of a timestamp.
3744 */
3745static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003746datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003747{
Tim Peters10cadce2003-01-23 19:58:02 +00003748 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003749 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003750 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003751
Tim Peters10cadce2003-01-23 19:58:02 +00003752 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3753 &tzinfo))
3754 return NULL;
3755 if (check_tzinfo_subclass(tzinfo) < 0)
3756 return NULL;
3757
3758 self = datetime_best_possible(cls,
3759 tzinfo == Py_None ? localtime : gmtime,
3760 tzinfo);
3761 if (self != NULL && tzinfo != Py_None) {
3762 /* Convert UTC to tzinfo's zone. */
3763 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003764 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003765 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003766 }
3767 return self;
3768}
3769
Tim Petersa9bc1682003-01-11 03:39:11 +00003770/* Return best possible UTC time -- this isn't constrained by the
3771 * precision of a timestamp.
3772 */
3773static PyObject *
3774datetime_utcnow(PyObject *cls, PyObject *dummy)
3775{
3776 return datetime_best_possible(cls, gmtime, Py_None);
3777}
3778
Tim Peters2a799bf2002-12-16 20:18:38 +00003779/* Return new local datetime from timestamp (Python timestamp -- a double). */
3780static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003781datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003782{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003783 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003784 double timestamp;
3785 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003786 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003787
Tim Peters2a44a8d2003-01-23 20:53:10 +00003788 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3789 keywords, &timestamp, &tzinfo))
3790 return NULL;
3791 if (check_tzinfo_subclass(tzinfo) < 0)
3792 return NULL;
3793
3794 self = datetime_from_timestamp(cls,
3795 tzinfo == Py_None ? localtime : gmtime,
3796 timestamp,
3797 tzinfo);
3798 if (self != NULL && tzinfo != Py_None) {
3799 /* Convert UTC to tzinfo's zone. */
3800 PyObject *temp = self;
3801 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3802 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003803 }
3804 return self;
3805}
3806
Tim Petersa9bc1682003-01-11 03:39:11 +00003807/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3808static PyObject *
3809datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3810{
3811 double timestamp;
3812 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003813
Tim Petersa9bc1682003-01-11 03:39:11 +00003814 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3815 result = datetime_from_timestamp(cls, gmtime, timestamp,
3816 Py_None);
3817 return result;
3818}
3819
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003820/* Return new datetime from time.strptime(). */
3821static PyObject *
3822datetime_strptime(PyObject *cls, PyObject *args)
3823{
3824 PyObject *result = NULL, *obj, *module;
Guido van Rossume8a17aa2007-08-29 17:28:42 +00003825 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003826
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003827 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003828 return NULL;
3829
3830 if ((module = PyImport_ImportModule("time")) == NULL)
3831 return NULL;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003832 obj = PyObject_CallMethod(module, "strptime", "uu", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003833 Py_DECREF(module);
3834
3835 if (obj != NULL) {
3836 int i, good_timetuple = 1;
3837 long int ia[6];
3838 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3839 for (i=0; i < 6; i++) {
3840 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003841 if (p == NULL) {
3842 Py_DECREF(obj);
3843 return NULL;
3844 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003845 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003846 ia[i] = PyInt_AsLong(p);
3847 else
3848 good_timetuple = 0;
3849 Py_DECREF(p);
3850 }
3851 else
3852 good_timetuple = 0;
3853 if (good_timetuple)
3854 result = PyObject_CallFunction(cls, "iiiiii",
3855 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3856 else
3857 PyErr_SetString(PyExc_ValueError,
3858 "unexpected value from time.strptime");
3859 Py_DECREF(obj);
3860 }
3861 return result;
3862}
3863
Tim Petersa9bc1682003-01-11 03:39:11 +00003864/* Return new datetime from date/datetime and time arguments. */
3865static PyObject *
3866datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3867{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003868 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003869 PyObject *date;
3870 PyObject *time;
3871 PyObject *result = NULL;
3872
3873 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3874 &PyDateTime_DateType, &date,
3875 &PyDateTime_TimeType, &time)) {
3876 PyObject *tzinfo = Py_None;
3877
3878 if (HASTZINFO(time))
3879 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3880 result = PyObject_CallFunction(cls, "iiiiiiiO",
3881 GET_YEAR(date),
3882 GET_MONTH(date),
3883 GET_DAY(date),
3884 TIME_GET_HOUR(time),
3885 TIME_GET_MINUTE(time),
3886 TIME_GET_SECOND(time),
3887 TIME_GET_MICROSECOND(time),
3888 tzinfo);
3889 }
3890 return result;
3891}
Tim Peters2a799bf2002-12-16 20:18:38 +00003892
3893/*
3894 * Destructor.
3895 */
3896
3897static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003898datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003899{
Tim Petersa9bc1682003-01-11 03:39:11 +00003900 if (HASTZINFO(self)) {
3901 Py_XDECREF(self->tzinfo);
3902 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003903 Py_Type(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003904}
3905
3906/*
3907 * Indirect access to tzinfo methods.
3908 */
3909
Tim Peters2a799bf2002-12-16 20:18:38 +00003910/* These are all METH_NOARGS, so don't need to check the arglist. */
3911static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003912datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3913 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3914 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003915}
3916
3917static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003918datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3919 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3920 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003921}
3922
3923static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003924datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3925 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3926 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003927}
3928
3929/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003930 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003931 */
3932
Tim Petersa9bc1682003-01-11 03:39:11 +00003933/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3934 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003935 */
3936static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003937add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3938 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003939{
Tim Petersa9bc1682003-01-11 03:39:11 +00003940 /* Note that the C-level additions can't overflow, because of
3941 * invariant bounds on the member values.
3942 */
3943 int year = GET_YEAR(date);
3944 int month = GET_MONTH(date);
3945 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3946 int hour = DATE_GET_HOUR(date);
3947 int minute = DATE_GET_MINUTE(date);
3948 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3949 int microsecond = DATE_GET_MICROSECOND(date) +
3950 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003951
Tim Petersa9bc1682003-01-11 03:39:11 +00003952 assert(factor == 1 || factor == -1);
3953 if (normalize_datetime(&year, &month, &day,
3954 &hour, &minute, &second, &microsecond) < 0)
3955 return NULL;
3956 else
3957 return new_datetime(year, month, day,
3958 hour, minute, second, microsecond,
3959 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003960}
3961
3962static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003963datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003964{
Tim Petersa9bc1682003-01-11 03:39:11 +00003965 if (PyDateTime_Check(left)) {
3966 /* datetime + ??? */
3967 if (PyDelta_Check(right))
3968 /* datetime + delta */
3969 return add_datetime_timedelta(
3970 (PyDateTime_DateTime *)left,
3971 (PyDateTime_Delta *)right,
3972 1);
3973 }
3974 else if (PyDelta_Check(left)) {
3975 /* delta + datetime */
3976 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3977 (PyDateTime_Delta *) left,
3978 1);
3979 }
3980 Py_INCREF(Py_NotImplemented);
3981 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003982}
3983
3984static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003985datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003986{
3987 PyObject *result = Py_NotImplemented;
3988
3989 if (PyDateTime_Check(left)) {
3990 /* datetime - ??? */
3991 if (PyDateTime_Check(right)) {
3992 /* datetime - datetime */
3993 naivety n1, n2;
3994 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003995 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003996
Tim Peterse39a80c2002-12-30 21:28:52 +00003997 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3998 right, &offset2, &n2,
3999 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00004000 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00004001 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00004002 if (n1 != n2) {
4003 PyErr_SetString(PyExc_TypeError,
4004 "can't subtract offset-naive and "
4005 "offset-aware datetimes");
4006 return NULL;
4007 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004008 delta_d = ymd_to_ord(GET_YEAR(left),
4009 GET_MONTH(left),
4010 GET_DAY(left)) -
4011 ymd_to_ord(GET_YEAR(right),
4012 GET_MONTH(right),
4013 GET_DAY(right));
4014 /* These can't overflow, since the values are
4015 * normalized. At most this gives the number of
4016 * seconds in one day.
4017 */
4018 delta_s = (DATE_GET_HOUR(left) -
4019 DATE_GET_HOUR(right)) * 3600 +
4020 (DATE_GET_MINUTE(left) -
4021 DATE_GET_MINUTE(right)) * 60 +
4022 (DATE_GET_SECOND(left) -
4023 DATE_GET_SECOND(right));
4024 delta_us = DATE_GET_MICROSECOND(left) -
4025 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004026 /* (left - offset1) - (right - offset2) =
4027 * (left - right) + (offset2 - offset1)
4028 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004029 delta_s += (offset2 - offset1) * 60;
4030 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004031 }
4032 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004033 /* datetime - delta */
4034 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004035 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004036 (PyDateTime_Delta *)right,
4037 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004038 }
4039 }
4040
4041 if (result == Py_NotImplemented)
4042 Py_INCREF(result);
4043 return result;
4044}
4045
4046/* Various ways to turn a datetime into a string. */
4047
4048static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004049datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004050{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004051 const char *type_name = Py_Type(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004052 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004053
Tim Petersa9bc1682003-01-11 03:39:11 +00004054 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004055 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004056 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004057 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004058 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4059 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4060 DATE_GET_SECOND(self),
4061 DATE_GET_MICROSECOND(self));
4062 }
4063 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004064 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004065 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004066 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004067 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4068 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4069 DATE_GET_SECOND(self));
4070 }
4071 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004072 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004073 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004074 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004075 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4076 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4077 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004078 if (baserepr == NULL || ! HASTZINFO(self))
4079 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004080 return append_keyword_tzinfo(baserepr, self->tzinfo);
4081}
4082
Tim Petersa9bc1682003-01-11 03:39:11 +00004083static PyObject *
4084datetime_str(PyDateTime_DateTime *self)
4085{
4086 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4087}
Tim Peters2a799bf2002-12-16 20:18:38 +00004088
4089static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004090datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004091{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004092 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004093 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004094 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004095 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004096 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004097
Walter Dörwaldd0941302007-07-01 21:58:22 +00004098 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004099 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004100 if (us)
4101 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4102 GET_YEAR(self), GET_MONTH(self),
4103 GET_DAY(self), (int)sep,
4104 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4105 DATE_GET_SECOND(self), us);
4106 else
4107 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4108 GET_YEAR(self), GET_MONTH(self),
4109 GET_DAY(self), (int)sep,
4110 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4111 DATE_GET_SECOND(self));
4112
4113 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004114 return result;
4115
4116 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004117 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004118 (PyObject *)self) < 0) {
4119 Py_DECREF(result);
4120 return NULL;
4121 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004122 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004123 return result;
4124}
4125
Tim Petersa9bc1682003-01-11 03:39:11 +00004126static PyObject *
4127datetime_ctime(PyDateTime_DateTime *self)
4128{
4129 return format_ctime((PyDateTime_Date *)self,
4130 DATE_GET_HOUR(self),
4131 DATE_GET_MINUTE(self),
4132 DATE_GET_SECOND(self));
4133}
4134
Tim Peters2a799bf2002-12-16 20:18:38 +00004135/* Miscellaneous methods. */
4136
Tim Petersa9bc1682003-01-11 03:39:11 +00004137static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004138datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004139{
4140 int diff;
4141 naivety n1, n2;
4142 int offset1, offset2;
4143
4144 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004145 if (PyDate_Check(other)) {
4146 /* Prevent invocation of date_richcompare. We want to
4147 return NotImplemented here to give the other object
4148 a chance. But since DateTime is a subclass of
4149 Date, if the other object is a Date, it would
4150 compute an ordering based on the date part alone,
4151 and we don't want that. So force unequal or
4152 uncomparable here in that case. */
4153 if (op == Py_EQ)
4154 Py_RETURN_FALSE;
4155 if (op == Py_NE)
4156 Py_RETURN_TRUE;
4157 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004158 }
Guido van Rossum19960592006-08-24 17:29:38 +00004159 Py_INCREF(Py_NotImplemented);
4160 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004161 }
4162
Guido van Rossum19960592006-08-24 17:29:38 +00004163 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4164 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004165 return NULL;
4166 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4167 /* If they're both naive, or both aware and have the same offsets,
4168 * we get off cheap. Note that if they're both naive, offset1 ==
4169 * offset2 == 0 at this point.
4170 */
4171 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004172 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4173 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004174 _PyDateTime_DATETIME_DATASIZE);
4175 return diff_to_bool(diff, op);
4176 }
4177
4178 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4179 PyDateTime_Delta *delta;
4180
4181 assert(offset1 != offset2); /* else last "if" handled it */
4182 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4183 other);
4184 if (delta == NULL)
4185 return NULL;
4186 diff = GET_TD_DAYS(delta);
4187 if (diff == 0)
4188 diff = GET_TD_SECONDS(delta) |
4189 GET_TD_MICROSECONDS(delta);
4190 Py_DECREF(delta);
4191 return diff_to_bool(diff, op);
4192 }
4193
4194 assert(n1 != n2);
4195 PyErr_SetString(PyExc_TypeError,
4196 "can't compare offset-naive and "
4197 "offset-aware datetimes");
4198 return NULL;
4199}
4200
4201static long
4202datetime_hash(PyDateTime_DateTime *self)
4203{
4204 if (self->hashcode == -1) {
4205 naivety n;
4206 int offset;
4207 PyObject *temp;
4208
4209 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4210 &offset);
4211 assert(n != OFFSET_UNKNOWN);
4212 if (n == OFFSET_ERROR)
4213 return -1;
4214
4215 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00004216 if (n == OFFSET_NAIVE) {
4217 self->hashcode = generic_hash(
4218 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4219 return self->hashcode;
4220 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004221 else {
4222 int days;
4223 int seconds;
4224
4225 assert(n == OFFSET_AWARE);
4226 assert(HASTZINFO(self));
4227 days = ymd_to_ord(GET_YEAR(self),
4228 GET_MONTH(self),
4229 GET_DAY(self));
4230 seconds = DATE_GET_HOUR(self) * 3600 +
4231 (DATE_GET_MINUTE(self) - offset) * 60 +
4232 DATE_GET_SECOND(self);
4233 temp = new_delta(days,
4234 seconds,
4235 DATE_GET_MICROSECOND(self),
4236 1);
4237 }
4238 if (temp != NULL) {
4239 self->hashcode = PyObject_Hash(temp);
4240 Py_DECREF(temp);
4241 }
4242 }
4243 return self->hashcode;
4244}
Tim Peters2a799bf2002-12-16 20:18:38 +00004245
4246static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004247datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004248{
4249 PyObject *clone;
4250 PyObject *tuple;
4251 int y = GET_YEAR(self);
4252 int m = GET_MONTH(self);
4253 int d = GET_DAY(self);
4254 int hh = DATE_GET_HOUR(self);
4255 int mm = DATE_GET_MINUTE(self);
4256 int ss = DATE_GET_SECOND(self);
4257 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004258 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004259
4260 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004261 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004262 &y, &m, &d, &hh, &mm, &ss, &us,
4263 &tzinfo))
4264 return NULL;
4265 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4266 if (tuple == NULL)
4267 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004268 clone = datetime_new(Py_Type(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004269 Py_DECREF(tuple);
4270 return clone;
4271}
4272
4273static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004274datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004275{
Tim Peters52dcce22003-01-23 16:36:11 +00004276 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004277 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004278 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004279
Tim Peters80475bb2002-12-25 07:40:55 +00004280 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004281 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004282
Tim Peters52dcce22003-01-23 16:36:11 +00004283 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4284 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004285 return NULL;
4286
Tim Peters52dcce22003-01-23 16:36:11 +00004287 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4288 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004289
Tim Peters52dcce22003-01-23 16:36:11 +00004290 /* Conversion to self's own time zone is a NOP. */
4291 if (self->tzinfo == tzinfo) {
4292 Py_INCREF(self);
4293 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004294 }
Tim Peters521fc152002-12-31 17:36:56 +00004295
Tim Peters52dcce22003-01-23 16:36:11 +00004296 /* Convert self to UTC. */
4297 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4298 if (offset == -1 && PyErr_Occurred())
4299 return NULL;
4300 if (none)
4301 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004302
Tim Peters52dcce22003-01-23 16:36:11 +00004303 y = GET_YEAR(self);
4304 m = GET_MONTH(self);
4305 d = GET_DAY(self);
4306 hh = DATE_GET_HOUR(self);
4307 mm = DATE_GET_MINUTE(self);
4308 ss = DATE_GET_SECOND(self);
4309 us = DATE_GET_MICROSECOND(self);
4310
4311 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004312 if ((mm < 0 || mm >= 60) &&
4313 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004314 return NULL;
4315
4316 /* Attach new tzinfo and let fromutc() do the rest. */
4317 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4318 if (result != NULL) {
4319 PyObject *temp = result;
4320
4321 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4322 Py_DECREF(temp);
4323 }
Tim Petersadf64202003-01-04 06:03:15 +00004324 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004325
Tim Peters52dcce22003-01-23 16:36:11 +00004326NeedAware:
4327 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4328 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004329 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004330}
4331
4332static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004333datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004334{
4335 int dstflag = -1;
4336
Tim Petersa9bc1682003-01-11 03:39:11 +00004337 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004338 int none;
4339
4340 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4341 if (dstflag == -1 && PyErr_Occurred())
4342 return NULL;
4343
4344 if (none)
4345 dstflag = -1;
4346 else if (dstflag != 0)
4347 dstflag = 1;
4348
4349 }
4350 return build_struct_time(GET_YEAR(self),
4351 GET_MONTH(self),
4352 GET_DAY(self),
4353 DATE_GET_HOUR(self),
4354 DATE_GET_MINUTE(self),
4355 DATE_GET_SECOND(self),
4356 dstflag);
4357}
4358
4359static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004360datetime_getdate(PyDateTime_DateTime *self)
4361{
4362 return new_date(GET_YEAR(self),
4363 GET_MONTH(self),
4364 GET_DAY(self));
4365}
4366
4367static PyObject *
4368datetime_gettime(PyDateTime_DateTime *self)
4369{
4370 return new_time(DATE_GET_HOUR(self),
4371 DATE_GET_MINUTE(self),
4372 DATE_GET_SECOND(self),
4373 DATE_GET_MICROSECOND(self),
4374 Py_None);
4375}
4376
4377static PyObject *
4378datetime_gettimetz(PyDateTime_DateTime *self)
4379{
4380 return new_time(DATE_GET_HOUR(self),
4381 DATE_GET_MINUTE(self),
4382 DATE_GET_SECOND(self),
4383 DATE_GET_MICROSECOND(self),
4384 HASTZINFO(self) ? self->tzinfo : Py_None);
4385}
4386
4387static PyObject *
4388datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004389{
4390 int y = GET_YEAR(self);
4391 int m = GET_MONTH(self);
4392 int d = GET_DAY(self);
4393 int hh = DATE_GET_HOUR(self);
4394 int mm = DATE_GET_MINUTE(self);
4395 int ss = DATE_GET_SECOND(self);
4396 int us = 0; /* microseconds are ignored in a timetuple */
4397 int offset = 0;
4398
Tim Petersa9bc1682003-01-11 03:39:11 +00004399 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004400 int none;
4401
4402 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4403 if (offset == -1 && PyErr_Occurred())
4404 return NULL;
4405 }
4406 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4407 * 0 in a UTC timetuple regardless of what dst() says.
4408 */
4409 if (offset) {
4410 /* Subtract offset minutes & normalize. */
4411 int stat;
4412
4413 mm -= offset;
4414 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4415 if (stat < 0) {
4416 /* At the edges, it's possible we overflowed
4417 * beyond MINYEAR or MAXYEAR.
4418 */
4419 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4420 PyErr_Clear();
4421 else
4422 return NULL;
4423 }
4424 }
4425 return build_struct_time(y, m, d, hh, mm, ss, 0);
4426}
4427
Tim Peters371935f2003-02-01 01:52:50 +00004428/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004429
Tim Petersa9bc1682003-01-11 03:39:11 +00004430/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004431 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4432 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004433 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004434 */
4435static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004436datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004437{
4438 PyObject *basestate;
4439 PyObject *result = NULL;
4440
Martin v. Löwis10a60b32007-07-18 02:28:27 +00004441 basestate = PyBytes_FromStringAndSize((char *)self->data,
4442 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004443 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004444 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004445 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004446 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004447 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004448 Py_DECREF(basestate);
4449 }
4450 return result;
4451}
4452
4453static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004454datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004455{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004456 return Py_BuildValue("(ON)", Py_Type(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004457}
4458
Tim Petersa9bc1682003-01-11 03:39:11 +00004459static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004460
Tim Peters2a799bf2002-12-16 20:18:38 +00004461 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004462
Tim Petersa9bc1682003-01-11 03:39:11 +00004463 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004464 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004465 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004466
Tim Petersa9bc1682003-01-11 03:39:11 +00004467 {"utcnow", (PyCFunction)datetime_utcnow,
4468 METH_NOARGS | METH_CLASS,
4469 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4470
4471 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004472 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004473 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004474
Tim Petersa9bc1682003-01-11 03:39:11 +00004475 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4476 METH_VARARGS | METH_CLASS,
4477 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4478 "(like time.time()).")},
4479
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004480 {"strptime", (PyCFunction)datetime_strptime,
4481 METH_VARARGS | METH_CLASS,
4482 PyDoc_STR("string, format -> new datetime parsed from a string "
4483 "(like time.strptime()).")},
4484
Tim Petersa9bc1682003-01-11 03:39:11 +00004485 {"combine", (PyCFunction)datetime_combine,
4486 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4487 PyDoc_STR("date, time -> datetime with same date and time fields")},
4488
Tim Peters2a799bf2002-12-16 20:18:38 +00004489 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004490
Tim Petersa9bc1682003-01-11 03:39:11 +00004491 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4492 PyDoc_STR("Return date object with same year, month and day.")},
4493
4494 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4495 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4496
4497 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4498 PyDoc_STR("Return time object with same time and tzinfo.")},
4499
4500 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4501 PyDoc_STR("Return ctime() style string.")},
4502
4503 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004504 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4505
Tim Petersa9bc1682003-01-11 03:39:11 +00004506 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004507 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4508
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004509 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004510 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4511 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4512 "sep is used to separate the year from the time, and "
4513 "defaults to 'T'.")},
4514
Tim Petersa9bc1682003-01-11 03:39:11 +00004515 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004516 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4517
Tim Petersa9bc1682003-01-11 03:39:11 +00004518 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004519 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4520
Tim Petersa9bc1682003-01-11 03:39:11 +00004521 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004522 PyDoc_STR("Return self.tzinfo.dst(self).")},
4523
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004524 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004525 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004526
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004527 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004528 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4529
Guido van Rossum177e41a2003-01-30 22:06:23 +00004530 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4531 PyDoc_STR("__reduce__() -> (cls, state)")},
4532
Tim Peters2a799bf2002-12-16 20:18:38 +00004533 {NULL, NULL}
4534};
4535
Tim Petersa9bc1682003-01-11 03:39:11 +00004536static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004537PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4538\n\
4539The year, month and day arguments are required. tzinfo may be None, or an\n\
4540instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004541
Tim Petersa9bc1682003-01-11 03:39:11 +00004542static PyNumberMethods datetime_as_number = {
4543 datetime_add, /* nb_add */
4544 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004545 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004546 0, /* nb_remainder */
4547 0, /* nb_divmod */
4548 0, /* nb_power */
4549 0, /* nb_negative */
4550 0, /* nb_positive */
4551 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004552 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004553};
4554
Neal Norwitz227b5332006-03-22 09:28:35 +00004555static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004556 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004557 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004558 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004559 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004560 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004561 0, /* tp_print */
4562 0, /* tp_getattr */
4563 0, /* tp_setattr */
4564 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004565 (reprfunc)datetime_repr, /* tp_repr */
4566 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004567 0, /* tp_as_sequence */
4568 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004569 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004570 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004571 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004572 PyObject_GenericGetAttr, /* tp_getattro */
4573 0, /* tp_setattro */
4574 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004575 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004576 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004577 0, /* tp_traverse */
4578 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004579 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004580 0, /* tp_weaklistoffset */
4581 0, /* tp_iter */
4582 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004583 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004584 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004585 datetime_getset, /* tp_getset */
4586 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004587 0, /* tp_dict */
4588 0, /* tp_descr_get */
4589 0, /* tp_descr_set */
4590 0, /* tp_dictoffset */
4591 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004592 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004593 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004594 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004595};
4596
4597/* ---------------------------------------------------------------------------
4598 * Module methods and initialization.
4599 */
4600
4601static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004602 {NULL, NULL}
4603};
4604
Tim Peters9ddf40b2004-06-20 22:41:32 +00004605/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4606 * datetime.h.
4607 */
4608static PyDateTime_CAPI CAPI = {
4609 &PyDateTime_DateType,
4610 &PyDateTime_DateTimeType,
4611 &PyDateTime_TimeType,
4612 &PyDateTime_DeltaType,
4613 &PyDateTime_TZInfoType,
4614 new_date_ex,
4615 new_datetime_ex,
4616 new_time_ex,
4617 new_delta_ex,
4618 datetime_fromtimestamp,
4619 date_fromtimestamp
4620};
4621
4622
Tim Peters2a799bf2002-12-16 20:18:38 +00004623PyMODINIT_FUNC
4624initdatetime(void)
4625{
4626 PyObject *m; /* a module object */
4627 PyObject *d; /* its dict */
4628 PyObject *x;
4629
Tim Peters2a799bf2002-12-16 20:18:38 +00004630 m = Py_InitModule3("datetime", module_methods,
4631 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004632 if (m == NULL)
4633 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004634
4635 if (PyType_Ready(&PyDateTime_DateType) < 0)
4636 return;
4637 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4638 return;
4639 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4640 return;
4641 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4642 return;
4643 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4644 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004645
Tim Peters2a799bf2002-12-16 20:18:38 +00004646 /* timedelta values */
4647 d = PyDateTime_DeltaType.tp_dict;
4648
Tim Peters2a799bf2002-12-16 20:18:38 +00004649 x = new_delta(0, 0, 1, 0);
4650 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4651 return;
4652 Py_DECREF(x);
4653
4654 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4655 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4656 return;
4657 Py_DECREF(x);
4658
4659 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4660 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4661 return;
4662 Py_DECREF(x);
4663
4664 /* date values */
4665 d = PyDateTime_DateType.tp_dict;
4666
4667 x = new_date(1, 1, 1);
4668 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4669 return;
4670 Py_DECREF(x);
4671
4672 x = new_date(MAXYEAR, 12, 31);
4673 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4674 return;
4675 Py_DECREF(x);
4676
4677 x = new_delta(1, 0, 0, 0);
4678 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4679 return;
4680 Py_DECREF(x);
4681
Tim Peters37f39822003-01-10 03:49:02 +00004682 /* time values */
4683 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004684
Tim Peters37f39822003-01-10 03:49:02 +00004685 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004686 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4687 return;
4688 Py_DECREF(x);
4689
Tim Peters37f39822003-01-10 03:49:02 +00004690 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004691 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4692 return;
4693 Py_DECREF(x);
4694
4695 x = new_delta(0, 0, 1, 0);
4696 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4697 return;
4698 Py_DECREF(x);
4699
Tim Petersa9bc1682003-01-11 03:39:11 +00004700 /* datetime values */
4701 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004702
Tim Petersa9bc1682003-01-11 03:39:11 +00004703 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004704 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4705 return;
4706 Py_DECREF(x);
4707
Tim Petersa9bc1682003-01-11 03:39:11 +00004708 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004709 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4710 return;
4711 Py_DECREF(x);
4712
4713 x = new_delta(0, 0, 1, 0);
4714 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4715 return;
4716 Py_DECREF(x);
4717
Tim Peters2a799bf2002-12-16 20:18:38 +00004718 /* module initialization */
4719 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4720 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4721
4722 Py_INCREF(&PyDateTime_DateType);
4723 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4724
Tim Petersa9bc1682003-01-11 03:39:11 +00004725 Py_INCREF(&PyDateTime_DateTimeType);
4726 PyModule_AddObject(m, "datetime",
4727 (PyObject *)&PyDateTime_DateTimeType);
4728
4729 Py_INCREF(&PyDateTime_TimeType);
4730 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4731
Tim Peters2a799bf2002-12-16 20:18:38 +00004732 Py_INCREF(&PyDateTime_DeltaType);
4733 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4734
Tim Peters2a799bf2002-12-16 20:18:38 +00004735 Py_INCREF(&PyDateTime_TZInfoType);
4736 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4737
Tim Peters9ddf40b2004-06-20 22:41:32 +00004738 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4739 NULL);
4740 if (x == NULL)
4741 return;
4742 PyModule_AddObject(m, "datetime_CAPI", x);
4743
Tim Peters2a799bf2002-12-16 20:18:38 +00004744 /* A 4-year cycle has an extra leap day over what we'd get from
4745 * pasting together 4 single years.
4746 */
4747 assert(DI4Y == 4 * 365 + 1);
4748 assert(DI4Y == days_before_year(4+1));
4749
4750 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4751 * get from pasting together 4 100-year cycles.
4752 */
4753 assert(DI400Y == 4 * DI100Y + 1);
4754 assert(DI400Y == days_before_year(400+1));
4755
4756 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4757 * pasting together 25 4-year cycles.
4758 */
4759 assert(DI100Y == 25 * DI4Y - 1);
4760 assert(DI100Y == days_before_year(100+1));
4761
4762 us_per_us = PyInt_FromLong(1);
4763 us_per_ms = PyInt_FromLong(1000);
4764 us_per_second = PyInt_FromLong(1000000);
4765 us_per_minute = PyInt_FromLong(60000000);
4766 seconds_per_day = PyInt_FromLong(24 * 3600);
4767 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4768 us_per_minute == NULL || seconds_per_day == NULL)
4769 return;
4770
4771 /* The rest are too big for 32-bit ints, but even
4772 * us_per_week fits in 40 bits, so doubles should be exact.
4773 */
4774 us_per_hour = PyLong_FromDouble(3600000000.0);
4775 us_per_day = PyLong_FromDouble(86400000000.0);
4776 us_per_week = PyLong_FromDouble(604800000000.0);
4777 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4778 return;
4779}
Tim Petersf3615152003-01-01 21:51:37 +00004780
4781/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004782Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004783 x.n = x stripped of its timezone -- its naive time.
4784 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4785 return None
4786 x.d = x.dst(), and assuming that doesn't raise an exception or
4787 return None
4788 x.s = x's standard offset, x.o - x.d
4789
4790Now some derived rules, where k is a duration (timedelta).
4791
47921. x.o = x.s + x.d
4793 This follows from the definition of x.s.
4794
Tim Petersc5dc4da2003-01-02 17:55:03 +000047952. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004796 This is actually a requirement, an assumption we need to make about
4797 sane tzinfo classes.
4798
47993. The naive UTC time corresponding to x is x.n - x.o.
4800 This is again a requirement for a sane tzinfo class.
4801
48024. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004803 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004804
Tim Petersc5dc4da2003-01-02 17:55:03 +000048055. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004806 Again follows from how arithmetic is defined.
4807
Tim Peters8bb5ad22003-01-24 02:44:45 +00004808Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004809(meaning that the various tzinfo methods exist, and don't blow up or return
4810None when called).
4811
Tim Petersa9bc1682003-01-11 03:39:11 +00004812The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004813x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004814
4815By #3, we want
4816
Tim Peters8bb5ad22003-01-24 02:44:45 +00004817 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004818
4819The algorithm starts by attaching tz to x.n, and calling that y. So
4820x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4821becomes true; in effect, we want to solve [2] for k:
4822
Tim Peters8bb5ad22003-01-24 02:44:45 +00004823 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004824
4825By #1, this is the same as
4826
Tim Peters8bb5ad22003-01-24 02:44:45 +00004827 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004828
4829By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4830Substituting that into [3],
4831
Tim Peters8bb5ad22003-01-24 02:44:45 +00004832 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4833 k - (y+k).s - (y+k).d = 0; rearranging,
4834 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4835 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004836
Tim Peters8bb5ad22003-01-24 02:44:45 +00004837On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4838approximate k by ignoring the (y+k).d term at first. Note that k can't be
4839very large, since all offset-returning methods return a duration of magnitude
4840less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4841be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004842
4843In any case, the new value is
4844
Tim Peters8bb5ad22003-01-24 02:44:45 +00004845 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004846
Tim Peters8bb5ad22003-01-24 02:44:45 +00004847It's helpful to step back at look at [4] from a higher level: it's simply
4848mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004849
4850At this point, if
4851
Tim Peters8bb5ad22003-01-24 02:44:45 +00004852 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004853
4854we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004855at the start of daylight time. Picture US Eastern for concreteness. The wall
4856time 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 +00004857sense then. The docs ask that an Eastern tzinfo class consider such a time to
4858be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4859on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004860the only spelling that makes sense on the local wall clock.
4861
Tim Petersc5dc4da2003-01-02 17:55:03 +00004862In fact, if [5] holds at this point, we do have the standard-time spelling,
4863but that takes a bit of proof. We first prove a stronger result. What's the
4864difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004865
Tim Peters8bb5ad22003-01-24 02:44:45 +00004866 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004867
Tim Petersc5dc4da2003-01-02 17:55:03 +00004868Now
4869 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004870 (y + y.s).n = by #5
4871 y.n + y.s = since y.n = x.n
4872 x.n + y.s = since z and y are have the same tzinfo member,
4873 y.s = z.s by #2
4874 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004875
Tim Petersc5dc4da2003-01-02 17:55:03 +00004876Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004877
Tim Petersc5dc4da2003-01-02 17:55:03 +00004878 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004879 x.n - ((x.n + z.s) - z.o) = expanding
4880 x.n - x.n - z.s + z.o = cancelling
4881 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004882 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004883
Tim Petersc5dc4da2003-01-02 17:55:03 +00004884So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004885
Tim Petersc5dc4da2003-01-02 17:55:03 +00004886If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004887spelling we wanted in the endcase described above. We're done. Contrarily,
4888if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004889
Tim Petersc5dc4da2003-01-02 17:55:03 +00004890If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4891add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004892local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004893
Tim Petersc5dc4da2003-01-02 17:55:03 +00004894Let
Tim Petersf3615152003-01-01 21:51:37 +00004895
Tim Peters4fede1a2003-01-04 00:26:59 +00004896 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004897
Tim Peters4fede1a2003-01-04 00:26:59 +00004898and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004899
Tim Peters8bb5ad22003-01-24 02:44:45 +00004900 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004901
Tim Peters8bb5ad22003-01-24 02:44:45 +00004902If so, we're done. If not, the tzinfo class is insane, according to the
4903assumptions we've made. This also requires a bit of proof. As before, let's
4904compute the difference between the LHS and RHS of [8] (and skipping some of
4905the justifications for the kinds of substitutions we've done several times
4906already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004907
Tim Peters8bb5ad22003-01-24 02:44:45 +00004908 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4909 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4910 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4911 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4912 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004913 - z.o + z'.o = #1 twice
4914 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4915 z'.d - z.d
4916
4917So 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 +00004918we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4919return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004920
Tim Peters8bb5ad22003-01-24 02:44:45 +00004921How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4922a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4923would have to change the result dst() returns: we start in DST, and moving
4924a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004925
Tim Peters8bb5ad22003-01-24 02:44:45 +00004926There isn't a sane case where this can happen. The closest it gets is at
4927the end of DST, where there's an hour in UTC with no spelling in a hybrid
4928tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4929that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4930UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4931time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4932clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4933standard time. Since that's what the local clock *does*, we want to map both
4934UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004935in local time, but so it goes -- it's the way the local clock works.
4936
Tim Peters8bb5ad22003-01-24 02:44:45 +00004937When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4938so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4939z' = 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 +00004940(correctly) concludes that z' is not UTC-equivalent to x.
4941
4942Because we know z.d said z was in daylight time (else [5] would have held and
4943we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004944and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004945return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4946but the reasoning doesn't depend on the example -- it depends on there being
4947two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004948z' must be in standard time, and is the spelling we want in this case.
4949
4950Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4951concerned (because it takes z' as being in standard time rather than the
4952daylight time we intend here), but returning it gives the real-life "local
4953clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4954tz.
4955
4956When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4957the 1:MM standard time spelling we want.
4958
4959So how can this break? One of the assumptions must be violated. Two
4960possibilities:
4961
49621) [2] effectively says that y.s is invariant across all y belong to a given
4963 time zone. This isn't true if, for political reasons or continental drift,
4964 a region decides to change its base offset from UTC.
4965
49662) There may be versions of "double daylight" time where the tail end of
4967 the analysis gives up a step too early. I haven't thought about that
4968 enough to say.
4969
4970In any case, it's clear that the default fromutc() is strong enough to handle
4971"almost all" time zones: so long as the standard offset is invariant, it
4972doesn't matter if daylight time transition points change from year to year, or
4973if daylight time is skipped in some years; it doesn't matter how large or
4974small dst() may get within its bounds; and it doesn't even matter if some
4975perverse time zone returns a negative dst()). So a breaking case must be
4976pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004977--------------------------------------------------------------------------- */