blob: f31b44c058d191459bb004b9a42f851cb442274e [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'",
767 p->ob_type->tp_name);
768 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'",
858 name, u->ob_type->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
Tim Peters855fe882002-12-22 03:43:39 +0000930 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000931 */
932static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000933call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000934{
935 PyObject *result;
936
937 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000938 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000939 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000940
Tim Peters855fe882002-12-22 03:43:39 +0000941 if (tzinfo == Py_None) {
942 result = Py_None;
943 Py_INCREF(result);
944 }
945 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000946 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000947
948 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
949 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
Tim Peters2a799bf2002-12-16 20:18:38 +0000950 "return None or a string, not '%s'",
951 result->ob_type->tp_name);
952 Py_DECREF(result);
953 result = NULL;
954 }
955 return result;
956}
957
958typedef enum {
959 /* an exception has been set; the caller should pass it on */
960 OFFSET_ERROR,
961
Tim Petersa9bc1682003-01-11 03:39:11 +0000962 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000963 OFFSET_UNKNOWN,
964
965 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000966 * datetime with !hastzinfo
967 * datetime with None tzinfo,
968 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000969 * time with !hastzinfo
970 * time with None tzinfo,
971 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000972 */
973 OFFSET_NAIVE,
974
Tim Petersa9bc1682003-01-11 03:39:11 +0000975 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000976 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000977} naivety;
978
Tim Peters14b69412002-12-22 18:10:22 +0000979/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 * the "naivety" typedef for details. If the type is aware, *offset is set
981 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000982 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000983 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000984 */
985static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000986classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000987{
988 int none;
989 PyObject *tzinfo;
990
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +0000993 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +0000994 if (tzinfo == Py_None)
995 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +0000996 if (tzinfo == NULL) {
997 /* note that a datetime passes the PyDate_Check test */
998 return (PyTime_Check(op) || PyDate_Check(op)) ?
999 OFFSET_NAIVE : OFFSET_UNKNOWN;
1000 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001001 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (*offset == -1 && PyErr_Occurred())
1003 return OFFSET_ERROR;
1004 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1005}
1006
Tim Peters00237032002-12-27 02:21:51 +00001007/* Classify two objects as to whether they're naive or offset-aware.
1008 * This isn't quite the same as calling classify_utcoffset() twice: for
1009 * binary operations (comparison and subtraction), we generally want to
1010 * ignore the tzinfo members if they're identical. This is by design,
1011 * so that results match "naive" expectations when mixing objects from a
1012 * single timezone. So in that case, this sets both offsets to 0 and
1013 * both naiveties to OFFSET_NAIVE.
1014 * The function returns 0 if everything's OK, and -1 on error.
1015 */
1016static int
1017classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001018 PyObject *tzinfoarg1,
1019 PyObject *o2, int *offset2, naivety *n2,
1020 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001021{
1022 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1023 *offset1 = *offset2 = 0;
1024 *n1 = *n2 = OFFSET_NAIVE;
1025 }
1026 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001027 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001028 if (*n1 == OFFSET_ERROR)
1029 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001030 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001031 if (*n2 == OFFSET_ERROR)
1032 return -1;
1033 }
1034 return 0;
1035}
1036
Tim Peters2a799bf2002-12-16 20:18:38 +00001037/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1038 * stuff
1039 * ", tzinfo=" + repr(tzinfo)
1040 * before the closing ")".
1041 */
1042static PyObject *
1043append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1044{
1045 PyObject *temp;
1046
Walter Dörwald1ab83302007-05-18 17:15:44 +00001047 assert(PyUnicode_Check(repr));
Tim Peters2a799bf2002-12-16 20:18:38 +00001048 assert(tzinfo);
1049 if (tzinfo == Py_None)
1050 return repr;
1051 /* Get rid of the trailing ')'. */
Walter Dörwald1ab83302007-05-18 17:15:44 +00001052 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1053 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1054 PyUnicode_GET_SIZE(repr) - 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001055 Py_DECREF(repr);
1056 if (temp == NULL)
1057 return NULL;
Walter Dörwald517bcfe2007-05-23 20:45:05 +00001058 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1059 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00001060 return repr;
1061}
1062
1063/* ---------------------------------------------------------------------------
1064 * String format helpers.
1065 */
1066
1067static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001068format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001069{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001070 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001071 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1072 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001073 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001074 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1075 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1076 };
1077
1078 char buffer[128];
1079 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1080
1081 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1082 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1083 GET_DAY(date), hours, minutes, seconds,
1084 GET_YEAR(date));
1085 return PyString_FromString(buffer);
1086}
1087
1088/* Add an hours & minutes UTC offset string to buf. buf has no more than
1089 * buflen bytes remaining. The UTC offset is gotten by calling
1090 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1091 * *buf, and that's all. Else the returned value is checked for sanity (an
1092 * integer in range), and if that's OK it's converted to an hours & minutes
1093 * string of the form
1094 * sign HH sep MM
1095 * Returns 0 if everything is OK. If the return value from utcoffset() is
1096 * bogus, an appropriate exception is set and -1 is returned.
1097 */
1098static int
Tim Peters328fff72002-12-20 01:31:27 +00001099format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001100 PyObject *tzinfo, PyObject *tzinfoarg)
1101{
1102 int offset;
1103 int hours;
1104 int minutes;
1105 char sign;
1106 int none;
1107
1108 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1109 if (offset == -1 && PyErr_Occurred())
1110 return -1;
1111 if (none) {
1112 *buf = '\0';
1113 return 0;
1114 }
1115 sign = '+';
1116 if (offset < 0) {
1117 sign = '-';
1118 offset = - offset;
1119 }
1120 hours = divmod(offset, 60, &minutes);
1121 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1122 return 0;
1123}
1124
1125/* I sure don't want to reproduce the strftime code from the time module,
1126 * so this imports the module and calls it. All the hair is due to
1127 * giving special meanings to the %z and %Z format codes via a preprocessing
1128 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001129 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1130 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001131 */
1132static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001133wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1134 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001135{
1136 PyObject *result = NULL; /* guilty until proved innocent */
1137
1138 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1139 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1140
Guido van Rossumbce56a62007-05-10 18:04:33 +00001141 const char *pin;/* pointer to next char in input format */
1142 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001143 char ch; /* next char in input format */
1144
1145 PyObject *newfmt = NULL; /* py string, the output format */
1146 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001147 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001148 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001149 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001150
Guido van Rossumbce56a62007-05-10 18:04:33 +00001151 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001152 int ntoappend; /* # of bytes to append to output buffer */
1153
Tim Peters2a799bf2002-12-16 20:18:38 +00001154 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001155 assert(PyString_Check(format) || PyUnicode_Check(format));
1156
1157 /* Convert the input format to a C string and size */
1158 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1159 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001160
Tim Petersd6844152002-12-22 20:58:42 +00001161 /* Give up if the year is before 1900.
1162 * Python strftime() plays games with the year, and different
1163 * games depending on whether envar PYTHON2K is set. This makes
1164 * years before 1900 a nightmare, even if the platform strftime
1165 * supports them (and not all do).
1166 * We could get a lot farther here by avoiding Python's strftime
1167 * wrapper and calling the C strftime() directly, but that isn't
1168 * an option in the Python implementation of this module.
1169 */
1170 {
1171 long year;
1172 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1173 if (pyyear == NULL) return NULL;
1174 assert(PyInt_Check(pyyear));
1175 year = PyInt_AsLong(pyyear);
1176 Py_DECREF(pyyear);
1177 if (year < 1900) {
1178 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1179 "1900; the datetime strftime() "
1180 "methods require year >= 1900",
1181 year);
1182 return NULL;
1183 }
1184 }
1185
Tim Peters2a799bf2002-12-16 20:18:38 +00001186 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001187 * a new format. Since computing the replacements for those codes
1188 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001189 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001190 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001191 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1192 if (newfmt == NULL) goto Done;
1193 pnew = PyString_AsString(newfmt);
1194 usednew = 0;
1195
Tim Peters2a799bf2002-12-16 20:18:38 +00001196 while ((ch = *pin++) != '\0') {
1197 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001198 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001199 ntoappend = 1;
1200 }
1201 else if ((ch = *pin++) == '\0') {
1202 /* There's a lone trailing %; doesn't make sense. */
1203 PyErr_SetString(PyExc_ValueError, "strftime format "
1204 "ends with raw %");
1205 goto Done;
1206 }
1207 /* A % has been seen and ch is the character after it. */
1208 else if (ch == 'z') {
1209 if (zreplacement == NULL) {
1210 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001211 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001212 PyObject *tzinfo = get_tzinfo_member(object);
1213 zreplacement = PyString_FromString("");
1214 if (zreplacement == NULL) goto Done;
1215 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001216 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001217 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001218 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001219 "",
1220 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001221 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001222 goto Done;
1223 Py_DECREF(zreplacement);
1224 zreplacement = PyString_FromString(buf);
1225 if (zreplacement == NULL) goto Done;
1226 }
1227 }
1228 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001229 ptoappend = PyString_AS_STRING(zreplacement);
1230 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001231 }
1232 else if (ch == 'Z') {
1233 /* format tzname */
1234 if (Zreplacement == NULL) {
1235 PyObject *tzinfo = get_tzinfo_member(object);
1236 Zreplacement = PyString_FromString("");
1237 if (Zreplacement == NULL) goto Done;
1238 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001239 PyObject *temp;
1240 assert(tzinfoarg != NULL);
1241 temp = call_tzname(tzinfo, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001242 if (temp == NULL) goto Done;
1243 if (temp != Py_None) {
1244 assert(PyString_Check(temp));
1245 /* Since the tzname is getting
1246 * stuffed into the format, we
1247 * have to double any % signs
1248 * so that strftime doesn't
1249 * treat them as format codes.
1250 */
1251 Py_DECREF(Zreplacement);
1252 Zreplacement = PyObject_CallMethod(
1253 temp, "replace",
1254 "ss", "%", "%%");
1255 Py_DECREF(temp);
1256 if (Zreplacement == NULL)
1257 goto Done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001258 if (!PyString_Check(Zreplacement)) {
1259 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1260 goto Done;
1261 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001262 }
1263 else
1264 Py_DECREF(temp);
1265 }
1266 }
1267 assert(Zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001268 ptoappend = PyString_AS_STRING(Zreplacement);
1269 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001270 }
1271 else {
Tim Peters328fff72002-12-20 01:31:27 +00001272 /* percent followed by neither z nor Z */
1273 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001274 ntoappend = 2;
1275 }
1276
1277 /* Append the ntoappend chars starting at ptoappend to
1278 * the new format.
1279 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001280 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001281 assert(ntoappend >= 0);
1282 if (ntoappend == 0)
1283 continue;
1284 while (usednew + ntoappend > totalnew) {
1285 int bigger = totalnew << 1;
1286 if ((bigger >> 1) != totalnew) { /* overflow */
1287 PyErr_NoMemory();
1288 goto Done;
1289 }
1290 if (_PyString_Resize(&newfmt, bigger) < 0)
1291 goto Done;
1292 totalnew = bigger;
1293 pnew = PyString_AsString(newfmt) + usednew;
1294 }
1295 memcpy(pnew, ptoappend, ntoappend);
1296 pnew += ntoappend;
1297 usednew += ntoappend;
1298 assert(usednew <= totalnew);
1299 } /* end while() */
1300
1301 if (_PyString_Resize(&newfmt, usednew) < 0)
1302 goto Done;
1303 {
1304 PyObject *time = PyImport_ImportModule("time");
1305 if (time == NULL)
1306 goto Done;
1307 result = PyObject_CallMethod(time, "strftime", "OO",
1308 newfmt, timetuple);
1309 Py_DECREF(time);
1310 }
1311 Done:
1312 Py_XDECREF(zreplacement);
1313 Py_XDECREF(Zreplacement);
1314 Py_XDECREF(newfmt);
1315 return result;
1316}
1317
1318static char *
1319isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1320{
1321 int x;
1322 x = PyOS_snprintf(buffer, bufflen,
1323 "%04d-%02d-%02d",
1324 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1325 return buffer + x;
1326}
1327
1328static void
1329isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1330{
1331 int us = DATE_GET_MICROSECOND(dt);
1332
1333 PyOS_snprintf(buffer, bufflen,
1334 "%02d:%02d:%02d", /* 8 characters */
1335 DATE_GET_HOUR(dt),
1336 DATE_GET_MINUTE(dt),
1337 DATE_GET_SECOND(dt));
1338 if (us)
1339 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1340}
1341
1342/* ---------------------------------------------------------------------------
1343 * Wrap functions from the time module. These aren't directly available
1344 * from C. Perhaps they should be.
1345 */
1346
1347/* Call time.time() and return its result (a Python float). */
1348static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001349time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001350{
1351 PyObject *result = NULL;
1352 PyObject *time = PyImport_ImportModule("time");
1353
1354 if (time != NULL) {
1355 result = PyObject_CallMethod(time, "time", "()");
1356 Py_DECREF(time);
1357 }
1358 return result;
1359}
1360
1361/* Build a time.struct_time. The weekday and day number are automatically
1362 * computed from the y,m,d args.
1363 */
1364static PyObject *
1365build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1366{
1367 PyObject *time;
1368 PyObject *result = NULL;
1369
1370 time = PyImport_ImportModule("time");
1371 if (time != NULL) {
1372 result = PyObject_CallMethod(time, "struct_time",
1373 "((iiiiiiiii))",
1374 y, m, d,
1375 hh, mm, ss,
1376 weekday(y, m, d),
1377 days_before_month(y, m) + d,
1378 dstflag);
1379 Py_DECREF(time);
1380 }
1381 return result;
1382}
1383
1384/* ---------------------------------------------------------------------------
1385 * Miscellaneous helpers.
1386 */
1387
Guido van Rossum19960592006-08-24 17:29:38 +00001388/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001389 * The comparisons here all most naturally compute a cmp()-like result.
1390 * This little helper turns that into a bool result for rich comparisons.
1391 */
1392static PyObject *
1393diff_to_bool(int diff, int op)
1394{
1395 PyObject *result;
1396 int istrue;
1397
1398 switch (op) {
1399 case Py_EQ: istrue = diff == 0; break;
1400 case Py_NE: istrue = diff != 0; break;
1401 case Py_LE: istrue = diff <= 0; break;
1402 case Py_GE: istrue = diff >= 0; break;
1403 case Py_LT: istrue = diff < 0; break;
1404 case Py_GT: istrue = diff > 0; break;
1405 default:
1406 assert(! "op unknown");
1407 istrue = 0; /* To shut up compiler */
1408 }
1409 result = istrue ? Py_True : Py_False;
1410 Py_INCREF(result);
1411 return result;
1412}
1413
Tim Peters07534a62003-02-07 22:50:28 +00001414/* Raises a "can't compare" TypeError and returns NULL. */
1415static PyObject *
1416cmperror(PyObject *a, PyObject *b)
1417{
1418 PyErr_Format(PyExc_TypeError,
1419 "can't compare %s to %s",
1420 a->ob_type->tp_name, b->ob_type->tp_name);
1421 return NULL;
1422}
1423
Tim Peters2a799bf2002-12-16 20:18:38 +00001424/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001425 * Cached Python objects; these are set by the module init function.
1426 */
1427
1428/* Conversion factors. */
1429static PyObject *us_per_us = NULL; /* 1 */
1430static PyObject *us_per_ms = NULL; /* 1000 */
1431static PyObject *us_per_second = NULL; /* 1000000 */
1432static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1433static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1434static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1435static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1436static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1437
Tim Peters2a799bf2002-12-16 20:18:38 +00001438/* ---------------------------------------------------------------------------
1439 * Class implementations.
1440 */
1441
1442/*
1443 * PyDateTime_Delta implementation.
1444 */
1445
1446/* Convert a timedelta to a number of us,
1447 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1448 * as a Python int or long.
1449 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1450 * due to ubiquitous overflow possibilities.
1451 */
1452static PyObject *
1453delta_to_microseconds(PyDateTime_Delta *self)
1454{
1455 PyObject *x1 = NULL;
1456 PyObject *x2 = NULL;
1457 PyObject *x3 = NULL;
1458 PyObject *result = NULL;
1459
1460 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1461 if (x1 == NULL)
1462 goto Done;
1463 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1464 if (x2 == NULL)
1465 goto Done;
1466 Py_DECREF(x1);
1467 x1 = NULL;
1468
1469 /* x2 has days in seconds */
1470 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1471 if (x1 == NULL)
1472 goto Done;
1473 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1474 if (x3 == NULL)
1475 goto Done;
1476 Py_DECREF(x1);
1477 Py_DECREF(x2);
1478 x1 = x2 = NULL;
1479
1480 /* x3 has days+seconds in seconds */
1481 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1482 if (x1 == NULL)
1483 goto Done;
1484 Py_DECREF(x3);
1485 x3 = NULL;
1486
1487 /* x1 has days+seconds in us */
1488 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1489 if (x2 == NULL)
1490 goto Done;
1491 result = PyNumber_Add(x1, x2);
1492
1493Done:
1494 Py_XDECREF(x1);
1495 Py_XDECREF(x2);
1496 Py_XDECREF(x3);
1497 return result;
1498}
1499
1500/* Convert a number of us (as a Python int or long) to a timedelta.
1501 */
1502static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001503microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001504{
1505 int us;
1506 int s;
1507 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001508 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001509
1510 PyObject *tuple = NULL;
1511 PyObject *num = NULL;
1512 PyObject *result = NULL;
1513
1514 tuple = PyNumber_Divmod(pyus, us_per_second);
1515 if (tuple == NULL)
1516 goto Done;
1517
1518 num = PyTuple_GetItem(tuple, 1); /* us */
1519 if (num == NULL)
1520 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001521 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001522 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001523 if (temp == -1 && PyErr_Occurred())
1524 goto Done;
1525 assert(0 <= temp && temp < 1000000);
1526 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001527 if (us < 0) {
1528 /* The divisor was positive, so this must be an error. */
1529 assert(PyErr_Occurred());
1530 goto Done;
1531 }
1532
1533 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1534 if (num == NULL)
1535 goto Done;
1536 Py_INCREF(num);
1537 Py_DECREF(tuple);
1538
1539 tuple = PyNumber_Divmod(num, seconds_per_day);
1540 if (tuple == NULL)
1541 goto Done;
1542 Py_DECREF(num);
1543
1544 num = PyTuple_GetItem(tuple, 1); /* seconds */
1545 if (num == NULL)
1546 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001547 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001548 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001549 if (temp == -1 && PyErr_Occurred())
1550 goto Done;
1551 assert(0 <= temp && temp < 24*3600);
1552 s = (int)temp;
1553
Tim Peters2a799bf2002-12-16 20:18:38 +00001554 if (s < 0) {
1555 /* The divisor was positive, so this must be an error. */
1556 assert(PyErr_Occurred());
1557 goto Done;
1558 }
1559
1560 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1561 if (num == NULL)
1562 goto Done;
1563 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001564 temp = PyLong_AsLong(num);
1565 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001566 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001567 d = (int)temp;
1568 if ((long)d != temp) {
1569 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1570 "large to fit in a C int");
1571 goto Done;
1572 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001573 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001574
1575Done:
1576 Py_XDECREF(tuple);
1577 Py_XDECREF(num);
1578 return result;
1579}
1580
Tim Petersb0c854d2003-05-17 15:57:00 +00001581#define microseconds_to_delta(pymicros) \
1582 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1583
Tim Peters2a799bf2002-12-16 20:18:38 +00001584static PyObject *
1585multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1586{
1587 PyObject *pyus_in;
1588 PyObject *pyus_out;
1589 PyObject *result;
1590
1591 pyus_in = delta_to_microseconds(delta);
1592 if (pyus_in == NULL)
1593 return NULL;
1594
1595 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1596 Py_DECREF(pyus_in);
1597 if (pyus_out == NULL)
1598 return NULL;
1599
1600 result = microseconds_to_delta(pyus_out);
1601 Py_DECREF(pyus_out);
1602 return result;
1603}
1604
1605static PyObject *
1606divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1607{
1608 PyObject *pyus_in;
1609 PyObject *pyus_out;
1610 PyObject *result;
1611
1612 pyus_in = delta_to_microseconds(delta);
1613 if (pyus_in == NULL)
1614 return NULL;
1615
1616 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1617 Py_DECREF(pyus_in);
1618 if (pyus_out == NULL)
1619 return NULL;
1620
1621 result = microseconds_to_delta(pyus_out);
1622 Py_DECREF(pyus_out);
1623 return result;
1624}
1625
1626static PyObject *
1627delta_add(PyObject *left, PyObject *right)
1628{
1629 PyObject *result = Py_NotImplemented;
1630
1631 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1632 /* delta + delta */
1633 /* The C-level additions can't overflow because of the
1634 * invariant bounds.
1635 */
1636 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1637 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1638 int microseconds = GET_TD_MICROSECONDS(left) +
1639 GET_TD_MICROSECONDS(right);
1640 result = new_delta(days, seconds, microseconds, 1);
1641 }
1642
1643 if (result == Py_NotImplemented)
1644 Py_INCREF(result);
1645 return result;
1646}
1647
1648static PyObject *
1649delta_negative(PyDateTime_Delta *self)
1650{
1651 return new_delta(-GET_TD_DAYS(self),
1652 -GET_TD_SECONDS(self),
1653 -GET_TD_MICROSECONDS(self),
1654 1);
1655}
1656
1657static PyObject *
1658delta_positive(PyDateTime_Delta *self)
1659{
1660 /* Could optimize this (by returning self) if this isn't a
1661 * subclass -- but who uses unary + ? Approximately nobody.
1662 */
1663 return new_delta(GET_TD_DAYS(self),
1664 GET_TD_SECONDS(self),
1665 GET_TD_MICROSECONDS(self),
1666 0);
1667}
1668
1669static PyObject *
1670delta_abs(PyDateTime_Delta *self)
1671{
1672 PyObject *result;
1673
1674 assert(GET_TD_MICROSECONDS(self) >= 0);
1675 assert(GET_TD_SECONDS(self) >= 0);
1676
1677 if (GET_TD_DAYS(self) < 0)
1678 result = delta_negative(self);
1679 else
1680 result = delta_positive(self);
1681
1682 return result;
1683}
1684
1685static PyObject *
1686delta_subtract(PyObject *left, PyObject *right)
1687{
1688 PyObject *result = Py_NotImplemented;
1689
1690 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1691 /* delta - delta */
1692 PyObject *minus_right = PyNumber_Negative(right);
1693 if (minus_right) {
1694 result = delta_add(left, minus_right);
1695 Py_DECREF(minus_right);
1696 }
1697 else
1698 result = NULL;
1699 }
1700
1701 if (result == Py_NotImplemented)
1702 Py_INCREF(result);
1703 return result;
1704}
1705
Tim Peters2a799bf2002-12-16 20:18:38 +00001706static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001707delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001708{
Tim Petersaa7d8492003-02-08 03:28:59 +00001709 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001710 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001711 if (diff == 0) {
1712 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1713 if (diff == 0)
1714 diff = GET_TD_MICROSECONDS(self) -
1715 GET_TD_MICROSECONDS(other);
1716 }
Guido van Rossum19960592006-08-24 17:29:38 +00001717 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001718 }
Guido van Rossum19960592006-08-24 17:29:38 +00001719 else {
1720 Py_INCREF(Py_NotImplemented);
1721 return Py_NotImplemented;
1722 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001723}
1724
1725static PyObject *delta_getstate(PyDateTime_Delta *self);
1726
1727static long
1728delta_hash(PyDateTime_Delta *self)
1729{
1730 if (self->hashcode == -1) {
1731 PyObject *temp = delta_getstate(self);
1732 if (temp != NULL) {
1733 self->hashcode = PyObject_Hash(temp);
1734 Py_DECREF(temp);
1735 }
1736 }
1737 return self->hashcode;
1738}
1739
1740static PyObject *
1741delta_multiply(PyObject *left, PyObject *right)
1742{
1743 PyObject *result = Py_NotImplemented;
1744
1745 if (PyDelta_Check(left)) {
1746 /* delta * ??? */
1747 if (PyInt_Check(right) || PyLong_Check(right))
1748 result = multiply_int_timedelta(right,
1749 (PyDateTime_Delta *) left);
1750 }
1751 else if (PyInt_Check(left) || PyLong_Check(left))
1752 result = multiply_int_timedelta(left,
1753 (PyDateTime_Delta *) right);
1754
1755 if (result == Py_NotImplemented)
1756 Py_INCREF(result);
1757 return result;
1758}
1759
1760static PyObject *
1761delta_divide(PyObject *left, PyObject *right)
1762{
1763 PyObject *result = Py_NotImplemented;
1764
1765 if (PyDelta_Check(left)) {
1766 /* delta * ??? */
1767 if (PyInt_Check(right) || PyLong_Check(right))
1768 result = divide_timedelta_int(
1769 (PyDateTime_Delta *)left,
1770 right);
1771 }
1772
1773 if (result == Py_NotImplemented)
1774 Py_INCREF(result);
1775 return result;
1776}
1777
1778/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1779 * timedelta constructor. sofar is the # of microseconds accounted for
1780 * so far, and there are factor microseconds per current unit, the number
1781 * of which is given by num. num * factor is added to sofar in a
1782 * numerically careful way, and that's the result. Any fractional
1783 * microseconds left over (this can happen if num is a float type) are
1784 * added into *leftover.
1785 * Note that there are many ways this can give an error (NULL) return.
1786 */
1787static PyObject *
1788accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1789 double *leftover)
1790{
1791 PyObject *prod;
1792 PyObject *sum;
1793
1794 assert(num != NULL);
1795
1796 if (PyInt_Check(num) || PyLong_Check(num)) {
1797 prod = PyNumber_Multiply(num, factor);
1798 if (prod == NULL)
1799 return NULL;
1800 sum = PyNumber_Add(sofar, prod);
1801 Py_DECREF(prod);
1802 return sum;
1803 }
1804
1805 if (PyFloat_Check(num)) {
1806 double dnum;
1807 double fracpart;
1808 double intpart;
1809 PyObject *x;
1810 PyObject *y;
1811
1812 /* The Plan: decompose num into an integer part and a
1813 * fractional part, num = intpart + fracpart.
1814 * Then num * factor ==
1815 * intpart * factor + fracpart * factor
1816 * and the LHS can be computed exactly in long arithmetic.
1817 * The RHS is again broken into an int part and frac part.
1818 * and the frac part is added into *leftover.
1819 */
1820 dnum = PyFloat_AsDouble(num);
1821 if (dnum == -1.0 && PyErr_Occurred())
1822 return NULL;
1823 fracpart = modf(dnum, &intpart);
1824 x = PyLong_FromDouble(intpart);
1825 if (x == NULL)
1826 return NULL;
1827
1828 prod = PyNumber_Multiply(x, factor);
1829 Py_DECREF(x);
1830 if (prod == NULL)
1831 return NULL;
1832
1833 sum = PyNumber_Add(sofar, prod);
1834 Py_DECREF(prod);
1835 if (sum == NULL)
1836 return NULL;
1837
1838 if (fracpart == 0.0)
1839 return sum;
1840 /* So far we've lost no information. Dealing with the
1841 * fractional part requires float arithmetic, and may
1842 * lose a little info.
1843 */
1844 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001845 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001846
1847 dnum *= fracpart;
1848 fracpart = modf(dnum, &intpart);
1849 x = PyLong_FromDouble(intpart);
1850 if (x == NULL) {
1851 Py_DECREF(sum);
1852 return NULL;
1853 }
1854
1855 y = PyNumber_Add(sum, x);
1856 Py_DECREF(sum);
1857 Py_DECREF(x);
1858 *leftover += fracpart;
1859 return y;
1860 }
1861
1862 PyErr_Format(PyExc_TypeError,
1863 "unsupported type for timedelta %s component: %s",
1864 tag, num->ob_type->tp_name);
1865 return NULL;
1866}
1867
1868static PyObject *
1869delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1870{
1871 PyObject *self = NULL;
1872
1873 /* Argument objects. */
1874 PyObject *day = NULL;
1875 PyObject *second = NULL;
1876 PyObject *us = NULL;
1877 PyObject *ms = NULL;
1878 PyObject *minute = NULL;
1879 PyObject *hour = NULL;
1880 PyObject *week = NULL;
1881
1882 PyObject *x = NULL; /* running sum of microseconds */
1883 PyObject *y = NULL; /* temp sum of microseconds */
1884 double leftover_us = 0.0;
1885
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001886 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001887 "days", "seconds", "microseconds", "milliseconds",
1888 "minutes", "hours", "weeks", NULL
1889 };
1890
1891 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1892 keywords,
1893 &day, &second, &us,
1894 &ms, &minute, &hour, &week) == 0)
1895 goto Done;
1896
1897 x = PyInt_FromLong(0);
1898 if (x == NULL)
1899 goto Done;
1900
1901#define CLEANUP \
1902 Py_DECREF(x); \
1903 x = y; \
1904 if (x == NULL) \
1905 goto Done
1906
1907 if (us) {
1908 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1909 CLEANUP;
1910 }
1911 if (ms) {
1912 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1913 CLEANUP;
1914 }
1915 if (second) {
1916 y = accum("seconds", x, second, us_per_second, &leftover_us);
1917 CLEANUP;
1918 }
1919 if (minute) {
1920 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1921 CLEANUP;
1922 }
1923 if (hour) {
1924 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1925 CLEANUP;
1926 }
1927 if (day) {
1928 y = accum("days", x, day, us_per_day, &leftover_us);
1929 CLEANUP;
1930 }
1931 if (week) {
1932 y = accum("weeks", x, week, us_per_week, &leftover_us);
1933 CLEANUP;
1934 }
1935 if (leftover_us) {
1936 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001937 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001938 if (temp == NULL) {
1939 Py_DECREF(x);
1940 goto Done;
1941 }
1942 y = PyNumber_Add(x, temp);
1943 Py_DECREF(temp);
1944 CLEANUP;
1945 }
1946
Tim Petersb0c854d2003-05-17 15:57:00 +00001947 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001948 Py_DECREF(x);
1949Done:
1950 return self;
1951
1952#undef CLEANUP
1953}
1954
1955static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001956delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001957{
1958 return (GET_TD_DAYS(self) != 0
1959 || GET_TD_SECONDS(self) != 0
1960 || GET_TD_MICROSECONDS(self) != 0);
1961}
1962
1963static PyObject *
1964delta_repr(PyDateTime_Delta *self)
1965{
1966 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001967 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001968 self->ob_type->tp_name,
1969 GET_TD_DAYS(self),
1970 GET_TD_SECONDS(self),
1971 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001972 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001973 return PyUnicode_FromFormat("%s(%d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001974 self->ob_type->tp_name,
1975 GET_TD_DAYS(self),
1976 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001977
Walter Dörwald1ab83302007-05-18 17:15:44 +00001978 return PyUnicode_FromFormat("%s(%d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001979 self->ob_type->tp_name,
1980 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001981}
1982
1983static PyObject *
1984delta_str(PyDateTime_Delta *self)
1985{
1986 int days = GET_TD_DAYS(self);
1987 int seconds = GET_TD_SECONDS(self);
1988 int us = GET_TD_MICROSECONDS(self);
1989 int hours;
1990 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00001991 char buf[100];
1992 char *pbuf = buf;
1993 size_t buflen = sizeof(buf);
1994 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001995
1996 minutes = divmod(seconds, 60, &seconds);
1997 hours = divmod(minutes, 60, &minutes);
1998
1999 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002000 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2001 (days == 1 || days == -1) ? "" : "s");
2002 if (n < 0 || (size_t)n >= buflen)
2003 goto Fail;
2004 pbuf += n;
2005 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002006 }
2007
Tim Petersba873472002-12-18 20:19:21 +00002008 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2009 hours, minutes, seconds);
2010 if (n < 0 || (size_t)n >= buflen)
2011 goto Fail;
2012 pbuf += n;
2013 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002014
2015 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002016 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2017 if (n < 0 || (size_t)n >= buflen)
2018 goto Fail;
2019 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002020 }
2021
Tim Petersba873472002-12-18 20:19:21 +00002022 return PyString_FromStringAndSize(buf, pbuf - buf);
2023
2024 Fail:
2025 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2026 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002027}
2028
Tim Peters371935f2003-02-01 01:52:50 +00002029/* Pickle support, a simple use of __reduce__. */
2030
Tim Petersb57f8f02003-02-01 02:54:15 +00002031/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002032static PyObject *
2033delta_getstate(PyDateTime_Delta *self)
2034{
2035 return Py_BuildValue("iii", GET_TD_DAYS(self),
2036 GET_TD_SECONDS(self),
2037 GET_TD_MICROSECONDS(self));
2038}
2039
Tim Peters2a799bf2002-12-16 20:18:38 +00002040static PyObject *
2041delta_reduce(PyDateTime_Delta* self)
2042{
Tim Peters8a60c222003-02-01 01:47:29 +00002043 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002044}
2045
2046#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2047
2048static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002049
Neal Norwitzdfb80862002-12-19 02:30:56 +00002050 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002051 PyDoc_STR("Number of days.")},
2052
Neal Norwitzdfb80862002-12-19 02:30:56 +00002053 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002054 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2055
Neal Norwitzdfb80862002-12-19 02:30:56 +00002056 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002057 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2058 {NULL}
2059};
2060
2061static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002062 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2063 PyDoc_STR("__reduce__() -> (cls, state)")},
2064
Tim Peters2a799bf2002-12-16 20:18:38 +00002065 {NULL, NULL},
2066};
2067
2068static char delta_doc[] =
2069PyDoc_STR("Difference between two datetime values.");
2070
2071static PyNumberMethods delta_as_number = {
2072 delta_add, /* nb_add */
2073 delta_subtract, /* nb_subtract */
2074 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002075 0, /* nb_remainder */
2076 0, /* nb_divmod */
2077 0, /* nb_power */
2078 (unaryfunc)delta_negative, /* nb_negative */
2079 (unaryfunc)delta_positive, /* nb_positive */
2080 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002081 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002082 0, /*nb_invert*/
2083 0, /*nb_lshift*/
2084 0, /*nb_rshift*/
2085 0, /*nb_and*/
2086 0, /*nb_xor*/
2087 0, /*nb_or*/
2088 0, /*nb_coerce*/
2089 0, /*nb_int*/
2090 0, /*nb_long*/
2091 0, /*nb_float*/
2092 0, /*nb_oct*/
2093 0, /*nb_hex*/
2094 0, /*nb_inplace_add*/
2095 0, /*nb_inplace_subtract*/
2096 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002097 0, /*nb_inplace_remainder*/
2098 0, /*nb_inplace_power*/
2099 0, /*nb_inplace_lshift*/
2100 0, /*nb_inplace_rshift*/
2101 0, /*nb_inplace_and*/
2102 0, /*nb_inplace_xor*/
2103 0, /*nb_inplace_or*/
2104 delta_divide, /* nb_floor_divide */
2105 0, /* nb_true_divide */
2106 0, /* nb_inplace_floor_divide */
2107 0, /* nb_inplace_true_divide */
2108};
2109
2110static PyTypeObject PyDateTime_DeltaType = {
2111 PyObject_HEAD_INIT(NULL)
2112 0, /* ob_size */
2113 "datetime.timedelta", /* tp_name */
2114 sizeof(PyDateTime_Delta), /* tp_basicsize */
2115 0, /* tp_itemsize */
2116 0, /* tp_dealloc */
2117 0, /* tp_print */
2118 0, /* tp_getattr */
2119 0, /* tp_setattr */
2120 0, /* tp_compare */
2121 (reprfunc)delta_repr, /* tp_repr */
2122 &delta_as_number, /* tp_as_number */
2123 0, /* tp_as_sequence */
2124 0, /* tp_as_mapping */
2125 (hashfunc)delta_hash, /* tp_hash */
2126 0, /* tp_call */
2127 (reprfunc)delta_str, /* tp_str */
2128 PyObject_GenericGetAttr, /* tp_getattro */
2129 0, /* tp_setattro */
2130 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002131 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002132 delta_doc, /* tp_doc */
2133 0, /* tp_traverse */
2134 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002135 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002136 0, /* tp_weaklistoffset */
2137 0, /* tp_iter */
2138 0, /* tp_iternext */
2139 delta_methods, /* tp_methods */
2140 delta_members, /* tp_members */
2141 0, /* tp_getset */
2142 0, /* tp_base */
2143 0, /* tp_dict */
2144 0, /* tp_descr_get */
2145 0, /* tp_descr_set */
2146 0, /* tp_dictoffset */
2147 0, /* tp_init */
2148 0, /* tp_alloc */
2149 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002150 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002151};
2152
2153/*
2154 * PyDateTime_Date implementation.
2155 */
2156
2157/* Accessor properties. */
2158
2159static PyObject *
2160date_year(PyDateTime_Date *self, void *unused)
2161{
2162 return PyInt_FromLong(GET_YEAR(self));
2163}
2164
2165static PyObject *
2166date_month(PyDateTime_Date *self, void *unused)
2167{
2168 return PyInt_FromLong(GET_MONTH(self));
2169}
2170
2171static PyObject *
2172date_day(PyDateTime_Date *self, void *unused)
2173{
2174 return PyInt_FromLong(GET_DAY(self));
2175}
2176
2177static PyGetSetDef date_getset[] = {
2178 {"year", (getter)date_year},
2179 {"month", (getter)date_month},
2180 {"day", (getter)date_day},
2181 {NULL}
2182};
2183
2184/* Constructors. */
2185
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002186static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002187
Tim Peters2a799bf2002-12-16 20:18:38 +00002188static PyObject *
2189date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2190{
2191 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002192 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002193 int year;
2194 int month;
2195 int day;
2196
Guido van Rossum177e41a2003-01-30 22:06:23 +00002197 /* Check for invocation from pickle with __getstate__ state */
2198 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002199 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002200 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2201 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002202 {
Tim Peters70533e22003-02-01 04:40:04 +00002203 PyDateTime_Date *me;
2204
Tim Peters604c0132004-06-07 23:04:33 +00002205 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002206 if (me != NULL) {
2207 char *pdata = PyString_AS_STRING(state);
2208 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2209 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002210 }
Tim Peters70533e22003-02-01 04:40:04 +00002211 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002212 }
2213
Tim Peters12bf3392002-12-24 05:41:27 +00002214 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002215 &year, &month, &day)) {
2216 if (check_date_args(year, month, day) < 0)
2217 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002218 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002219 }
2220 return self;
2221}
2222
2223/* Return new date from localtime(t). */
2224static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002225date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002226{
2227 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002228 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002229 PyObject *result = NULL;
2230
Tim Peters1b6f7a92004-06-20 02:50:16 +00002231 t = _PyTime_DoubleToTimet(ts);
2232 if (t == (time_t)-1 && PyErr_Occurred())
2233 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002234 tm = localtime(&t);
2235 if (tm)
2236 result = PyObject_CallFunction(cls, "iii",
2237 tm->tm_year + 1900,
2238 tm->tm_mon + 1,
2239 tm->tm_mday);
2240 else
2241 PyErr_SetString(PyExc_ValueError,
2242 "timestamp out of range for "
2243 "platform localtime() function");
2244 return result;
2245}
2246
2247/* Return new date from current time.
2248 * We say this is equivalent to fromtimestamp(time.time()), and the
2249 * only way to be sure of that is to *call* time.time(). That's not
2250 * generally the same as calling C's time.
2251 */
2252static PyObject *
2253date_today(PyObject *cls, PyObject *dummy)
2254{
2255 PyObject *time;
2256 PyObject *result;
2257
2258 time = time_time();
2259 if (time == NULL)
2260 return NULL;
2261
2262 /* Note well: today() is a class method, so this may not call
2263 * date.fromtimestamp. For example, it may call
2264 * datetime.fromtimestamp. That's why we need all the accuracy
2265 * time.time() delivers; if someone were gonzo about optimization,
2266 * date.today() could get away with plain C time().
2267 */
2268 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2269 Py_DECREF(time);
2270 return result;
2271}
2272
2273/* Return new date from given timestamp (Python timestamp -- a double). */
2274static PyObject *
2275date_fromtimestamp(PyObject *cls, PyObject *args)
2276{
2277 double timestamp;
2278 PyObject *result = NULL;
2279
2280 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002281 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002282 return result;
2283}
2284
2285/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2286 * the ordinal is out of range.
2287 */
2288static PyObject *
2289date_fromordinal(PyObject *cls, PyObject *args)
2290{
2291 PyObject *result = NULL;
2292 int ordinal;
2293
2294 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2295 int year;
2296 int month;
2297 int day;
2298
2299 if (ordinal < 1)
2300 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2301 ">= 1");
2302 else {
2303 ord_to_ymd(ordinal, &year, &month, &day);
2304 result = PyObject_CallFunction(cls, "iii",
2305 year, month, day);
2306 }
2307 }
2308 return result;
2309}
2310
2311/*
2312 * Date arithmetic.
2313 */
2314
2315/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2316 * instead.
2317 */
2318static PyObject *
2319add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2320{
2321 PyObject *result = NULL;
2322 int year = GET_YEAR(date);
2323 int month = GET_MONTH(date);
2324 int deltadays = GET_TD_DAYS(delta);
2325 /* C-level overflow is impossible because |deltadays| < 1e9. */
2326 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2327
2328 if (normalize_date(&year, &month, &day) >= 0)
2329 result = new_date(year, month, day);
2330 return result;
2331}
2332
2333static PyObject *
2334date_add(PyObject *left, PyObject *right)
2335{
2336 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2337 Py_INCREF(Py_NotImplemented);
2338 return Py_NotImplemented;
2339 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002340 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002341 /* date + ??? */
2342 if (PyDelta_Check(right))
2343 /* date + delta */
2344 return add_date_timedelta((PyDateTime_Date *) left,
2345 (PyDateTime_Delta *) right,
2346 0);
2347 }
2348 else {
2349 /* ??? + date
2350 * 'right' must be one of us, or we wouldn't have been called
2351 */
2352 if (PyDelta_Check(left))
2353 /* delta + date */
2354 return add_date_timedelta((PyDateTime_Date *) right,
2355 (PyDateTime_Delta *) left,
2356 0);
2357 }
2358 Py_INCREF(Py_NotImplemented);
2359 return Py_NotImplemented;
2360}
2361
2362static PyObject *
2363date_subtract(PyObject *left, PyObject *right)
2364{
2365 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2366 Py_INCREF(Py_NotImplemented);
2367 return Py_NotImplemented;
2368 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002369 if (PyDate_Check(left)) {
2370 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002371 /* date - date */
2372 int left_ord = ymd_to_ord(GET_YEAR(left),
2373 GET_MONTH(left),
2374 GET_DAY(left));
2375 int right_ord = ymd_to_ord(GET_YEAR(right),
2376 GET_MONTH(right),
2377 GET_DAY(right));
2378 return new_delta(left_ord - right_ord, 0, 0, 0);
2379 }
2380 if (PyDelta_Check(right)) {
2381 /* date - delta */
2382 return add_date_timedelta((PyDateTime_Date *) left,
2383 (PyDateTime_Delta *) right,
2384 1);
2385 }
2386 }
2387 Py_INCREF(Py_NotImplemented);
2388 return Py_NotImplemented;
2389}
2390
2391
2392/* Various ways to turn a date into a string. */
2393
2394static PyObject *
2395date_repr(PyDateTime_Date *self)
2396{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002397 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2398 self->ob_type->tp_name,
2399 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002400}
2401
2402static PyObject *
2403date_isoformat(PyDateTime_Date *self)
2404{
2405 char buffer[128];
2406
2407 isoformat_date(self, buffer, sizeof(buffer));
2408 return PyString_FromString(buffer);
2409}
2410
Tim Peterse2df5ff2003-05-02 18:39:55 +00002411/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002412static PyObject *
2413date_str(PyDateTime_Date *self)
2414{
2415 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2416}
2417
2418
2419static PyObject *
2420date_ctime(PyDateTime_Date *self)
2421{
2422 return format_ctime(self, 0, 0, 0);
2423}
2424
2425static PyObject *
2426date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2427{
2428 /* This method can be inherited, and needs to call the
2429 * timetuple() method appropriate to self's class.
2430 */
2431 PyObject *result;
2432 PyObject *format;
2433 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002434 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002435
Guido van Rossumbce56a62007-05-10 18:04:33 +00002436 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2437 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002438 return NULL;
2439
2440 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2441 if (tuple == NULL)
2442 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002443 result = wrap_strftime((PyObject *)self, format, tuple,
2444 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002445 Py_DECREF(tuple);
2446 return result;
2447}
2448
2449/* ISO methods. */
2450
2451static PyObject *
2452date_isoweekday(PyDateTime_Date *self)
2453{
2454 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2455
2456 return PyInt_FromLong(dow + 1);
2457}
2458
2459static PyObject *
2460date_isocalendar(PyDateTime_Date *self)
2461{
2462 int year = GET_YEAR(self);
2463 int week1_monday = iso_week1_monday(year);
2464 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2465 int week;
2466 int day;
2467
2468 week = divmod(today - week1_monday, 7, &day);
2469 if (week < 0) {
2470 --year;
2471 week1_monday = iso_week1_monday(year);
2472 week = divmod(today - week1_monday, 7, &day);
2473 }
2474 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2475 ++year;
2476 week = 0;
2477 }
2478 return Py_BuildValue("iii", year, week + 1, day + 1);
2479}
2480
2481/* Miscellaneous methods. */
2482
Tim Peters2a799bf2002-12-16 20:18:38 +00002483static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002484date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002485{
Guido van Rossum19960592006-08-24 17:29:38 +00002486 if (PyDate_Check(other)) {
2487 int diff = memcmp(((PyDateTime_Date *)self)->data,
2488 ((PyDateTime_Date *)other)->data,
2489 _PyDateTime_DATE_DATASIZE);
2490 return diff_to_bool(diff, op);
2491 }
2492 else {
Tim Peters07534a62003-02-07 22:50:28 +00002493 Py_INCREF(Py_NotImplemented);
2494 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002495 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002496}
2497
2498static PyObject *
2499date_timetuple(PyDateTime_Date *self)
2500{
2501 return build_struct_time(GET_YEAR(self),
2502 GET_MONTH(self),
2503 GET_DAY(self),
2504 0, 0, 0, -1);
2505}
2506
Tim Peters12bf3392002-12-24 05:41:27 +00002507static PyObject *
2508date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2509{
2510 PyObject *clone;
2511 PyObject *tuple;
2512 int year = GET_YEAR(self);
2513 int month = GET_MONTH(self);
2514 int day = GET_DAY(self);
2515
2516 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2517 &year, &month, &day))
2518 return NULL;
2519 tuple = Py_BuildValue("iii", year, month, day);
2520 if (tuple == NULL)
2521 return NULL;
2522 clone = date_new(self->ob_type, tuple, NULL);
2523 Py_DECREF(tuple);
2524 return clone;
2525}
2526
Tim Peters2a799bf2002-12-16 20:18:38 +00002527static PyObject *date_getstate(PyDateTime_Date *self);
2528
2529static long
2530date_hash(PyDateTime_Date *self)
2531{
2532 if (self->hashcode == -1) {
2533 PyObject *temp = date_getstate(self);
2534 if (temp != NULL) {
2535 self->hashcode = PyObject_Hash(temp);
2536 Py_DECREF(temp);
2537 }
2538 }
2539 return self->hashcode;
2540}
2541
2542static PyObject *
2543date_toordinal(PyDateTime_Date *self)
2544{
2545 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2546 GET_DAY(self)));
2547}
2548
2549static PyObject *
2550date_weekday(PyDateTime_Date *self)
2551{
2552 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2553
2554 return PyInt_FromLong(dow);
2555}
2556
Tim Peters371935f2003-02-01 01:52:50 +00002557/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002558
Tim Petersb57f8f02003-02-01 02:54:15 +00002559/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002560static PyObject *
2561date_getstate(PyDateTime_Date *self)
2562{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002563 return Py_BuildValue(
2564 "(N)",
2565 PyString_FromStringAndSize((char *)self->data,
2566 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002567}
2568
2569static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002570date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002571{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002572 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002573}
2574
2575static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002576
Tim Peters2a799bf2002-12-16 20:18:38 +00002577 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002578
Tim Peters2a799bf2002-12-16 20:18:38 +00002579 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2580 METH_CLASS,
2581 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2582 "time.time()).")},
2583
2584 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2585 METH_CLASS,
2586 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2587 "ordinal.")},
2588
2589 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2590 PyDoc_STR("Current date or datetime: same as "
2591 "self.__class__.fromtimestamp(time.time()).")},
2592
2593 /* Instance methods: */
2594
2595 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2596 PyDoc_STR("Return ctime() style string.")},
2597
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002598 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002599 PyDoc_STR("format -> strftime() style string.")},
2600
2601 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2602 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2603
2604 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2605 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2606 "weekday.")},
2607
2608 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2609 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2610
2611 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2612 PyDoc_STR("Return the day of the week represented by the date.\n"
2613 "Monday == 1 ... Sunday == 7")},
2614
2615 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2616 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2617 "1 is day 1.")},
2618
2619 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2620 PyDoc_STR("Return the day of the week represented by the date.\n"
2621 "Monday == 0 ... Sunday == 6")},
2622
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002623 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002624 PyDoc_STR("Return date with new specified fields.")},
2625
Guido van Rossum177e41a2003-01-30 22:06:23 +00002626 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2627 PyDoc_STR("__reduce__() -> (cls, state)")},
2628
Tim Peters2a799bf2002-12-16 20:18:38 +00002629 {NULL, NULL}
2630};
2631
2632static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002633PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002634
2635static PyNumberMethods date_as_number = {
2636 date_add, /* nb_add */
2637 date_subtract, /* nb_subtract */
2638 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002639 0, /* nb_remainder */
2640 0, /* nb_divmod */
2641 0, /* nb_power */
2642 0, /* nb_negative */
2643 0, /* nb_positive */
2644 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002645 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002646};
2647
2648static PyTypeObject PyDateTime_DateType = {
2649 PyObject_HEAD_INIT(NULL)
2650 0, /* ob_size */
2651 "datetime.date", /* tp_name */
2652 sizeof(PyDateTime_Date), /* tp_basicsize */
2653 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002654 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002655 0, /* tp_print */
2656 0, /* tp_getattr */
2657 0, /* tp_setattr */
2658 0, /* tp_compare */
2659 (reprfunc)date_repr, /* tp_repr */
2660 &date_as_number, /* tp_as_number */
2661 0, /* tp_as_sequence */
2662 0, /* tp_as_mapping */
2663 (hashfunc)date_hash, /* tp_hash */
2664 0, /* tp_call */
2665 (reprfunc)date_str, /* tp_str */
2666 PyObject_GenericGetAttr, /* tp_getattro */
2667 0, /* tp_setattro */
2668 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002669 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002670 date_doc, /* tp_doc */
2671 0, /* tp_traverse */
2672 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002673 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002674 0, /* tp_weaklistoffset */
2675 0, /* tp_iter */
2676 0, /* tp_iternext */
2677 date_methods, /* tp_methods */
2678 0, /* tp_members */
2679 date_getset, /* tp_getset */
2680 0, /* tp_base */
2681 0, /* tp_dict */
2682 0, /* tp_descr_get */
2683 0, /* tp_descr_set */
2684 0, /* tp_dictoffset */
2685 0, /* tp_init */
2686 0, /* tp_alloc */
2687 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002688 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002689};
2690
2691/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002692 * PyDateTime_TZInfo implementation.
2693 */
2694
2695/* This is a pure abstract base class, so doesn't do anything beyond
2696 * raising NotImplemented exceptions. Real tzinfo classes need
2697 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002698 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002699 * be subclasses of this tzinfo class, which is easy and quick to check).
2700 *
2701 * Note: For reasons having to do with pickling of subclasses, we have
2702 * to allow tzinfo objects to be instantiated. This wasn't an issue
2703 * in the Python implementation (__init__() could raise NotImplementedError
2704 * there without ill effect), but doing so in the C implementation hit a
2705 * brick wall.
2706 */
2707
2708static PyObject *
2709tzinfo_nogo(const char* methodname)
2710{
2711 PyErr_Format(PyExc_NotImplementedError,
2712 "a tzinfo subclass must implement %s()",
2713 methodname);
2714 return NULL;
2715}
2716
2717/* Methods. A subclass must implement these. */
2718
Tim Peters52dcce22003-01-23 16:36:11 +00002719static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002720tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2721{
2722 return tzinfo_nogo("tzname");
2723}
2724
Tim Peters52dcce22003-01-23 16:36:11 +00002725static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002726tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2727{
2728 return tzinfo_nogo("utcoffset");
2729}
2730
Tim Peters52dcce22003-01-23 16:36:11 +00002731static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002732tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2733{
2734 return tzinfo_nogo("dst");
2735}
2736
Tim Peters52dcce22003-01-23 16:36:11 +00002737static PyObject *
2738tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2739{
2740 int y, m, d, hh, mm, ss, us;
2741
2742 PyObject *result;
2743 int off, dst;
2744 int none;
2745 int delta;
2746
2747 if (! PyDateTime_Check(dt)) {
2748 PyErr_SetString(PyExc_TypeError,
2749 "fromutc: argument must be a datetime");
2750 return NULL;
2751 }
2752 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2753 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2754 "is not self");
2755 return NULL;
2756 }
2757
2758 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2759 if (off == -1 && PyErr_Occurred())
2760 return NULL;
2761 if (none) {
2762 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2763 "utcoffset() result required");
2764 return NULL;
2765 }
2766
2767 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2768 if (dst == -1 && PyErr_Occurred())
2769 return NULL;
2770 if (none) {
2771 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2772 "dst() result required");
2773 return NULL;
2774 }
2775
2776 y = GET_YEAR(dt);
2777 m = GET_MONTH(dt);
2778 d = GET_DAY(dt);
2779 hh = DATE_GET_HOUR(dt);
2780 mm = DATE_GET_MINUTE(dt);
2781 ss = DATE_GET_SECOND(dt);
2782 us = DATE_GET_MICROSECOND(dt);
2783
2784 delta = off - dst;
2785 mm += delta;
2786 if ((mm < 0 || mm >= 60) &&
2787 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002788 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002789 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2790 if (result == NULL)
2791 return result;
2792
2793 dst = call_dst(dt->tzinfo, result, &none);
2794 if (dst == -1 && PyErr_Occurred())
2795 goto Fail;
2796 if (none)
2797 goto Inconsistent;
2798 if (dst == 0)
2799 return result;
2800
2801 mm += dst;
2802 if ((mm < 0 || mm >= 60) &&
2803 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2804 goto Fail;
2805 Py_DECREF(result);
2806 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2807 return result;
2808
2809Inconsistent:
2810 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2811 "inconsistent results; cannot convert");
2812
2813 /* fall thru to failure */
2814Fail:
2815 Py_DECREF(result);
2816 return NULL;
2817}
2818
Tim Peters2a799bf2002-12-16 20:18:38 +00002819/*
2820 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002821 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002822 */
2823
Guido van Rossum177e41a2003-01-30 22:06:23 +00002824static PyObject *
2825tzinfo_reduce(PyObject *self)
2826{
2827 PyObject *args, *state, *tmp;
2828 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002829
Guido van Rossum177e41a2003-01-30 22:06:23 +00002830 tmp = PyTuple_New(0);
2831 if (tmp == NULL)
2832 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002833
Guido van Rossum177e41a2003-01-30 22:06:23 +00002834 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2835 if (getinitargs != NULL) {
2836 args = PyObject_CallObject(getinitargs, tmp);
2837 Py_DECREF(getinitargs);
2838 if (args == NULL) {
2839 Py_DECREF(tmp);
2840 return NULL;
2841 }
2842 }
2843 else {
2844 PyErr_Clear();
2845 args = tmp;
2846 Py_INCREF(args);
2847 }
2848
2849 getstate = PyObject_GetAttrString(self, "__getstate__");
2850 if (getstate != NULL) {
2851 state = PyObject_CallObject(getstate, tmp);
2852 Py_DECREF(getstate);
2853 if (state == NULL) {
2854 Py_DECREF(args);
2855 Py_DECREF(tmp);
2856 return NULL;
2857 }
2858 }
2859 else {
2860 PyObject **dictptr;
2861 PyErr_Clear();
2862 state = Py_None;
2863 dictptr = _PyObject_GetDictPtr(self);
2864 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2865 state = *dictptr;
2866 Py_INCREF(state);
2867 }
2868
2869 Py_DECREF(tmp);
2870
2871 if (state == Py_None) {
2872 Py_DECREF(state);
2873 return Py_BuildValue("(ON)", self->ob_type, args);
2874 }
2875 else
2876 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2877}
Tim Peters2a799bf2002-12-16 20:18:38 +00002878
2879static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002880
Tim Peters2a799bf2002-12-16 20:18:38 +00002881 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2882 PyDoc_STR("datetime -> string name of time zone.")},
2883
2884 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2885 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2886 "west of UTC).")},
2887
2888 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2889 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2890
Tim Peters52dcce22003-01-23 16:36:11 +00002891 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2892 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2893
Guido van Rossum177e41a2003-01-30 22:06:23 +00002894 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2895 PyDoc_STR("-> (cls, state)")},
2896
Tim Peters2a799bf2002-12-16 20:18:38 +00002897 {NULL, NULL}
2898};
2899
2900static char tzinfo_doc[] =
2901PyDoc_STR("Abstract base class for time zone info objects.");
2902
Neal Norwitz227b5332006-03-22 09:28:35 +00002903static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002904 PyObject_HEAD_INIT(NULL)
2905 0, /* ob_size */
2906 "datetime.tzinfo", /* tp_name */
2907 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2908 0, /* tp_itemsize */
2909 0, /* tp_dealloc */
2910 0, /* tp_print */
2911 0, /* tp_getattr */
2912 0, /* tp_setattr */
2913 0, /* tp_compare */
2914 0, /* tp_repr */
2915 0, /* tp_as_number */
2916 0, /* tp_as_sequence */
2917 0, /* tp_as_mapping */
2918 0, /* tp_hash */
2919 0, /* tp_call */
2920 0, /* tp_str */
2921 PyObject_GenericGetAttr, /* tp_getattro */
2922 0, /* tp_setattro */
2923 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002924 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002925 tzinfo_doc, /* tp_doc */
2926 0, /* tp_traverse */
2927 0, /* tp_clear */
2928 0, /* tp_richcompare */
2929 0, /* tp_weaklistoffset */
2930 0, /* tp_iter */
2931 0, /* tp_iternext */
2932 tzinfo_methods, /* tp_methods */
2933 0, /* tp_members */
2934 0, /* tp_getset */
2935 0, /* tp_base */
2936 0, /* tp_dict */
2937 0, /* tp_descr_get */
2938 0, /* tp_descr_set */
2939 0, /* tp_dictoffset */
2940 0, /* tp_init */
2941 0, /* tp_alloc */
2942 PyType_GenericNew, /* tp_new */
2943 0, /* tp_free */
2944};
2945
2946/*
Tim Peters37f39822003-01-10 03:49:02 +00002947 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002948 */
2949
Tim Peters37f39822003-01-10 03:49:02 +00002950/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002951 */
2952
2953static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002954time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002955{
Tim Peters37f39822003-01-10 03:49:02 +00002956 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002957}
2958
Tim Peters37f39822003-01-10 03:49:02 +00002959static PyObject *
2960time_minute(PyDateTime_Time *self, void *unused)
2961{
2962 return PyInt_FromLong(TIME_GET_MINUTE(self));
2963}
2964
2965/* The name time_second conflicted with some platform header file. */
2966static PyObject *
2967py_time_second(PyDateTime_Time *self, void *unused)
2968{
2969 return PyInt_FromLong(TIME_GET_SECOND(self));
2970}
2971
2972static PyObject *
2973time_microsecond(PyDateTime_Time *self, void *unused)
2974{
2975 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2976}
2977
2978static PyObject *
2979time_tzinfo(PyDateTime_Time *self, void *unused)
2980{
Tim Petersa032d2e2003-01-11 00:15:54 +00002981 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002982 Py_INCREF(result);
2983 return result;
2984}
2985
2986static PyGetSetDef time_getset[] = {
2987 {"hour", (getter)time_hour},
2988 {"minute", (getter)time_minute},
2989 {"second", (getter)py_time_second},
2990 {"microsecond", (getter)time_microsecond},
2991 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00002992 {NULL}
2993};
2994
2995/*
2996 * Constructors.
2997 */
2998
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002999static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003000 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003001
Tim Peters2a799bf2002-12-16 20:18:38 +00003002static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003003time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003004{
3005 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003006 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003007 int hour = 0;
3008 int minute = 0;
3009 int second = 0;
3010 int usecond = 0;
3011 PyObject *tzinfo = Py_None;
3012
Guido van Rossum177e41a2003-01-30 22:06:23 +00003013 /* Check for invocation from pickle with __getstate__ state */
3014 if (PyTuple_GET_SIZE(args) >= 1 &&
3015 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003016 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003017 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3018 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003019 {
Tim Peters70533e22003-02-01 04:40:04 +00003020 PyDateTime_Time *me;
3021 char aware;
3022
3023 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003024 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003025 if (check_tzinfo_subclass(tzinfo) < 0) {
3026 PyErr_SetString(PyExc_TypeError, "bad "
3027 "tzinfo state arg");
3028 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003029 }
3030 }
Tim Peters70533e22003-02-01 04:40:04 +00003031 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003032 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003033 if (me != NULL) {
3034 char *pdata = PyString_AS_STRING(state);
3035
3036 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3037 me->hashcode = -1;
3038 me->hastzinfo = aware;
3039 if (aware) {
3040 Py_INCREF(tzinfo);
3041 me->tzinfo = tzinfo;
3042 }
3043 }
3044 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003045 }
3046
Tim Peters37f39822003-01-10 03:49:02 +00003047 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003048 &hour, &minute, &second, &usecond,
3049 &tzinfo)) {
3050 if (check_time_args(hour, minute, second, usecond) < 0)
3051 return NULL;
3052 if (check_tzinfo_subclass(tzinfo) < 0)
3053 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003054 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3055 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003056 }
3057 return self;
3058}
3059
3060/*
3061 * Destructor.
3062 */
3063
3064static void
Tim Peters37f39822003-01-10 03:49:02 +00003065time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003066{
Tim Petersa032d2e2003-01-11 00:15:54 +00003067 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003068 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003069 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003070 self->ob_type->tp_free((PyObject *)self);
3071}
3072
3073/*
Tim Peters855fe882002-12-22 03:43:39 +00003074 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003075 */
3076
Tim Peters2a799bf2002-12-16 20:18:38 +00003077/* These are all METH_NOARGS, so don't need to check the arglist. */
3078static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003079time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003080 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003081 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003082}
3083
3084static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003085time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003086 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003087 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003088}
3089
3090static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003091time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003092 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003093 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003094}
3095
3096/*
Tim Peters37f39822003-01-10 03:49:02 +00003097 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003098 */
3099
3100static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003101time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003102{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003103 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003104 int h = TIME_GET_HOUR(self);
3105 int m = TIME_GET_MINUTE(self);
3106 int s = TIME_GET_SECOND(self);
3107 int us = TIME_GET_MICROSECOND(self);
3108 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003109
Tim Peters37f39822003-01-10 03:49:02 +00003110 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003111 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3112 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003113 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003114 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3115 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003116 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003117 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003118 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003119 result = append_keyword_tzinfo(result, self->tzinfo);
3120 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003121}
3122
Tim Peters37f39822003-01-10 03:49:02 +00003123static PyObject *
3124time_str(PyDateTime_Time *self)
3125{
3126 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3127}
Tim Peters2a799bf2002-12-16 20:18:38 +00003128
3129static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003130time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003131{
3132 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003133 PyObject *result;
3134 /* Reuse the time format code from the datetime type. */
3135 PyDateTime_DateTime datetime;
3136 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003137
Tim Peters37f39822003-01-10 03:49:02 +00003138 /* Copy over just the time bytes. */
3139 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3140 self->data,
3141 _PyDateTime_TIME_DATASIZE);
3142
3143 isoformat_time(pdatetime, buf, sizeof(buf));
3144 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003145 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003146 return result;
3147
3148 /* We need to append the UTC offset. */
3149 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003150 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003151 Py_DECREF(result);
3152 return NULL;
3153 }
3154 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3155 return result;
3156}
3157
Tim Peters37f39822003-01-10 03:49:02 +00003158static PyObject *
3159time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3160{
3161 PyObject *result;
3162 PyObject *format;
3163 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003164 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003165
Guido van Rossumbce56a62007-05-10 18:04:33 +00003166 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3167 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003168 return NULL;
3169
3170 /* Python's strftime does insane things with the year part of the
3171 * timetuple. The year is forced to (the otherwise nonsensical)
3172 * 1900 to worm around that.
3173 */
3174 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003175 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003176 TIME_GET_HOUR(self),
3177 TIME_GET_MINUTE(self),
3178 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003179 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003180 if (tuple == NULL)
3181 return NULL;
3182 assert(PyTuple_Size(tuple) == 9);
3183 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3184 Py_DECREF(tuple);
3185 return result;
3186}
Tim Peters2a799bf2002-12-16 20:18:38 +00003187
3188/*
3189 * Miscellaneous methods.
3190 */
3191
Tim Peters37f39822003-01-10 03:49:02 +00003192static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003193time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003194{
3195 int diff;
3196 naivety n1, n2;
3197 int offset1, offset2;
3198
3199 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003200 Py_INCREF(Py_NotImplemented);
3201 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003202 }
Guido van Rossum19960592006-08-24 17:29:38 +00003203 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3204 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003205 return NULL;
3206 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3207 /* If they're both naive, or both aware and have the same offsets,
3208 * we get off cheap. Note that if they're both naive, offset1 ==
3209 * offset2 == 0 at this point.
3210 */
3211 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003212 diff = memcmp(((PyDateTime_Time *)self)->data,
3213 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003214 _PyDateTime_TIME_DATASIZE);
3215 return diff_to_bool(diff, op);
3216 }
3217
3218 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3219 assert(offset1 != offset2); /* else last "if" handled it */
3220 /* Convert everything except microseconds to seconds. These
3221 * can't overflow (no more than the # of seconds in 2 days).
3222 */
3223 offset1 = TIME_GET_HOUR(self) * 3600 +
3224 (TIME_GET_MINUTE(self) - offset1) * 60 +
3225 TIME_GET_SECOND(self);
3226 offset2 = TIME_GET_HOUR(other) * 3600 +
3227 (TIME_GET_MINUTE(other) - offset2) * 60 +
3228 TIME_GET_SECOND(other);
3229 diff = offset1 - offset2;
3230 if (diff == 0)
3231 diff = TIME_GET_MICROSECOND(self) -
3232 TIME_GET_MICROSECOND(other);
3233 return diff_to_bool(diff, op);
3234 }
3235
3236 assert(n1 != n2);
3237 PyErr_SetString(PyExc_TypeError,
3238 "can't compare offset-naive and "
3239 "offset-aware times");
3240 return NULL;
3241}
3242
3243static long
3244time_hash(PyDateTime_Time *self)
3245{
3246 if (self->hashcode == -1) {
3247 naivety n;
3248 int offset;
3249 PyObject *temp;
3250
3251 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3252 assert(n != OFFSET_UNKNOWN);
3253 if (n == OFFSET_ERROR)
3254 return -1;
3255
3256 /* Reduce this to a hash of another object. */
3257 if (offset == 0)
3258 temp = PyString_FromStringAndSize((char *)self->data,
3259 _PyDateTime_TIME_DATASIZE);
3260 else {
3261 int hour;
3262 int minute;
3263
3264 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003265 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003266 hour = divmod(TIME_GET_HOUR(self) * 60 +
3267 TIME_GET_MINUTE(self) - offset,
3268 60,
3269 &minute);
3270 if (0 <= hour && hour < 24)
3271 temp = new_time(hour, minute,
3272 TIME_GET_SECOND(self),
3273 TIME_GET_MICROSECOND(self),
3274 Py_None);
3275 else
3276 temp = Py_BuildValue("iiii",
3277 hour, minute,
3278 TIME_GET_SECOND(self),
3279 TIME_GET_MICROSECOND(self));
3280 }
3281 if (temp != NULL) {
3282 self->hashcode = PyObject_Hash(temp);
3283 Py_DECREF(temp);
3284 }
3285 }
3286 return self->hashcode;
3287}
Tim Peters2a799bf2002-12-16 20:18:38 +00003288
Tim Peters12bf3392002-12-24 05:41:27 +00003289static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003290time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003291{
3292 PyObject *clone;
3293 PyObject *tuple;
3294 int hh = TIME_GET_HOUR(self);
3295 int mm = TIME_GET_MINUTE(self);
3296 int ss = TIME_GET_SECOND(self);
3297 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003298 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003299
3300 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003301 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003302 &hh, &mm, &ss, &us, &tzinfo))
3303 return NULL;
3304 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3305 if (tuple == NULL)
3306 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003307 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003308 Py_DECREF(tuple);
3309 return clone;
3310}
3311
Tim Peters2a799bf2002-12-16 20:18:38 +00003312static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003313time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003314{
3315 int offset;
3316 int none;
3317
3318 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3319 /* Since utcoffset is in whole minutes, nothing can
3320 * alter the conclusion that this is nonzero.
3321 */
3322 return 1;
3323 }
3324 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003325 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003326 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003327 if (offset == -1 && PyErr_Occurred())
3328 return -1;
3329 }
3330 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3331}
3332
Tim Peters371935f2003-02-01 01:52:50 +00003333/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003334
Tim Peters33e0f382003-01-10 02:05:14 +00003335/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003336 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3337 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003338 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003339 */
3340static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003341time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003342{
3343 PyObject *basestate;
3344 PyObject *result = NULL;
3345
Tim Peters33e0f382003-01-10 02:05:14 +00003346 basestate = PyString_FromStringAndSize((char *)self->data,
3347 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003348 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003349 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003350 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003351 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003352 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003353 Py_DECREF(basestate);
3354 }
3355 return result;
3356}
3357
3358static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003359time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003360{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003361 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003362}
3363
Tim Peters37f39822003-01-10 03:49:02 +00003364static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003365
Thomas Wouterscf297e42007-02-23 15:07:44 +00003366 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003367 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3368 "[+HH:MM].")},
3369
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003370 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003371 PyDoc_STR("format -> strftime() style string.")},
3372
3373 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003374 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3375
Tim Peters37f39822003-01-10 03:49:02 +00003376 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003377 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3378
Tim Peters37f39822003-01-10 03:49:02 +00003379 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003380 PyDoc_STR("Return self.tzinfo.dst(self).")},
3381
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003382 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003383 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003384
Guido van Rossum177e41a2003-01-30 22:06:23 +00003385 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3386 PyDoc_STR("__reduce__() -> (cls, state)")},
3387
Tim Peters2a799bf2002-12-16 20:18:38 +00003388 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003389};
3390
Tim Peters37f39822003-01-10 03:49:02 +00003391static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003392PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3393\n\
3394All arguments are optional. tzinfo may be None, or an instance of\n\
3395a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003396
Tim Peters37f39822003-01-10 03:49:02 +00003397static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003398 0, /* nb_add */
3399 0, /* nb_subtract */
3400 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003401 0, /* nb_remainder */
3402 0, /* nb_divmod */
3403 0, /* nb_power */
3404 0, /* nb_negative */
3405 0, /* nb_positive */
3406 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003407 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003408};
3409
Neal Norwitz227b5332006-03-22 09:28:35 +00003410static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003411 PyObject_HEAD_INIT(NULL)
3412 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003413 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003414 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003415 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003416 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003417 0, /* tp_print */
3418 0, /* tp_getattr */
3419 0, /* tp_setattr */
3420 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003421 (reprfunc)time_repr, /* tp_repr */
3422 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003423 0, /* tp_as_sequence */
3424 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003425 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003426 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003427 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 PyObject_GenericGetAttr, /* tp_getattro */
3429 0, /* tp_setattro */
3430 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003431 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003432 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003433 0, /* tp_traverse */
3434 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003435 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003436 0, /* tp_weaklistoffset */
3437 0, /* tp_iter */
3438 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003439 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003440 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003441 time_getset, /* tp_getset */
3442 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003443 0, /* tp_dict */
3444 0, /* tp_descr_get */
3445 0, /* tp_descr_set */
3446 0, /* tp_dictoffset */
3447 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003448 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003449 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003450 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003451};
3452
3453/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003454 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003455 */
3456
Tim Petersa9bc1682003-01-11 03:39:11 +00003457/* Accessor properties. Properties for day, month, and year are inherited
3458 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003459 */
3460
3461static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003462datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003463{
Tim Petersa9bc1682003-01-11 03:39:11 +00003464 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003465}
3466
Tim Petersa9bc1682003-01-11 03:39:11 +00003467static PyObject *
3468datetime_minute(PyDateTime_DateTime *self, void *unused)
3469{
3470 return PyInt_FromLong(DATE_GET_MINUTE(self));
3471}
3472
3473static PyObject *
3474datetime_second(PyDateTime_DateTime *self, void *unused)
3475{
3476 return PyInt_FromLong(DATE_GET_SECOND(self));
3477}
3478
3479static PyObject *
3480datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3481{
3482 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3483}
3484
3485static PyObject *
3486datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3487{
3488 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3489 Py_INCREF(result);
3490 return result;
3491}
3492
3493static PyGetSetDef datetime_getset[] = {
3494 {"hour", (getter)datetime_hour},
3495 {"minute", (getter)datetime_minute},
3496 {"second", (getter)datetime_second},
3497 {"microsecond", (getter)datetime_microsecond},
3498 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003499 {NULL}
3500};
3501
3502/*
3503 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003504 */
3505
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003506static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003507 "year", "month", "day", "hour", "minute", "second",
3508 "microsecond", "tzinfo", NULL
3509};
3510
Tim Peters2a799bf2002-12-16 20:18:38 +00003511static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003512datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003513{
3514 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003515 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003516 int year;
3517 int month;
3518 int day;
3519 int hour = 0;
3520 int minute = 0;
3521 int second = 0;
3522 int usecond = 0;
3523 PyObject *tzinfo = Py_None;
3524
Guido van Rossum177e41a2003-01-30 22:06:23 +00003525 /* Check for invocation from pickle with __getstate__ state */
3526 if (PyTuple_GET_SIZE(args) >= 1 &&
3527 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003528 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003529 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3530 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003531 {
Tim Peters70533e22003-02-01 04:40:04 +00003532 PyDateTime_DateTime *me;
3533 char aware;
3534
3535 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003536 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003537 if (check_tzinfo_subclass(tzinfo) < 0) {
3538 PyErr_SetString(PyExc_TypeError, "bad "
3539 "tzinfo state arg");
3540 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003541 }
3542 }
Tim Peters70533e22003-02-01 04:40:04 +00003543 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003544 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003545 if (me != NULL) {
3546 char *pdata = PyString_AS_STRING(state);
3547
3548 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3549 me->hashcode = -1;
3550 me->hastzinfo = aware;
3551 if (aware) {
3552 Py_INCREF(tzinfo);
3553 me->tzinfo = tzinfo;
3554 }
3555 }
3556 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003557 }
3558
Tim Petersa9bc1682003-01-11 03:39:11 +00003559 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003560 &year, &month, &day, &hour, &minute,
3561 &second, &usecond, &tzinfo)) {
3562 if (check_date_args(year, month, day) < 0)
3563 return NULL;
3564 if (check_time_args(hour, minute, second, usecond) < 0)
3565 return NULL;
3566 if (check_tzinfo_subclass(tzinfo) < 0)
3567 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003568 self = new_datetime_ex(year, month, day,
3569 hour, minute, second, usecond,
3570 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003571 }
3572 return self;
3573}
3574
Tim Petersa9bc1682003-01-11 03:39:11 +00003575/* TM_FUNC is the shared type of localtime() and gmtime(). */
3576typedef struct tm *(*TM_FUNC)(const time_t *timer);
3577
3578/* Internal helper.
3579 * Build datetime from a time_t and a distinct count of microseconds.
3580 * Pass localtime or gmtime for f, to control the interpretation of timet.
3581 */
3582static PyObject *
3583datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3584 PyObject *tzinfo)
3585{
3586 struct tm *tm;
3587 PyObject *result = NULL;
3588
3589 tm = f(&timet);
3590 if (tm) {
3591 /* The platform localtime/gmtime may insert leap seconds,
3592 * indicated by tm->tm_sec > 59. We don't care about them,
3593 * except to the extent that passing them on to the datetime
3594 * constructor would raise ValueError for a reason that
3595 * made no sense to the user.
3596 */
3597 if (tm->tm_sec > 59)
3598 tm->tm_sec = 59;
3599 result = PyObject_CallFunction(cls, "iiiiiiiO",
3600 tm->tm_year + 1900,
3601 tm->tm_mon + 1,
3602 tm->tm_mday,
3603 tm->tm_hour,
3604 tm->tm_min,
3605 tm->tm_sec,
3606 us,
3607 tzinfo);
3608 }
3609 else
3610 PyErr_SetString(PyExc_ValueError,
3611 "timestamp out of range for "
3612 "platform localtime()/gmtime() function");
3613 return result;
3614}
3615
3616/* Internal helper.
3617 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3618 * to control the interpretation of the timestamp. Since a double doesn't
3619 * have enough bits to cover a datetime's full range of precision, it's
3620 * better to call datetime_from_timet_and_us provided you have a way
3621 * to get that much precision (e.g., C time() isn't good enough).
3622 */
3623static PyObject *
3624datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3625 PyObject *tzinfo)
3626{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003627 time_t timet;
3628 double fraction;
3629 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003630
Tim Peters1b6f7a92004-06-20 02:50:16 +00003631 timet = _PyTime_DoubleToTimet(timestamp);
3632 if (timet == (time_t)-1 && PyErr_Occurred())
3633 return NULL;
3634 fraction = timestamp - (double)timet;
3635 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003636 if (us < 0) {
3637 /* Truncation towards zero is not what we wanted
3638 for negative numbers (Python's mod semantics) */
3639 timet -= 1;
3640 us += 1000000;
3641 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003642 /* If timestamp is less than one microsecond smaller than a
3643 * full second, round up. Otherwise, ValueErrors are raised
3644 * for some floats. */
3645 if (us == 1000000) {
3646 timet += 1;
3647 us = 0;
3648 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003649 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3650}
3651
3652/* Internal helper.
3653 * Build most accurate possible datetime for current time. Pass localtime or
3654 * gmtime for f as appropriate.
3655 */
3656static PyObject *
3657datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3658{
3659#ifdef HAVE_GETTIMEOFDAY
3660 struct timeval t;
3661
3662#ifdef GETTIMEOFDAY_NO_TZ
3663 gettimeofday(&t);
3664#else
3665 gettimeofday(&t, (struct timezone *)NULL);
3666#endif
3667 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3668 tzinfo);
3669
3670#else /* ! HAVE_GETTIMEOFDAY */
3671 /* No flavor of gettimeofday exists on this platform. Python's
3672 * time.time() does a lot of other platform tricks to get the
3673 * best time it can on the platform, and we're not going to do
3674 * better than that (if we could, the better code would belong
3675 * in time.time()!) We're limited by the precision of a double,
3676 * though.
3677 */
3678 PyObject *time;
3679 double dtime;
3680
3681 time = time_time();
3682 if (time == NULL)
3683 return NULL;
3684 dtime = PyFloat_AsDouble(time);
3685 Py_DECREF(time);
3686 if (dtime == -1.0 && PyErr_Occurred())
3687 return NULL;
3688 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3689#endif /* ! HAVE_GETTIMEOFDAY */
3690}
3691
Tim Peters2a799bf2002-12-16 20:18:38 +00003692/* Return best possible local time -- this isn't constrained by the
3693 * precision of a timestamp.
3694 */
3695static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003696datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003697{
Tim Peters10cadce2003-01-23 19:58:02 +00003698 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003699 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003700 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003701
Tim Peters10cadce2003-01-23 19:58:02 +00003702 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3703 &tzinfo))
3704 return NULL;
3705 if (check_tzinfo_subclass(tzinfo) < 0)
3706 return NULL;
3707
3708 self = datetime_best_possible(cls,
3709 tzinfo == Py_None ? localtime : gmtime,
3710 tzinfo);
3711 if (self != NULL && tzinfo != Py_None) {
3712 /* Convert UTC to tzinfo's zone. */
3713 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003714 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003715 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003716 }
3717 return self;
3718}
3719
Tim Petersa9bc1682003-01-11 03:39:11 +00003720/* Return best possible UTC time -- this isn't constrained by the
3721 * precision of a timestamp.
3722 */
3723static PyObject *
3724datetime_utcnow(PyObject *cls, PyObject *dummy)
3725{
3726 return datetime_best_possible(cls, gmtime, Py_None);
3727}
3728
Tim Peters2a799bf2002-12-16 20:18:38 +00003729/* Return new local datetime from timestamp (Python timestamp -- a double). */
3730static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003731datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003732{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003733 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003734 double timestamp;
3735 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003736 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003737
Tim Peters2a44a8d2003-01-23 20:53:10 +00003738 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3739 keywords, &timestamp, &tzinfo))
3740 return NULL;
3741 if (check_tzinfo_subclass(tzinfo) < 0)
3742 return NULL;
3743
3744 self = datetime_from_timestamp(cls,
3745 tzinfo == Py_None ? localtime : gmtime,
3746 timestamp,
3747 tzinfo);
3748 if (self != NULL && tzinfo != Py_None) {
3749 /* Convert UTC to tzinfo's zone. */
3750 PyObject *temp = self;
3751 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3752 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003753 }
3754 return self;
3755}
3756
Tim Petersa9bc1682003-01-11 03:39:11 +00003757/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3758static PyObject *
3759datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3760{
3761 double timestamp;
3762 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003763
Tim Petersa9bc1682003-01-11 03:39:11 +00003764 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3765 result = datetime_from_timestamp(cls, gmtime, timestamp,
3766 Py_None);
3767 return result;
3768}
3769
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003770/* Return new datetime from time.strptime(). */
3771static PyObject *
3772datetime_strptime(PyObject *cls, PyObject *args)
3773{
3774 PyObject *result = NULL, *obj, *module;
3775 const char *string, *format;
3776
3777 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3778 return NULL;
3779
3780 if ((module = PyImport_ImportModule("time")) == NULL)
3781 return NULL;
3782 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3783 Py_DECREF(module);
3784
3785 if (obj != NULL) {
3786 int i, good_timetuple = 1;
3787 long int ia[6];
3788 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3789 for (i=0; i < 6; i++) {
3790 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003791 if (p == NULL) {
3792 Py_DECREF(obj);
3793 return NULL;
3794 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003795 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003796 ia[i] = PyInt_AsLong(p);
3797 else
3798 good_timetuple = 0;
3799 Py_DECREF(p);
3800 }
3801 else
3802 good_timetuple = 0;
3803 if (good_timetuple)
3804 result = PyObject_CallFunction(cls, "iiiiii",
3805 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3806 else
3807 PyErr_SetString(PyExc_ValueError,
3808 "unexpected value from time.strptime");
3809 Py_DECREF(obj);
3810 }
3811 return result;
3812}
3813
Tim Petersa9bc1682003-01-11 03:39:11 +00003814/* Return new datetime from date/datetime and time arguments. */
3815static PyObject *
3816datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3817{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003818 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003819 PyObject *date;
3820 PyObject *time;
3821 PyObject *result = NULL;
3822
3823 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3824 &PyDateTime_DateType, &date,
3825 &PyDateTime_TimeType, &time)) {
3826 PyObject *tzinfo = Py_None;
3827
3828 if (HASTZINFO(time))
3829 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3830 result = PyObject_CallFunction(cls, "iiiiiiiO",
3831 GET_YEAR(date),
3832 GET_MONTH(date),
3833 GET_DAY(date),
3834 TIME_GET_HOUR(time),
3835 TIME_GET_MINUTE(time),
3836 TIME_GET_SECOND(time),
3837 TIME_GET_MICROSECOND(time),
3838 tzinfo);
3839 }
3840 return result;
3841}
Tim Peters2a799bf2002-12-16 20:18:38 +00003842
3843/*
3844 * Destructor.
3845 */
3846
3847static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003848datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003849{
Tim Petersa9bc1682003-01-11 03:39:11 +00003850 if (HASTZINFO(self)) {
3851 Py_XDECREF(self->tzinfo);
3852 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003853 self->ob_type->tp_free((PyObject *)self);
3854}
3855
3856/*
3857 * Indirect access to tzinfo methods.
3858 */
3859
Tim Peters2a799bf2002-12-16 20:18:38 +00003860/* These are all METH_NOARGS, so don't need to check the arglist. */
3861static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003862datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3863 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3864 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003865}
3866
3867static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003868datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3869 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3870 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003871}
3872
3873static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003874datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3875 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3876 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003877}
3878
3879/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003880 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003881 */
3882
Tim Petersa9bc1682003-01-11 03:39:11 +00003883/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3884 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003885 */
3886static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003887add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3888 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003889{
Tim Petersa9bc1682003-01-11 03:39:11 +00003890 /* Note that the C-level additions can't overflow, because of
3891 * invariant bounds on the member values.
3892 */
3893 int year = GET_YEAR(date);
3894 int month = GET_MONTH(date);
3895 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3896 int hour = DATE_GET_HOUR(date);
3897 int minute = DATE_GET_MINUTE(date);
3898 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3899 int microsecond = DATE_GET_MICROSECOND(date) +
3900 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003901
Tim Petersa9bc1682003-01-11 03:39:11 +00003902 assert(factor == 1 || factor == -1);
3903 if (normalize_datetime(&year, &month, &day,
3904 &hour, &minute, &second, &microsecond) < 0)
3905 return NULL;
3906 else
3907 return new_datetime(year, month, day,
3908 hour, minute, second, microsecond,
3909 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003910}
3911
3912static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003913datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003914{
Tim Petersa9bc1682003-01-11 03:39:11 +00003915 if (PyDateTime_Check(left)) {
3916 /* datetime + ??? */
3917 if (PyDelta_Check(right))
3918 /* datetime + delta */
3919 return add_datetime_timedelta(
3920 (PyDateTime_DateTime *)left,
3921 (PyDateTime_Delta *)right,
3922 1);
3923 }
3924 else if (PyDelta_Check(left)) {
3925 /* delta + datetime */
3926 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3927 (PyDateTime_Delta *) left,
3928 1);
3929 }
3930 Py_INCREF(Py_NotImplemented);
3931 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003932}
3933
3934static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003935datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003936{
3937 PyObject *result = Py_NotImplemented;
3938
3939 if (PyDateTime_Check(left)) {
3940 /* datetime - ??? */
3941 if (PyDateTime_Check(right)) {
3942 /* datetime - datetime */
3943 naivety n1, n2;
3944 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003945 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003946
Tim Peterse39a80c2002-12-30 21:28:52 +00003947 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3948 right, &offset2, &n2,
3949 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003950 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003951 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003952 if (n1 != n2) {
3953 PyErr_SetString(PyExc_TypeError,
3954 "can't subtract offset-naive and "
3955 "offset-aware datetimes");
3956 return NULL;
3957 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003958 delta_d = ymd_to_ord(GET_YEAR(left),
3959 GET_MONTH(left),
3960 GET_DAY(left)) -
3961 ymd_to_ord(GET_YEAR(right),
3962 GET_MONTH(right),
3963 GET_DAY(right));
3964 /* These can't overflow, since the values are
3965 * normalized. At most this gives the number of
3966 * seconds in one day.
3967 */
3968 delta_s = (DATE_GET_HOUR(left) -
3969 DATE_GET_HOUR(right)) * 3600 +
3970 (DATE_GET_MINUTE(left) -
3971 DATE_GET_MINUTE(right)) * 60 +
3972 (DATE_GET_SECOND(left) -
3973 DATE_GET_SECOND(right));
3974 delta_us = DATE_GET_MICROSECOND(left) -
3975 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003976 /* (left - offset1) - (right - offset2) =
3977 * (left - right) + (offset2 - offset1)
3978 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003979 delta_s += (offset2 - offset1) * 60;
3980 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003981 }
3982 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003983 /* datetime - delta */
3984 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003985 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00003986 (PyDateTime_Delta *)right,
3987 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003988 }
3989 }
3990
3991 if (result == Py_NotImplemented)
3992 Py_INCREF(result);
3993 return result;
3994}
3995
3996/* Various ways to turn a datetime into a string. */
3997
3998static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003999datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004000{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004001 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004002 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004003
Tim Petersa9bc1682003-01-11 03:39:11 +00004004 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004005 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004006 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004007 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004008 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4009 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4010 DATE_GET_SECOND(self),
4011 DATE_GET_MICROSECOND(self));
4012 }
4013 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004014 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004015 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004016 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004017 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4018 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4019 DATE_GET_SECOND(self));
4020 }
4021 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004022 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004023 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004024 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004025 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4026 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4027 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004028 if (baserepr == NULL || ! HASTZINFO(self))
4029 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004030 return append_keyword_tzinfo(baserepr, self->tzinfo);
4031}
4032
Tim Petersa9bc1682003-01-11 03:39:11 +00004033static PyObject *
4034datetime_str(PyDateTime_DateTime *self)
4035{
4036 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4037}
Tim Peters2a799bf2002-12-16 20:18:38 +00004038
4039static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004040datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004041{
Tim Petersa9bc1682003-01-11 03:39:11 +00004042 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004043 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004044 char buffer[100];
4045 char *cp;
4046 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004047
Tim Petersa9bc1682003-01-11 03:39:11 +00004048 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4049 &sep))
4050 return NULL;
4051 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4052 assert(cp != NULL);
4053 *cp++ = sep;
4054 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4055 result = PyString_FromString(buffer);
4056 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004057 return result;
4058
4059 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004060 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004061 (PyObject *)self) < 0) {
4062 Py_DECREF(result);
4063 return NULL;
4064 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004065 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004066 return result;
4067}
4068
Tim Petersa9bc1682003-01-11 03:39:11 +00004069static PyObject *
4070datetime_ctime(PyDateTime_DateTime *self)
4071{
4072 return format_ctime((PyDateTime_Date *)self,
4073 DATE_GET_HOUR(self),
4074 DATE_GET_MINUTE(self),
4075 DATE_GET_SECOND(self));
4076}
4077
Tim Peters2a799bf2002-12-16 20:18:38 +00004078/* Miscellaneous methods. */
4079
Tim Petersa9bc1682003-01-11 03:39:11 +00004080static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004081datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004082{
4083 int diff;
4084 naivety n1, n2;
4085 int offset1, offset2;
4086
4087 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004088 if (PyDate_Check(other)) {
4089 /* Prevent invocation of date_richcompare. We want to
4090 return NotImplemented here to give the other object
4091 a chance. But since DateTime is a subclass of
4092 Date, if the other object is a Date, it would
4093 compute an ordering based on the date part alone,
4094 and we don't want that. So force unequal or
4095 uncomparable here in that case. */
4096 if (op == Py_EQ)
4097 Py_RETURN_FALSE;
4098 if (op == Py_NE)
4099 Py_RETURN_TRUE;
4100 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004101 }
Guido van Rossum19960592006-08-24 17:29:38 +00004102 Py_INCREF(Py_NotImplemented);
4103 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004104 }
4105
Guido van Rossum19960592006-08-24 17:29:38 +00004106 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4107 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004108 return NULL;
4109 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4110 /* If they're both naive, or both aware and have the same offsets,
4111 * we get off cheap. Note that if they're both naive, offset1 ==
4112 * offset2 == 0 at this point.
4113 */
4114 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004115 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4116 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004117 _PyDateTime_DATETIME_DATASIZE);
4118 return diff_to_bool(diff, op);
4119 }
4120
4121 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4122 PyDateTime_Delta *delta;
4123
4124 assert(offset1 != offset2); /* else last "if" handled it */
4125 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4126 other);
4127 if (delta == NULL)
4128 return NULL;
4129 diff = GET_TD_DAYS(delta);
4130 if (diff == 0)
4131 diff = GET_TD_SECONDS(delta) |
4132 GET_TD_MICROSECONDS(delta);
4133 Py_DECREF(delta);
4134 return diff_to_bool(diff, op);
4135 }
4136
4137 assert(n1 != n2);
4138 PyErr_SetString(PyExc_TypeError,
4139 "can't compare offset-naive and "
4140 "offset-aware datetimes");
4141 return NULL;
4142}
4143
4144static long
4145datetime_hash(PyDateTime_DateTime *self)
4146{
4147 if (self->hashcode == -1) {
4148 naivety n;
4149 int offset;
4150 PyObject *temp;
4151
4152 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4153 &offset);
4154 assert(n != OFFSET_UNKNOWN);
4155 if (n == OFFSET_ERROR)
4156 return -1;
4157
4158 /* Reduce this to a hash of another object. */
4159 if (n == OFFSET_NAIVE)
4160 temp = PyString_FromStringAndSize(
4161 (char *)self->data,
4162 _PyDateTime_DATETIME_DATASIZE);
4163 else {
4164 int days;
4165 int seconds;
4166
4167 assert(n == OFFSET_AWARE);
4168 assert(HASTZINFO(self));
4169 days = ymd_to_ord(GET_YEAR(self),
4170 GET_MONTH(self),
4171 GET_DAY(self));
4172 seconds = DATE_GET_HOUR(self) * 3600 +
4173 (DATE_GET_MINUTE(self) - offset) * 60 +
4174 DATE_GET_SECOND(self);
4175 temp = new_delta(days,
4176 seconds,
4177 DATE_GET_MICROSECOND(self),
4178 1);
4179 }
4180 if (temp != NULL) {
4181 self->hashcode = PyObject_Hash(temp);
4182 Py_DECREF(temp);
4183 }
4184 }
4185 return self->hashcode;
4186}
Tim Peters2a799bf2002-12-16 20:18:38 +00004187
4188static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004189datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004190{
4191 PyObject *clone;
4192 PyObject *tuple;
4193 int y = GET_YEAR(self);
4194 int m = GET_MONTH(self);
4195 int d = GET_DAY(self);
4196 int hh = DATE_GET_HOUR(self);
4197 int mm = DATE_GET_MINUTE(self);
4198 int ss = DATE_GET_SECOND(self);
4199 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004200 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004201
4202 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004203 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004204 &y, &m, &d, &hh, &mm, &ss, &us,
4205 &tzinfo))
4206 return NULL;
4207 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4208 if (tuple == NULL)
4209 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004210 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004211 Py_DECREF(tuple);
4212 return clone;
4213}
4214
4215static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004216datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004217{
Tim Peters52dcce22003-01-23 16:36:11 +00004218 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004219 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004220 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004221
Tim Peters80475bb2002-12-25 07:40:55 +00004222 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004223 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004224
Tim Peters52dcce22003-01-23 16:36:11 +00004225 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4226 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004227 return NULL;
4228
Tim Peters52dcce22003-01-23 16:36:11 +00004229 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4230 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004231
Tim Peters52dcce22003-01-23 16:36:11 +00004232 /* Conversion to self's own time zone is a NOP. */
4233 if (self->tzinfo == tzinfo) {
4234 Py_INCREF(self);
4235 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004236 }
Tim Peters521fc152002-12-31 17:36:56 +00004237
Tim Peters52dcce22003-01-23 16:36:11 +00004238 /* Convert self to UTC. */
4239 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4240 if (offset == -1 && PyErr_Occurred())
4241 return NULL;
4242 if (none)
4243 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004244
Tim Peters52dcce22003-01-23 16:36:11 +00004245 y = GET_YEAR(self);
4246 m = GET_MONTH(self);
4247 d = GET_DAY(self);
4248 hh = DATE_GET_HOUR(self);
4249 mm = DATE_GET_MINUTE(self);
4250 ss = DATE_GET_SECOND(self);
4251 us = DATE_GET_MICROSECOND(self);
4252
4253 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004254 if ((mm < 0 || mm >= 60) &&
4255 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004256 return NULL;
4257
4258 /* Attach new tzinfo and let fromutc() do the rest. */
4259 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4260 if (result != NULL) {
4261 PyObject *temp = result;
4262
4263 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4264 Py_DECREF(temp);
4265 }
Tim Petersadf64202003-01-04 06:03:15 +00004266 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004267
Tim Peters52dcce22003-01-23 16:36:11 +00004268NeedAware:
4269 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4270 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004271 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004272}
4273
4274static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004275datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004276{
4277 int dstflag = -1;
4278
Tim Petersa9bc1682003-01-11 03:39:11 +00004279 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004280 int none;
4281
4282 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4283 if (dstflag == -1 && PyErr_Occurred())
4284 return NULL;
4285
4286 if (none)
4287 dstflag = -1;
4288 else if (dstflag != 0)
4289 dstflag = 1;
4290
4291 }
4292 return build_struct_time(GET_YEAR(self),
4293 GET_MONTH(self),
4294 GET_DAY(self),
4295 DATE_GET_HOUR(self),
4296 DATE_GET_MINUTE(self),
4297 DATE_GET_SECOND(self),
4298 dstflag);
4299}
4300
4301static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004302datetime_getdate(PyDateTime_DateTime *self)
4303{
4304 return new_date(GET_YEAR(self),
4305 GET_MONTH(self),
4306 GET_DAY(self));
4307}
4308
4309static PyObject *
4310datetime_gettime(PyDateTime_DateTime *self)
4311{
4312 return new_time(DATE_GET_HOUR(self),
4313 DATE_GET_MINUTE(self),
4314 DATE_GET_SECOND(self),
4315 DATE_GET_MICROSECOND(self),
4316 Py_None);
4317}
4318
4319static PyObject *
4320datetime_gettimetz(PyDateTime_DateTime *self)
4321{
4322 return new_time(DATE_GET_HOUR(self),
4323 DATE_GET_MINUTE(self),
4324 DATE_GET_SECOND(self),
4325 DATE_GET_MICROSECOND(self),
4326 HASTZINFO(self) ? self->tzinfo : Py_None);
4327}
4328
4329static PyObject *
4330datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004331{
4332 int y = GET_YEAR(self);
4333 int m = GET_MONTH(self);
4334 int d = GET_DAY(self);
4335 int hh = DATE_GET_HOUR(self);
4336 int mm = DATE_GET_MINUTE(self);
4337 int ss = DATE_GET_SECOND(self);
4338 int us = 0; /* microseconds are ignored in a timetuple */
4339 int offset = 0;
4340
Tim Petersa9bc1682003-01-11 03:39:11 +00004341 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004342 int none;
4343
4344 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4345 if (offset == -1 && PyErr_Occurred())
4346 return NULL;
4347 }
4348 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4349 * 0 in a UTC timetuple regardless of what dst() says.
4350 */
4351 if (offset) {
4352 /* Subtract offset minutes & normalize. */
4353 int stat;
4354
4355 mm -= offset;
4356 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4357 if (stat < 0) {
4358 /* At the edges, it's possible we overflowed
4359 * beyond MINYEAR or MAXYEAR.
4360 */
4361 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4362 PyErr_Clear();
4363 else
4364 return NULL;
4365 }
4366 }
4367 return build_struct_time(y, m, d, hh, mm, ss, 0);
4368}
4369
Tim Peters371935f2003-02-01 01:52:50 +00004370/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004371
Tim Petersa9bc1682003-01-11 03:39:11 +00004372/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004373 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4374 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004375 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004376 */
4377static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004378datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004379{
4380 PyObject *basestate;
4381 PyObject *result = NULL;
4382
Tim Peters33e0f382003-01-10 02:05:14 +00004383 basestate = PyString_FromStringAndSize((char *)self->data,
4384 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004385 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004386 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004387 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004388 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004389 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004390 Py_DECREF(basestate);
4391 }
4392 return result;
4393}
4394
4395static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004396datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004397{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004398 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004399}
4400
Tim Petersa9bc1682003-01-11 03:39:11 +00004401static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004402
Tim Peters2a799bf2002-12-16 20:18:38 +00004403 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004404
Tim Petersa9bc1682003-01-11 03:39:11 +00004405 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004406 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004407 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004408
Tim Petersa9bc1682003-01-11 03:39:11 +00004409 {"utcnow", (PyCFunction)datetime_utcnow,
4410 METH_NOARGS | METH_CLASS,
4411 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4412
4413 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004414 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004415 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004416
Tim Petersa9bc1682003-01-11 03:39:11 +00004417 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4418 METH_VARARGS | METH_CLASS,
4419 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4420 "(like time.time()).")},
4421
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004422 {"strptime", (PyCFunction)datetime_strptime,
4423 METH_VARARGS | METH_CLASS,
4424 PyDoc_STR("string, format -> new datetime parsed from a string "
4425 "(like time.strptime()).")},
4426
Tim Petersa9bc1682003-01-11 03:39:11 +00004427 {"combine", (PyCFunction)datetime_combine,
4428 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4429 PyDoc_STR("date, time -> datetime with same date and time fields")},
4430
Tim Peters2a799bf2002-12-16 20:18:38 +00004431 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004432
Tim Petersa9bc1682003-01-11 03:39:11 +00004433 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4434 PyDoc_STR("Return date object with same year, month and day.")},
4435
4436 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4437 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4438
4439 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4440 PyDoc_STR("Return time object with same time and tzinfo.")},
4441
4442 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4443 PyDoc_STR("Return ctime() style string.")},
4444
4445 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004446 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4447
Tim Petersa9bc1682003-01-11 03:39:11 +00004448 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004449 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4450
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004451 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004452 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4453 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4454 "sep is used to separate the year from the time, and "
4455 "defaults to 'T'.")},
4456
Tim Petersa9bc1682003-01-11 03:39:11 +00004457 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004458 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4459
Tim Petersa9bc1682003-01-11 03:39:11 +00004460 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004461 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4462
Tim Petersa9bc1682003-01-11 03:39:11 +00004463 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004464 PyDoc_STR("Return self.tzinfo.dst(self).")},
4465
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004466 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004467 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004468
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004469 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004470 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4471
Guido van Rossum177e41a2003-01-30 22:06:23 +00004472 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4473 PyDoc_STR("__reduce__() -> (cls, state)")},
4474
Tim Peters2a799bf2002-12-16 20:18:38 +00004475 {NULL, NULL}
4476};
4477
Tim Petersa9bc1682003-01-11 03:39:11 +00004478static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004479PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4480\n\
4481The year, month and day arguments are required. tzinfo may be None, or an\n\
4482instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004483
Tim Petersa9bc1682003-01-11 03:39:11 +00004484static PyNumberMethods datetime_as_number = {
4485 datetime_add, /* nb_add */
4486 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004487 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004488 0, /* nb_remainder */
4489 0, /* nb_divmod */
4490 0, /* nb_power */
4491 0, /* nb_negative */
4492 0, /* nb_positive */
4493 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004494 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004495};
4496
Neal Norwitz227b5332006-03-22 09:28:35 +00004497static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004498 PyObject_HEAD_INIT(NULL)
4499 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004500 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004501 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004502 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004503 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004504 0, /* tp_print */
4505 0, /* tp_getattr */
4506 0, /* tp_setattr */
4507 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004508 (reprfunc)datetime_repr, /* tp_repr */
4509 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004510 0, /* tp_as_sequence */
4511 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004512 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004513 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004514 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004515 PyObject_GenericGetAttr, /* tp_getattro */
4516 0, /* tp_setattro */
4517 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004518 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004519 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004520 0, /* tp_traverse */
4521 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004522 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004523 0, /* tp_weaklistoffset */
4524 0, /* tp_iter */
4525 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004526 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004528 datetime_getset, /* tp_getset */
4529 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004530 0, /* tp_dict */
4531 0, /* tp_descr_get */
4532 0, /* tp_descr_set */
4533 0, /* tp_dictoffset */
4534 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004535 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004536 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004537 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004538};
4539
4540/* ---------------------------------------------------------------------------
4541 * Module methods and initialization.
4542 */
4543
4544static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004545 {NULL, NULL}
4546};
4547
Tim Peters9ddf40b2004-06-20 22:41:32 +00004548/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4549 * datetime.h.
4550 */
4551static PyDateTime_CAPI CAPI = {
4552 &PyDateTime_DateType,
4553 &PyDateTime_DateTimeType,
4554 &PyDateTime_TimeType,
4555 &PyDateTime_DeltaType,
4556 &PyDateTime_TZInfoType,
4557 new_date_ex,
4558 new_datetime_ex,
4559 new_time_ex,
4560 new_delta_ex,
4561 datetime_fromtimestamp,
4562 date_fromtimestamp
4563};
4564
4565
Tim Peters2a799bf2002-12-16 20:18:38 +00004566PyMODINIT_FUNC
4567initdatetime(void)
4568{
4569 PyObject *m; /* a module object */
4570 PyObject *d; /* its dict */
4571 PyObject *x;
4572
Tim Peters2a799bf2002-12-16 20:18:38 +00004573 m = Py_InitModule3("datetime", module_methods,
4574 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004575 if (m == NULL)
4576 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004577
4578 if (PyType_Ready(&PyDateTime_DateType) < 0)
4579 return;
4580 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4581 return;
4582 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4583 return;
4584 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4585 return;
4586 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4587 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004588
Tim Peters2a799bf2002-12-16 20:18:38 +00004589 /* timedelta values */
4590 d = PyDateTime_DeltaType.tp_dict;
4591
Tim Peters2a799bf2002-12-16 20:18:38 +00004592 x = new_delta(0, 0, 1, 0);
4593 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4594 return;
4595 Py_DECREF(x);
4596
4597 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4598 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4599 return;
4600 Py_DECREF(x);
4601
4602 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4603 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4604 return;
4605 Py_DECREF(x);
4606
4607 /* date values */
4608 d = PyDateTime_DateType.tp_dict;
4609
4610 x = new_date(1, 1, 1);
4611 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4612 return;
4613 Py_DECREF(x);
4614
4615 x = new_date(MAXYEAR, 12, 31);
4616 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4617 return;
4618 Py_DECREF(x);
4619
4620 x = new_delta(1, 0, 0, 0);
4621 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4622 return;
4623 Py_DECREF(x);
4624
Tim Peters37f39822003-01-10 03:49:02 +00004625 /* time values */
4626 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004627
Tim Peters37f39822003-01-10 03:49:02 +00004628 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004629 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4630 return;
4631 Py_DECREF(x);
4632
Tim Peters37f39822003-01-10 03:49:02 +00004633 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004634 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4635 return;
4636 Py_DECREF(x);
4637
4638 x = new_delta(0, 0, 1, 0);
4639 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4640 return;
4641 Py_DECREF(x);
4642
Tim Petersa9bc1682003-01-11 03:39:11 +00004643 /* datetime values */
4644 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004645
Tim Petersa9bc1682003-01-11 03:39:11 +00004646 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004647 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4648 return;
4649 Py_DECREF(x);
4650
Tim Petersa9bc1682003-01-11 03:39:11 +00004651 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004652 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4653 return;
4654 Py_DECREF(x);
4655
4656 x = new_delta(0, 0, 1, 0);
4657 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4658 return;
4659 Py_DECREF(x);
4660
Tim Peters2a799bf2002-12-16 20:18:38 +00004661 /* module initialization */
4662 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4663 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4664
4665 Py_INCREF(&PyDateTime_DateType);
4666 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4667
Tim Petersa9bc1682003-01-11 03:39:11 +00004668 Py_INCREF(&PyDateTime_DateTimeType);
4669 PyModule_AddObject(m, "datetime",
4670 (PyObject *)&PyDateTime_DateTimeType);
4671
4672 Py_INCREF(&PyDateTime_TimeType);
4673 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4674
Tim Peters2a799bf2002-12-16 20:18:38 +00004675 Py_INCREF(&PyDateTime_DeltaType);
4676 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4677
Tim Peters2a799bf2002-12-16 20:18:38 +00004678 Py_INCREF(&PyDateTime_TZInfoType);
4679 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4680
Tim Peters9ddf40b2004-06-20 22:41:32 +00004681 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4682 NULL);
4683 if (x == NULL)
4684 return;
4685 PyModule_AddObject(m, "datetime_CAPI", x);
4686
Tim Peters2a799bf2002-12-16 20:18:38 +00004687 /* A 4-year cycle has an extra leap day over what we'd get from
4688 * pasting together 4 single years.
4689 */
4690 assert(DI4Y == 4 * 365 + 1);
4691 assert(DI4Y == days_before_year(4+1));
4692
4693 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4694 * get from pasting together 4 100-year cycles.
4695 */
4696 assert(DI400Y == 4 * DI100Y + 1);
4697 assert(DI400Y == days_before_year(400+1));
4698
4699 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4700 * pasting together 25 4-year cycles.
4701 */
4702 assert(DI100Y == 25 * DI4Y - 1);
4703 assert(DI100Y == days_before_year(100+1));
4704
4705 us_per_us = PyInt_FromLong(1);
4706 us_per_ms = PyInt_FromLong(1000);
4707 us_per_second = PyInt_FromLong(1000000);
4708 us_per_minute = PyInt_FromLong(60000000);
4709 seconds_per_day = PyInt_FromLong(24 * 3600);
4710 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4711 us_per_minute == NULL || seconds_per_day == NULL)
4712 return;
4713
4714 /* The rest are too big for 32-bit ints, but even
4715 * us_per_week fits in 40 bits, so doubles should be exact.
4716 */
4717 us_per_hour = PyLong_FromDouble(3600000000.0);
4718 us_per_day = PyLong_FromDouble(86400000000.0);
4719 us_per_week = PyLong_FromDouble(604800000000.0);
4720 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4721 return;
4722}
Tim Petersf3615152003-01-01 21:51:37 +00004723
4724/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004725Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004726 x.n = x stripped of its timezone -- its naive time.
4727 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4728 return None
4729 x.d = x.dst(), and assuming that doesn't raise an exception or
4730 return None
4731 x.s = x's standard offset, x.o - x.d
4732
4733Now some derived rules, where k is a duration (timedelta).
4734
47351. x.o = x.s + x.d
4736 This follows from the definition of x.s.
4737
Tim Petersc5dc4da2003-01-02 17:55:03 +000047382. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004739 This is actually a requirement, an assumption we need to make about
4740 sane tzinfo classes.
4741
47423. The naive UTC time corresponding to x is x.n - x.o.
4743 This is again a requirement for a sane tzinfo class.
4744
47454. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004746 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004747
Tim Petersc5dc4da2003-01-02 17:55:03 +000047485. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004749 Again follows from how arithmetic is defined.
4750
Tim Peters8bb5ad22003-01-24 02:44:45 +00004751Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004752(meaning that the various tzinfo methods exist, and don't blow up or return
4753None when called).
4754
Tim Petersa9bc1682003-01-11 03:39:11 +00004755The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004756x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004757
4758By #3, we want
4759
Tim Peters8bb5ad22003-01-24 02:44:45 +00004760 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004761
4762The algorithm starts by attaching tz to x.n, and calling that y. So
4763x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4764becomes true; in effect, we want to solve [2] for k:
4765
Tim Peters8bb5ad22003-01-24 02:44:45 +00004766 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004767
4768By #1, this is the same as
4769
Tim Peters8bb5ad22003-01-24 02:44:45 +00004770 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004771
4772By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4773Substituting that into [3],
4774
Tim Peters8bb5ad22003-01-24 02:44:45 +00004775 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4776 k - (y+k).s - (y+k).d = 0; rearranging,
4777 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4778 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004779
Tim Peters8bb5ad22003-01-24 02:44:45 +00004780On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4781approximate k by ignoring the (y+k).d term at first. Note that k can't be
4782very large, since all offset-returning methods return a duration of magnitude
4783less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4784be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004785
4786In any case, the new value is
4787
Tim Peters8bb5ad22003-01-24 02:44:45 +00004788 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004789
Tim Peters8bb5ad22003-01-24 02:44:45 +00004790It's helpful to step back at look at [4] from a higher level: it's simply
4791mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004792
4793At this point, if
4794
Tim Peters8bb5ad22003-01-24 02:44:45 +00004795 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004796
4797we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004798at the start of daylight time. Picture US Eastern for concreteness. The wall
4799time 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 +00004800sense then. The docs ask that an Eastern tzinfo class consider such a time to
4801be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4802on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004803the only spelling that makes sense on the local wall clock.
4804
Tim Petersc5dc4da2003-01-02 17:55:03 +00004805In fact, if [5] holds at this point, we do have the standard-time spelling,
4806but that takes a bit of proof. We first prove a stronger result. What's the
4807difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004808
Tim Peters8bb5ad22003-01-24 02:44:45 +00004809 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004810
Tim Petersc5dc4da2003-01-02 17:55:03 +00004811Now
4812 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004813 (y + y.s).n = by #5
4814 y.n + y.s = since y.n = x.n
4815 x.n + y.s = since z and y are have the same tzinfo member,
4816 y.s = z.s by #2
4817 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004818
Tim Petersc5dc4da2003-01-02 17:55:03 +00004819Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004820
Tim Petersc5dc4da2003-01-02 17:55:03 +00004821 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004822 x.n - ((x.n + z.s) - z.o) = expanding
4823 x.n - x.n - z.s + z.o = cancelling
4824 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004825 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004826
Tim Petersc5dc4da2003-01-02 17:55:03 +00004827So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004828
Tim Petersc5dc4da2003-01-02 17:55:03 +00004829If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004830spelling we wanted in the endcase described above. We're done. Contrarily,
4831if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004832
Tim Petersc5dc4da2003-01-02 17:55:03 +00004833If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4834add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004835local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004836
Tim Petersc5dc4da2003-01-02 17:55:03 +00004837Let
Tim Petersf3615152003-01-01 21:51:37 +00004838
Tim Peters4fede1a2003-01-04 00:26:59 +00004839 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004840
Tim Peters4fede1a2003-01-04 00:26:59 +00004841and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004842
Tim Peters8bb5ad22003-01-24 02:44:45 +00004843 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004844
Tim Peters8bb5ad22003-01-24 02:44:45 +00004845If so, we're done. If not, the tzinfo class is insane, according to the
4846assumptions we've made. This also requires a bit of proof. As before, let's
4847compute the difference between the LHS and RHS of [8] (and skipping some of
4848the justifications for the kinds of substitutions we've done several times
4849already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004850
Tim Peters8bb5ad22003-01-24 02:44:45 +00004851 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4852 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4853 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4854 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4855 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004856 - z.o + z'.o = #1 twice
4857 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4858 z'.d - z.d
4859
4860So 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 +00004861we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4862return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004863
Tim Peters8bb5ad22003-01-24 02:44:45 +00004864How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4865a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4866would have to change the result dst() returns: we start in DST, and moving
4867a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004868
Tim Peters8bb5ad22003-01-24 02:44:45 +00004869There isn't a sane case where this can happen. The closest it gets is at
4870the end of DST, where there's an hour in UTC with no spelling in a hybrid
4871tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4872that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4873UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4874time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4875clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4876standard time. Since that's what the local clock *does*, we want to map both
4877UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004878in local time, but so it goes -- it's the way the local clock works.
4879
Tim Peters8bb5ad22003-01-24 02:44:45 +00004880When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4881so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4882z' = 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 +00004883(correctly) concludes that z' is not UTC-equivalent to x.
4884
4885Because we know z.d said z was in daylight time (else [5] would have held and
4886we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004887and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004888return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4889but the reasoning doesn't depend on the example -- it depends on there being
4890two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004891z' must be in standard time, and is the spelling we want in this case.
4892
4893Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4894concerned (because it takes z' as being in standard time rather than the
4895daylight time we intend here), but returning it gives the real-life "local
4896clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4897tz.
4898
4899When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4900the 1:MM standard time spelling we want.
4901
4902So how can this break? One of the assumptions must be violated. Two
4903possibilities:
4904
49051) [2] effectively says that y.s is invariant across all y belong to a given
4906 time zone. This isn't true if, for political reasons or continental drift,
4907 a region decides to change its base offset from UTC.
4908
49092) There may be versions of "double daylight" time where the tail end of
4910 the analysis gives up a step too early. I haven't thought about that
4911 enough to say.
4912
4913In any case, it's clear that the default fromutc() is strong enough to handle
4914"almost all" time zones: so long as the standard offset is invariant, it
4915doesn't matter if daylight time transition points change from year to year, or
4916if daylight time is skipped in some years; it doesn't matter how large or
4917small dst() may get within its bounds; and it doesn't even matter if some
4918perverse time zone returns a negative dst()). So a breaking case must be
4919pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004920--------------------------------------------------------------------------- */