blob: 6c2d5a057f629f9a18b5f7450a7acc73b2a0aab3 [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'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000767 Py_TYPE(p)->tp_name);
Tim Peters855fe882002-12-22 03:43:39 +0000768 return -1;
769}
770
Tim Petersbad8ff02002-12-30 20:52:32 +0000771/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000772 * If tzinfo is None, returns None.
773 */
774static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000775call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000776{
777 PyObject *result;
778
Tim Petersbad8ff02002-12-30 20:52:32 +0000779 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
784 }
785 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000787 return result;
788}
789
Tim Peters2a799bf2002-12-16 20:18:38 +0000790/* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
793 */
794static PyObject *
795get_tzinfo_member(PyObject *self)
796{
797 PyObject *tzinfo = NULL;
798
Tim Petersa9bc1682003-01-11 03:39:11 +0000799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000801 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
804 return tzinfo;
805}
806
Tim Petersbad8ff02002-12-30 20:52:32 +0000807/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * Else *none is set to 0 and the integer method result is returned.
814 */
815static int
816call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
818{
819 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000820 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000821
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
825
826 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 if (u == NULL)
829 return -1;
830
Tim Peters27362852002-12-23 16:17:39 +0000831 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 result = 0;
833 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000834 }
Tim Peters855fe882002-12-22 03:43:39 +0000835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
842 */
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000851 }
852 }
853 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000854 else {
855 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000856 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000857 "timedelta, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +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'",
Christian Heimes90aa7642007-12-19 02:45:37 +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 Rossum98297ee2007-11-06 21:34:58 +00001136 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 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;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001161 if (!PyUnicode_Check(Zreplacement)) {
Neal Norwitzaea70e02007-08-12 04:32:26 +00001162 PyErr_SetString(PyExc_TypeError,
1163 "tzname.replace() did not return a string");
1164 goto Error;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001165 }
1166 return Zreplacement;
1167
1168 Error:
1169 Py_DECREF(Zreplacement);
1170 return NULL;
1171}
1172
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001173static PyObject *
1174make_freplacement(PyObject *object)
1175{
Christian Heimesb186d002008-03-18 15:15:01 +00001176 char freplacement[64];
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001177 if (PyTime_Check(object))
1178 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1179 else if (PyDateTime_Check(object))
1180 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1181 else
1182 sprintf(freplacement, "%06d", 0);
1183
Christian Heimes72b710a2008-05-26 13:28:38 +00001184 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001185}
1186
Tim Peters2a799bf2002-12-16 20:18:38 +00001187/* I sure don't want to reproduce the strftime code from the time module,
1188 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001189 * giving special meanings to the %z, %Z and %f format codes via a
1190 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001191 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1192 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001193 */
1194static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001195wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1196 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001197{
1198 PyObject *result = NULL; /* guilty until proved innocent */
1199
1200 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1201 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001202 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001203
Georg Brandlf78e02b2008-06-10 17:40:04 +00001204 const char *pin; /* pointer to next char in input format */
1205 Py_ssize_t flen; /* length of input format */
1206 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001207
1208 PyObject *newfmt = NULL; /* py string, the output format */
1209 char *pnew; /* pointer to available byte in output format */
Georg Brandlf78e02b2008-06-10 17:40:04 +00001210 size_t totalnew; /* number bytes total in output format buffer,
1211 exclusive of trailing \0 */
1212 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001213
Georg Brandlf78e02b2008-06-10 17:40:04 +00001214 const char *ptoappend; /* ptr to string to append to output buffer */
Brett Cannon27da8122007-11-06 23:15:11 +00001215 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001216
Tim Peters2a799bf2002-12-16 20:18:38 +00001217 assert(object && format && timetuple);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001218 assert(PyUnicode_Check(format));
Neal Norwitz908c8712007-08-27 04:58:38 +00001219 /* Convert the input format to a C string and size */
Alexandre Vassalottia85998a2008-05-03 18:24:43 +00001220 pin = PyUnicode_AsStringAndSize(format, &flen);
Neal Norwitz908c8712007-08-27 04:58:38 +00001221 if (!pin)
1222 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001223
Tim Petersd6844152002-12-22 20:58:42 +00001224 /* Give up if the year is before 1900.
1225 * Python strftime() plays games with the year, and different
1226 * games depending on whether envar PYTHON2K is set. This makes
1227 * years before 1900 a nightmare, even if the platform strftime
1228 * supports them (and not all do).
1229 * We could get a lot farther here by avoiding Python's strftime
1230 * wrapper and calling the C strftime() directly, but that isn't
1231 * an option in the Python implementation of this module.
1232 */
1233 {
1234 long year;
1235 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1236 if (pyyear == NULL) return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001237 assert(PyLong_Check(pyyear));
1238 year = PyLong_AsLong(pyyear);
Tim Petersd6844152002-12-22 20:58:42 +00001239 Py_DECREF(pyyear);
1240 if (year < 1900) {
1241 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1242 "1900; the datetime strftime() "
1243 "methods require year >= 1900",
1244 year);
1245 return NULL;
1246 }
1247 }
1248
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001249 /* Scan the input format, looking for %z/%Z/%f escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001250 * a new format. Since computing the replacements for those codes
1251 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001252 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001253 totalnew = flen + 1; /* realistic if no %z/%Z */
Christian Heimes72b710a2008-05-26 13:28:38 +00001254 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
Tim Peters2a799bf2002-12-16 20:18:38 +00001255 if (newfmt == NULL) goto Done;
Christian Heimes72b710a2008-05-26 13:28:38 +00001256 pnew = PyBytes_AsString(newfmt);
Tim Peters2a799bf2002-12-16 20:18:38 +00001257 usednew = 0;
1258
Tim Peters2a799bf2002-12-16 20:18:38 +00001259 while ((ch = *pin++) != '\0') {
1260 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001261 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001262 ntoappend = 1;
1263 }
1264 else if ((ch = *pin++) == '\0') {
1265 /* There's a lone trailing %; doesn't make sense. */
1266 PyErr_SetString(PyExc_ValueError, "strftime format "
1267 "ends with raw %");
1268 goto Done;
1269 }
1270 /* A % has been seen and ch is the character after it. */
1271 else if (ch == 'z') {
1272 if (zreplacement == NULL) {
1273 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001274 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001275 PyObject *tzinfo = get_tzinfo_member(object);
Christian Heimes72b710a2008-05-26 13:28:38 +00001276 zreplacement = PyBytes_FromStringAndSize("", 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001277 if (zreplacement == NULL) goto Done;
1278 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001279 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001280 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001281 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001282 "",
1283 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001284 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001285 goto Done;
1286 Py_DECREF(zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001287 zreplacement =
Christian Heimes72b710a2008-05-26 13:28:38 +00001288 PyBytes_FromStringAndSize(buf,
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001289 strlen(buf));
1290 if (zreplacement == NULL)
1291 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001292 }
1293 }
1294 assert(zreplacement != NULL);
Christian Heimes72b710a2008-05-26 13:28:38 +00001295 ptoappend = PyBytes_AS_STRING(zreplacement);
1296 ntoappend = PyBytes_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001297 }
1298 else if (ch == 'Z') {
1299 /* format tzname */
1300 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001301 Zreplacement = make_Zreplacement(object,
1302 tzinfoarg);
1303 if (Zreplacement == NULL)
1304 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001305 }
1306 assert(Zreplacement != NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001307 assert(PyUnicode_Check(Zreplacement));
1308 ptoappend = PyUnicode_AsStringAndSize(Zreplacement,
1309 &ntoappend);
Christian Heimes90aa7642007-12-19 02:45:37 +00001310 ntoappend = Py_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001311 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001312 else if (ch == 'f') {
1313 /* format microseconds */
1314 if (freplacement == NULL) {
1315 freplacement = make_freplacement(object);
1316 if (freplacement == NULL)
1317 goto Done;
1318 }
1319 assert(freplacement != NULL);
Christian Heimes72b710a2008-05-26 13:28:38 +00001320 assert(PyBytes_Check(freplacement));
1321 ptoappend = PyBytes_AS_STRING(freplacement);
1322 ntoappend = PyBytes_GET_SIZE(freplacement);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001323 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001324 else {
Tim Peters328fff72002-12-20 01:31:27 +00001325 /* percent followed by neither z nor Z */
1326 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001327 ntoappend = 2;
1328 }
1329
1330 /* Append the ntoappend chars starting at ptoappend to
1331 * the new format.
1332 */
Tim Peters2a799bf2002-12-16 20:18:38 +00001333 if (ntoappend == 0)
1334 continue;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001335 assert(ptoappend != NULL);
1336 assert(ntoappend > 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001337 while (usednew + ntoappend > totalnew) {
Georg Brandlf78e02b2008-06-10 17:40:04 +00001338 size_t bigger = totalnew << 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001339 if ((bigger >> 1) != totalnew) { /* overflow */
1340 PyErr_NoMemory();
1341 goto Done;
1342 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001343 if (_PyBytes_Resize(&newfmt, bigger) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001344 goto Done;
1345 totalnew = bigger;
Christian Heimes72b710a2008-05-26 13:28:38 +00001346 pnew = PyBytes_AsString(newfmt) + usednew;
Tim Peters2a799bf2002-12-16 20:18:38 +00001347 }
1348 memcpy(pnew, ptoappend, ntoappend);
1349 pnew += ntoappend;
1350 usednew += ntoappend;
1351 assert(usednew <= totalnew);
1352 } /* end while() */
1353
Christian Heimes72b710a2008-05-26 13:28:38 +00001354 if (_PyBytes_Resize(&newfmt, usednew) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001355 goto Done;
1356 {
Neal Norwitz908c8712007-08-27 04:58:38 +00001357 PyObject *format;
Christian Heimes072c0f12008-01-03 23:01:04 +00001358 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001359 if (time == NULL)
1360 goto Done;
Christian Heimes72b710a2008-05-26 13:28:38 +00001361 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
Neal Norwitz908c8712007-08-27 04:58:38 +00001362 if (format != NULL) {
1363 result = PyObject_CallMethod(time, "strftime", "OO",
1364 format, timetuple);
1365 Py_DECREF(format);
1366 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001367 Py_DECREF(time);
1368 }
1369 Done:
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001370 Py_XDECREF(freplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001371 Py_XDECREF(zreplacement);
1372 Py_XDECREF(Zreplacement);
1373 Py_XDECREF(newfmt);
1374 return result;
1375}
1376
Tim Peters2a799bf2002-12-16 20:18:38 +00001377/* ---------------------------------------------------------------------------
1378 * Wrap functions from the time module. These aren't directly available
1379 * from C. Perhaps they should be.
1380 */
1381
1382/* Call time.time() and return its result (a Python float). */
1383static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001384time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001385{
1386 PyObject *result = NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001387 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001388
1389 if (time != NULL) {
1390 result = PyObject_CallMethod(time, "time", "()");
1391 Py_DECREF(time);
1392 }
1393 return result;
1394}
1395
1396/* Build a time.struct_time. The weekday and day number are automatically
1397 * computed from the y,m,d args.
1398 */
1399static PyObject *
1400build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1401{
1402 PyObject *time;
1403 PyObject *result = NULL;
1404
Christian Heimes072c0f12008-01-03 23:01:04 +00001405 time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001406 if (time != NULL) {
1407 result = PyObject_CallMethod(time, "struct_time",
1408 "((iiiiiiiii))",
1409 y, m, d,
1410 hh, mm, ss,
1411 weekday(y, m, d),
1412 days_before_month(y, m) + d,
1413 dstflag);
1414 Py_DECREF(time);
1415 }
1416 return result;
1417}
1418
1419/* ---------------------------------------------------------------------------
1420 * Miscellaneous helpers.
1421 */
1422
Guido van Rossum19960592006-08-24 17:29:38 +00001423/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001424 * The comparisons here all most naturally compute a cmp()-like result.
1425 * This little helper turns that into a bool result for rich comparisons.
1426 */
1427static PyObject *
1428diff_to_bool(int diff, int op)
1429{
1430 PyObject *result;
1431 int istrue;
1432
1433 switch (op) {
1434 case Py_EQ: istrue = diff == 0; break;
1435 case Py_NE: istrue = diff != 0; break;
1436 case Py_LE: istrue = diff <= 0; break;
1437 case Py_GE: istrue = diff >= 0; break;
1438 case Py_LT: istrue = diff < 0; break;
1439 case Py_GT: istrue = diff > 0; break;
1440 default:
1441 assert(! "op unknown");
1442 istrue = 0; /* To shut up compiler */
1443 }
1444 result = istrue ? Py_True : Py_False;
1445 Py_INCREF(result);
1446 return result;
1447}
1448
Tim Peters07534a62003-02-07 22:50:28 +00001449/* Raises a "can't compare" TypeError and returns NULL. */
1450static PyObject *
1451cmperror(PyObject *a, PyObject *b)
1452{
1453 PyErr_Format(PyExc_TypeError,
1454 "can't compare %s to %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001455 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001456 return NULL;
1457}
1458
Tim Peters2a799bf2002-12-16 20:18:38 +00001459/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001460 * Cached Python objects; these are set by the module init function.
1461 */
1462
1463/* Conversion factors. */
1464static PyObject *us_per_us = NULL; /* 1 */
1465static PyObject *us_per_ms = NULL; /* 1000 */
1466static PyObject *us_per_second = NULL; /* 1000000 */
1467static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1468static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1469static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1470static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1471static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1472
Tim Peters2a799bf2002-12-16 20:18:38 +00001473/* ---------------------------------------------------------------------------
1474 * Class implementations.
1475 */
1476
1477/*
1478 * PyDateTime_Delta implementation.
1479 */
1480
1481/* Convert a timedelta to a number of us,
1482 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1483 * as a Python int or long.
1484 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1485 * due to ubiquitous overflow possibilities.
1486 */
1487static PyObject *
1488delta_to_microseconds(PyDateTime_Delta *self)
1489{
1490 PyObject *x1 = NULL;
1491 PyObject *x2 = NULL;
1492 PyObject *x3 = NULL;
1493 PyObject *result = NULL;
1494
Christian Heimes217cfd12007-12-02 14:31:20 +00001495 x1 = PyLong_FromLong(GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001496 if (x1 == NULL)
1497 goto Done;
1498 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1499 if (x2 == NULL)
1500 goto Done;
1501 Py_DECREF(x1);
1502 x1 = NULL;
1503
1504 /* x2 has days in seconds */
Christian Heimes217cfd12007-12-02 14:31:20 +00001505 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
Tim Peters2a799bf2002-12-16 20:18:38 +00001506 if (x1 == NULL)
1507 goto Done;
1508 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1509 if (x3 == NULL)
1510 goto Done;
1511 Py_DECREF(x1);
1512 Py_DECREF(x2);
1513 x1 = x2 = NULL;
1514
1515 /* x3 has days+seconds in seconds */
1516 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1517 if (x1 == NULL)
1518 goto Done;
1519 Py_DECREF(x3);
1520 x3 = NULL;
1521
1522 /* x1 has days+seconds in us */
Christian Heimes217cfd12007-12-02 14:31:20 +00001523 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001524 if (x2 == NULL)
1525 goto Done;
1526 result = PyNumber_Add(x1, x2);
1527
1528Done:
1529 Py_XDECREF(x1);
1530 Py_XDECREF(x2);
1531 Py_XDECREF(x3);
1532 return result;
1533}
1534
1535/* Convert a number of us (as a Python int or long) to a timedelta.
1536 */
1537static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001538microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001539{
1540 int us;
1541 int s;
1542 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001543 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001544
1545 PyObject *tuple = NULL;
1546 PyObject *num = NULL;
1547 PyObject *result = NULL;
1548
1549 tuple = PyNumber_Divmod(pyus, us_per_second);
1550 if (tuple == NULL)
1551 goto Done;
1552
1553 num = PyTuple_GetItem(tuple, 1); /* us */
1554 if (num == NULL)
1555 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001556 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001557 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001558 if (temp == -1 && PyErr_Occurred())
1559 goto Done;
1560 assert(0 <= temp && temp < 1000000);
1561 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001562 if (us < 0) {
1563 /* The divisor was positive, so this must be an error. */
1564 assert(PyErr_Occurred());
1565 goto Done;
1566 }
1567
1568 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1569 if (num == NULL)
1570 goto Done;
1571 Py_INCREF(num);
1572 Py_DECREF(tuple);
1573
1574 tuple = PyNumber_Divmod(num, seconds_per_day);
1575 if (tuple == NULL)
1576 goto Done;
1577 Py_DECREF(num);
1578
1579 num = PyTuple_GetItem(tuple, 1); /* seconds */
1580 if (num == NULL)
1581 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001582 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001583 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001584 if (temp == -1 && PyErr_Occurred())
1585 goto Done;
1586 assert(0 <= temp && temp < 24*3600);
1587 s = (int)temp;
1588
Tim Peters2a799bf2002-12-16 20:18:38 +00001589 if (s < 0) {
1590 /* The divisor was positive, so this must be an error. */
1591 assert(PyErr_Occurred());
1592 goto Done;
1593 }
1594
1595 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1596 if (num == NULL)
1597 goto Done;
1598 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001599 temp = PyLong_AsLong(num);
1600 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001601 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001602 d = (int)temp;
1603 if ((long)d != temp) {
1604 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1605 "large to fit in a C int");
1606 goto Done;
1607 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001608 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001609
1610Done:
1611 Py_XDECREF(tuple);
1612 Py_XDECREF(num);
1613 return result;
1614}
1615
Tim Petersb0c854d2003-05-17 15:57:00 +00001616#define microseconds_to_delta(pymicros) \
1617 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1618
Tim Peters2a799bf2002-12-16 20:18:38 +00001619static PyObject *
1620multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
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_Multiply(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 *
1641divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1642{
1643 PyObject *pyus_in;
1644 PyObject *pyus_out;
1645 PyObject *result;
1646
1647 pyus_in = delta_to_microseconds(delta);
1648 if (pyus_in == NULL)
1649 return NULL;
1650
1651 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1652 Py_DECREF(pyus_in);
1653 if (pyus_out == NULL)
1654 return NULL;
1655
1656 result = microseconds_to_delta(pyus_out);
1657 Py_DECREF(pyus_out);
1658 return result;
1659}
1660
1661static PyObject *
1662delta_add(PyObject *left, PyObject *right)
1663{
1664 PyObject *result = Py_NotImplemented;
1665
1666 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1667 /* delta + delta */
1668 /* The C-level additions can't overflow because of the
1669 * invariant bounds.
1670 */
1671 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1672 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1673 int microseconds = GET_TD_MICROSECONDS(left) +
1674 GET_TD_MICROSECONDS(right);
1675 result = new_delta(days, seconds, microseconds, 1);
1676 }
1677
1678 if (result == Py_NotImplemented)
1679 Py_INCREF(result);
1680 return result;
1681}
1682
1683static PyObject *
1684delta_negative(PyDateTime_Delta *self)
1685{
1686 return new_delta(-GET_TD_DAYS(self),
1687 -GET_TD_SECONDS(self),
1688 -GET_TD_MICROSECONDS(self),
1689 1);
1690}
1691
1692static PyObject *
1693delta_positive(PyDateTime_Delta *self)
1694{
1695 /* Could optimize this (by returning self) if this isn't a
1696 * subclass -- but who uses unary + ? Approximately nobody.
1697 */
1698 return new_delta(GET_TD_DAYS(self),
1699 GET_TD_SECONDS(self),
1700 GET_TD_MICROSECONDS(self),
1701 0);
1702}
1703
1704static PyObject *
1705delta_abs(PyDateTime_Delta *self)
1706{
1707 PyObject *result;
1708
1709 assert(GET_TD_MICROSECONDS(self) >= 0);
1710 assert(GET_TD_SECONDS(self) >= 0);
1711
1712 if (GET_TD_DAYS(self) < 0)
1713 result = delta_negative(self);
1714 else
1715 result = delta_positive(self);
1716
1717 return result;
1718}
1719
1720static PyObject *
1721delta_subtract(PyObject *left, PyObject *right)
1722{
1723 PyObject *result = Py_NotImplemented;
1724
1725 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1726 /* delta - delta */
1727 PyObject *minus_right = PyNumber_Negative(right);
1728 if (minus_right) {
1729 result = delta_add(left, minus_right);
1730 Py_DECREF(minus_right);
1731 }
1732 else
1733 result = NULL;
1734 }
1735
1736 if (result == Py_NotImplemented)
1737 Py_INCREF(result);
1738 return result;
1739}
1740
Tim Peters2a799bf2002-12-16 20:18:38 +00001741static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001742delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001743{
Tim Petersaa7d8492003-02-08 03:28:59 +00001744 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001745 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001746 if (diff == 0) {
1747 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1748 if (diff == 0)
1749 diff = GET_TD_MICROSECONDS(self) -
1750 GET_TD_MICROSECONDS(other);
1751 }
Guido van Rossum19960592006-08-24 17:29:38 +00001752 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001753 }
Guido van Rossum19960592006-08-24 17:29:38 +00001754 else {
1755 Py_INCREF(Py_NotImplemented);
1756 return Py_NotImplemented;
1757 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001758}
1759
1760static PyObject *delta_getstate(PyDateTime_Delta *self);
1761
1762static long
1763delta_hash(PyDateTime_Delta *self)
1764{
1765 if (self->hashcode == -1) {
1766 PyObject *temp = delta_getstate(self);
1767 if (temp != NULL) {
1768 self->hashcode = PyObject_Hash(temp);
1769 Py_DECREF(temp);
1770 }
1771 }
1772 return self->hashcode;
1773}
1774
1775static PyObject *
1776delta_multiply(PyObject *left, PyObject *right)
1777{
1778 PyObject *result = Py_NotImplemented;
1779
1780 if (PyDelta_Check(left)) {
1781 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001782 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001783 result = multiply_int_timedelta(right,
1784 (PyDateTime_Delta *) left);
1785 }
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001786 else if (PyLong_Check(left))
Tim Peters2a799bf2002-12-16 20:18:38 +00001787 result = multiply_int_timedelta(left,
1788 (PyDateTime_Delta *) right);
1789
1790 if (result == Py_NotImplemented)
1791 Py_INCREF(result);
1792 return result;
1793}
1794
1795static PyObject *
1796delta_divide(PyObject *left, PyObject *right)
1797{
1798 PyObject *result = Py_NotImplemented;
1799
1800 if (PyDelta_Check(left)) {
1801 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001802 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001803 result = divide_timedelta_int(
1804 (PyDateTime_Delta *)left,
1805 right);
1806 }
1807
1808 if (result == Py_NotImplemented)
1809 Py_INCREF(result);
1810 return result;
1811}
1812
1813/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1814 * timedelta constructor. sofar is the # of microseconds accounted for
1815 * so far, and there are factor microseconds per current unit, the number
1816 * of which is given by num. num * factor is added to sofar in a
1817 * numerically careful way, and that's the result. Any fractional
1818 * microseconds left over (this can happen if num is a float type) are
1819 * added into *leftover.
1820 * Note that there are many ways this can give an error (NULL) return.
1821 */
1822static PyObject *
1823accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1824 double *leftover)
1825{
1826 PyObject *prod;
1827 PyObject *sum;
1828
1829 assert(num != NULL);
1830
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001831 if (PyLong_Check(num)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00001832 prod = PyNumber_Multiply(num, factor);
1833 if (prod == NULL)
1834 return NULL;
1835 sum = PyNumber_Add(sofar, prod);
1836 Py_DECREF(prod);
1837 return sum;
1838 }
1839
1840 if (PyFloat_Check(num)) {
1841 double dnum;
1842 double fracpart;
1843 double intpart;
1844 PyObject *x;
1845 PyObject *y;
1846
1847 /* The Plan: decompose num into an integer part and a
1848 * fractional part, num = intpart + fracpart.
1849 * Then num * factor ==
1850 * intpart * factor + fracpart * factor
1851 * and the LHS can be computed exactly in long arithmetic.
1852 * The RHS is again broken into an int part and frac part.
1853 * and the frac part is added into *leftover.
1854 */
1855 dnum = PyFloat_AsDouble(num);
1856 if (dnum == -1.0 && PyErr_Occurred())
1857 return NULL;
1858 fracpart = modf(dnum, &intpart);
1859 x = PyLong_FromDouble(intpart);
1860 if (x == NULL)
1861 return NULL;
1862
1863 prod = PyNumber_Multiply(x, factor);
1864 Py_DECREF(x);
1865 if (prod == NULL)
1866 return NULL;
1867
1868 sum = PyNumber_Add(sofar, prod);
1869 Py_DECREF(prod);
1870 if (sum == NULL)
1871 return NULL;
1872
1873 if (fracpart == 0.0)
1874 return sum;
1875 /* So far we've lost no information. Dealing with the
1876 * fractional part requires float arithmetic, and may
1877 * lose a little info.
1878 */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001879 assert(PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001880 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001881
1882 dnum *= fracpart;
1883 fracpart = modf(dnum, &intpart);
1884 x = PyLong_FromDouble(intpart);
1885 if (x == NULL) {
1886 Py_DECREF(sum);
1887 return NULL;
1888 }
1889
1890 y = PyNumber_Add(sum, x);
1891 Py_DECREF(sum);
1892 Py_DECREF(x);
1893 *leftover += fracpart;
1894 return y;
1895 }
1896
1897 PyErr_Format(PyExc_TypeError,
1898 "unsupported type for timedelta %s component: %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001899 tag, Py_TYPE(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001900 return NULL;
1901}
1902
1903static PyObject *
1904delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1905{
1906 PyObject *self = NULL;
1907
1908 /* Argument objects. */
1909 PyObject *day = NULL;
1910 PyObject *second = NULL;
1911 PyObject *us = NULL;
1912 PyObject *ms = NULL;
1913 PyObject *minute = NULL;
1914 PyObject *hour = NULL;
1915 PyObject *week = NULL;
1916
1917 PyObject *x = NULL; /* running sum of microseconds */
1918 PyObject *y = NULL; /* temp sum of microseconds */
1919 double leftover_us = 0.0;
1920
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001921 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001922 "days", "seconds", "microseconds", "milliseconds",
1923 "minutes", "hours", "weeks", NULL
1924 };
1925
1926 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1927 keywords,
1928 &day, &second, &us,
1929 &ms, &minute, &hour, &week) == 0)
1930 goto Done;
1931
Christian Heimes217cfd12007-12-02 14:31:20 +00001932 x = PyLong_FromLong(0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001933 if (x == NULL)
1934 goto Done;
1935
1936#define CLEANUP \
1937 Py_DECREF(x); \
1938 x = y; \
1939 if (x == NULL) \
1940 goto Done
1941
1942 if (us) {
1943 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1944 CLEANUP;
1945 }
1946 if (ms) {
1947 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1948 CLEANUP;
1949 }
1950 if (second) {
1951 y = accum("seconds", x, second, us_per_second, &leftover_us);
1952 CLEANUP;
1953 }
1954 if (minute) {
1955 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1956 CLEANUP;
1957 }
1958 if (hour) {
1959 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1960 CLEANUP;
1961 }
1962 if (day) {
1963 y = accum("days", x, day, us_per_day, &leftover_us);
1964 CLEANUP;
1965 }
1966 if (week) {
1967 y = accum("weeks", x, week, us_per_week, &leftover_us);
1968 CLEANUP;
1969 }
1970 if (leftover_us) {
1971 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001972 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001973 if (temp == NULL) {
1974 Py_DECREF(x);
1975 goto Done;
1976 }
1977 y = PyNumber_Add(x, temp);
1978 Py_DECREF(temp);
1979 CLEANUP;
1980 }
1981
Tim Petersb0c854d2003-05-17 15:57:00 +00001982 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001983 Py_DECREF(x);
1984Done:
1985 return self;
1986
1987#undef CLEANUP
1988}
1989
1990static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001991delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001992{
1993 return (GET_TD_DAYS(self) != 0
1994 || GET_TD_SECONDS(self) != 0
1995 || GET_TD_MICROSECONDS(self) != 0);
1996}
1997
1998static PyObject *
1999delta_repr(PyDateTime_Delta *self)
2000{
2001 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00002002 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002003 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002004 GET_TD_DAYS(self),
2005 GET_TD_SECONDS(self),
2006 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002007 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00002008 return PyUnicode_FromFormat("%s(%d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002009 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002010 GET_TD_DAYS(self),
2011 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002012
Walter Dörwald1ab83302007-05-18 17:15:44 +00002013 return PyUnicode_FromFormat("%s(%d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002014 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002015 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002016}
2017
2018static PyObject *
2019delta_str(PyDateTime_Delta *self)
2020{
Tim Peters2a799bf2002-12-16 20:18:38 +00002021 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002022 int seconds = GET_TD_SECONDS(self);
2023 int minutes = divmod(seconds, 60, &seconds);
2024 int hours = divmod(minutes, 60, &minutes);
2025 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002026
2027 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002028 if (us)
2029 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2030 days, (days == 1 || days == -1) ? "" : "s",
2031 hours, minutes, seconds, us);
2032 else
2033 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2034 days, (days == 1 || days == -1) ? "" : "s",
2035 hours, minutes, seconds);
2036 } else {
2037 if (us)
2038 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2039 hours, minutes, seconds, us);
2040 else
2041 return PyUnicode_FromFormat("%d:%02d:%02d",
2042 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002043 }
2044
Tim Peters2a799bf2002-12-16 20:18:38 +00002045}
2046
Tim Peters371935f2003-02-01 01:52:50 +00002047/* Pickle support, a simple use of __reduce__. */
2048
Tim Petersb57f8f02003-02-01 02:54:15 +00002049/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002050static PyObject *
2051delta_getstate(PyDateTime_Delta *self)
2052{
2053 return Py_BuildValue("iii", GET_TD_DAYS(self),
2054 GET_TD_SECONDS(self),
2055 GET_TD_MICROSECONDS(self));
2056}
2057
Tim Peters2a799bf2002-12-16 20:18:38 +00002058static PyObject *
2059delta_reduce(PyDateTime_Delta* self)
2060{
Christian Heimes90aa7642007-12-19 02:45:37 +00002061 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002062}
2063
2064#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2065
2066static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002067
Neal Norwitzdfb80862002-12-19 02:30:56 +00002068 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002069 PyDoc_STR("Number of days.")},
2070
Neal Norwitzdfb80862002-12-19 02:30:56 +00002071 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002072 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2073
Neal Norwitzdfb80862002-12-19 02:30:56 +00002074 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002075 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2076 {NULL}
2077};
2078
2079static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002080 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2081 PyDoc_STR("__reduce__() -> (cls, state)")},
2082
Tim Peters2a799bf2002-12-16 20:18:38 +00002083 {NULL, NULL},
2084};
2085
2086static char delta_doc[] =
2087PyDoc_STR("Difference between two datetime values.");
2088
2089static PyNumberMethods delta_as_number = {
2090 delta_add, /* nb_add */
2091 delta_subtract, /* nb_subtract */
2092 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002093 0, /* nb_remainder */
2094 0, /* nb_divmod */
2095 0, /* nb_power */
2096 (unaryfunc)delta_negative, /* nb_negative */
2097 (unaryfunc)delta_positive, /* nb_positive */
2098 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002099 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002100 0, /*nb_invert*/
2101 0, /*nb_lshift*/
2102 0, /*nb_rshift*/
2103 0, /*nb_and*/
2104 0, /*nb_xor*/
2105 0, /*nb_or*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002106 0, /*nb_int*/
2107 0, /*nb_long*/
2108 0, /*nb_float*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002109 0, /*nb_inplace_add*/
2110 0, /*nb_inplace_subtract*/
2111 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002112 0, /*nb_inplace_remainder*/
2113 0, /*nb_inplace_power*/
2114 0, /*nb_inplace_lshift*/
2115 0, /*nb_inplace_rshift*/
2116 0, /*nb_inplace_and*/
2117 0, /*nb_inplace_xor*/
2118 0, /*nb_inplace_or*/
2119 delta_divide, /* nb_floor_divide */
2120 0, /* nb_true_divide */
2121 0, /* nb_inplace_floor_divide */
2122 0, /* nb_inplace_true_divide */
2123};
2124
2125static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002126 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002127 "datetime.timedelta", /* tp_name */
2128 sizeof(PyDateTime_Delta), /* tp_basicsize */
2129 0, /* tp_itemsize */
2130 0, /* tp_dealloc */
2131 0, /* tp_print */
2132 0, /* tp_getattr */
2133 0, /* tp_setattr */
2134 0, /* tp_compare */
2135 (reprfunc)delta_repr, /* tp_repr */
2136 &delta_as_number, /* tp_as_number */
2137 0, /* tp_as_sequence */
2138 0, /* tp_as_mapping */
2139 (hashfunc)delta_hash, /* tp_hash */
2140 0, /* tp_call */
2141 (reprfunc)delta_str, /* tp_str */
2142 PyObject_GenericGetAttr, /* tp_getattro */
2143 0, /* tp_setattro */
2144 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002145 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002146 delta_doc, /* tp_doc */
2147 0, /* tp_traverse */
2148 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002149 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002150 0, /* tp_weaklistoffset */
2151 0, /* tp_iter */
2152 0, /* tp_iternext */
2153 delta_methods, /* tp_methods */
2154 delta_members, /* tp_members */
2155 0, /* tp_getset */
2156 0, /* tp_base */
2157 0, /* tp_dict */
2158 0, /* tp_descr_get */
2159 0, /* tp_descr_set */
2160 0, /* tp_dictoffset */
2161 0, /* tp_init */
2162 0, /* tp_alloc */
2163 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002164 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002165};
2166
2167/*
2168 * PyDateTime_Date implementation.
2169 */
2170
2171/* Accessor properties. */
2172
2173static PyObject *
2174date_year(PyDateTime_Date *self, void *unused)
2175{
Christian Heimes217cfd12007-12-02 14:31:20 +00002176 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002177}
2178
2179static PyObject *
2180date_month(PyDateTime_Date *self, void *unused)
2181{
Christian Heimes217cfd12007-12-02 14:31:20 +00002182 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002183}
2184
2185static PyObject *
2186date_day(PyDateTime_Date *self, void *unused)
2187{
Christian Heimes217cfd12007-12-02 14:31:20 +00002188 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002189}
2190
2191static PyGetSetDef date_getset[] = {
2192 {"year", (getter)date_year},
2193 {"month", (getter)date_month},
2194 {"day", (getter)date_day},
2195 {NULL}
2196};
2197
2198/* Constructors. */
2199
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002200static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002201
Tim Peters2a799bf2002-12-16 20:18:38 +00002202static PyObject *
2203date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2204{
2205 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002206 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002207 int year;
2208 int month;
2209 int day;
2210
Guido van Rossum177e41a2003-01-30 22:06:23 +00002211 /* Check for invocation from pickle with __getstate__ state */
2212 if (PyTuple_GET_SIZE(args) == 1 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00002213 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2214 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2215 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002216 {
Tim Peters70533e22003-02-01 04:40:04 +00002217 PyDateTime_Date *me;
2218
Tim Peters604c0132004-06-07 23:04:33 +00002219 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002220 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00002221 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002222 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2223 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002224 }
Tim Peters70533e22003-02-01 04:40:04 +00002225 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002226 }
2227
Tim Peters12bf3392002-12-24 05:41:27 +00002228 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002229 &year, &month, &day)) {
2230 if (check_date_args(year, month, day) < 0)
2231 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002232 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002233 }
2234 return self;
2235}
2236
2237/* Return new date from localtime(t). */
2238static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002239date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002240{
2241 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002242 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002243 PyObject *result = NULL;
2244
Tim Peters1b6f7a92004-06-20 02:50:16 +00002245 t = _PyTime_DoubleToTimet(ts);
2246 if (t == (time_t)-1 && PyErr_Occurred())
2247 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002248 tm = localtime(&t);
2249 if (tm)
2250 result = PyObject_CallFunction(cls, "iii",
2251 tm->tm_year + 1900,
2252 tm->tm_mon + 1,
2253 tm->tm_mday);
2254 else
2255 PyErr_SetString(PyExc_ValueError,
2256 "timestamp out of range for "
2257 "platform localtime() function");
2258 return result;
2259}
2260
2261/* Return new date from current time.
2262 * We say this is equivalent to fromtimestamp(time.time()), and the
2263 * only way to be sure of that is to *call* time.time(). That's not
2264 * generally the same as calling C's time.
2265 */
2266static PyObject *
2267date_today(PyObject *cls, PyObject *dummy)
2268{
2269 PyObject *time;
2270 PyObject *result;
2271
2272 time = time_time();
2273 if (time == NULL)
2274 return NULL;
2275
2276 /* Note well: today() is a class method, so this may not call
2277 * date.fromtimestamp. For example, it may call
2278 * datetime.fromtimestamp. That's why we need all the accuracy
2279 * time.time() delivers; if someone were gonzo about optimization,
2280 * date.today() could get away with plain C time().
2281 */
2282 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2283 Py_DECREF(time);
2284 return result;
2285}
2286
2287/* Return new date from given timestamp (Python timestamp -- a double). */
2288static PyObject *
2289date_fromtimestamp(PyObject *cls, PyObject *args)
2290{
2291 double timestamp;
2292 PyObject *result = NULL;
2293
2294 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002295 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002296 return result;
2297}
2298
2299/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2300 * the ordinal is out of range.
2301 */
2302static PyObject *
2303date_fromordinal(PyObject *cls, PyObject *args)
2304{
2305 PyObject *result = NULL;
2306 int ordinal;
2307
2308 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2309 int year;
2310 int month;
2311 int day;
2312
2313 if (ordinal < 1)
2314 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2315 ">= 1");
2316 else {
2317 ord_to_ymd(ordinal, &year, &month, &day);
2318 result = PyObject_CallFunction(cls, "iii",
2319 year, month, day);
2320 }
2321 }
2322 return result;
2323}
2324
2325/*
2326 * Date arithmetic.
2327 */
2328
2329/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2330 * instead.
2331 */
2332static PyObject *
2333add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2334{
2335 PyObject *result = NULL;
2336 int year = GET_YEAR(date);
2337 int month = GET_MONTH(date);
2338 int deltadays = GET_TD_DAYS(delta);
2339 /* C-level overflow is impossible because |deltadays| < 1e9. */
2340 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2341
2342 if (normalize_date(&year, &month, &day) >= 0)
2343 result = new_date(year, month, day);
2344 return result;
2345}
2346
2347static PyObject *
2348date_add(PyObject *left, PyObject *right)
2349{
2350 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2351 Py_INCREF(Py_NotImplemented);
2352 return Py_NotImplemented;
2353 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002354 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002355 /* date + ??? */
2356 if (PyDelta_Check(right))
2357 /* date + delta */
2358 return add_date_timedelta((PyDateTime_Date *) left,
2359 (PyDateTime_Delta *) right,
2360 0);
2361 }
2362 else {
2363 /* ??? + date
2364 * 'right' must be one of us, or we wouldn't have been called
2365 */
2366 if (PyDelta_Check(left))
2367 /* delta + date */
2368 return add_date_timedelta((PyDateTime_Date *) right,
2369 (PyDateTime_Delta *) left,
2370 0);
2371 }
2372 Py_INCREF(Py_NotImplemented);
2373 return Py_NotImplemented;
2374}
2375
2376static PyObject *
2377date_subtract(PyObject *left, PyObject *right)
2378{
2379 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2380 Py_INCREF(Py_NotImplemented);
2381 return Py_NotImplemented;
2382 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002383 if (PyDate_Check(left)) {
2384 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002385 /* date - date */
2386 int left_ord = ymd_to_ord(GET_YEAR(left),
2387 GET_MONTH(left),
2388 GET_DAY(left));
2389 int right_ord = ymd_to_ord(GET_YEAR(right),
2390 GET_MONTH(right),
2391 GET_DAY(right));
2392 return new_delta(left_ord - right_ord, 0, 0, 0);
2393 }
2394 if (PyDelta_Check(right)) {
2395 /* date - delta */
2396 return add_date_timedelta((PyDateTime_Date *) left,
2397 (PyDateTime_Delta *) right,
2398 1);
2399 }
2400 }
2401 Py_INCREF(Py_NotImplemented);
2402 return Py_NotImplemented;
2403}
2404
2405
2406/* Various ways to turn a date into a string. */
2407
2408static PyObject *
2409date_repr(PyDateTime_Date *self)
2410{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002411 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002412 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002413 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002414}
2415
2416static PyObject *
2417date_isoformat(PyDateTime_Date *self)
2418{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002419 return PyUnicode_FromFormat("%04d-%02d-%02d",
2420 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002421}
2422
Tim Peterse2df5ff2003-05-02 18:39:55 +00002423/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002424static PyObject *
2425date_str(PyDateTime_Date *self)
2426{
2427 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2428}
2429
2430
2431static PyObject *
2432date_ctime(PyDateTime_Date *self)
2433{
2434 return format_ctime(self, 0, 0, 0);
2435}
2436
2437static PyObject *
2438date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2439{
2440 /* This method can be inherited, and needs to call the
2441 * timetuple() method appropriate to self's class.
2442 */
2443 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002444 PyObject *tuple;
Georg Brandlf78e02b2008-06-10 17:40:04 +00002445 PyObject *format;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002446 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002447
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002448 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00002449 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002450 return NULL;
2451
2452 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2453 if (tuple == NULL)
2454 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002455 result = wrap_strftime((PyObject *)self, format, tuple,
2456 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002457 Py_DECREF(tuple);
2458 return result;
2459}
2460
Eric Smith1ba31142007-09-11 18:06:02 +00002461static PyObject *
2462date_format(PyDateTime_Date *self, PyObject *args)
2463{
2464 PyObject *format;
2465
2466 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2467 return NULL;
2468
2469 /* if the format is zero length, return str(self) */
2470 if (PyUnicode_GetSize(format) == 0)
Thomas Heller519a0422007-11-15 20:48:54 +00002471 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002472
2473 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
2474}
2475
Tim Peters2a799bf2002-12-16 20:18:38 +00002476/* ISO methods. */
2477
2478static PyObject *
2479date_isoweekday(PyDateTime_Date *self)
2480{
2481 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2482
Christian Heimes217cfd12007-12-02 14:31:20 +00002483 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002484}
2485
2486static PyObject *
2487date_isocalendar(PyDateTime_Date *self)
2488{
2489 int year = GET_YEAR(self);
2490 int week1_monday = iso_week1_monday(year);
2491 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2492 int week;
2493 int day;
2494
2495 week = divmod(today - week1_monday, 7, &day);
2496 if (week < 0) {
2497 --year;
2498 week1_monday = iso_week1_monday(year);
2499 week = divmod(today - week1_monday, 7, &day);
2500 }
2501 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2502 ++year;
2503 week = 0;
2504 }
2505 return Py_BuildValue("iii", year, week + 1, day + 1);
2506}
2507
2508/* Miscellaneous methods. */
2509
Tim Peters2a799bf2002-12-16 20:18:38 +00002510static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002511date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002512{
Guido van Rossum19960592006-08-24 17:29:38 +00002513 if (PyDate_Check(other)) {
2514 int diff = memcmp(((PyDateTime_Date *)self)->data,
2515 ((PyDateTime_Date *)other)->data,
2516 _PyDateTime_DATE_DATASIZE);
2517 return diff_to_bool(diff, op);
2518 }
2519 else {
Tim Peters07534a62003-02-07 22:50:28 +00002520 Py_INCREF(Py_NotImplemented);
2521 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002522 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002523}
2524
2525static PyObject *
2526date_timetuple(PyDateTime_Date *self)
2527{
2528 return build_struct_time(GET_YEAR(self),
2529 GET_MONTH(self),
2530 GET_DAY(self),
2531 0, 0, 0, -1);
2532}
2533
Tim Peters12bf3392002-12-24 05:41:27 +00002534static PyObject *
2535date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2536{
2537 PyObject *clone;
2538 PyObject *tuple;
2539 int year = GET_YEAR(self);
2540 int month = GET_MONTH(self);
2541 int day = GET_DAY(self);
2542
2543 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2544 &year, &month, &day))
2545 return NULL;
2546 tuple = Py_BuildValue("iii", year, month, day);
2547 if (tuple == NULL)
2548 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002549 clone = date_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002550 Py_DECREF(tuple);
2551 return clone;
2552}
2553
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002554/*
2555 Borrowed from stringobject.c, originally it was string_hash()
2556*/
2557static long
2558generic_hash(unsigned char *data, int len)
2559{
2560 register unsigned char *p;
2561 register long x;
2562
2563 p = (unsigned char *) data;
2564 x = *p << 7;
2565 while (--len >= 0)
2566 x = (1000003*x) ^ *p++;
2567 x ^= len;
2568 if (x == -1)
2569 x = -2;
2570
2571 return x;
2572}
2573
2574
2575static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002576
2577static long
2578date_hash(PyDateTime_Date *self)
2579{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002580 if (self->hashcode == -1)
2581 self->hashcode = generic_hash(
2582 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002583
Tim Peters2a799bf2002-12-16 20:18:38 +00002584 return self->hashcode;
2585}
2586
2587static PyObject *
2588date_toordinal(PyDateTime_Date *self)
2589{
Christian Heimes217cfd12007-12-02 14:31:20 +00002590 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
Tim Peters2a799bf2002-12-16 20:18:38 +00002591 GET_DAY(self)));
2592}
2593
2594static PyObject *
2595date_weekday(PyDateTime_Date *self)
2596{
2597 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2598
Christian Heimes217cfd12007-12-02 14:31:20 +00002599 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002600}
2601
Tim Peters371935f2003-02-01 01:52:50 +00002602/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002603
Tim Petersb57f8f02003-02-01 02:54:15 +00002604/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002605static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002606date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002607{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002608 PyObject* field;
Christian Heimes72b710a2008-05-26 13:28:38 +00002609 field = PyBytes_FromStringAndSize((char*)self->data,
Guido van Rossum254348e2007-11-21 19:29:53 +00002610 _PyDateTime_DATE_DATASIZE);
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002611 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002612}
2613
2614static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002615date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002616{
Christian Heimes90aa7642007-12-19 02:45:37 +00002617 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002618}
2619
2620static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002621
Tim Peters2a799bf2002-12-16 20:18:38 +00002622 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002623
Tim Peters2a799bf2002-12-16 20:18:38 +00002624 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2625 METH_CLASS,
2626 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2627 "time.time()).")},
2628
2629 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2630 METH_CLASS,
2631 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2632 "ordinal.")},
2633
2634 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2635 PyDoc_STR("Current date or datetime: same as "
2636 "self.__class__.fromtimestamp(time.time()).")},
2637
2638 /* Instance methods: */
2639
2640 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2641 PyDoc_STR("Return ctime() style string.")},
2642
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002643 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002644 PyDoc_STR("format -> strftime() style string.")},
2645
Eric Smith1ba31142007-09-11 18:06:02 +00002646 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2647 PyDoc_STR("Formats self with strftime.")},
2648
Tim Peters2a799bf2002-12-16 20:18:38 +00002649 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2650 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2651
2652 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2653 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2654 "weekday.")},
2655
2656 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2657 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2658
2659 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2660 PyDoc_STR("Return the day of the week represented by the date.\n"
2661 "Monday == 1 ... Sunday == 7")},
2662
2663 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2664 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2665 "1 is day 1.")},
2666
2667 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2668 PyDoc_STR("Return the day of the week represented by the date.\n"
2669 "Monday == 0 ... Sunday == 6")},
2670
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002671 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002672 PyDoc_STR("Return date with new specified fields.")},
2673
Guido van Rossum177e41a2003-01-30 22:06:23 +00002674 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2675 PyDoc_STR("__reduce__() -> (cls, state)")},
2676
Tim Peters2a799bf2002-12-16 20:18:38 +00002677 {NULL, NULL}
2678};
2679
2680static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002681PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002682
2683static PyNumberMethods date_as_number = {
2684 date_add, /* nb_add */
2685 date_subtract, /* nb_subtract */
2686 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002687 0, /* nb_remainder */
2688 0, /* nb_divmod */
2689 0, /* nb_power */
2690 0, /* nb_negative */
2691 0, /* nb_positive */
2692 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002693 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002694};
2695
2696static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002697 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002698 "datetime.date", /* tp_name */
2699 sizeof(PyDateTime_Date), /* tp_basicsize */
2700 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002701 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002702 0, /* tp_print */
2703 0, /* tp_getattr */
2704 0, /* tp_setattr */
2705 0, /* tp_compare */
2706 (reprfunc)date_repr, /* tp_repr */
2707 &date_as_number, /* tp_as_number */
2708 0, /* tp_as_sequence */
2709 0, /* tp_as_mapping */
2710 (hashfunc)date_hash, /* tp_hash */
2711 0, /* tp_call */
2712 (reprfunc)date_str, /* tp_str */
2713 PyObject_GenericGetAttr, /* tp_getattro */
2714 0, /* tp_setattro */
2715 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002716 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002717 date_doc, /* tp_doc */
2718 0, /* tp_traverse */
2719 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002720 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002721 0, /* tp_weaklistoffset */
2722 0, /* tp_iter */
2723 0, /* tp_iternext */
2724 date_methods, /* tp_methods */
2725 0, /* tp_members */
2726 date_getset, /* tp_getset */
2727 0, /* tp_base */
2728 0, /* tp_dict */
2729 0, /* tp_descr_get */
2730 0, /* tp_descr_set */
2731 0, /* tp_dictoffset */
2732 0, /* tp_init */
2733 0, /* tp_alloc */
2734 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002735 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002736};
2737
2738/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002739 * PyDateTime_TZInfo implementation.
2740 */
2741
2742/* This is a pure abstract base class, so doesn't do anything beyond
2743 * raising NotImplemented exceptions. Real tzinfo classes need
2744 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002745 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002746 * be subclasses of this tzinfo class, which is easy and quick to check).
2747 *
2748 * Note: For reasons having to do with pickling of subclasses, we have
2749 * to allow tzinfo objects to be instantiated. This wasn't an issue
2750 * in the Python implementation (__init__() could raise NotImplementedError
2751 * there without ill effect), but doing so in the C implementation hit a
2752 * brick wall.
2753 */
2754
2755static PyObject *
2756tzinfo_nogo(const char* methodname)
2757{
2758 PyErr_Format(PyExc_NotImplementedError,
2759 "a tzinfo subclass must implement %s()",
2760 methodname);
2761 return NULL;
2762}
2763
2764/* Methods. A subclass must implement these. */
2765
Tim Peters52dcce22003-01-23 16:36:11 +00002766static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002767tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2768{
2769 return tzinfo_nogo("tzname");
2770}
2771
Tim Peters52dcce22003-01-23 16:36:11 +00002772static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002773tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2774{
2775 return tzinfo_nogo("utcoffset");
2776}
2777
Tim Peters52dcce22003-01-23 16:36:11 +00002778static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002779tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2780{
2781 return tzinfo_nogo("dst");
2782}
2783
Tim Peters52dcce22003-01-23 16:36:11 +00002784static PyObject *
2785tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2786{
2787 int y, m, d, hh, mm, ss, us;
2788
2789 PyObject *result;
2790 int off, dst;
2791 int none;
2792 int delta;
2793
2794 if (! PyDateTime_Check(dt)) {
2795 PyErr_SetString(PyExc_TypeError,
2796 "fromutc: argument must be a datetime");
2797 return NULL;
2798 }
2799 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2800 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2801 "is not self");
2802 return NULL;
2803 }
2804
2805 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2806 if (off == -1 && PyErr_Occurred())
2807 return NULL;
2808 if (none) {
2809 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2810 "utcoffset() result required");
2811 return NULL;
2812 }
2813
2814 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2815 if (dst == -1 && PyErr_Occurred())
2816 return NULL;
2817 if (none) {
2818 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2819 "dst() result required");
2820 return NULL;
2821 }
2822
2823 y = GET_YEAR(dt);
2824 m = GET_MONTH(dt);
2825 d = GET_DAY(dt);
2826 hh = DATE_GET_HOUR(dt);
2827 mm = DATE_GET_MINUTE(dt);
2828 ss = DATE_GET_SECOND(dt);
2829 us = DATE_GET_MICROSECOND(dt);
2830
2831 delta = off - dst;
2832 mm += delta;
2833 if ((mm < 0 || mm >= 60) &&
2834 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002835 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002836 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2837 if (result == NULL)
2838 return result;
2839
2840 dst = call_dst(dt->tzinfo, result, &none);
2841 if (dst == -1 && PyErr_Occurred())
2842 goto Fail;
2843 if (none)
2844 goto Inconsistent;
2845 if (dst == 0)
2846 return result;
2847
2848 mm += dst;
2849 if ((mm < 0 || mm >= 60) &&
2850 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2851 goto Fail;
2852 Py_DECREF(result);
2853 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2854 return result;
2855
2856Inconsistent:
2857 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2858 "inconsistent results; cannot convert");
2859
2860 /* fall thru to failure */
2861Fail:
2862 Py_DECREF(result);
2863 return NULL;
2864}
2865
Tim Peters2a799bf2002-12-16 20:18:38 +00002866/*
2867 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002868 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002869 */
2870
Guido van Rossum177e41a2003-01-30 22:06:23 +00002871static PyObject *
2872tzinfo_reduce(PyObject *self)
2873{
2874 PyObject *args, *state, *tmp;
2875 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002876
Guido van Rossum177e41a2003-01-30 22:06:23 +00002877 tmp = PyTuple_New(0);
2878 if (tmp == NULL)
2879 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002880
Guido van Rossum177e41a2003-01-30 22:06:23 +00002881 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2882 if (getinitargs != NULL) {
2883 args = PyObject_CallObject(getinitargs, tmp);
2884 Py_DECREF(getinitargs);
2885 if (args == NULL) {
2886 Py_DECREF(tmp);
2887 return NULL;
2888 }
2889 }
2890 else {
2891 PyErr_Clear();
2892 args = tmp;
2893 Py_INCREF(args);
2894 }
2895
2896 getstate = PyObject_GetAttrString(self, "__getstate__");
2897 if (getstate != NULL) {
2898 state = PyObject_CallObject(getstate, tmp);
2899 Py_DECREF(getstate);
2900 if (state == NULL) {
2901 Py_DECREF(args);
2902 Py_DECREF(tmp);
2903 return NULL;
2904 }
2905 }
2906 else {
2907 PyObject **dictptr;
2908 PyErr_Clear();
2909 state = Py_None;
2910 dictptr = _PyObject_GetDictPtr(self);
2911 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2912 state = *dictptr;
2913 Py_INCREF(state);
2914 }
2915
2916 Py_DECREF(tmp);
2917
2918 if (state == Py_None) {
2919 Py_DECREF(state);
Christian Heimes90aa7642007-12-19 02:45:37 +00002920 return Py_BuildValue("(ON)", Py_TYPE(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002921 }
2922 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002923 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002924}
Tim Peters2a799bf2002-12-16 20:18:38 +00002925
2926static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002927
Tim Peters2a799bf2002-12-16 20:18:38 +00002928 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2929 PyDoc_STR("datetime -> string name of time zone.")},
2930
2931 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2932 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2933 "west of UTC).")},
2934
2935 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2936 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2937
Tim Peters52dcce22003-01-23 16:36:11 +00002938 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2939 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2940
Guido van Rossum177e41a2003-01-30 22:06:23 +00002941 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2942 PyDoc_STR("-> (cls, state)")},
2943
Tim Peters2a799bf2002-12-16 20:18:38 +00002944 {NULL, NULL}
2945};
2946
2947static char tzinfo_doc[] =
2948PyDoc_STR("Abstract base class for time zone info objects.");
2949
Neal Norwitz227b5332006-03-22 09:28:35 +00002950static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002951 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002952 "datetime.tzinfo", /* tp_name */
2953 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2954 0, /* tp_itemsize */
2955 0, /* tp_dealloc */
2956 0, /* tp_print */
2957 0, /* tp_getattr */
2958 0, /* tp_setattr */
2959 0, /* tp_compare */
2960 0, /* tp_repr */
2961 0, /* tp_as_number */
2962 0, /* tp_as_sequence */
2963 0, /* tp_as_mapping */
2964 0, /* tp_hash */
2965 0, /* tp_call */
2966 0, /* tp_str */
2967 PyObject_GenericGetAttr, /* tp_getattro */
2968 0, /* tp_setattro */
2969 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002970 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002971 tzinfo_doc, /* tp_doc */
2972 0, /* tp_traverse */
2973 0, /* tp_clear */
2974 0, /* tp_richcompare */
2975 0, /* tp_weaklistoffset */
2976 0, /* tp_iter */
2977 0, /* tp_iternext */
2978 tzinfo_methods, /* tp_methods */
2979 0, /* tp_members */
2980 0, /* tp_getset */
2981 0, /* tp_base */
2982 0, /* tp_dict */
2983 0, /* tp_descr_get */
2984 0, /* tp_descr_set */
2985 0, /* tp_dictoffset */
2986 0, /* tp_init */
2987 0, /* tp_alloc */
2988 PyType_GenericNew, /* tp_new */
2989 0, /* tp_free */
2990};
2991
2992/*
Tim Peters37f39822003-01-10 03:49:02 +00002993 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002994 */
2995
Tim Peters37f39822003-01-10 03:49:02 +00002996/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002997 */
2998
2999static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003000time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003001{
Christian Heimes217cfd12007-12-02 14:31:20 +00003002 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003003}
3004
Tim Peters37f39822003-01-10 03:49:02 +00003005static PyObject *
3006time_minute(PyDateTime_Time *self, void *unused)
3007{
Christian Heimes217cfd12007-12-02 14:31:20 +00003008 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003009}
3010
3011/* The name time_second conflicted with some platform header file. */
3012static PyObject *
3013py_time_second(PyDateTime_Time *self, void *unused)
3014{
Christian Heimes217cfd12007-12-02 14:31:20 +00003015 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003016}
3017
3018static PyObject *
3019time_microsecond(PyDateTime_Time *self, void *unused)
3020{
Christian Heimes217cfd12007-12-02 14:31:20 +00003021 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003022}
3023
3024static PyObject *
3025time_tzinfo(PyDateTime_Time *self, void *unused)
3026{
Tim Petersa032d2e2003-01-11 00:15:54 +00003027 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003028 Py_INCREF(result);
3029 return result;
3030}
3031
3032static PyGetSetDef time_getset[] = {
3033 {"hour", (getter)time_hour},
3034 {"minute", (getter)time_minute},
3035 {"second", (getter)py_time_second},
3036 {"microsecond", (getter)time_microsecond},
3037 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003038 {NULL}
3039};
3040
3041/*
3042 * Constructors.
3043 */
3044
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003045static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003046 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003047
Tim Peters2a799bf2002-12-16 20:18:38 +00003048static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003049time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003050{
3051 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003052 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003053 int hour = 0;
3054 int minute = 0;
3055 int second = 0;
3056 int usecond = 0;
3057 PyObject *tzinfo = Py_None;
3058
Guido van Rossum177e41a2003-01-30 22:06:23 +00003059 /* Check for invocation from pickle with __getstate__ state */
3060 if (PyTuple_GET_SIZE(args) >= 1 &&
3061 PyTuple_GET_SIZE(args) <= 2 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00003062 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3063 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3064 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003065 {
Tim Peters70533e22003-02-01 04:40:04 +00003066 PyDateTime_Time *me;
3067 char aware;
3068
3069 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003070 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003071 if (check_tzinfo_subclass(tzinfo) < 0) {
3072 PyErr_SetString(PyExc_TypeError, "bad "
3073 "tzinfo state arg");
3074 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003075 }
3076 }
Tim Peters70533e22003-02-01 04:40:04 +00003077 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003078 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003079 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003080 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003081
3082 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3083 me->hashcode = -1;
3084 me->hastzinfo = aware;
3085 if (aware) {
3086 Py_INCREF(tzinfo);
3087 me->tzinfo = tzinfo;
3088 }
3089 }
3090 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003091 }
3092
Tim Peters37f39822003-01-10 03:49:02 +00003093 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003094 &hour, &minute, &second, &usecond,
3095 &tzinfo)) {
3096 if (check_time_args(hour, minute, second, usecond) < 0)
3097 return NULL;
3098 if (check_tzinfo_subclass(tzinfo) < 0)
3099 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003100 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3101 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003102 }
3103 return self;
3104}
3105
3106/*
3107 * Destructor.
3108 */
3109
3110static void
Tim Peters37f39822003-01-10 03:49:02 +00003111time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003112{
Tim Petersa032d2e2003-01-11 00:15:54 +00003113 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003114 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003115 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003116 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003117}
3118
3119/*
Tim Peters855fe882002-12-22 03:43:39 +00003120 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003121 */
3122
Tim Peters2a799bf2002-12-16 20:18:38 +00003123/* These are all METH_NOARGS, so don't need to check the arglist. */
3124static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003125time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003126 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003127 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003128}
3129
3130static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003131time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003132 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003133 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003134}
3135
3136static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003137time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003138 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003139 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003140}
3141
3142/*
Tim Peters37f39822003-01-10 03:49:02 +00003143 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003144 */
3145
3146static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003147time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003148{
Christian Heimes90aa7642007-12-19 02:45:37 +00003149 const char *type_name = Py_TYPE(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003150 int h = TIME_GET_HOUR(self);
3151 int m = TIME_GET_MINUTE(self);
3152 int s = TIME_GET_SECOND(self);
3153 int us = TIME_GET_MICROSECOND(self);
3154 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003155
Tim Peters37f39822003-01-10 03:49:02 +00003156 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003157 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3158 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003159 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003160 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3161 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003162 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003163 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003164 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003165 result = append_keyword_tzinfo(result, self->tzinfo);
3166 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003167}
3168
Tim Peters37f39822003-01-10 03:49:02 +00003169static PyObject *
3170time_str(PyDateTime_Time *self)
3171{
3172 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3173}
Tim Peters2a799bf2002-12-16 20:18:38 +00003174
3175static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003176time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003177{
3178 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003179 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003180 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003181
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003182 if (us)
3183 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3184 TIME_GET_HOUR(self),
3185 TIME_GET_MINUTE(self),
3186 TIME_GET_SECOND(self),
3187 us);
3188 else
3189 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3190 TIME_GET_HOUR(self),
3191 TIME_GET_MINUTE(self),
3192 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003193
Tim Petersa032d2e2003-01-11 00:15:54 +00003194 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003195 return result;
3196
3197 /* We need to append the UTC offset. */
3198 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003199 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003200 Py_DECREF(result);
3201 return NULL;
3202 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003203 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003204 return result;
3205}
3206
Tim Peters37f39822003-01-10 03:49:02 +00003207static PyObject *
3208time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3209{
3210 PyObject *result;
Tim Peters37f39822003-01-10 03:49:02 +00003211 PyObject *tuple;
Georg Brandlf78e02b2008-06-10 17:40:04 +00003212 PyObject *format;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003213 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003214
Guido van Rossum98297ee2007-11-06 21:34:58 +00003215 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00003216 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003217 return NULL;
3218
3219 /* Python's strftime does insane things with the year part of the
3220 * timetuple. The year is forced to (the otherwise nonsensical)
3221 * 1900 to worm around that.
3222 */
3223 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003224 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003225 TIME_GET_HOUR(self),
3226 TIME_GET_MINUTE(self),
3227 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003228 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003229 if (tuple == NULL)
3230 return NULL;
3231 assert(PyTuple_Size(tuple) == 9);
Georg Brandlf78e02b2008-06-10 17:40:04 +00003232 result = wrap_strftime((PyObject *)self, format, tuple,
3233 Py_None);
Tim Peters37f39822003-01-10 03:49:02 +00003234 Py_DECREF(tuple);
3235 return result;
3236}
Tim Peters2a799bf2002-12-16 20:18:38 +00003237
3238/*
3239 * Miscellaneous methods.
3240 */
3241
Tim Peters37f39822003-01-10 03:49:02 +00003242static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003243time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003244{
3245 int diff;
3246 naivety n1, n2;
3247 int offset1, offset2;
3248
3249 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003250 Py_INCREF(Py_NotImplemented);
3251 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003252 }
Guido van Rossum19960592006-08-24 17:29:38 +00003253 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3254 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003255 return NULL;
3256 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3257 /* If they're both naive, or both aware and have the same offsets,
3258 * we get off cheap. Note that if they're both naive, offset1 ==
3259 * offset2 == 0 at this point.
3260 */
3261 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003262 diff = memcmp(((PyDateTime_Time *)self)->data,
3263 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003264 _PyDateTime_TIME_DATASIZE);
3265 return diff_to_bool(diff, op);
3266 }
3267
3268 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3269 assert(offset1 != offset2); /* else last "if" handled it */
3270 /* Convert everything except microseconds to seconds. These
3271 * can't overflow (no more than the # of seconds in 2 days).
3272 */
3273 offset1 = TIME_GET_HOUR(self) * 3600 +
3274 (TIME_GET_MINUTE(self) - offset1) * 60 +
3275 TIME_GET_SECOND(self);
3276 offset2 = TIME_GET_HOUR(other) * 3600 +
3277 (TIME_GET_MINUTE(other) - offset2) * 60 +
3278 TIME_GET_SECOND(other);
3279 diff = offset1 - offset2;
3280 if (diff == 0)
3281 diff = TIME_GET_MICROSECOND(self) -
3282 TIME_GET_MICROSECOND(other);
3283 return diff_to_bool(diff, op);
3284 }
3285
3286 assert(n1 != n2);
3287 PyErr_SetString(PyExc_TypeError,
3288 "can't compare offset-naive and "
3289 "offset-aware times");
3290 return NULL;
3291}
3292
3293static long
3294time_hash(PyDateTime_Time *self)
3295{
3296 if (self->hashcode == -1) {
3297 naivety n;
3298 int offset;
3299 PyObject *temp;
3300
3301 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3302 assert(n != OFFSET_UNKNOWN);
3303 if (n == OFFSET_ERROR)
3304 return -1;
3305
3306 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003307 if (offset == 0) {
3308 self->hashcode = generic_hash(
3309 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3310 return self->hashcode;
3311 }
Tim Peters37f39822003-01-10 03:49:02 +00003312 else {
3313 int hour;
3314 int minute;
3315
3316 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003317 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003318 hour = divmod(TIME_GET_HOUR(self) * 60 +
3319 TIME_GET_MINUTE(self) - offset,
3320 60,
3321 &minute);
3322 if (0 <= hour && hour < 24)
3323 temp = new_time(hour, minute,
3324 TIME_GET_SECOND(self),
3325 TIME_GET_MICROSECOND(self),
3326 Py_None);
3327 else
3328 temp = Py_BuildValue("iiii",
3329 hour, minute,
3330 TIME_GET_SECOND(self),
3331 TIME_GET_MICROSECOND(self));
3332 }
3333 if (temp != NULL) {
3334 self->hashcode = PyObject_Hash(temp);
3335 Py_DECREF(temp);
3336 }
3337 }
3338 return self->hashcode;
3339}
Tim Peters2a799bf2002-12-16 20:18:38 +00003340
Tim Peters12bf3392002-12-24 05:41:27 +00003341static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003342time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003343{
3344 PyObject *clone;
3345 PyObject *tuple;
3346 int hh = TIME_GET_HOUR(self);
3347 int mm = TIME_GET_MINUTE(self);
3348 int ss = TIME_GET_SECOND(self);
3349 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003350 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003351
3352 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003353 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003354 &hh, &mm, &ss, &us, &tzinfo))
3355 return NULL;
3356 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3357 if (tuple == NULL)
3358 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003359 clone = time_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003360 Py_DECREF(tuple);
3361 return clone;
3362}
3363
Tim Peters2a799bf2002-12-16 20:18:38 +00003364static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003365time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003366{
3367 int offset;
3368 int none;
3369
3370 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3371 /* Since utcoffset is in whole minutes, nothing can
3372 * alter the conclusion that this is nonzero.
3373 */
3374 return 1;
3375 }
3376 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003377 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003378 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003379 if (offset == -1 && PyErr_Occurred())
3380 return -1;
3381 }
3382 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3383}
3384
Tim Peters371935f2003-02-01 01:52:50 +00003385/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003386
Tim Peters33e0f382003-01-10 02:05:14 +00003387/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003388 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3389 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003390 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003391 */
3392static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003393time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003394{
3395 PyObject *basestate;
3396 PyObject *result = NULL;
3397
Christian Heimes72b710a2008-05-26 13:28:38 +00003398 basestate = PyBytes_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003399 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003400 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003401 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003402 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003403 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003404 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003405 Py_DECREF(basestate);
3406 }
3407 return result;
3408}
3409
3410static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003411time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003412{
Christian Heimes90aa7642007-12-19 02:45:37 +00003413 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003414}
3415
Tim Peters37f39822003-01-10 03:49:02 +00003416static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003417
Thomas Wouterscf297e42007-02-23 15:07:44 +00003418 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003419 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3420 "[+HH:MM].")},
3421
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003422 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003423 PyDoc_STR("format -> strftime() style string.")},
3424
Eric Smith8fd3eba2008-02-17 19:48:00 +00003425 {"__format__", (PyCFunction)date_format, METH_VARARGS,
Eric Smith1ba31142007-09-11 18:06:02 +00003426 PyDoc_STR("Formats self with strftime.")},
3427
Tim Peters37f39822003-01-10 03:49:02 +00003428 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003429 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3430
Tim Peters37f39822003-01-10 03:49:02 +00003431 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003432 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3433
Tim Peters37f39822003-01-10 03:49:02 +00003434 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003435 PyDoc_STR("Return self.tzinfo.dst(self).")},
3436
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003437 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003438 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003439
Guido van Rossum177e41a2003-01-30 22:06:23 +00003440 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3441 PyDoc_STR("__reduce__() -> (cls, state)")},
3442
Tim Peters2a799bf2002-12-16 20:18:38 +00003443 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003444};
3445
Tim Peters37f39822003-01-10 03:49:02 +00003446static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003447PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3448\n\
3449All arguments are optional. tzinfo may be None, or an instance of\n\
3450a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003451
Tim Peters37f39822003-01-10 03:49:02 +00003452static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003453 0, /* nb_add */
3454 0, /* nb_subtract */
3455 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003456 0, /* nb_remainder */
3457 0, /* nb_divmod */
3458 0, /* nb_power */
3459 0, /* nb_negative */
3460 0, /* nb_positive */
3461 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003462 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003463};
3464
Neal Norwitz227b5332006-03-22 09:28:35 +00003465static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003466 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003467 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003468 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003469 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003470 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003471 0, /* tp_print */
3472 0, /* tp_getattr */
3473 0, /* tp_setattr */
3474 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003475 (reprfunc)time_repr, /* tp_repr */
3476 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003477 0, /* tp_as_sequence */
3478 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003479 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003480 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003481 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003482 PyObject_GenericGetAttr, /* tp_getattro */
3483 0, /* tp_setattro */
3484 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003485 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003486 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003487 0, /* tp_traverse */
3488 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003489 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003490 0, /* tp_weaklistoffset */
3491 0, /* tp_iter */
3492 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003493 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003494 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003495 time_getset, /* tp_getset */
3496 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003497 0, /* tp_dict */
3498 0, /* tp_descr_get */
3499 0, /* tp_descr_set */
3500 0, /* tp_dictoffset */
3501 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003502 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003503 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003504 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003505};
3506
3507/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003508 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003509 */
3510
Tim Petersa9bc1682003-01-11 03:39:11 +00003511/* Accessor properties. Properties for day, month, and year are inherited
3512 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003513 */
3514
3515static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003516datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003517{
Christian Heimes217cfd12007-12-02 14:31:20 +00003518 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003519}
3520
Tim Petersa9bc1682003-01-11 03:39:11 +00003521static PyObject *
3522datetime_minute(PyDateTime_DateTime *self, void *unused)
3523{
Christian Heimes217cfd12007-12-02 14:31:20 +00003524 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003525}
3526
3527static PyObject *
3528datetime_second(PyDateTime_DateTime *self, void *unused)
3529{
Christian Heimes217cfd12007-12-02 14:31:20 +00003530 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003531}
3532
3533static PyObject *
3534datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3535{
Christian Heimes217cfd12007-12-02 14:31:20 +00003536 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003537}
3538
3539static PyObject *
3540datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3541{
3542 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3543 Py_INCREF(result);
3544 return result;
3545}
3546
3547static PyGetSetDef datetime_getset[] = {
3548 {"hour", (getter)datetime_hour},
3549 {"minute", (getter)datetime_minute},
3550 {"second", (getter)datetime_second},
3551 {"microsecond", (getter)datetime_microsecond},
3552 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003553 {NULL}
3554};
3555
3556/*
3557 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003558 */
3559
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003560static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003561 "year", "month", "day", "hour", "minute", "second",
3562 "microsecond", "tzinfo", NULL
3563};
3564
Tim Peters2a799bf2002-12-16 20:18:38 +00003565static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003566datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003567{
3568 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003569 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003570 int year;
3571 int month;
3572 int day;
3573 int hour = 0;
3574 int minute = 0;
3575 int second = 0;
3576 int usecond = 0;
3577 PyObject *tzinfo = Py_None;
3578
Guido van Rossum177e41a2003-01-30 22:06:23 +00003579 /* Check for invocation from pickle with __getstate__ state */
3580 if (PyTuple_GET_SIZE(args) >= 1 &&
3581 PyTuple_GET_SIZE(args) <= 2 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00003582 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3583 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3584 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003585 {
Tim Peters70533e22003-02-01 04:40:04 +00003586 PyDateTime_DateTime *me;
3587 char aware;
3588
3589 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003590 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003591 if (check_tzinfo_subclass(tzinfo) < 0) {
3592 PyErr_SetString(PyExc_TypeError, "bad "
3593 "tzinfo state arg");
3594 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003595 }
3596 }
Tim Peters70533e22003-02-01 04:40:04 +00003597 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003598 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003599 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003600 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003601
3602 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3603 me->hashcode = -1;
3604 me->hastzinfo = aware;
3605 if (aware) {
3606 Py_INCREF(tzinfo);
3607 me->tzinfo = tzinfo;
3608 }
3609 }
3610 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003611 }
3612
Tim Petersa9bc1682003-01-11 03:39:11 +00003613 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003614 &year, &month, &day, &hour, &minute,
3615 &second, &usecond, &tzinfo)) {
3616 if (check_date_args(year, month, day) < 0)
3617 return NULL;
3618 if (check_time_args(hour, minute, second, usecond) < 0)
3619 return NULL;
3620 if (check_tzinfo_subclass(tzinfo) < 0)
3621 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003622 self = new_datetime_ex(year, month, day,
3623 hour, minute, second, usecond,
3624 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003625 }
3626 return self;
3627}
3628
Tim Petersa9bc1682003-01-11 03:39:11 +00003629/* TM_FUNC is the shared type of localtime() and gmtime(). */
3630typedef struct tm *(*TM_FUNC)(const time_t *timer);
3631
3632/* Internal helper.
3633 * Build datetime from a time_t and a distinct count of microseconds.
3634 * Pass localtime or gmtime for f, to control the interpretation of timet.
3635 */
3636static PyObject *
3637datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3638 PyObject *tzinfo)
3639{
3640 struct tm *tm;
3641 PyObject *result = NULL;
3642
3643 tm = f(&timet);
3644 if (tm) {
3645 /* The platform localtime/gmtime may insert leap seconds,
3646 * indicated by tm->tm_sec > 59. We don't care about them,
3647 * except to the extent that passing them on to the datetime
3648 * constructor would raise ValueError for a reason that
3649 * made no sense to the user.
3650 */
3651 if (tm->tm_sec > 59)
3652 tm->tm_sec = 59;
3653 result = PyObject_CallFunction(cls, "iiiiiiiO",
3654 tm->tm_year + 1900,
3655 tm->tm_mon + 1,
3656 tm->tm_mday,
3657 tm->tm_hour,
3658 tm->tm_min,
3659 tm->tm_sec,
3660 us,
3661 tzinfo);
3662 }
3663 else
3664 PyErr_SetString(PyExc_ValueError,
3665 "timestamp out of range for "
3666 "platform localtime()/gmtime() function");
3667 return result;
3668}
3669
3670/* Internal helper.
3671 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3672 * to control the interpretation of the timestamp. Since a double doesn't
3673 * have enough bits to cover a datetime's full range of precision, it's
3674 * better to call datetime_from_timet_and_us provided you have a way
3675 * to get that much precision (e.g., C time() isn't good enough).
3676 */
3677static PyObject *
3678datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3679 PyObject *tzinfo)
3680{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003681 time_t timet;
3682 double fraction;
3683 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003684
Tim Peters1b6f7a92004-06-20 02:50:16 +00003685 timet = _PyTime_DoubleToTimet(timestamp);
3686 if (timet == (time_t)-1 && PyErr_Occurred())
3687 return NULL;
3688 fraction = timestamp - (double)timet;
3689 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003690 if (us < 0) {
3691 /* Truncation towards zero is not what we wanted
3692 for negative numbers (Python's mod semantics) */
3693 timet -= 1;
3694 us += 1000000;
3695 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003696 /* If timestamp is less than one microsecond smaller than a
3697 * full second, round up. Otherwise, ValueErrors are raised
3698 * for some floats. */
3699 if (us == 1000000) {
3700 timet += 1;
3701 us = 0;
3702 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003703 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3704}
3705
3706/* Internal helper.
3707 * Build most accurate possible datetime for current time. Pass localtime or
3708 * gmtime for f as appropriate.
3709 */
3710static PyObject *
3711datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3712{
3713#ifdef HAVE_GETTIMEOFDAY
3714 struct timeval t;
3715
3716#ifdef GETTIMEOFDAY_NO_TZ
3717 gettimeofday(&t);
3718#else
3719 gettimeofday(&t, (struct timezone *)NULL);
3720#endif
3721 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3722 tzinfo);
3723
3724#else /* ! HAVE_GETTIMEOFDAY */
3725 /* No flavor of gettimeofday exists on this platform. Python's
3726 * time.time() does a lot of other platform tricks to get the
3727 * best time it can on the platform, and we're not going to do
3728 * better than that (if we could, the better code would belong
3729 * in time.time()!) We're limited by the precision of a double,
3730 * though.
3731 */
3732 PyObject *time;
3733 double dtime;
3734
3735 time = time_time();
3736 if (time == NULL)
3737 return NULL;
3738 dtime = PyFloat_AsDouble(time);
3739 Py_DECREF(time);
3740 if (dtime == -1.0 && PyErr_Occurred())
3741 return NULL;
3742 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3743#endif /* ! HAVE_GETTIMEOFDAY */
3744}
3745
Tim Peters2a799bf2002-12-16 20:18:38 +00003746/* Return best possible local time -- this isn't constrained by the
3747 * precision of a timestamp.
3748 */
3749static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003750datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003751{
Tim Peters10cadce2003-01-23 19:58:02 +00003752 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003753 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003754 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003755
Tim Peters10cadce2003-01-23 19:58:02 +00003756 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3757 &tzinfo))
3758 return NULL;
3759 if (check_tzinfo_subclass(tzinfo) < 0)
3760 return NULL;
3761
3762 self = datetime_best_possible(cls,
3763 tzinfo == Py_None ? localtime : gmtime,
3764 tzinfo);
3765 if (self != NULL && tzinfo != Py_None) {
3766 /* Convert UTC to tzinfo's zone. */
3767 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003768 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003769 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003770 }
3771 return self;
3772}
3773
Tim Petersa9bc1682003-01-11 03:39:11 +00003774/* Return best possible UTC time -- this isn't constrained by the
3775 * precision of a timestamp.
3776 */
3777static PyObject *
3778datetime_utcnow(PyObject *cls, PyObject *dummy)
3779{
3780 return datetime_best_possible(cls, gmtime, Py_None);
3781}
3782
Tim Peters2a799bf2002-12-16 20:18:38 +00003783/* Return new local datetime from timestamp (Python timestamp -- a double). */
3784static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003785datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003786{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003787 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003788 double timestamp;
3789 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003790 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003791
Tim Peters2a44a8d2003-01-23 20:53:10 +00003792 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3793 keywords, &timestamp, &tzinfo))
3794 return NULL;
3795 if (check_tzinfo_subclass(tzinfo) < 0)
3796 return NULL;
3797
3798 self = datetime_from_timestamp(cls,
3799 tzinfo == Py_None ? localtime : gmtime,
3800 timestamp,
3801 tzinfo);
3802 if (self != NULL && tzinfo != Py_None) {
3803 /* Convert UTC to tzinfo's zone. */
3804 PyObject *temp = self;
3805 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3806 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003807 }
3808 return self;
3809}
3810
Tim Petersa9bc1682003-01-11 03:39:11 +00003811/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3812static PyObject *
3813datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3814{
3815 double timestamp;
3816 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003817
Tim Petersa9bc1682003-01-11 03:39:11 +00003818 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3819 result = datetime_from_timestamp(cls, gmtime, timestamp,
3820 Py_None);
3821 return result;
3822}
3823
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003824/* Return new datetime from time.strptime(). */
3825static PyObject *
3826datetime_strptime(PyObject *cls, PyObject *args)
3827{
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003828 static PyObject *module = NULL;
3829 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
Guido van Rossume8a17aa2007-08-29 17:28:42 +00003830 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003831
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003832 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003833 return NULL;
3834
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003835 if (module == NULL &&
3836 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003837 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003838
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003839 /* _strptime._strptime returns a two-element tuple. The first
3840 element is a time.struct_time object. The second is the
3841 microseconds (which are not defined for time.struct_time). */
Mark Dickinsonfc689dd2008-03-16 03:45:34 +00003842 obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003843 if (obj != NULL) {
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003844 int i, good_timetuple = 1;
3845 long int ia[7];
3846 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
3847 st = PySequence_GetItem(obj, 0);
3848 frac = PySequence_GetItem(obj, 1);
3849 if (st == NULL || frac == NULL)
3850 good_timetuple = 0;
3851 /* copy y/m/d/h/m/s values out of the
3852 time.struct_time */
3853 if (good_timetuple &&
3854 PySequence_Check(st) &&
3855 PySequence_Size(st) >= 6) {
3856 for (i=0; i < 6; i++) {
3857 PyObject *p = PySequence_GetItem(st, i);
3858 if (p == NULL) {
3859 good_timetuple = 0;
3860 break;
3861 }
3862 if (PyLong_Check(p))
3863 ia[i] = PyLong_AsLong(p);
3864 else
3865 good_timetuple = 0;
3866 Py_DECREF(p);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003867 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003868/* if (PyLong_CheckExact(p)) {
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00003869 ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
3870 if (overflow)
3871 good_timetuple = 0;
3872 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003873 else
3874 good_timetuple = 0;
3875 Py_DECREF(p);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003876*/ }
3877 else
3878 good_timetuple = 0;
3879 /* follow that up with a little dose of microseconds */
3880 if (PyLong_Check(frac))
3881 ia[6] = PyLong_AsLong(frac);
3882 else
3883 good_timetuple = 0;
3884 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003885 else
3886 good_timetuple = 0;
3887 if (good_timetuple)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003888 result = PyObject_CallFunction(cls, "iiiiiii",
3889 ia[0], ia[1], ia[2],
3890 ia[3], ia[4], ia[5],
3891 ia[6]);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003892 else
3893 PyErr_SetString(PyExc_ValueError,
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003894 "unexpected value from _strptime._strptime");
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003895 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003896 Py_XDECREF(obj);
3897 Py_XDECREF(st);
3898 Py_XDECREF(frac);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003899 return result;
3900}
3901
Tim Petersa9bc1682003-01-11 03:39:11 +00003902/* Return new datetime from date/datetime and time arguments. */
3903static PyObject *
3904datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3905{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003906 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003907 PyObject *date;
3908 PyObject *time;
3909 PyObject *result = NULL;
3910
3911 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3912 &PyDateTime_DateType, &date,
3913 &PyDateTime_TimeType, &time)) {
3914 PyObject *tzinfo = Py_None;
3915
3916 if (HASTZINFO(time))
3917 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3918 result = PyObject_CallFunction(cls, "iiiiiiiO",
3919 GET_YEAR(date),
3920 GET_MONTH(date),
3921 GET_DAY(date),
3922 TIME_GET_HOUR(time),
3923 TIME_GET_MINUTE(time),
3924 TIME_GET_SECOND(time),
3925 TIME_GET_MICROSECOND(time),
3926 tzinfo);
3927 }
3928 return result;
3929}
Tim Peters2a799bf2002-12-16 20:18:38 +00003930
3931/*
3932 * Destructor.
3933 */
3934
3935static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003936datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003937{
Tim Petersa9bc1682003-01-11 03:39:11 +00003938 if (HASTZINFO(self)) {
3939 Py_XDECREF(self->tzinfo);
3940 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003941 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003942}
3943
3944/*
3945 * Indirect access to tzinfo methods.
3946 */
3947
Tim Peters2a799bf2002-12-16 20:18:38 +00003948/* These are all METH_NOARGS, so don't need to check the arglist. */
3949static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003950datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3951 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3952 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003953}
3954
3955static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003956datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3957 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3958 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003959}
3960
3961static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003962datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3963 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3964 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003965}
3966
3967/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003968 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003969 */
3970
Tim Petersa9bc1682003-01-11 03:39:11 +00003971/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3972 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003973 */
3974static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003975add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3976 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003977{
Tim Petersa9bc1682003-01-11 03:39:11 +00003978 /* Note that the C-level additions can't overflow, because of
3979 * invariant bounds on the member values.
3980 */
3981 int year = GET_YEAR(date);
3982 int month = GET_MONTH(date);
3983 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3984 int hour = DATE_GET_HOUR(date);
3985 int minute = DATE_GET_MINUTE(date);
3986 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3987 int microsecond = DATE_GET_MICROSECOND(date) +
3988 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003989
Tim Petersa9bc1682003-01-11 03:39:11 +00003990 assert(factor == 1 || factor == -1);
3991 if (normalize_datetime(&year, &month, &day,
3992 &hour, &minute, &second, &microsecond) < 0)
3993 return NULL;
3994 else
3995 return new_datetime(year, month, day,
3996 hour, minute, second, microsecond,
3997 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003998}
3999
4000static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004001datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004002{
Tim Petersa9bc1682003-01-11 03:39:11 +00004003 if (PyDateTime_Check(left)) {
4004 /* datetime + ??? */
4005 if (PyDelta_Check(right))
4006 /* datetime + delta */
4007 return add_datetime_timedelta(
4008 (PyDateTime_DateTime *)left,
4009 (PyDateTime_Delta *)right,
4010 1);
4011 }
4012 else if (PyDelta_Check(left)) {
4013 /* delta + datetime */
4014 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4015 (PyDateTime_Delta *) left,
4016 1);
4017 }
4018 Py_INCREF(Py_NotImplemented);
4019 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004020}
4021
4022static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004023datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004024{
4025 PyObject *result = Py_NotImplemented;
4026
4027 if (PyDateTime_Check(left)) {
4028 /* datetime - ??? */
4029 if (PyDateTime_Check(right)) {
4030 /* datetime - datetime */
4031 naivety n1, n2;
4032 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004033 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004034
Tim Peterse39a80c2002-12-30 21:28:52 +00004035 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4036 right, &offset2, &n2,
4037 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00004038 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00004039 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00004040 if (n1 != n2) {
4041 PyErr_SetString(PyExc_TypeError,
4042 "can't subtract offset-naive and "
4043 "offset-aware datetimes");
4044 return NULL;
4045 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004046 delta_d = ymd_to_ord(GET_YEAR(left),
4047 GET_MONTH(left),
4048 GET_DAY(left)) -
4049 ymd_to_ord(GET_YEAR(right),
4050 GET_MONTH(right),
4051 GET_DAY(right));
4052 /* These can't overflow, since the values are
4053 * normalized. At most this gives the number of
4054 * seconds in one day.
4055 */
4056 delta_s = (DATE_GET_HOUR(left) -
4057 DATE_GET_HOUR(right)) * 3600 +
4058 (DATE_GET_MINUTE(left) -
4059 DATE_GET_MINUTE(right)) * 60 +
4060 (DATE_GET_SECOND(left) -
4061 DATE_GET_SECOND(right));
4062 delta_us = DATE_GET_MICROSECOND(left) -
4063 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004064 /* (left - offset1) - (right - offset2) =
4065 * (left - right) + (offset2 - offset1)
4066 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004067 delta_s += (offset2 - offset1) * 60;
4068 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004069 }
4070 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004071 /* datetime - delta */
4072 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004073 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004074 (PyDateTime_Delta *)right,
4075 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004076 }
4077 }
4078
4079 if (result == Py_NotImplemented)
4080 Py_INCREF(result);
4081 return result;
4082}
4083
4084/* Various ways to turn a datetime into a string. */
4085
4086static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004087datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004088{
Christian Heimes90aa7642007-12-19 02:45:37 +00004089 const char *type_name = Py_TYPE(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004090 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004091
Tim Petersa9bc1682003-01-11 03:39:11 +00004092 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004093 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004094 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004095 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004096 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4097 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4098 DATE_GET_SECOND(self),
4099 DATE_GET_MICROSECOND(self));
4100 }
4101 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004102 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004103 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004104 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004105 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4106 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4107 DATE_GET_SECOND(self));
4108 }
4109 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004110 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004111 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004112 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004113 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4114 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4115 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004116 if (baserepr == NULL || ! HASTZINFO(self))
4117 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004118 return append_keyword_tzinfo(baserepr, self->tzinfo);
4119}
4120
Tim Petersa9bc1682003-01-11 03:39:11 +00004121static PyObject *
4122datetime_str(PyDateTime_DateTime *self)
4123{
4124 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4125}
Tim Peters2a799bf2002-12-16 20:18:38 +00004126
4127static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004128datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004129{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004130 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004131 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004132 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004133 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004134 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004135
Walter Dörwaldd0941302007-07-01 21:58:22 +00004136 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004137 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004138 if (us)
4139 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4140 GET_YEAR(self), GET_MONTH(self),
4141 GET_DAY(self), (int)sep,
4142 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4143 DATE_GET_SECOND(self), us);
4144 else
4145 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4146 GET_YEAR(self), GET_MONTH(self),
4147 GET_DAY(self), (int)sep,
4148 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4149 DATE_GET_SECOND(self));
4150
4151 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004152 return result;
4153
4154 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004155 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004156 (PyObject *)self) < 0) {
4157 Py_DECREF(result);
4158 return NULL;
4159 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004160 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004161 return result;
4162}
4163
Tim Petersa9bc1682003-01-11 03:39:11 +00004164static PyObject *
4165datetime_ctime(PyDateTime_DateTime *self)
4166{
4167 return format_ctime((PyDateTime_Date *)self,
4168 DATE_GET_HOUR(self),
4169 DATE_GET_MINUTE(self),
4170 DATE_GET_SECOND(self));
4171}
4172
Tim Peters2a799bf2002-12-16 20:18:38 +00004173/* Miscellaneous methods. */
4174
Tim Petersa9bc1682003-01-11 03:39:11 +00004175static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004176datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004177{
4178 int diff;
4179 naivety n1, n2;
4180 int offset1, offset2;
4181
4182 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004183 if (PyDate_Check(other)) {
4184 /* Prevent invocation of date_richcompare. We want to
4185 return NotImplemented here to give the other object
4186 a chance. But since DateTime is a subclass of
4187 Date, if the other object is a Date, it would
4188 compute an ordering based on the date part alone,
4189 and we don't want that. So force unequal or
4190 uncomparable here in that case. */
4191 if (op == Py_EQ)
4192 Py_RETURN_FALSE;
4193 if (op == Py_NE)
4194 Py_RETURN_TRUE;
4195 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004196 }
Guido van Rossum19960592006-08-24 17:29:38 +00004197 Py_INCREF(Py_NotImplemented);
4198 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004199 }
4200
Guido van Rossum19960592006-08-24 17:29:38 +00004201 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4202 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004203 return NULL;
4204 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4205 /* If they're both naive, or both aware and have the same offsets,
4206 * we get off cheap. Note that if they're both naive, offset1 ==
4207 * offset2 == 0 at this point.
4208 */
4209 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004210 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4211 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004212 _PyDateTime_DATETIME_DATASIZE);
4213 return diff_to_bool(diff, op);
4214 }
4215
4216 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4217 PyDateTime_Delta *delta;
4218
4219 assert(offset1 != offset2); /* else last "if" handled it */
4220 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4221 other);
4222 if (delta == NULL)
4223 return NULL;
4224 diff = GET_TD_DAYS(delta);
4225 if (diff == 0)
4226 diff = GET_TD_SECONDS(delta) |
4227 GET_TD_MICROSECONDS(delta);
4228 Py_DECREF(delta);
4229 return diff_to_bool(diff, op);
4230 }
4231
4232 assert(n1 != n2);
4233 PyErr_SetString(PyExc_TypeError,
4234 "can't compare offset-naive and "
4235 "offset-aware datetimes");
4236 return NULL;
4237}
4238
4239static long
4240datetime_hash(PyDateTime_DateTime *self)
4241{
4242 if (self->hashcode == -1) {
4243 naivety n;
4244 int offset;
4245 PyObject *temp;
4246
4247 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4248 &offset);
4249 assert(n != OFFSET_UNKNOWN);
4250 if (n == OFFSET_ERROR)
4251 return -1;
4252
4253 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00004254 if (n == OFFSET_NAIVE) {
4255 self->hashcode = generic_hash(
4256 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4257 return self->hashcode;
4258 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004259 else {
4260 int days;
4261 int seconds;
4262
4263 assert(n == OFFSET_AWARE);
4264 assert(HASTZINFO(self));
4265 days = ymd_to_ord(GET_YEAR(self),
4266 GET_MONTH(self),
4267 GET_DAY(self));
4268 seconds = DATE_GET_HOUR(self) * 3600 +
4269 (DATE_GET_MINUTE(self) - offset) * 60 +
4270 DATE_GET_SECOND(self);
4271 temp = new_delta(days,
4272 seconds,
4273 DATE_GET_MICROSECOND(self),
4274 1);
4275 }
4276 if (temp != NULL) {
4277 self->hashcode = PyObject_Hash(temp);
4278 Py_DECREF(temp);
4279 }
4280 }
4281 return self->hashcode;
4282}
Tim Peters2a799bf2002-12-16 20:18:38 +00004283
4284static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004285datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004286{
4287 PyObject *clone;
4288 PyObject *tuple;
4289 int y = GET_YEAR(self);
4290 int m = GET_MONTH(self);
4291 int d = GET_DAY(self);
4292 int hh = DATE_GET_HOUR(self);
4293 int mm = DATE_GET_MINUTE(self);
4294 int ss = DATE_GET_SECOND(self);
4295 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004296 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004297
4298 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004299 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004300 &y, &m, &d, &hh, &mm, &ss, &us,
4301 &tzinfo))
4302 return NULL;
4303 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4304 if (tuple == NULL)
4305 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00004306 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004307 Py_DECREF(tuple);
4308 return clone;
4309}
4310
4311static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004312datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004313{
Tim Peters52dcce22003-01-23 16:36:11 +00004314 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004315 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004316 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004317
Tim Peters80475bb2002-12-25 07:40:55 +00004318 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004319 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004320
Tim Peters52dcce22003-01-23 16:36:11 +00004321 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4322 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004323 return NULL;
4324
Tim Peters52dcce22003-01-23 16:36:11 +00004325 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4326 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004327
Tim Peters52dcce22003-01-23 16:36:11 +00004328 /* Conversion to self's own time zone is a NOP. */
4329 if (self->tzinfo == tzinfo) {
4330 Py_INCREF(self);
4331 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004332 }
Tim Peters521fc152002-12-31 17:36:56 +00004333
Tim Peters52dcce22003-01-23 16:36:11 +00004334 /* Convert self to UTC. */
4335 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4336 if (offset == -1 && PyErr_Occurred())
4337 return NULL;
4338 if (none)
4339 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004340
Tim Peters52dcce22003-01-23 16:36:11 +00004341 y = GET_YEAR(self);
4342 m = GET_MONTH(self);
4343 d = GET_DAY(self);
4344 hh = DATE_GET_HOUR(self);
4345 mm = DATE_GET_MINUTE(self);
4346 ss = DATE_GET_SECOND(self);
4347 us = DATE_GET_MICROSECOND(self);
4348
4349 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004350 if ((mm < 0 || mm >= 60) &&
4351 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004352 return NULL;
4353
4354 /* Attach new tzinfo and let fromutc() do the rest. */
4355 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4356 if (result != NULL) {
4357 PyObject *temp = result;
4358
4359 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4360 Py_DECREF(temp);
4361 }
Tim Petersadf64202003-01-04 06:03:15 +00004362 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004363
Tim Peters52dcce22003-01-23 16:36:11 +00004364NeedAware:
4365 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4366 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004367 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004368}
4369
4370static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004371datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004372{
4373 int dstflag = -1;
4374
Tim Petersa9bc1682003-01-11 03:39:11 +00004375 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004376 int none;
4377
4378 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4379 if (dstflag == -1 && PyErr_Occurred())
4380 return NULL;
4381
4382 if (none)
4383 dstflag = -1;
4384 else if (dstflag != 0)
4385 dstflag = 1;
4386
4387 }
4388 return build_struct_time(GET_YEAR(self),
4389 GET_MONTH(self),
4390 GET_DAY(self),
4391 DATE_GET_HOUR(self),
4392 DATE_GET_MINUTE(self),
4393 DATE_GET_SECOND(self),
4394 dstflag);
4395}
4396
4397static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004398datetime_getdate(PyDateTime_DateTime *self)
4399{
4400 return new_date(GET_YEAR(self),
4401 GET_MONTH(self),
4402 GET_DAY(self));
4403}
4404
4405static PyObject *
4406datetime_gettime(PyDateTime_DateTime *self)
4407{
4408 return new_time(DATE_GET_HOUR(self),
4409 DATE_GET_MINUTE(self),
4410 DATE_GET_SECOND(self),
4411 DATE_GET_MICROSECOND(self),
4412 Py_None);
4413}
4414
4415static PyObject *
4416datetime_gettimetz(PyDateTime_DateTime *self)
4417{
4418 return new_time(DATE_GET_HOUR(self),
4419 DATE_GET_MINUTE(self),
4420 DATE_GET_SECOND(self),
4421 DATE_GET_MICROSECOND(self),
4422 HASTZINFO(self) ? self->tzinfo : Py_None);
4423}
4424
4425static PyObject *
4426datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004427{
4428 int y = GET_YEAR(self);
4429 int m = GET_MONTH(self);
4430 int d = GET_DAY(self);
4431 int hh = DATE_GET_HOUR(self);
4432 int mm = DATE_GET_MINUTE(self);
4433 int ss = DATE_GET_SECOND(self);
4434 int us = 0; /* microseconds are ignored in a timetuple */
4435 int offset = 0;
4436
Tim Petersa9bc1682003-01-11 03:39:11 +00004437 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004438 int none;
4439
4440 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4441 if (offset == -1 && PyErr_Occurred())
4442 return NULL;
4443 }
4444 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4445 * 0 in a UTC timetuple regardless of what dst() says.
4446 */
4447 if (offset) {
4448 /* Subtract offset minutes & normalize. */
4449 int stat;
4450
4451 mm -= offset;
4452 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4453 if (stat < 0) {
4454 /* At the edges, it's possible we overflowed
4455 * beyond MINYEAR or MAXYEAR.
4456 */
4457 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4458 PyErr_Clear();
4459 else
4460 return NULL;
4461 }
4462 }
4463 return build_struct_time(y, m, d, hh, mm, ss, 0);
4464}
4465
Tim Peters371935f2003-02-01 01:52:50 +00004466/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004467
Tim Petersa9bc1682003-01-11 03:39:11 +00004468/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004469 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4470 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004471 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004472 */
4473static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004474datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004475{
4476 PyObject *basestate;
4477 PyObject *result = NULL;
4478
Christian Heimes72b710a2008-05-26 13:28:38 +00004479 basestate = PyBytes_FromStringAndSize((char *)self->data,
Guido van Rossum254348e2007-11-21 19:29:53 +00004480 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004481 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004482 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004483 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004484 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004485 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004486 Py_DECREF(basestate);
4487 }
4488 return result;
4489}
4490
4491static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004492datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004493{
Christian Heimes90aa7642007-12-19 02:45:37 +00004494 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004495}
4496
Tim Petersa9bc1682003-01-11 03:39:11 +00004497static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004498
Tim Peters2a799bf2002-12-16 20:18:38 +00004499 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004500
Tim Petersa9bc1682003-01-11 03:39:11 +00004501 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004502 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004503 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004504
Tim Petersa9bc1682003-01-11 03:39:11 +00004505 {"utcnow", (PyCFunction)datetime_utcnow,
4506 METH_NOARGS | METH_CLASS,
4507 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4508
4509 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004510 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004511 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004512
Tim Petersa9bc1682003-01-11 03:39:11 +00004513 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4514 METH_VARARGS | METH_CLASS,
4515 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4516 "(like time.time()).")},
4517
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004518 {"strptime", (PyCFunction)datetime_strptime,
4519 METH_VARARGS | METH_CLASS,
4520 PyDoc_STR("string, format -> new datetime parsed from a string "
4521 "(like time.strptime()).")},
4522
Tim Petersa9bc1682003-01-11 03:39:11 +00004523 {"combine", (PyCFunction)datetime_combine,
4524 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4525 PyDoc_STR("date, time -> datetime with same date and time fields")},
4526
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004528
Tim Petersa9bc1682003-01-11 03:39:11 +00004529 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4530 PyDoc_STR("Return date object with same year, month and day.")},
4531
4532 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4533 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4534
4535 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4536 PyDoc_STR("Return time object with same time and tzinfo.")},
4537
4538 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4539 PyDoc_STR("Return ctime() style string.")},
4540
4541 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004542 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4543
Tim Petersa9bc1682003-01-11 03:39:11 +00004544 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004545 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4546
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004547 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004548 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4549 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4550 "sep is used to separate the year from the time, and "
4551 "defaults to 'T'.")},
4552
Tim Petersa9bc1682003-01-11 03:39:11 +00004553 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004554 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4555
Tim Petersa9bc1682003-01-11 03:39:11 +00004556 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004557 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4558
Tim Petersa9bc1682003-01-11 03:39:11 +00004559 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004560 PyDoc_STR("Return self.tzinfo.dst(self).")},
4561
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004562 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004563 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004564
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004565 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004566 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4567
Guido van Rossum177e41a2003-01-30 22:06:23 +00004568 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4569 PyDoc_STR("__reduce__() -> (cls, state)")},
4570
Tim Peters2a799bf2002-12-16 20:18:38 +00004571 {NULL, NULL}
4572};
4573
Tim Petersa9bc1682003-01-11 03:39:11 +00004574static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004575PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4576\n\
4577The year, month and day arguments are required. tzinfo may be None, or an\n\
4578instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004579
Tim Petersa9bc1682003-01-11 03:39:11 +00004580static PyNumberMethods datetime_as_number = {
4581 datetime_add, /* nb_add */
4582 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004583 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004584 0, /* nb_remainder */
4585 0, /* nb_divmod */
4586 0, /* nb_power */
4587 0, /* nb_negative */
4588 0, /* nb_positive */
4589 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004590 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004591};
4592
Neal Norwitz227b5332006-03-22 09:28:35 +00004593static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004594 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004595 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004596 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004597 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004598 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004599 0, /* tp_print */
4600 0, /* tp_getattr */
4601 0, /* tp_setattr */
4602 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004603 (reprfunc)datetime_repr, /* tp_repr */
4604 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004605 0, /* tp_as_sequence */
4606 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004607 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004608 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004609 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004610 PyObject_GenericGetAttr, /* tp_getattro */
4611 0, /* tp_setattro */
4612 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004613 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004614 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004615 0, /* tp_traverse */
4616 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004617 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004618 0, /* tp_weaklistoffset */
4619 0, /* tp_iter */
4620 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004621 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004622 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004623 datetime_getset, /* tp_getset */
4624 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004625 0, /* tp_dict */
4626 0, /* tp_descr_get */
4627 0, /* tp_descr_set */
4628 0, /* tp_dictoffset */
4629 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004630 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004631 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004632 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004633};
4634
4635/* ---------------------------------------------------------------------------
4636 * Module methods and initialization.
4637 */
4638
4639static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004640 {NULL, NULL}
4641};
4642
Tim Peters9ddf40b2004-06-20 22:41:32 +00004643/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4644 * datetime.h.
4645 */
4646static PyDateTime_CAPI CAPI = {
4647 &PyDateTime_DateType,
4648 &PyDateTime_DateTimeType,
4649 &PyDateTime_TimeType,
4650 &PyDateTime_DeltaType,
4651 &PyDateTime_TZInfoType,
4652 new_date_ex,
4653 new_datetime_ex,
4654 new_time_ex,
4655 new_delta_ex,
4656 datetime_fromtimestamp,
4657 date_fromtimestamp
4658};
4659
4660
Martin v. Löwis1a214512008-06-11 05:26:20 +00004661
4662static struct PyModuleDef datetimemodule = {
4663 PyModuleDef_HEAD_INIT,
4664 "datetime",
4665 "Fast implementation of the datetime type.",
4666 -1,
4667 module_methods,
4668 NULL,
4669 NULL,
4670 NULL,
4671 NULL
4672};
4673
Tim Peters2a799bf2002-12-16 20:18:38 +00004674PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004675PyInit_datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00004676{
4677 PyObject *m; /* a module object */
4678 PyObject *d; /* its dict */
4679 PyObject *x;
4680
Martin v. Löwis1a214512008-06-11 05:26:20 +00004681 m = PyModule_Create(&datetimemodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004682 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004683 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004684
4685 if (PyType_Ready(&PyDateTime_DateType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004686 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004687 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004688 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004689 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004690 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004691 if (PyType_Ready(&PyDateTime_TimeType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004692 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004693 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004694 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004695
Tim Peters2a799bf2002-12-16 20:18:38 +00004696 /* timedelta values */
4697 d = PyDateTime_DeltaType.tp_dict;
4698
Tim Peters2a799bf2002-12-16 20:18:38 +00004699 x = new_delta(0, 0, 1, 0);
4700 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004701 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004702 Py_DECREF(x);
4703
4704 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4705 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004706 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004707 Py_DECREF(x);
4708
4709 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4710 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004711 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004712 Py_DECREF(x);
4713
4714 /* date values */
4715 d = PyDateTime_DateType.tp_dict;
4716
4717 x = new_date(1, 1, 1);
4718 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004719 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004720 Py_DECREF(x);
4721
4722 x = new_date(MAXYEAR, 12, 31);
4723 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004724 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004725 Py_DECREF(x);
4726
4727 x = new_delta(1, 0, 0, 0);
4728 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004729 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004730 Py_DECREF(x);
4731
Tim Peters37f39822003-01-10 03:49:02 +00004732 /* time values */
4733 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004734
Tim Peters37f39822003-01-10 03:49:02 +00004735 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004736 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004737 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004738 Py_DECREF(x);
4739
Tim Peters37f39822003-01-10 03:49:02 +00004740 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004741 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004742 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004743 Py_DECREF(x);
4744
4745 x = new_delta(0, 0, 1, 0);
4746 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004747 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004748 Py_DECREF(x);
4749
Tim Petersa9bc1682003-01-11 03:39:11 +00004750 /* datetime values */
4751 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004752
Tim Petersa9bc1682003-01-11 03:39:11 +00004753 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004754 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004755 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004756 Py_DECREF(x);
4757
Tim Petersa9bc1682003-01-11 03:39:11 +00004758 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004759 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004760 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004761 Py_DECREF(x);
4762
4763 x = new_delta(0, 0, 1, 0);
4764 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004765 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004766 Py_DECREF(x);
4767
Tim Peters2a799bf2002-12-16 20:18:38 +00004768 /* module initialization */
4769 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4770 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4771
4772 Py_INCREF(&PyDateTime_DateType);
4773 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4774
Tim Petersa9bc1682003-01-11 03:39:11 +00004775 Py_INCREF(&PyDateTime_DateTimeType);
4776 PyModule_AddObject(m, "datetime",
4777 (PyObject *)&PyDateTime_DateTimeType);
4778
4779 Py_INCREF(&PyDateTime_TimeType);
4780 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4781
Tim Peters2a799bf2002-12-16 20:18:38 +00004782 Py_INCREF(&PyDateTime_DeltaType);
4783 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4784
Tim Peters2a799bf2002-12-16 20:18:38 +00004785 Py_INCREF(&PyDateTime_TZInfoType);
4786 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4787
Tim Peters9ddf40b2004-06-20 22:41:32 +00004788 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4789 NULL);
4790 if (x == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004791 return NULL;
Tim Peters9ddf40b2004-06-20 22:41:32 +00004792 PyModule_AddObject(m, "datetime_CAPI", x);
4793
Tim Peters2a799bf2002-12-16 20:18:38 +00004794 /* A 4-year cycle has an extra leap day over what we'd get from
4795 * pasting together 4 single years.
4796 */
4797 assert(DI4Y == 4 * 365 + 1);
4798 assert(DI4Y == days_before_year(4+1));
4799
4800 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4801 * get from pasting together 4 100-year cycles.
4802 */
4803 assert(DI400Y == 4 * DI100Y + 1);
4804 assert(DI400Y == days_before_year(400+1));
4805
4806 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4807 * pasting together 25 4-year cycles.
4808 */
4809 assert(DI100Y == 25 * DI4Y - 1);
4810 assert(DI100Y == days_before_year(100+1));
4811
Christian Heimes217cfd12007-12-02 14:31:20 +00004812 us_per_us = PyLong_FromLong(1);
4813 us_per_ms = PyLong_FromLong(1000);
4814 us_per_second = PyLong_FromLong(1000000);
4815 us_per_minute = PyLong_FromLong(60000000);
4816 seconds_per_day = PyLong_FromLong(24 * 3600);
Tim Peters2a799bf2002-12-16 20:18:38 +00004817 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4818 us_per_minute == NULL || seconds_per_day == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004819 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004820
4821 /* The rest are too big for 32-bit ints, but even
4822 * us_per_week fits in 40 bits, so doubles should be exact.
4823 */
4824 us_per_hour = PyLong_FromDouble(3600000000.0);
4825 us_per_day = PyLong_FromDouble(86400000000.0);
4826 us_per_week = PyLong_FromDouble(604800000000.0);
4827 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004828 return NULL;
4829 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00004830}
Tim Petersf3615152003-01-01 21:51:37 +00004831
4832/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004833Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004834 x.n = x stripped of its timezone -- its naive time.
4835 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4836 return None
4837 x.d = x.dst(), and assuming that doesn't raise an exception or
4838 return None
4839 x.s = x's standard offset, x.o - x.d
4840
4841Now some derived rules, where k is a duration (timedelta).
4842
48431. x.o = x.s + x.d
4844 This follows from the definition of x.s.
4845
Tim Petersc5dc4da2003-01-02 17:55:03 +000048462. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004847 This is actually a requirement, an assumption we need to make about
4848 sane tzinfo classes.
4849
48503. The naive UTC time corresponding to x is x.n - x.o.
4851 This is again a requirement for a sane tzinfo class.
4852
48534. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004854 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004855
Tim Petersc5dc4da2003-01-02 17:55:03 +000048565. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004857 Again follows from how arithmetic is defined.
4858
Tim Peters8bb5ad22003-01-24 02:44:45 +00004859Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004860(meaning that the various tzinfo methods exist, and don't blow up or return
4861None when called).
4862
Tim Petersa9bc1682003-01-11 03:39:11 +00004863The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004864x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004865
4866By #3, we want
4867
Tim Peters8bb5ad22003-01-24 02:44:45 +00004868 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004869
4870The algorithm starts by attaching tz to x.n, and calling that y. So
4871x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4872becomes true; in effect, we want to solve [2] for k:
4873
Tim Peters8bb5ad22003-01-24 02:44:45 +00004874 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004875
4876By #1, this is the same as
4877
Tim Peters8bb5ad22003-01-24 02:44:45 +00004878 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004879
4880By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4881Substituting that into [3],
4882
Tim Peters8bb5ad22003-01-24 02:44:45 +00004883 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4884 k - (y+k).s - (y+k).d = 0; rearranging,
4885 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4886 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004887
Tim Peters8bb5ad22003-01-24 02:44:45 +00004888On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4889approximate k by ignoring the (y+k).d term at first. Note that k can't be
4890very large, since all offset-returning methods return a duration of magnitude
4891less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4892be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004893
4894In any case, the new value is
4895
Tim Peters8bb5ad22003-01-24 02:44:45 +00004896 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004897
Tim Peters8bb5ad22003-01-24 02:44:45 +00004898It's helpful to step back at look at [4] from a higher level: it's simply
4899mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004900
4901At this point, if
4902
Tim Peters8bb5ad22003-01-24 02:44:45 +00004903 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004904
4905we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004906at the start of daylight time. Picture US Eastern for concreteness. The wall
4907time 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 +00004908sense then. The docs ask that an Eastern tzinfo class consider such a time to
4909be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4910on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004911the only spelling that makes sense on the local wall clock.
4912
Tim Petersc5dc4da2003-01-02 17:55:03 +00004913In fact, if [5] holds at this point, we do have the standard-time spelling,
4914but that takes a bit of proof. We first prove a stronger result. What's the
4915difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004916
Tim Peters8bb5ad22003-01-24 02:44:45 +00004917 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004918
Tim Petersc5dc4da2003-01-02 17:55:03 +00004919Now
4920 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004921 (y + y.s).n = by #5
4922 y.n + y.s = since y.n = x.n
4923 x.n + y.s = since z and y are have the same tzinfo member,
4924 y.s = z.s by #2
4925 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004926
Tim Petersc5dc4da2003-01-02 17:55:03 +00004927Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004928
Tim Petersc5dc4da2003-01-02 17:55:03 +00004929 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004930 x.n - ((x.n + z.s) - z.o) = expanding
4931 x.n - x.n - z.s + z.o = cancelling
4932 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004933 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004934
Tim Petersc5dc4da2003-01-02 17:55:03 +00004935So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004936
Tim Petersc5dc4da2003-01-02 17:55:03 +00004937If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004938spelling we wanted in the endcase described above. We're done. Contrarily,
4939if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004940
Tim Petersc5dc4da2003-01-02 17:55:03 +00004941If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4942add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004943local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004944
Tim Petersc5dc4da2003-01-02 17:55:03 +00004945Let
Tim Petersf3615152003-01-01 21:51:37 +00004946
Tim Peters4fede1a2003-01-04 00:26:59 +00004947 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004948
Tim Peters4fede1a2003-01-04 00:26:59 +00004949and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004950
Tim Peters8bb5ad22003-01-24 02:44:45 +00004951 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004952
Tim Peters8bb5ad22003-01-24 02:44:45 +00004953If so, we're done. If not, the tzinfo class is insane, according to the
4954assumptions we've made. This also requires a bit of proof. As before, let's
4955compute the difference between the LHS and RHS of [8] (and skipping some of
4956the justifications for the kinds of substitutions we've done several times
4957already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004958
Tim Peters8bb5ad22003-01-24 02:44:45 +00004959 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4960 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4961 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4962 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4963 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004964 - z.o + z'.o = #1 twice
4965 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4966 z'.d - z.d
4967
4968So 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 +00004969we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4970return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004971
Tim Peters8bb5ad22003-01-24 02:44:45 +00004972How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4973a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4974would have to change the result dst() returns: we start in DST, and moving
4975a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004976
Tim Peters8bb5ad22003-01-24 02:44:45 +00004977There isn't a sane case where this can happen. The closest it gets is at
4978the end of DST, where there's an hour in UTC with no spelling in a hybrid
4979tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4980that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4981UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4982time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4983clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4984standard time. Since that's what the local clock *does*, we want to map both
4985UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004986in local time, but so it goes -- it's the way the local clock works.
4987
Tim Peters8bb5ad22003-01-24 02:44:45 +00004988When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4989so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4990z' = 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 +00004991(correctly) concludes that z' is not UTC-equivalent to x.
4992
4993Because we know z.d said z was in daylight time (else [5] would have held and
4994we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004995and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004996return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4997but the reasoning doesn't depend on the example -- it depends on there being
4998two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004999z' must be in standard time, and is the spelling we want in this case.
5000
5001Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5002concerned (because it takes z' as being in standard time rather than the
5003daylight time we intend here), but returning it gives the real-life "local
5004clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5005tz.
5006
5007When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5008the 1:MM standard time spelling we want.
5009
5010So how can this break? One of the assumptions must be violated. Two
5011possibilities:
5012
50131) [2] effectively says that y.s is invariant across all y belong to a given
5014 time zone. This isn't true if, for political reasons or continental drift,
5015 a region decides to change its base offset from UTC.
5016
50172) There may be versions of "double daylight" time where the tail end of
5018 the analysis gives up a step too early. I haven't thought about that
5019 enough to say.
5020
5021In any case, it's clear that the default fromutc() is strong enough to handle
5022"almost all" time zones: so long as the standard offset is invariant, it
5023doesn't matter if daylight time transition points change from year to year, or
5024if daylight time is skipped in some years; it doesn't matter how large or
5025small dst() may get within its bounds; and it doesn't even matter if some
5026perverse time zone returns a negative dst()). So a breaking case must be
5027pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005028--------------------------------------------------------------------------- */