blob: 835af61ec9fd8e316b2eaaf1dd9e3271353376ce [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
Guido van Rossume3d1d412007-05-23 21:24:35 +0000930 * returns NULL. If the result is a string, we ensure it is a Unicode
931 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000932 */
933static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000934call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000935{
936 PyObject *result;
937
938 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000939 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000940 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000941
Tim Peters855fe882002-12-22 03:43:39 +0000942 if (tzinfo == Py_None) {
943 result = Py_None;
944 Py_INCREF(result);
945 }
946 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000947 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000948
Guido van Rossume3d1d412007-05-23 21:24:35 +0000949 if (result != NULL && result != Py_None) {
950 if (!PyString_Check(result) && !PyUnicode_Check(result)) {
951 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
952 "return None or a string, not '%s'",
953 result->ob_type->tp_name);
954 Py_DECREF(result);
955 result = NULL;
956 }
957 else if (!PyUnicode_Check(result)) {
958 PyObject *temp = PyUnicode_FromObject(result);
959 Py_DECREF(result);
960 result = temp;
961 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000962 }
963 return result;
964}
965
966typedef enum {
967 /* an exception has been set; the caller should pass it on */
968 OFFSET_ERROR,
969
Tim Petersa9bc1682003-01-11 03:39:11 +0000970 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000971 OFFSET_UNKNOWN,
972
973 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000974 * datetime with !hastzinfo
975 * datetime with None tzinfo,
976 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000977 * time with !hastzinfo
978 * time with None tzinfo,
979 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 */
981 OFFSET_NAIVE,
982
Tim Petersa9bc1682003-01-11 03:39:11 +0000983 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000984 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000985} naivety;
986
Tim Peters14b69412002-12-22 18:10:22 +0000987/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000988 * the "naivety" typedef for details. If the type is aware, *offset is set
989 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000990 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 */
993static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000994classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000995{
996 int none;
997 PyObject *tzinfo;
998
Tim Peterse39a80c2002-12-30 21:28:52 +0000999 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001000 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +00001001 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (tzinfo == Py_None)
1003 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +00001004 if (tzinfo == NULL) {
1005 /* note that a datetime passes the PyDate_Check test */
1006 return (PyTime_Check(op) || PyDate_Check(op)) ?
1007 OFFSET_NAIVE : OFFSET_UNKNOWN;
1008 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001009 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001010 if (*offset == -1 && PyErr_Occurred())
1011 return OFFSET_ERROR;
1012 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1013}
1014
Tim Peters00237032002-12-27 02:21:51 +00001015/* Classify two objects as to whether they're naive or offset-aware.
1016 * This isn't quite the same as calling classify_utcoffset() twice: for
1017 * binary operations (comparison and subtraction), we generally want to
1018 * ignore the tzinfo members if they're identical. This is by design,
1019 * so that results match "naive" expectations when mixing objects from a
1020 * single timezone. So in that case, this sets both offsets to 0 and
1021 * both naiveties to OFFSET_NAIVE.
1022 * The function returns 0 if everything's OK, and -1 on error.
1023 */
1024static int
1025classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001026 PyObject *tzinfoarg1,
1027 PyObject *o2, int *offset2, naivety *n2,
1028 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001029{
1030 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1031 *offset1 = *offset2 = 0;
1032 *n1 = *n2 = OFFSET_NAIVE;
1033 }
1034 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001035 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001036 if (*n1 == OFFSET_ERROR)
1037 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001038 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001039 if (*n2 == OFFSET_ERROR)
1040 return -1;
1041 }
1042 return 0;
1043}
1044
Tim Peters2a799bf2002-12-16 20:18:38 +00001045/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1046 * stuff
1047 * ", tzinfo=" + repr(tzinfo)
1048 * before the closing ")".
1049 */
1050static PyObject *
1051append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1052{
1053 PyObject *temp;
1054
Walter Dörwald1ab83302007-05-18 17:15:44 +00001055 assert(PyUnicode_Check(repr));
Tim Peters2a799bf2002-12-16 20:18:38 +00001056 assert(tzinfo);
1057 if (tzinfo == Py_None)
1058 return repr;
1059 /* Get rid of the trailing ')'. */
Walter Dörwald1ab83302007-05-18 17:15:44 +00001060 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1061 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1062 PyUnicode_GET_SIZE(repr) - 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001063 Py_DECREF(repr);
1064 if (temp == NULL)
1065 return NULL;
Walter Dörwald517bcfe2007-05-23 20:45:05 +00001066 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1067 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00001068 return repr;
1069}
1070
1071/* ---------------------------------------------------------------------------
1072 * String format helpers.
1073 */
1074
1075static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001076format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001077{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001078 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001079 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1080 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001081 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001082 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1083 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1084 };
1085
Tim Peters2a799bf2002-12-16 20:18:38 +00001086 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1087
Walter Dörwald4af32b32007-05-31 16:19:50 +00001088 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1089 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1090 GET_DAY(date), hours, minutes, seconds,
1091 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001092}
1093
1094/* Add an hours & minutes UTC offset string to buf. buf has no more than
1095 * buflen bytes remaining. The UTC offset is gotten by calling
1096 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1097 * *buf, and that's all. Else the returned value is checked for sanity (an
1098 * integer in range), and if that's OK it's converted to an hours & minutes
1099 * string of the form
1100 * sign HH sep MM
1101 * Returns 0 if everything is OK. If the return value from utcoffset() is
1102 * bogus, an appropriate exception is set and -1 is returned.
1103 */
1104static int
Tim Peters328fff72002-12-20 01:31:27 +00001105format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001106 PyObject *tzinfo, PyObject *tzinfoarg)
1107{
1108 int offset;
1109 int hours;
1110 int minutes;
1111 char sign;
1112 int none;
1113
1114 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1115 if (offset == -1 && PyErr_Occurred())
1116 return -1;
1117 if (none) {
1118 *buf = '\0';
1119 return 0;
1120 }
1121 sign = '+';
1122 if (offset < 0) {
1123 sign = '-';
1124 offset = - offset;
1125 }
1126 hours = divmod(offset, 60, &minutes);
1127 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1128 return 0;
1129}
1130
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001131static PyObject *
1132make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1133{
1134 PyObject *tzinfo = get_tzinfo_member(object);
1135 PyObject *Zreplacement = PyString_FromString("");
1136 if (Zreplacement == NULL)
1137 return NULL;
1138 if (tzinfo != Py_None && tzinfo != NULL) {
1139 PyObject *temp;
1140 assert(tzinfoarg != NULL);
1141 temp = call_tzname(tzinfo, tzinfoarg);
1142 if (temp == NULL)
1143 goto Error;
1144 if (temp != Py_None) {
1145 assert(PyUnicode_Check(temp));
1146 /* Since the tzname is getting stuffed into the
1147 * format, we have to double any % signs so that
1148 * strftime doesn't treat them as format codes.
1149 */
1150 Py_DECREF(Zreplacement);
1151 Zreplacement = PyObject_CallMethod(temp, "replace",
1152 "ss", "%", "%%");
1153 Py_DECREF(temp);
1154 if (Zreplacement == NULL)
1155 return NULL;
1156 if (PyUnicode_Check(Zreplacement)) {
1157 Zreplacement =
1158 _PyUnicode_AsDefaultEncodedString(
1159 Zreplacement, NULL);
1160 if (Zreplacement == NULL)
1161 return NULL;
1162 }
1163 if (!PyString_Check(Zreplacement)) {
1164 PyErr_SetString(PyExc_TypeError,
1165 "tzname.replace() did not return a string");
1166 goto Error;
1167 }
1168 }
1169 else
1170 Py_DECREF(temp);
1171 }
1172 return Zreplacement;
1173
1174 Error:
1175 Py_DECREF(Zreplacement);
1176 return NULL;
1177}
1178
Tim Peters2a799bf2002-12-16 20:18:38 +00001179/* I sure don't want to reproduce the strftime code from the time module,
1180 * so this imports the module and calls it. All the hair is due to
1181 * giving special meanings to the %z and %Z format codes via a preprocessing
1182 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001183 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1184 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001185 */
1186static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001187wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1188 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001189{
1190 PyObject *result = NULL; /* guilty until proved innocent */
1191
1192 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1193 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1194
Guido van Rossumbce56a62007-05-10 18:04:33 +00001195 const char *pin;/* pointer to next char in input format */
1196 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001197 char ch; /* next char in input format */
1198
1199 PyObject *newfmt = NULL; /* py string, the output format */
1200 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001201 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001202 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001203 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001204
Guido van Rossumbce56a62007-05-10 18:04:33 +00001205 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001206 int ntoappend; /* # of bytes to append to output buffer */
1207
Tim Peters2a799bf2002-12-16 20:18:38 +00001208 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001209 assert(PyString_Check(format) || PyUnicode_Check(format));
1210
1211 /* Convert the input format to a C string and size */
1212 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1213 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001214
Tim Petersd6844152002-12-22 20:58:42 +00001215 /* Give up if the year is before 1900.
1216 * Python strftime() plays games with the year, and different
1217 * games depending on whether envar PYTHON2K is set. This makes
1218 * years before 1900 a nightmare, even if the platform strftime
1219 * supports them (and not all do).
1220 * We could get a lot farther here by avoiding Python's strftime
1221 * wrapper and calling the C strftime() directly, but that isn't
1222 * an option in the Python implementation of this module.
1223 */
1224 {
1225 long year;
1226 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1227 if (pyyear == NULL) return NULL;
1228 assert(PyInt_Check(pyyear));
1229 year = PyInt_AsLong(pyyear);
1230 Py_DECREF(pyyear);
1231 if (year < 1900) {
1232 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1233 "1900; the datetime strftime() "
1234 "methods require year >= 1900",
1235 year);
1236 return NULL;
1237 }
1238 }
1239
Tim Peters2a799bf2002-12-16 20:18:38 +00001240 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001241 * a new format. Since computing the replacements for those codes
1242 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001243 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001244 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001245 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1246 if (newfmt == NULL) goto Done;
1247 pnew = PyString_AsString(newfmt);
1248 usednew = 0;
1249
Tim Peters2a799bf2002-12-16 20:18:38 +00001250 while ((ch = *pin++) != '\0') {
1251 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001252 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001253 ntoappend = 1;
1254 }
1255 else if ((ch = *pin++) == '\0') {
1256 /* There's a lone trailing %; doesn't make sense. */
1257 PyErr_SetString(PyExc_ValueError, "strftime format "
1258 "ends with raw %");
1259 goto Done;
1260 }
1261 /* A % has been seen and ch is the character after it. */
1262 else if (ch == 'z') {
1263 if (zreplacement == NULL) {
1264 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001265 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001266 PyObject *tzinfo = get_tzinfo_member(object);
1267 zreplacement = PyString_FromString("");
1268 if (zreplacement == NULL) goto Done;
1269 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001270 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001271 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001272 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001273 "",
1274 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001275 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001276 goto Done;
1277 Py_DECREF(zreplacement);
1278 zreplacement = PyString_FromString(buf);
1279 if (zreplacement == NULL) goto Done;
1280 }
1281 }
1282 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001283 ptoappend = PyString_AS_STRING(zreplacement);
1284 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001285 }
1286 else if (ch == 'Z') {
1287 /* format tzname */
1288 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001289 Zreplacement = make_Zreplacement(object,
1290 tzinfoarg);
1291 if (Zreplacement == NULL)
1292 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001293 }
1294 assert(Zreplacement != NULL);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001295 assert(PyString_Check(Zreplacement));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001296 ptoappend = PyString_AS_STRING(Zreplacement);
1297 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001298 }
1299 else {
Tim Peters328fff72002-12-20 01:31:27 +00001300 /* percent followed by neither z nor Z */
1301 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001302 ntoappend = 2;
1303 }
1304
1305 /* Append the ntoappend chars starting at ptoappend to
1306 * the new format.
1307 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001308 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001309 assert(ntoappend >= 0);
1310 if (ntoappend == 0)
1311 continue;
1312 while (usednew + ntoappend > totalnew) {
1313 int bigger = totalnew << 1;
1314 if ((bigger >> 1) != totalnew) { /* overflow */
1315 PyErr_NoMemory();
1316 goto Done;
1317 }
1318 if (_PyString_Resize(&newfmt, bigger) < 0)
1319 goto Done;
1320 totalnew = bigger;
1321 pnew = PyString_AsString(newfmt) + usednew;
1322 }
1323 memcpy(pnew, ptoappend, ntoappend);
1324 pnew += ntoappend;
1325 usednew += ntoappend;
1326 assert(usednew <= totalnew);
1327 } /* end while() */
1328
1329 if (_PyString_Resize(&newfmt, usednew) < 0)
1330 goto Done;
1331 {
1332 PyObject *time = PyImport_ImportModule("time");
1333 if (time == NULL)
1334 goto Done;
1335 result = PyObject_CallMethod(time, "strftime", "OO",
1336 newfmt, timetuple);
1337 Py_DECREF(time);
1338 }
1339 Done:
1340 Py_XDECREF(zreplacement);
1341 Py_XDECREF(Zreplacement);
1342 Py_XDECREF(newfmt);
1343 return result;
1344}
1345
1346static char *
1347isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1348{
1349 int x;
1350 x = PyOS_snprintf(buffer, bufflen,
1351 "%04d-%02d-%02d",
1352 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1353 return buffer + x;
1354}
1355
1356static void
1357isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1358{
1359 int us = DATE_GET_MICROSECOND(dt);
1360
1361 PyOS_snprintf(buffer, bufflen,
1362 "%02d:%02d:%02d", /* 8 characters */
1363 DATE_GET_HOUR(dt),
1364 DATE_GET_MINUTE(dt),
1365 DATE_GET_SECOND(dt));
1366 if (us)
1367 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1368}
1369
1370/* ---------------------------------------------------------------------------
1371 * Wrap functions from the time module. These aren't directly available
1372 * from C. Perhaps they should be.
1373 */
1374
1375/* Call time.time() and return its result (a Python float). */
1376static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001377time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001378{
1379 PyObject *result = NULL;
1380 PyObject *time = PyImport_ImportModule("time");
1381
1382 if (time != NULL) {
1383 result = PyObject_CallMethod(time, "time", "()");
1384 Py_DECREF(time);
1385 }
1386 return result;
1387}
1388
1389/* Build a time.struct_time. The weekday and day number are automatically
1390 * computed from the y,m,d args.
1391 */
1392static PyObject *
1393build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1394{
1395 PyObject *time;
1396 PyObject *result = NULL;
1397
1398 time = PyImport_ImportModule("time");
1399 if (time != NULL) {
1400 result = PyObject_CallMethod(time, "struct_time",
1401 "((iiiiiiiii))",
1402 y, m, d,
1403 hh, mm, ss,
1404 weekday(y, m, d),
1405 days_before_month(y, m) + d,
1406 dstflag);
1407 Py_DECREF(time);
1408 }
1409 return result;
1410}
1411
1412/* ---------------------------------------------------------------------------
1413 * Miscellaneous helpers.
1414 */
1415
Guido van Rossum19960592006-08-24 17:29:38 +00001416/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001417 * The comparisons here all most naturally compute a cmp()-like result.
1418 * This little helper turns that into a bool result for rich comparisons.
1419 */
1420static PyObject *
1421diff_to_bool(int diff, int op)
1422{
1423 PyObject *result;
1424 int istrue;
1425
1426 switch (op) {
1427 case Py_EQ: istrue = diff == 0; break;
1428 case Py_NE: istrue = diff != 0; break;
1429 case Py_LE: istrue = diff <= 0; break;
1430 case Py_GE: istrue = diff >= 0; break;
1431 case Py_LT: istrue = diff < 0; break;
1432 case Py_GT: istrue = diff > 0; break;
1433 default:
1434 assert(! "op unknown");
1435 istrue = 0; /* To shut up compiler */
1436 }
1437 result = istrue ? Py_True : Py_False;
1438 Py_INCREF(result);
1439 return result;
1440}
1441
Tim Peters07534a62003-02-07 22:50:28 +00001442/* Raises a "can't compare" TypeError and returns NULL. */
1443static PyObject *
1444cmperror(PyObject *a, PyObject *b)
1445{
1446 PyErr_Format(PyExc_TypeError,
1447 "can't compare %s to %s",
1448 a->ob_type->tp_name, b->ob_type->tp_name);
1449 return NULL;
1450}
1451
Tim Peters2a799bf2002-12-16 20:18:38 +00001452/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001453 * Cached Python objects; these are set by the module init function.
1454 */
1455
1456/* Conversion factors. */
1457static PyObject *us_per_us = NULL; /* 1 */
1458static PyObject *us_per_ms = NULL; /* 1000 */
1459static PyObject *us_per_second = NULL; /* 1000000 */
1460static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1461static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1462static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1463static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1464static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1465
Tim Peters2a799bf2002-12-16 20:18:38 +00001466/* ---------------------------------------------------------------------------
1467 * Class implementations.
1468 */
1469
1470/*
1471 * PyDateTime_Delta implementation.
1472 */
1473
1474/* Convert a timedelta to a number of us,
1475 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1476 * as a Python int or long.
1477 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1478 * due to ubiquitous overflow possibilities.
1479 */
1480static PyObject *
1481delta_to_microseconds(PyDateTime_Delta *self)
1482{
1483 PyObject *x1 = NULL;
1484 PyObject *x2 = NULL;
1485 PyObject *x3 = NULL;
1486 PyObject *result = NULL;
1487
1488 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1489 if (x1 == NULL)
1490 goto Done;
1491 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1492 if (x2 == NULL)
1493 goto Done;
1494 Py_DECREF(x1);
1495 x1 = NULL;
1496
1497 /* x2 has days in seconds */
1498 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1499 if (x1 == NULL)
1500 goto Done;
1501 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1502 if (x3 == NULL)
1503 goto Done;
1504 Py_DECREF(x1);
1505 Py_DECREF(x2);
1506 x1 = x2 = NULL;
1507
1508 /* x3 has days+seconds in seconds */
1509 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1510 if (x1 == NULL)
1511 goto Done;
1512 Py_DECREF(x3);
1513 x3 = NULL;
1514
1515 /* x1 has days+seconds in us */
1516 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1517 if (x2 == NULL)
1518 goto Done;
1519 result = PyNumber_Add(x1, x2);
1520
1521Done:
1522 Py_XDECREF(x1);
1523 Py_XDECREF(x2);
1524 Py_XDECREF(x3);
1525 return result;
1526}
1527
1528/* Convert a number of us (as a Python int or long) to a timedelta.
1529 */
1530static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001531microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001532{
1533 int us;
1534 int s;
1535 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001536 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001537
1538 PyObject *tuple = NULL;
1539 PyObject *num = NULL;
1540 PyObject *result = NULL;
1541
1542 tuple = PyNumber_Divmod(pyus, us_per_second);
1543 if (tuple == NULL)
1544 goto Done;
1545
1546 num = PyTuple_GetItem(tuple, 1); /* us */
1547 if (num == NULL)
1548 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001549 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001550 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001551 if (temp == -1 && PyErr_Occurred())
1552 goto Done;
1553 assert(0 <= temp && temp < 1000000);
1554 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001555 if (us < 0) {
1556 /* The divisor was positive, so this must be an error. */
1557 assert(PyErr_Occurred());
1558 goto Done;
1559 }
1560
1561 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1562 if (num == NULL)
1563 goto Done;
1564 Py_INCREF(num);
1565 Py_DECREF(tuple);
1566
1567 tuple = PyNumber_Divmod(num, seconds_per_day);
1568 if (tuple == NULL)
1569 goto Done;
1570 Py_DECREF(num);
1571
1572 num = PyTuple_GetItem(tuple, 1); /* seconds */
1573 if (num == NULL)
1574 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001575 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001576 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001577 if (temp == -1 && PyErr_Occurred())
1578 goto Done;
1579 assert(0 <= temp && temp < 24*3600);
1580 s = (int)temp;
1581
Tim Peters2a799bf2002-12-16 20:18:38 +00001582 if (s < 0) {
1583 /* The divisor was positive, so this must be an error. */
1584 assert(PyErr_Occurred());
1585 goto Done;
1586 }
1587
1588 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1589 if (num == NULL)
1590 goto Done;
1591 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001592 temp = PyLong_AsLong(num);
1593 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001594 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001595 d = (int)temp;
1596 if ((long)d != temp) {
1597 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1598 "large to fit in a C int");
1599 goto Done;
1600 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001601 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001602
1603Done:
1604 Py_XDECREF(tuple);
1605 Py_XDECREF(num);
1606 return result;
1607}
1608
Tim Petersb0c854d2003-05-17 15:57:00 +00001609#define microseconds_to_delta(pymicros) \
1610 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1611
Tim Peters2a799bf2002-12-16 20:18:38 +00001612static PyObject *
1613multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1614{
1615 PyObject *pyus_in;
1616 PyObject *pyus_out;
1617 PyObject *result;
1618
1619 pyus_in = delta_to_microseconds(delta);
1620 if (pyus_in == NULL)
1621 return NULL;
1622
1623 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1624 Py_DECREF(pyus_in);
1625 if (pyus_out == NULL)
1626 return NULL;
1627
1628 result = microseconds_to_delta(pyus_out);
1629 Py_DECREF(pyus_out);
1630 return result;
1631}
1632
1633static PyObject *
1634divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1635{
1636 PyObject *pyus_in;
1637 PyObject *pyus_out;
1638 PyObject *result;
1639
1640 pyus_in = delta_to_microseconds(delta);
1641 if (pyus_in == NULL)
1642 return NULL;
1643
1644 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1645 Py_DECREF(pyus_in);
1646 if (pyus_out == NULL)
1647 return NULL;
1648
1649 result = microseconds_to_delta(pyus_out);
1650 Py_DECREF(pyus_out);
1651 return result;
1652}
1653
1654static PyObject *
1655delta_add(PyObject *left, PyObject *right)
1656{
1657 PyObject *result = Py_NotImplemented;
1658
1659 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1660 /* delta + delta */
1661 /* The C-level additions can't overflow because of the
1662 * invariant bounds.
1663 */
1664 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1665 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1666 int microseconds = GET_TD_MICROSECONDS(left) +
1667 GET_TD_MICROSECONDS(right);
1668 result = new_delta(days, seconds, microseconds, 1);
1669 }
1670
1671 if (result == Py_NotImplemented)
1672 Py_INCREF(result);
1673 return result;
1674}
1675
1676static PyObject *
1677delta_negative(PyDateTime_Delta *self)
1678{
1679 return new_delta(-GET_TD_DAYS(self),
1680 -GET_TD_SECONDS(self),
1681 -GET_TD_MICROSECONDS(self),
1682 1);
1683}
1684
1685static PyObject *
1686delta_positive(PyDateTime_Delta *self)
1687{
1688 /* Could optimize this (by returning self) if this isn't a
1689 * subclass -- but who uses unary + ? Approximately nobody.
1690 */
1691 return new_delta(GET_TD_DAYS(self),
1692 GET_TD_SECONDS(self),
1693 GET_TD_MICROSECONDS(self),
1694 0);
1695}
1696
1697static PyObject *
1698delta_abs(PyDateTime_Delta *self)
1699{
1700 PyObject *result;
1701
1702 assert(GET_TD_MICROSECONDS(self) >= 0);
1703 assert(GET_TD_SECONDS(self) >= 0);
1704
1705 if (GET_TD_DAYS(self) < 0)
1706 result = delta_negative(self);
1707 else
1708 result = delta_positive(self);
1709
1710 return result;
1711}
1712
1713static PyObject *
1714delta_subtract(PyObject *left, PyObject *right)
1715{
1716 PyObject *result = Py_NotImplemented;
1717
1718 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1719 /* delta - delta */
1720 PyObject *minus_right = PyNumber_Negative(right);
1721 if (minus_right) {
1722 result = delta_add(left, minus_right);
1723 Py_DECREF(minus_right);
1724 }
1725 else
1726 result = NULL;
1727 }
1728
1729 if (result == Py_NotImplemented)
1730 Py_INCREF(result);
1731 return result;
1732}
1733
Tim Peters2a799bf2002-12-16 20:18:38 +00001734static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001735delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001736{
Tim Petersaa7d8492003-02-08 03:28:59 +00001737 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001738 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001739 if (diff == 0) {
1740 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1741 if (diff == 0)
1742 diff = GET_TD_MICROSECONDS(self) -
1743 GET_TD_MICROSECONDS(other);
1744 }
Guido van Rossum19960592006-08-24 17:29:38 +00001745 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001746 }
Guido van Rossum19960592006-08-24 17:29:38 +00001747 else {
1748 Py_INCREF(Py_NotImplemented);
1749 return Py_NotImplemented;
1750 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001751}
1752
1753static PyObject *delta_getstate(PyDateTime_Delta *self);
1754
1755static long
1756delta_hash(PyDateTime_Delta *self)
1757{
1758 if (self->hashcode == -1) {
1759 PyObject *temp = delta_getstate(self);
1760 if (temp != NULL) {
1761 self->hashcode = PyObject_Hash(temp);
1762 Py_DECREF(temp);
1763 }
1764 }
1765 return self->hashcode;
1766}
1767
1768static PyObject *
1769delta_multiply(PyObject *left, PyObject *right)
1770{
1771 PyObject *result = Py_NotImplemented;
1772
1773 if (PyDelta_Check(left)) {
1774 /* delta * ??? */
1775 if (PyInt_Check(right) || PyLong_Check(right))
1776 result = multiply_int_timedelta(right,
1777 (PyDateTime_Delta *) left);
1778 }
1779 else if (PyInt_Check(left) || PyLong_Check(left))
1780 result = multiply_int_timedelta(left,
1781 (PyDateTime_Delta *) right);
1782
1783 if (result == Py_NotImplemented)
1784 Py_INCREF(result);
1785 return result;
1786}
1787
1788static PyObject *
1789delta_divide(PyObject *left, PyObject *right)
1790{
1791 PyObject *result = Py_NotImplemented;
1792
1793 if (PyDelta_Check(left)) {
1794 /* delta * ??? */
1795 if (PyInt_Check(right) || PyLong_Check(right))
1796 result = divide_timedelta_int(
1797 (PyDateTime_Delta *)left,
1798 right);
1799 }
1800
1801 if (result == Py_NotImplemented)
1802 Py_INCREF(result);
1803 return result;
1804}
1805
1806/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1807 * timedelta constructor. sofar is the # of microseconds accounted for
1808 * so far, and there are factor microseconds per current unit, the number
1809 * of which is given by num. num * factor is added to sofar in a
1810 * numerically careful way, and that's the result. Any fractional
1811 * microseconds left over (this can happen if num is a float type) are
1812 * added into *leftover.
1813 * Note that there are many ways this can give an error (NULL) return.
1814 */
1815static PyObject *
1816accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1817 double *leftover)
1818{
1819 PyObject *prod;
1820 PyObject *sum;
1821
1822 assert(num != NULL);
1823
1824 if (PyInt_Check(num) || PyLong_Check(num)) {
1825 prod = PyNumber_Multiply(num, factor);
1826 if (prod == NULL)
1827 return NULL;
1828 sum = PyNumber_Add(sofar, prod);
1829 Py_DECREF(prod);
1830 return sum;
1831 }
1832
1833 if (PyFloat_Check(num)) {
1834 double dnum;
1835 double fracpart;
1836 double intpart;
1837 PyObject *x;
1838 PyObject *y;
1839
1840 /* The Plan: decompose num into an integer part and a
1841 * fractional part, num = intpart + fracpart.
1842 * Then num * factor ==
1843 * intpart * factor + fracpart * factor
1844 * and the LHS can be computed exactly in long arithmetic.
1845 * The RHS is again broken into an int part and frac part.
1846 * and the frac part is added into *leftover.
1847 */
1848 dnum = PyFloat_AsDouble(num);
1849 if (dnum == -1.0 && PyErr_Occurred())
1850 return NULL;
1851 fracpart = modf(dnum, &intpart);
1852 x = PyLong_FromDouble(intpart);
1853 if (x == NULL)
1854 return NULL;
1855
1856 prod = PyNumber_Multiply(x, factor);
1857 Py_DECREF(x);
1858 if (prod == NULL)
1859 return NULL;
1860
1861 sum = PyNumber_Add(sofar, prod);
1862 Py_DECREF(prod);
1863 if (sum == NULL)
1864 return NULL;
1865
1866 if (fracpart == 0.0)
1867 return sum;
1868 /* So far we've lost no information. Dealing with the
1869 * fractional part requires float arithmetic, and may
1870 * lose a little info.
1871 */
1872 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001873 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001874
1875 dnum *= fracpart;
1876 fracpart = modf(dnum, &intpart);
1877 x = PyLong_FromDouble(intpart);
1878 if (x == NULL) {
1879 Py_DECREF(sum);
1880 return NULL;
1881 }
1882
1883 y = PyNumber_Add(sum, x);
1884 Py_DECREF(sum);
1885 Py_DECREF(x);
1886 *leftover += fracpart;
1887 return y;
1888 }
1889
1890 PyErr_Format(PyExc_TypeError,
1891 "unsupported type for timedelta %s component: %s",
1892 tag, num->ob_type->tp_name);
1893 return NULL;
1894}
1895
1896static PyObject *
1897delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1898{
1899 PyObject *self = NULL;
1900
1901 /* Argument objects. */
1902 PyObject *day = NULL;
1903 PyObject *second = NULL;
1904 PyObject *us = NULL;
1905 PyObject *ms = NULL;
1906 PyObject *minute = NULL;
1907 PyObject *hour = NULL;
1908 PyObject *week = NULL;
1909
1910 PyObject *x = NULL; /* running sum of microseconds */
1911 PyObject *y = NULL; /* temp sum of microseconds */
1912 double leftover_us = 0.0;
1913
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001914 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001915 "days", "seconds", "microseconds", "milliseconds",
1916 "minutes", "hours", "weeks", NULL
1917 };
1918
1919 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1920 keywords,
1921 &day, &second, &us,
1922 &ms, &minute, &hour, &week) == 0)
1923 goto Done;
1924
1925 x = PyInt_FromLong(0);
1926 if (x == NULL)
1927 goto Done;
1928
1929#define CLEANUP \
1930 Py_DECREF(x); \
1931 x = y; \
1932 if (x == NULL) \
1933 goto Done
1934
1935 if (us) {
1936 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1937 CLEANUP;
1938 }
1939 if (ms) {
1940 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1941 CLEANUP;
1942 }
1943 if (second) {
1944 y = accum("seconds", x, second, us_per_second, &leftover_us);
1945 CLEANUP;
1946 }
1947 if (minute) {
1948 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1949 CLEANUP;
1950 }
1951 if (hour) {
1952 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1953 CLEANUP;
1954 }
1955 if (day) {
1956 y = accum("days", x, day, us_per_day, &leftover_us);
1957 CLEANUP;
1958 }
1959 if (week) {
1960 y = accum("weeks", x, week, us_per_week, &leftover_us);
1961 CLEANUP;
1962 }
1963 if (leftover_us) {
1964 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001965 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001966 if (temp == NULL) {
1967 Py_DECREF(x);
1968 goto Done;
1969 }
1970 y = PyNumber_Add(x, temp);
1971 Py_DECREF(temp);
1972 CLEANUP;
1973 }
1974
Tim Petersb0c854d2003-05-17 15:57:00 +00001975 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001976 Py_DECREF(x);
1977Done:
1978 return self;
1979
1980#undef CLEANUP
1981}
1982
1983static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001984delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001985{
1986 return (GET_TD_DAYS(self) != 0
1987 || GET_TD_SECONDS(self) != 0
1988 || GET_TD_MICROSECONDS(self) != 0);
1989}
1990
1991static PyObject *
1992delta_repr(PyDateTime_Delta *self)
1993{
1994 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001995 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001996 self->ob_type->tp_name,
1997 GET_TD_DAYS(self),
1998 GET_TD_SECONDS(self),
1999 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002000 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00002001 return PyUnicode_FromFormat("%s(%d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002002 self->ob_type->tp_name,
2003 GET_TD_DAYS(self),
2004 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002005
Walter Dörwald1ab83302007-05-18 17:15:44 +00002006 return PyUnicode_FromFormat("%s(%d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002007 self->ob_type->tp_name,
2008 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002009}
2010
2011static PyObject *
2012delta_str(PyDateTime_Delta *self)
2013{
2014 int days = GET_TD_DAYS(self);
2015 int seconds = GET_TD_SECONDS(self);
2016 int us = GET_TD_MICROSECONDS(self);
2017 int hours;
2018 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00002019 char buf[100];
2020 char *pbuf = buf;
2021 size_t buflen = sizeof(buf);
2022 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002023
2024 minutes = divmod(seconds, 60, &seconds);
2025 hours = divmod(minutes, 60, &minutes);
2026
2027 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002028 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2029 (days == 1 || days == -1) ? "" : "s");
2030 if (n < 0 || (size_t)n >= buflen)
2031 goto Fail;
2032 pbuf += n;
2033 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002034 }
2035
Tim Petersba873472002-12-18 20:19:21 +00002036 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2037 hours, minutes, seconds);
2038 if (n < 0 || (size_t)n >= buflen)
2039 goto Fail;
2040 pbuf += n;
2041 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002042
2043 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002044 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2045 if (n < 0 || (size_t)n >= buflen)
2046 goto Fail;
2047 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002048 }
2049
Tim Petersba873472002-12-18 20:19:21 +00002050 return PyString_FromStringAndSize(buf, pbuf - buf);
2051
2052 Fail:
2053 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2054 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002055}
2056
Tim Peters371935f2003-02-01 01:52:50 +00002057/* Pickle support, a simple use of __reduce__. */
2058
Tim Petersb57f8f02003-02-01 02:54:15 +00002059/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002060static PyObject *
2061delta_getstate(PyDateTime_Delta *self)
2062{
2063 return Py_BuildValue("iii", GET_TD_DAYS(self),
2064 GET_TD_SECONDS(self),
2065 GET_TD_MICROSECONDS(self));
2066}
2067
Tim Peters2a799bf2002-12-16 20:18:38 +00002068static PyObject *
2069delta_reduce(PyDateTime_Delta* self)
2070{
Tim Peters8a60c222003-02-01 01:47:29 +00002071 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002072}
2073
2074#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2075
2076static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002077
Neal Norwitzdfb80862002-12-19 02:30:56 +00002078 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002079 PyDoc_STR("Number of days.")},
2080
Neal Norwitzdfb80862002-12-19 02:30:56 +00002081 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002082 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2083
Neal Norwitzdfb80862002-12-19 02:30:56 +00002084 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002085 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2086 {NULL}
2087};
2088
2089static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002090 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2091 PyDoc_STR("__reduce__() -> (cls, state)")},
2092
Tim Peters2a799bf2002-12-16 20:18:38 +00002093 {NULL, NULL},
2094};
2095
2096static char delta_doc[] =
2097PyDoc_STR("Difference between two datetime values.");
2098
2099static PyNumberMethods delta_as_number = {
2100 delta_add, /* nb_add */
2101 delta_subtract, /* nb_subtract */
2102 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002103 0, /* nb_remainder */
2104 0, /* nb_divmod */
2105 0, /* nb_power */
2106 (unaryfunc)delta_negative, /* nb_negative */
2107 (unaryfunc)delta_positive, /* nb_positive */
2108 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002109 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002110 0, /*nb_invert*/
2111 0, /*nb_lshift*/
2112 0, /*nb_rshift*/
2113 0, /*nb_and*/
2114 0, /*nb_xor*/
2115 0, /*nb_or*/
2116 0, /*nb_coerce*/
2117 0, /*nb_int*/
2118 0, /*nb_long*/
2119 0, /*nb_float*/
2120 0, /*nb_oct*/
2121 0, /*nb_hex*/
2122 0, /*nb_inplace_add*/
2123 0, /*nb_inplace_subtract*/
2124 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002125 0, /*nb_inplace_remainder*/
2126 0, /*nb_inplace_power*/
2127 0, /*nb_inplace_lshift*/
2128 0, /*nb_inplace_rshift*/
2129 0, /*nb_inplace_and*/
2130 0, /*nb_inplace_xor*/
2131 0, /*nb_inplace_or*/
2132 delta_divide, /* nb_floor_divide */
2133 0, /* nb_true_divide */
2134 0, /* nb_inplace_floor_divide */
2135 0, /* nb_inplace_true_divide */
2136};
2137
2138static PyTypeObject PyDateTime_DeltaType = {
2139 PyObject_HEAD_INIT(NULL)
2140 0, /* ob_size */
2141 "datetime.timedelta", /* tp_name */
2142 sizeof(PyDateTime_Delta), /* tp_basicsize */
2143 0, /* tp_itemsize */
2144 0, /* tp_dealloc */
2145 0, /* tp_print */
2146 0, /* tp_getattr */
2147 0, /* tp_setattr */
2148 0, /* tp_compare */
2149 (reprfunc)delta_repr, /* tp_repr */
2150 &delta_as_number, /* tp_as_number */
2151 0, /* tp_as_sequence */
2152 0, /* tp_as_mapping */
2153 (hashfunc)delta_hash, /* tp_hash */
2154 0, /* tp_call */
2155 (reprfunc)delta_str, /* tp_str */
2156 PyObject_GenericGetAttr, /* tp_getattro */
2157 0, /* tp_setattro */
2158 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002159 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002160 delta_doc, /* tp_doc */
2161 0, /* tp_traverse */
2162 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002163 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002164 0, /* tp_weaklistoffset */
2165 0, /* tp_iter */
2166 0, /* tp_iternext */
2167 delta_methods, /* tp_methods */
2168 delta_members, /* tp_members */
2169 0, /* tp_getset */
2170 0, /* tp_base */
2171 0, /* tp_dict */
2172 0, /* tp_descr_get */
2173 0, /* tp_descr_set */
2174 0, /* tp_dictoffset */
2175 0, /* tp_init */
2176 0, /* tp_alloc */
2177 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002178 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002179};
2180
2181/*
2182 * PyDateTime_Date implementation.
2183 */
2184
2185/* Accessor properties. */
2186
2187static PyObject *
2188date_year(PyDateTime_Date *self, void *unused)
2189{
2190 return PyInt_FromLong(GET_YEAR(self));
2191}
2192
2193static PyObject *
2194date_month(PyDateTime_Date *self, void *unused)
2195{
2196 return PyInt_FromLong(GET_MONTH(self));
2197}
2198
2199static PyObject *
2200date_day(PyDateTime_Date *self, void *unused)
2201{
2202 return PyInt_FromLong(GET_DAY(self));
2203}
2204
2205static PyGetSetDef date_getset[] = {
2206 {"year", (getter)date_year},
2207 {"month", (getter)date_month},
2208 {"day", (getter)date_day},
2209 {NULL}
2210};
2211
2212/* Constructors. */
2213
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002214static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002215
Tim Peters2a799bf2002-12-16 20:18:38 +00002216static PyObject *
2217date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2218{
2219 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002220 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002221 int year;
2222 int month;
2223 int day;
2224
Guido van Rossum177e41a2003-01-30 22:06:23 +00002225 /* Check for invocation from pickle with __getstate__ state */
2226 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002227 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002228 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2229 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002230 {
Tim Peters70533e22003-02-01 04:40:04 +00002231 PyDateTime_Date *me;
2232
Tim Peters604c0132004-06-07 23:04:33 +00002233 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002234 if (me != NULL) {
2235 char *pdata = PyString_AS_STRING(state);
2236 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2237 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002238 }
Tim Peters70533e22003-02-01 04:40:04 +00002239 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002240 }
2241
Tim Peters12bf3392002-12-24 05:41:27 +00002242 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002243 &year, &month, &day)) {
2244 if (check_date_args(year, month, day) < 0)
2245 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002246 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002247 }
2248 return self;
2249}
2250
2251/* Return new date from localtime(t). */
2252static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002253date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002254{
2255 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002256 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002257 PyObject *result = NULL;
2258
Tim Peters1b6f7a92004-06-20 02:50:16 +00002259 t = _PyTime_DoubleToTimet(ts);
2260 if (t == (time_t)-1 && PyErr_Occurred())
2261 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002262 tm = localtime(&t);
2263 if (tm)
2264 result = PyObject_CallFunction(cls, "iii",
2265 tm->tm_year + 1900,
2266 tm->tm_mon + 1,
2267 tm->tm_mday);
2268 else
2269 PyErr_SetString(PyExc_ValueError,
2270 "timestamp out of range for "
2271 "platform localtime() function");
2272 return result;
2273}
2274
2275/* Return new date from current time.
2276 * We say this is equivalent to fromtimestamp(time.time()), and the
2277 * only way to be sure of that is to *call* time.time(). That's not
2278 * generally the same as calling C's time.
2279 */
2280static PyObject *
2281date_today(PyObject *cls, PyObject *dummy)
2282{
2283 PyObject *time;
2284 PyObject *result;
2285
2286 time = time_time();
2287 if (time == NULL)
2288 return NULL;
2289
2290 /* Note well: today() is a class method, so this may not call
2291 * date.fromtimestamp. For example, it may call
2292 * datetime.fromtimestamp. That's why we need all the accuracy
2293 * time.time() delivers; if someone were gonzo about optimization,
2294 * date.today() could get away with plain C time().
2295 */
2296 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2297 Py_DECREF(time);
2298 return result;
2299}
2300
2301/* Return new date from given timestamp (Python timestamp -- a double). */
2302static PyObject *
2303date_fromtimestamp(PyObject *cls, PyObject *args)
2304{
2305 double timestamp;
2306 PyObject *result = NULL;
2307
2308 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002309 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002310 return result;
2311}
2312
2313/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2314 * the ordinal is out of range.
2315 */
2316static PyObject *
2317date_fromordinal(PyObject *cls, PyObject *args)
2318{
2319 PyObject *result = NULL;
2320 int ordinal;
2321
2322 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2323 int year;
2324 int month;
2325 int day;
2326
2327 if (ordinal < 1)
2328 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2329 ">= 1");
2330 else {
2331 ord_to_ymd(ordinal, &year, &month, &day);
2332 result = PyObject_CallFunction(cls, "iii",
2333 year, month, day);
2334 }
2335 }
2336 return result;
2337}
2338
2339/*
2340 * Date arithmetic.
2341 */
2342
2343/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2344 * instead.
2345 */
2346static PyObject *
2347add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2348{
2349 PyObject *result = NULL;
2350 int year = GET_YEAR(date);
2351 int month = GET_MONTH(date);
2352 int deltadays = GET_TD_DAYS(delta);
2353 /* C-level overflow is impossible because |deltadays| < 1e9. */
2354 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2355
2356 if (normalize_date(&year, &month, &day) >= 0)
2357 result = new_date(year, month, day);
2358 return result;
2359}
2360
2361static PyObject *
2362date_add(PyObject *left, PyObject *right)
2363{
2364 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2365 Py_INCREF(Py_NotImplemented);
2366 return Py_NotImplemented;
2367 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002368 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002369 /* date + ??? */
2370 if (PyDelta_Check(right))
2371 /* date + delta */
2372 return add_date_timedelta((PyDateTime_Date *) left,
2373 (PyDateTime_Delta *) right,
2374 0);
2375 }
2376 else {
2377 /* ??? + date
2378 * 'right' must be one of us, or we wouldn't have been called
2379 */
2380 if (PyDelta_Check(left))
2381 /* delta + date */
2382 return add_date_timedelta((PyDateTime_Date *) right,
2383 (PyDateTime_Delta *) left,
2384 0);
2385 }
2386 Py_INCREF(Py_NotImplemented);
2387 return Py_NotImplemented;
2388}
2389
2390static PyObject *
2391date_subtract(PyObject *left, PyObject *right)
2392{
2393 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2394 Py_INCREF(Py_NotImplemented);
2395 return Py_NotImplemented;
2396 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002397 if (PyDate_Check(left)) {
2398 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002399 /* date - date */
2400 int left_ord = ymd_to_ord(GET_YEAR(left),
2401 GET_MONTH(left),
2402 GET_DAY(left));
2403 int right_ord = ymd_to_ord(GET_YEAR(right),
2404 GET_MONTH(right),
2405 GET_DAY(right));
2406 return new_delta(left_ord - right_ord, 0, 0, 0);
2407 }
2408 if (PyDelta_Check(right)) {
2409 /* date - delta */
2410 return add_date_timedelta((PyDateTime_Date *) left,
2411 (PyDateTime_Delta *) right,
2412 1);
2413 }
2414 }
2415 Py_INCREF(Py_NotImplemented);
2416 return Py_NotImplemented;
2417}
2418
2419
2420/* Various ways to turn a date into a string. */
2421
2422static PyObject *
2423date_repr(PyDateTime_Date *self)
2424{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002425 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2426 self->ob_type->tp_name,
2427 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002428}
2429
2430static PyObject *
2431date_isoformat(PyDateTime_Date *self)
2432{
2433 char buffer[128];
2434
2435 isoformat_date(self, buffer, sizeof(buffer));
2436 return PyString_FromString(buffer);
2437}
2438
Tim Peterse2df5ff2003-05-02 18:39:55 +00002439/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002440static PyObject *
2441date_str(PyDateTime_Date *self)
2442{
2443 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2444}
2445
2446
2447static PyObject *
2448date_ctime(PyDateTime_Date *self)
2449{
2450 return format_ctime(self, 0, 0, 0);
2451}
2452
2453static PyObject *
2454date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2455{
2456 /* This method can be inherited, and needs to call the
2457 * timetuple() method appropriate to self's class.
2458 */
2459 PyObject *result;
2460 PyObject *format;
2461 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002462 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002463
Guido van Rossumbce56a62007-05-10 18:04:33 +00002464 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2465 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002466 return NULL;
2467
2468 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2469 if (tuple == NULL)
2470 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002471 result = wrap_strftime((PyObject *)self, format, tuple,
2472 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002473 Py_DECREF(tuple);
2474 return result;
2475}
2476
2477/* ISO methods. */
2478
2479static PyObject *
2480date_isoweekday(PyDateTime_Date *self)
2481{
2482 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2483
2484 return PyInt_FromLong(dow + 1);
2485}
2486
2487static PyObject *
2488date_isocalendar(PyDateTime_Date *self)
2489{
2490 int year = GET_YEAR(self);
2491 int week1_monday = iso_week1_monday(year);
2492 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2493 int week;
2494 int day;
2495
2496 week = divmod(today - week1_monday, 7, &day);
2497 if (week < 0) {
2498 --year;
2499 week1_monday = iso_week1_monday(year);
2500 week = divmod(today - week1_monday, 7, &day);
2501 }
2502 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2503 ++year;
2504 week = 0;
2505 }
2506 return Py_BuildValue("iii", year, week + 1, day + 1);
2507}
2508
2509/* Miscellaneous methods. */
2510
Tim Peters2a799bf2002-12-16 20:18:38 +00002511static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002512date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002513{
Guido van Rossum19960592006-08-24 17:29:38 +00002514 if (PyDate_Check(other)) {
2515 int diff = memcmp(((PyDateTime_Date *)self)->data,
2516 ((PyDateTime_Date *)other)->data,
2517 _PyDateTime_DATE_DATASIZE);
2518 return diff_to_bool(diff, op);
2519 }
2520 else {
Tim Peters07534a62003-02-07 22:50:28 +00002521 Py_INCREF(Py_NotImplemented);
2522 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002523 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002524}
2525
2526static PyObject *
2527date_timetuple(PyDateTime_Date *self)
2528{
2529 return build_struct_time(GET_YEAR(self),
2530 GET_MONTH(self),
2531 GET_DAY(self),
2532 0, 0, 0, -1);
2533}
2534
Tim Peters12bf3392002-12-24 05:41:27 +00002535static PyObject *
2536date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2537{
2538 PyObject *clone;
2539 PyObject *tuple;
2540 int year = GET_YEAR(self);
2541 int month = GET_MONTH(self);
2542 int day = GET_DAY(self);
2543
2544 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2545 &year, &month, &day))
2546 return NULL;
2547 tuple = Py_BuildValue("iii", year, month, day);
2548 if (tuple == NULL)
2549 return NULL;
2550 clone = date_new(self->ob_type, tuple, NULL);
2551 Py_DECREF(tuple);
2552 return clone;
2553}
2554
Tim Peters2a799bf2002-12-16 20:18:38 +00002555static PyObject *date_getstate(PyDateTime_Date *self);
2556
2557static long
2558date_hash(PyDateTime_Date *self)
2559{
2560 if (self->hashcode == -1) {
2561 PyObject *temp = date_getstate(self);
2562 if (temp != NULL) {
2563 self->hashcode = PyObject_Hash(temp);
2564 Py_DECREF(temp);
2565 }
2566 }
2567 return self->hashcode;
2568}
2569
2570static PyObject *
2571date_toordinal(PyDateTime_Date *self)
2572{
2573 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2574 GET_DAY(self)));
2575}
2576
2577static PyObject *
2578date_weekday(PyDateTime_Date *self)
2579{
2580 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2581
2582 return PyInt_FromLong(dow);
2583}
2584
Tim Peters371935f2003-02-01 01:52:50 +00002585/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002586
Tim Petersb57f8f02003-02-01 02:54:15 +00002587/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002588static PyObject *
2589date_getstate(PyDateTime_Date *self)
2590{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002591 return Py_BuildValue(
2592 "(N)",
2593 PyString_FromStringAndSize((char *)self->data,
2594 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002595}
2596
2597static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002598date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002599{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002600 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002601}
2602
2603static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002604
Tim Peters2a799bf2002-12-16 20:18:38 +00002605 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002606
Tim Peters2a799bf2002-12-16 20:18:38 +00002607 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2608 METH_CLASS,
2609 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2610 "time.time()).")},
2611
2612 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2613 METH_CLASS,
2614 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2615 "ordinal.")},
2616
2617 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2618 PyDoc_STR("Current date or datetime: same as "
2619 "self.__class__.fromtimestamp(time.time()).")},
2620
2621 /* Instance methods: */
2622
2623 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2624 PyDoc_STR("Return ctime() style string.")},
2625
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002626 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002627 PyDoc_STR("format -> strftime() style string.")},
2628
2629 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2630 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2631
2632 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2633 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2634 "weekday.")},
2635
2636 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2637 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2638
2639 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2640 PyDoc_STR("Return the day of the week represented by the date.\n"
2641 "Monday == 1 ... Sunday == 7")},
2642
2643 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2644 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2645 "1 is day 1.")},
2646
2647 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2648 PyDoc_STR("Return the day of the week represented by the date.\n"
2649 "Monday == 0 ... Sunday == 6")},
2650
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002651 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002652 PyDoc_STR("Return date with new specified fields.")},
2653
Guido van Rossum177e41a2003-01-30 22:06:23 +00002654 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2655 PyDoc_STR("__reduce__() -> (cls, state)")},
2656
Tim Peters2a799bf2002-12-16 20:18:38 +00002657 {NULL, NULL}
2658};
2659
2660static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002661PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002662
2663static PyNumberMethods date_as_number = {
2664 date_add, /* nb_add */
2665 date_subtract, /* nb_subtract */
2666 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002667 0, /* nb_remainder */
2668 0, /* nb_divmod */
2669 0, /* nb_power */
2670 0, /* nb_negative */
2671 0, /* nb_positive */
2672 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002673 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002674};
2675
2676static PyTypeObject PyDateTime_DateType = {
2677 PyObject_HEAD_INIT(NULL)
2678 0, /* ob_size */
2679 "datetime.date", /* tp_name */
2680 sizeof(PyDateTime_Date), /* tp_basicsize */
2681 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002682 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002683 0, /* tp_print */
2684 0, /* tp_getattr */
2685 0, /* tp_setattr */
2686 0, /* tp_compare */
2687 (reprfunc)date_repr, /* tp_repr */
2688 &date_as_number, /* tp_as_number */
2689 0, /* tp_as_sequence */
2690 0, /* tp_as_mapping */
2691 (hashfunc)date_hash, /* tp_hash */
2692 0, /* tp_call */
2693 (reprfunc)date_str, /* tp_str */
2694 PyObject_GenericGetAttr, /* tp_getattro */
2695 0, /* tp_setattro */
2696 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002697 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002698 date_doc, /* tp_doc */
2699 0, /* tp_traverse */
2700 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002701 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002702 0, /* tp_weaklistoffset */
2703 0, /* tp_iter */
2704 0, /* tp_iternext */
2705 date_methods, /* tp_methods */
2706 0, /* tp_members */
2707 date_getset, /* tp_getset */
2708 0, /* tp_base */
2709 0, /* tp_dict */
2710 0, /* tp_descr_get */
2711 0, /* tp_descr_set */
2712 0, /* tp_dictoffset */
2713 0, /* tp_init */
2714 0, /* tp_alloc */
2715 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002716 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002717};
2718
2719/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002720 * PyDateTime_TZInfo implementation.
2721 */
2722
2723/* This is a pure abstract base class, so doesn't do anything beyond
2724 * raising NotImplemented exceptions. Real tzinfo classes need
2725 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002726 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002727 * be subclasses of this tzinfo class, which is easy and quick to check).
2728 *
2729 * Note: For reasons having to do with pickling of subclasses, we have
2730 * to allow tzinfo objects to be instantiated. This wasn't an issue
2731 * in the Python implementation (__init__() could raise NotImplementedError
2732 * there without ill effect), but doing so in the C implementation hit a
2733 * brick wall.
2734 */
2735
2736static PyObject *
2737tzinfo_nogo(const char* methodname)
2738{
2739 PyErr_Format(PyExc_NotImplementedError,
2740 "a tzinfo subclass must implement %s()",
2741 methodname);
2742 return NULL;
2743}
2744
2745/* Methods. A subclass must implement these. */
2746
Tim Peters52dcce22003-01-23 16:36:11 +00002747static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002748tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2749{
2750 return tzinfo_nogo("tzname");
2751}
2752
Tim Peters52dcce22003-01-23 16:36:11 +00002753static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002754tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2755{
2756 return tzinfo_nogo("utcoffset");
2757}
2758
Tim Peters52dcce22003-01-23 16:36:11 +00002759static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002760tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2761{
2762 return tzinfo_nogo("dst");
2763}
2764
Tim Peters52dcce22003-01-23 16:36:11 +00002765static PyObject *
2766tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2767{
2768 int y, m, d, hh, mm, ss, us;
2769
2770 PyObject *result;
2771 int off, dst;
2772 int none;
2773 int delta;
2774
2775 if (! PyDateTime_Check(dt)) {
2776 PyErr_SetString(PyExc_TypeError,
2777 "fromutc: argument must be a datetime");
2778 return NULL;
2779 }
2780 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2781 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2782 "is not self");
2783 return NULL;
2784 }
2785
2786 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2787 if (off == -1 && PyErr_Occurred())
2788 return NULL;
2789 if (none) {
2790 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2791 "utcoffset() result required");
2792 return NULL;
2793 }
2794
2795 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2796 if (dst == -1 && PyErr_Occurred())
2797 return NULL;
2798 if (none) {
2799 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2800 "dst() result required");
2801 return NULL;
2802 }
2803
2804 y = GET_YEAR(dt);
2805 m = GET_MONTH(dt);
2806 d = GET_DAY(dt);
2807 hh = DATE_GET_HOUR(dt);
2808 mm = DATE_GET_MINUTE(dt);
2809 ss = DATE_GET_SECOND(dt);
2810 us = DATE_GET_MICROSECOND(dt);
2811
2812 delta = off - dst;
2813 mm += delta;
2814 if ((mm < 0 || mm >= 60) &&
2815 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002816 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002817 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2818 if (result == NULL)
2819 return result;
2820
2821 dst = call_dst(dt->tzinfo, result, &none);
2822 if (dst == -1 && PyErr_Occurred())
2823 goto Fail;
2824 if (none)
2825 goto Inconsistent;
2826 if (dst == 0)
2827 return result;
2828
2829 mm += dst;
2830 if ((mm < 0 || mm >= 60) &&
2831 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2832 goto Fail;
2833 Py_DECREF(result);
2834 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2835 return result;
2836
2837Inconsistent:
2838 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2839 "inconsistent results; cannot convert");
2840
2841 /* fall thru to failure */
2842Fail:
2843 Py_DECREF(result);
2844 return NULL;
2845}
2846
Tim Peters2a799bf2002-12-16 20:18:38 +00002847/*
2848 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002849 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002850 */
2851
Guido van Rossum177e41a2003-01-30 22:06:23 +00002852static PyObject *
2853tzinfo_reduce(PyObject *self)
2854{
2855 PyObject *args, *state, *tmp;
2856 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002857
Guido van Rossum177e41a2003-01-30 22:06:23 +00002858 tmp = PyTuple_New(0);
2859 if (tmp == NULL)
2860 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002861
Guido van Rossum177e41a2003-01-30 22:06:23 +00002862 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2863 if (getinitargs != NULL) {
2864 args = PyObject_CallObject(getinitargs, tmp);
2865 Py_DECREF(getinitargs);
2866 if (args == NULL) {
2867 Py_DECREF(tmp);
2868 return NULL;
2869 }
2870 }
2871 else {
2872 PyErr_Clear();
2873 args = tmp;
2874 Py_INCREF(args);
2875 }
2876
2877 getstate = PyObject_GetAttrString(self, "__getstate__");
2878 if (getstate != NULL) {
2879 state = PyObject_CallObject(getstate, tmp);
2880 Py_DECREF(getstate);
2881 if (state == NULL) {
2882 Py_DECREF(args);
2883 Py_DECREF(tmp);
2884 return NULL;
2885 }
2886 }
2887 else {
2888 PyObject **dictptr;
2889 PyErr_Clear();
2890 state = Py_None;
2891 dictptr = _PyObject_GetDictPtr(self);
2892 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2893 state = *dictptr;
2894 Py_INCREF(state);
2895 }
2896
2897 Py_DECREF(tmp);
2898
2899 if (state == Py_None) {
2900 Py_DECREF(state);
2901 return Py_BuildValue("(ON)", self->ob_type, args);
2902 }
2903 else
2904 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2905}
Tim Peters2a799bf2002-12-16 20:18:38 +00002906
2907static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002908
Tim Peters2a799bf2002-12-16 20:18:38 +00002909 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2910 PyDoc_STR("datetime -> string name of time zone.")},
2911
2912 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2913 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2914 "west of UTC).")},
2915
2916 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2917 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2918
Tim Peters52dcce22003-01-23 16:36:11 +00002919 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2920 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2921
Guido van Rossum177e41a2003-01-30 22:06:23 +00002922 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2923 PyDoc_STR("-> (cls, state)")},
2924
Tim Peters2a799bf2002-12-16 20:18:38 +00002925 {NULL, NULL}
2926};
2927
2928static char tzinfo_doc[] =
2929PyDoc_STR("Abstract base class for time zone info objects.");
2930
Neal Norwitz227b5332006-03-22 09:28:35 +00002931static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002932 PyObject_HEAD_INIT(NULL)
2933 0, /* ob_size */
2934 "datetime.tzinfo", /* tp_name */
2935 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2936 0, /* tp_itemsize */
2937 0, /* tp_dealloc */
2938 0, /* tp_print */
2939 0, /* tp_getattr */
2940 0, /* tp_setattr */
2941 0, /* tp_compare */
2942 0, /* tp_repr */
2943 0, /* tp_as_number */
2944 0, /* tp_as_sequence */
2945 0, /* tp_as_mapping */
2946 0, /* tp_hash */
2947 0, /* tp_call */
2948 0, /* tp_str */
2949 PyObject_GenericGetAttr, /* tp_getattro */
2950 0, /* tp_setattro */
2951 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002952 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002953 tzinfo_doc, /* tp_doc */
2954 0, /* tp_traverse */
2955 0, /* tp_clear */
2956 0, /* tp_richcompare */
2957 0, /* tp_weaklistoffset */
2958 0, /* tp_iter */
2959 0, /* tp_iternext */
2960 tzinfo_methods, /* tp_methods */
2961 0, /* tp_members */
2962 0, /* tp_getset */
2963 0, /* tp_base */
2964 0, /* tp_dict */
2965 0, /* tp_descr_get */
2966 0, /* tp_descr_set */
2967 0, /* tp_dictoffset */
2968 0, /* tp_init */
2969 0, /* tp_alloc */
2970 PyType_GenericNew, /* tp_new */
2971 0, /* tp_free */
2972};
2973
2974/*
Tim Peters37f39822003-01-10 03:49:02 +00002975 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002976 */
2977
Tim Peters37f39822003-01-10 03:49:02 +00002978/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002979 */
2980
2981static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002982time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002983{
Tim Peters37f39822003-01-10 03:49:02 +00002984 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002985}
2986
Tim Peters37f39822003-01-10 03:49:02 +00002987static PyObject *
2988time_minute(PyDateTime_Time *self, void *unused)
2989{
2990 return PyInt_FromLong(TIME_GET_MINUTE(self));
2991}
2992
2993/* The name time_second conflicted with some platform header file. */
2994static PyObject *
2995py_time_second(PyDateTime_Time *self, void *unused)
2996{
2997 return PyInt_FromLong(TIME_GET_SECOND(self));
2998}
2999
3000static PyObject *
3001time_microsecond(PyDateTime_Time *self, void *unused)
3002{
3003 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3004}
3005
3006static PyObject *
3007time_tzinfo(PyDateTime_Time *self, void *unused)
3008{
Tim Petersa032d2e2003-01-11 00:15:54 +00003009 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003010 Py_INCREF(result);
3011 return result;
3012}
3013
3014static PyGetSetDef time_getset[] = {
3015 {"hour", (getter)time_hour},
3016 {"minute", (getter)time_minute},
3017 {"second", (getter)py_time_second},
3018 {"microsecond", (getter)time_microsecond},
3019 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003020 {NULL}
3021};
3022
3023/*
3024 * Constructors.
3025 */
3026
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003027static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003028 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003029
Tim Peters2a799bf2002-12-16 20:18:38 +00003030static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003031time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003032{
3033 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003034 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003035 int hour = 0;
3036 int minute = 0;
3037 int second = 0;
3038 int usecond = 0;
3039 PyObject *tzinfo = Py_None;
3040
Guido van Rossum177e41a2003-01-30 22:06:23 +00003041 /* Check for invocation from pickle with __getstate__ state */
3042 if (PyTuple_GET_SIZE(args) >= 1 &&
3043 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003044 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003045 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3046 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003047 {
Tim Peters70533e22003-02-01 04:40:04 +00003048 PyDateTime_Time *me;
3049 char aware;
3050
3051 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003052 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003053 if (check_tzinfo_subclass(tzinfo) < 0) {
3054 PyErr_SetString(PyExc_TypeError, "bad "
3055 "tzinfo state arg");
3056 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003057 }
3058 }
Tim Peters70533e22003-02-01 04:40:04 +00003059 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003060 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003061 if (me != NULL) {
3062 char *pdata = PyString_AS_STRING(state);
3063
3064 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3065 me->hashcode = -1;
3066 me->hastzinfo = aware;
3067 if (aware) {
3068 Py_INCREF(tzinfo);
3069 me->tzinfo = tzinfo;
3070 }
3071 }
3072 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003073 }
3074
Tim Peters37f39822003-01-10 03:49:02 +00003075 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003076 &hour, &minute, &second, &usecond,
3077 &tzinfo)) {
3078 if (check_time_args(hour, minute, second, usecond) < 0)
3079 return NULL;
3080 if (check_tzinfo_subclass(tzinfo) < 0)
3081 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003082 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3083 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003084 }
3085 return self;
3086}
3087
3088/*
3089 * Destructor.
3090 */
3091
3092static void
Tim Peters37f39822003-01-10 03:49:02 +00003093time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003094{
Tim Petersa032d2e2003-01-11 00:15:54 +00003095 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003096 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003097 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003098 self->ob_type->tp_free((PyObject *)self);
3099}
3100
3101/*
Tim Peters855fe882002-12-22 03:43:39 +00003102 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003103 */
3104
Tim Peters2a799bf2002-12-16 20:18:38 +00003105/* These are all METH_NOARGS, so don't need to check the arglist. */
3106static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003107time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003108 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003109 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003110}
3111
3112static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003113time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003114 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003115 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003116}
3117
3118static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003119time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003120 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003121 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003122}
3123
3124/*
Tim Peters37f39822003-01-10 03:49:02 +00003125 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003126 */
3127
3128static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003129time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003130{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003131 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003132 int h = TIME_GET_HOUR(self);
3133 int m = TIME_GET_MINUTE(self);
3134 int s = TIME_GET_SECOND(self);
3135 int us = TIME_GET_MICROSECOND(self);
3136 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003137
Tim Peters37f39822003-01-10 03:49:02 +00003138 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003139 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3140 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003141 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003142 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3143 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003144 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003145 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003146 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003147 result = append_keyword_tzinfo(result, self->tzinfo);
3148 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003149}
3150
Tim Peters37f39822003-01-10 03:49:02 +00003151static PyObject *
3152time_str(PyDateTime_Time *self)
3153{
3154 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3155}
Tim Peters2a799bf2002-12-16 20:18:38 +00003156
3157static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003158time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003159{
3160 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003161 PyObject *result;
3162 /* Reuse the time format code from the datetime type. */
3163 PyDateTime_DateTime datetime;
3164 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003165
Tim Peters37f39822003-01-10 03:49:02 +00003166 /* Copy over just the time bytes. */
3167 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3168 self->data,
3169 _PyDateTime_TIME_DATASIZE);
3170
3171 isoformat_time(pdatetime, buf, sizeof(buf));
3172 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003173 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003174 return result;
3175
3176 /* We need to append the UTC offset. */
3177 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003178 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003179 Py_DECREF(result);
3180 return NULL;
3181 }
3182 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3183 return result;
3184}
3185
Tim Peters37f39822003-01-10 03:49:02 +00003186static PyObject *
3187time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3188{
3189 PyObject *result;
3190 PyObject *format;
3191 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003192 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003193
Guido van Rossumbce56a62007-05-10 18:04:33 +00003194 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3195 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003196 return NULL;
3197
3198 /* Python's strftime does insane things with the year part of the
3199 * timetuple. The year is forced to (the otherwise nonsensical)
3200 * 1900 to worm around that.
3201 */
3202 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003203 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003204 TIME_GET_HOUR(self),
3205 TIME_GET_MINUTE(self),
3206 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003207 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003208 if (tuple == NULL)
3209 return NULL;
3210 assert(PyTuple_Size(tuple) == 9);
3211 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3212 Py_DECREF(tuple);
3213 return result;
3214}
Tim Peters2a799bf2002-12-16 20:18:38 +00003215
3216/*
3217 * Miscellaneous methods.
3218 */
3219
Tim Peters37f39822003-01-10 03:49:02 +00003220static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003221time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003222{
3223 int diff;
3224 naivety n1, n2;
3225 int offset1, offset2;
3226
3227 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003228 Py_INCREF(Py_NotImplemented);
3229 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003230 }
Guido van Rossum19960592006-08-24 17:29:38 +00003231 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3232 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003233 return NULL;
3234 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3235 /* If they're both naive, or both aware and have the same offsets,
3236 * we get off cheap. Note that if they're both naive, offset1 ==
3237 * offset2 == 0 at this point.
3238 */
3239 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003240 diff = memcmp(((PyDateTime_Time *)self)->data,
3241 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003242 _PyDateTime_TIME_DATASIZE);
3243 return diff_to_bool(diff, op);
3244 }
3245
3246 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3247 assert(offset1 != offset2); /* else last "if" handled it */
3248 /* Convert everything except microseconds to seconds. These
3249 * can't overflow (no more than the # of seconds in 2 days).
3250 */
3251 offset1 = TIME_GET_HOUR(self) * 3600 +
3252 (TIME_GET_MINUTE(self) - offset1) * 60 +
3253 TIME_GET_SECOND(self);
3254 offset2 = TIME_GET_HOUR(other) * 3600 +
3255 (TIME_GET_MINUTE(other) - offset2) * 60 +
3256 TIME_GET_SECOND(other);
3257 diff = offset1 - offset2;
3258 if (diff == 0)
3259 diff = TIME_GET_MICROSECOND(self) -
3260 TIME_GET_MICROSECOND(other);
3261 return diff_to_bool(diff, op);
3262 }
3263
3264 assert(n1 != n2);
3265 PyErr_SetString(PyExc_TypeError,
3266 "can't compare offset-naive and "
3267 "offset-aware times");
3268 return NULL;
3269}
3270
3271static long
3272time_hash(PyDateTime_Time *self)
3273{
3274 if (self->hashcode == -1) {
3275 naivety n;
3276 int offset;
3277 PyObject *temp;
3278
3279 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3280 assert(n != OFFSET_UNKNOWN);
3281 if (n == OFFSET_ERROR)
3282 return -1;
3283
3284 /* Reduce this to a hash of another object. */
3285 if (offset == 0)
3286 temp = PyString_FromStringAndSize((char *)self->data,
3287 _PyDateTime_TIME_DATASIZE);
3288 else {
3289 int hour;
3290 int minute;
3291
3292 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003293 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003294 hour = divmod(TIME_GET_HOUR(self) * 60 +
3295 TIME_GET_MINUTE(self) - offset,
3296 60,
3297 &minute);
3298 if (0 <= hour && hour < 24)
3299 temp = new_time(hour, minute,
3300 TIME_GET_SECOND(self),
3301 TIME_GET_MICROSECOND(self),
3302 Py_None);
3303 else
3304 temp = Py_BuildValue("iiii",
3305 hour, minute,
3306 TIME_GET_SECOND(self),
3307 TIME_GET_MICROSECOND(self));
3308 }
3309 if (temp != NULL) {
3310 self->hashcode = PyObject_Hash(temp);
3311 Py_DECREF(temp);
3312 }
3313 }
3314 return self->hashcode;
3315}
Tim Peters2a799bf2002-12-16 20:18:38 +00003316
Tim Peters12bf3392002-12-24 05:41:27 +00003317static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003318time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003319{
3320 PyObject *clone;
3321 PyObject *tuple;
3322 int hh = TIME_GET_HOUR(self);
3323 int mm = TIME_GET_MINUTE(self);
3324 int ss = TIME_GET_SECOND(self);
3325 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003326 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003327
3328 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003329 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003330 &hh, &mm, &ss, &us, &tzinfo))
3331 return NULL;
3332 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3333 if (tuple == NULL)
3334 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003335 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003336 Py_DECREF(tuple);
3337 return clone;
3338}
3339
Tim Peters2a799bf2002-12-16 20:18:38 +00003340static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003341time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003342{
3343 int offset;
3344 int none;
3345
3346 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3347 /* Since utcoffset is in whole minutes, nothing can
3348 * alter the conclusion that this is nonzero.
3349 */
3350 return 1;
3351 }
3352 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003353 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003354 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003355 if (offset == -1 && PyErr_Occurred())
3356 return -1;
3357 }
3358 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3359}
3360
Tim Peters371935f2003-02-01 01:52:50 +00003361/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003362
Tim Peters33e0f382003-01-10 02:05:14 +00003363/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003364 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3365 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003366 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003367 */
3368static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003369time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003370{
3371 PyObject *basestate;
3372 PyObject *result = NULL;
3373
Tim Peters33e0f382003-01-10 02:05:14 +00003374 basestate = PyString_FromStringAndSize((char *)self->data,
3375 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003376 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003377 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003378 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003379 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003380 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003381 Py_DECREF(basestate);
3382 }
3383 return result;
3384}
3385
3386static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003387time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003388{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003389 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003390}
3391
Tim Peters37f39822003-01-10 03:49:02 +00003392static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003393
Thomas Wouterscf297e42007-02-23 15:07:44 +00003394 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003395 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3396 "[+HH:MM].")},
3397
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003398 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003399 PyDoc_STR("format -> strftime() style string.")},
3400
3401 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003402 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3403
Tim Peters37f39822003-01-10 03:49:02 +00003404 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003405 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3406
Tim Peters37f39822003-01-10 03:49:02 +00003407 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003408 PyDoc_STR("Return self.tzinfo.dst(self).")},
3409
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003410 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003411 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003412
Guido van Rossum177e41a2003-01-30 22:06:23 +00003413 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3414 PyDoc_STR("__reduce__() -> (cls, state)")},
3415
Tim Peters2a799bf2002-12-16 20:18:38 +00003416 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003417};
3418
Tim Peters37f39822003-01-10 03:49:02 +00003419static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003420PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3421\n\
3422All arguments are optional. tzinfo may be None, or an instance of\n\
3423a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003424
Tim Peters37f39822003-01-10 03:49:02 +00003425static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003426 0, /* nb_add */
3427 0, /* nb_subtract */
3428 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003429 0, /* nb_remainder */
3430 0, /* nb_divmod */
3431 0, /* nb_power */
3432 0, /* nb_negative */
3433 0, /* nb_positive */
3434 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003435 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003436};
3437
Neal Norwitz227b5332006-03-22 09:28:35 +00003438static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003439 PyObject_HEAD_INIT(NULL)
3440 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003441 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003442 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003443 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003444 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003445 0, /* tp_print */
3446 0, /* tp_getattr */
3447 0, /* tp_setattr */
3448 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003449 (reprfunc)time_repr, /* tp_repr */
3450 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003451 0, /* tp_as_sequence */
3452 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003453 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003454 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003455 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003456 PyObject_GenericGetAttr, /* tp_getattro */
3457 0, /* tp_setattro */
3458 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003459 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003460 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003461 0, /* tp_traverse */
3462 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003463 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003464 0, /* tp_weaklistoffset */
3465 0, /* tp_iter */
3466 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003467 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003468 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003469 time_getset, /* tp_getset */
3470 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003471 0, /* tp_dict */
3472 0, /* tp_descr_get */
3473 0, /* tp_descr_set */
3474 0, /* tp_dictoffset */
3475 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003476 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003477 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003478 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003479};
3480
3481/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003482 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003483 */
3484
Tim Petersa9bc1682003-01-11 03:39:11 +00003485/* Accessor properties. Properties for day, month, and year are inherited
3486 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003487 */
3488
3489static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003490datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003491{
Tim Petersa9bc1682003-01-11 03:39:11 +00003492 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003493}
3494
Tim Petersa9bc1682003-01-11 03:39:11 +00003495static PyObject *
3496datetime_minute(PyDateTime_DateTime *self, void *unused)
3497{
3498 return PyInt_FromLong(DATE_GET_MINUTE(self));
3499}
3500
3501static PyObject *
3502datetime_second(PyDateTime_DateTime *self, void *unused)
3503{
3504 return PyInt_FromLong(DATE_GET_SECOND(self));
3505}
3506
3507static PyObject *
3508datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3509{
3510 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3511}
3512
3513static PyObject *
3514datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3515{
3516 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3517 Py_INCREF(result);
3518 return result;
3519}
3520
3521static PyGetSetDef datetime_getset[] = {
3522 {"hour", (getter)datetime_hour},
3523 {"minute", (getter)datetime_minute},
3524 {"second", (getter)datetime_second},
3525 {"microsecond", (getter)datetime_microsecond},
3526 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003527 {NULL}
3528};
3529
3530/*
3531 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003532 */
3533
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003534static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003535 "year", "month", "day", "hour", "minute", "second",
3536 "microsecond", "tzinfo", NULL
3537};
3538
Tim Peters2a799bf2002-12-16 20:18:38 +00003539static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003540datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003541{
3542 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003543 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003544 int year;
3545 int month;
3546 int day;
3547 int hour = 0;
3548 int minute = 0;
3549 int second = 0;
3550 int usecond = 0;
3551 PyObject *tzinfo = Py_None;
3552
Guido van Rossum177e41a2003-01-30 22:06:23 +00003553 /* Check for invocation from pickle with __getstate__ state */
3554 if (PyTuple_GET_SIZE(args) >= 1 &&
3555 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003556 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003557 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3558 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003559 {
Tim Peters70533e22003-02-01 04:40:04 +00003560 PyDateTime_DateTime *me;
3561 char aware;
3562
3563 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003564 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003565 if (check_tzinfo_subclass(tzinfo) < 0) {
3566 PyErr_SetString(PyExc_TypeError, "bad "
3567 "tzinfo state arg");
3568 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003569 }
3570 }
Tim Peters70533e22003-02-01 04:40:04 +00003571 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003572 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003573 if (me != NULL) {
3574 char *pdata = PyString_AS_STRING(state);
3575
3576 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3577 me->hashcode = -1;
3578 me->hastzinfo = aware;
3579 if (aware) {
3580 Py_INCREF(tzinfo);
3581 me->tzinfo = tzinfo;
3582 }
3583 }
3584 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003585 }
3586
Tim Petersa9bc1682003-01-11 03:39:11 +00003587 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003588 &year, &month, &day, &hour, &minute,
3589 &second, &usecond, &tzinfo)) {
3590 if (check_date_args(year, month, day) < 0)
3591 return NULL;
3592 if (check_time_args(hour, minute, second, usecond) < 0)
3593 return NULL;
3594 if (check_tzinfo_subclass(tzinfo) < 0)
3595 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003596 self = new_datetime_ex(year, month, day,
3597 hour, minute, second, usecond,
3598 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003599 }
3600 return self;
3601}
3602
Tim Petersa9bc1682003-01-11 03:39:11 +00003603/* TM_FUNC is the shared type of localtime() and gmtime(). */
3604typedef struct tm *(*TM_FUNC)(const time_t *timer);
3605
3606/* Internal helper.
3607 * Build datetime from a time_t and a distinct count of microseconds.
3608 * Pass localtime or gmtime for f, to control the interpretation of timet.
3609 */
3610static PyObject *
3611datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3612 PyObject *tzinfo)
3613{
3614 struct tm *tm;
3615 PyObject *result = NULL;
3616
3617 tm = f(&timet);
3618 if (tm) {
3619 /* The platform localtime/gmtime may insert leap seconds,
3620 * indicated by tm->tm_sec > 59. We don't care about them,
3621 * except to the extent that passing them on to the datetime
3622 * constructor would raise ValueError for a reason that
3623 * made no sense to the user.
3624 */
3625 if (tm->tm_sec > 59)
3626 tm->tm_sec = 59;
3627 result = PyObject_CallFunction(cls, "iiiiiiiO",
3628 tm->tm_year + 1900,
3629 tm->tm_mon + 1,
3630 tm->tm_mday,
3631 tm->tm_hour,
3632 tm->tm_min,
3633 tm->tm_sec,
3634 us,
3635 tzinfo);
3636 }
3637 else
3638 PyErr_SetString(PyExc_ValueError,
3639 "timestamp out of range for "
3640 "platform localtime()/gmtime() function");
3641 return result;
3642}
3643
3644/* Internal helper.
3645 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3646 * to control the interpretation of the timestamp. Since a double doesn't
3647 * have enough bits to cover a datetime's full range of precision, it's
3648 * better to call datetime_from_timet_and_us provided you have a way
3649 * to get that much precision (e.g., C time() isn't good enough).
3650 */
3651static PyObject *
3652datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3653 PyObject *tzinfo)
3654{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003655 time_t timet;
3656 double fraction;
3657 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003658
Tim Peters1b6f7a92004-06-20 02:50:16 +00003659 timet = _PyTime_DoubleToTimet(timestamp);
3660 if (timet == (time_t)-1 && PyErr_Occurred())
3661 return NULL;
3662 fraction = timestamp - (double)timet;
3663 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003664 if (us < 0) {
3665 /* Truncation towards zero is not what we wanted
3666 for negative numbers (Python's mod semantics) */
3667 timet -= 1;
3668 us += 1000000;
3669 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003670 /* If timestamp is less than one microsecond smaller than a
3671 * full second, round up. Otherwise, ValueErrors are raised
3672 * for some floats. */
3673 if (us == 1000000) {
3674 timet += 1;
3675 us = 0;
3676 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003677 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3678}
3679
3680/* Internal helper.
3681 * Build most accurate possible datetime for current time. Pass localtime or
3682 * gmtime for f as appropriate.
3683 */
3684static PyObject *
3685datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3686{
3687#ifdef HAVE_GETTIMEOFDAY
3688 struct timeval t;
3689
3690#ifdef GETTIMEOFDAY_NO_TZ
3691 gettimeofday(&t);
3692#else
3693 gettimeofday(&t, (struct timezone *)NULL);
3694#endif
3695 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3696 tzinfo);
3697
3698#else /* ! HAVE_GETTIMEOFDAY */
3699 /* No flavor of gettimeofday exists on this platform. Python's
3700 * time.time() does a lot of other platform tricks to get the
3701 * best time it can on the platform, and we're not going to do
3702 * better than that (if we could, the better code would belong
3703 * in time.time()!) We're limited by the precision of a double,
3704 * though.
3705 */
3706 PyObject *time;
3707 double dtime;
3708
3709 time = time_time();
3710 if (time == NULL)
3711 return NULL;
3712 dtime = PyFloat_AsDouble(time);
3713 Py_DECREF(time);
3714 if (dtime == -1.0 && PyErr_Occurred())
3715 return NULL;
3716 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3717#endif /* ! HAVE_GETTIMEOFDAY */
3718}
3719
Tim Peters2a799bf2002-12-16 20:18:38 +00003720/* Return best possible local time -- this isn't constrained by the
3721 * precision of a timestamp.
3722 */
3723static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003724datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003725{
Tim Peters10cadce2003-01-23 19:58:02 +00003726 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003727 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003728 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003729
Tim Peters10cadce2003-01-23 19:58:02 +00003730 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3731 &tzinfo))
3732 return NULL;
3733 if (check_tzinfo_subclass(tzinfo) < 0)
3734 return NULL;
3735
3736 self = datetime_best_possible(cls,
3737 tzinfo == Py_None ? localtime : gmtime,
3738 tzinfo);
3739 if (self != NULL && tzinfo != Py_None) {
3740 /* Convert UTC to tzinfo's zone. */
3741 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003742 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003743 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003744 }
3745 return self;
3746}
3747
Tim Petersa9bc1682003-01-11 03:39:11 +00003748/* Return best possible UTC time -- this isn't constrained by the
3749 * precision of a timestamp.
3750 */
3751static PyObject *
3752datetime_utcnow(PyObject *cls, PyObject *dummy)
3753{
3754 return datetime_best_possible(cls, gmtime, Py_None);
3755}
3756
Tim Peters2a799bf2002-12-16 20:18:38 +00003757/* Return new local datetime from timestamp (Python timestamp -- a double). */
3758static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003759datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003760{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003761 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003762 double timestamp;
3763 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003764 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003765
Tim Peters2a44a8d2003-01-23 20:53:10 +00003766 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3767 keywords, &timestamp, &tzinfo))
3768 return NULL;
3769 if (check_tzinfo_subclass(tzinfo) < 0)
3770 return NULL;
3771
3772 self = datetime_from_timestamp(cls,
3773 tzinfo == Py_None ? localtime : gmtime,
3774 timestamp,
3775 tzinfo);
3776 if (self != NULL && tzinfo != Py_None) {
3777 /* Convert UTC to tzinfo's zone. */
3778 PyObject *temp = self;
3779 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3780 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003781 }
3782 return self;
3783}
3784
Tim Petersa9bc1682003-01-11 03:39:11 +00003785/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3786static PyObject *
3787datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3788{
3789 double timestamp;
3790 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003791
Tim Petersa9bc1682003-01-11 03:39:11 +00003792 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3793 result = datetime_from_timestamp(cls, gmtime, timestamp,
3794 Py_None);
3795 return result;
3796}
3797
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003798/* Return new datetime from time.strptime(). */
3799static PyObject *
3800datetime_strptime(PyObject *cls, PyObject *args)
3801{
3802 PyObject *result = NULL, *obj, *module;
3803 const char *string, *format;
3804
3805 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3806 return NULL;
3807
3808 if ((module = PyImport_ImportModule("time")) == NULL)
3809 return NULL;
3810 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3811 Py_DECREF(module);
3812
3813 if (obj != NULL) {
3814 int i, good_timetuple = 1;
3815 long int ia[6];
3816 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3817 for (i=0; i < 6; i++) {
3818 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003819 if (p == NULL) {
3820 Py_DECREF(obj);
3821 return NULL;
3822 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003823 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003824 ia[i] = PyInt_AsLong(p);
3825 else
3826 good_timetuple = 0;
3827 Py_DECREF(p);
3828 }
3829 else
3830 good_timetuple = 0;
3831 if (good_timetuple)
3832 result = PyObject_CallFunction(cls, "iiiiii",
3833 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3834 else
3835 PyErr_SetString(PyExc_ValueError,
3836 "unexpected value from time.strptime");
3837 Py_DECREF(obj);
3838 }
3839 return result;
3840}
3841
Tim Petersa9bc1682003-01-11 03:39:11 +00003842/* Return new datetime from date/datetime and time arguments. */
3843static PyObject *
3844datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3845{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003846 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003847 PyObject *date;
3848 PyObject *time;
3849 PyObject *result = NULL;
3850
3851 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3852 &PyDateTime_DateType, &date,
3853 &PyDateTime_TimeType, &time)) {
3854 PyObject *tzinfo = Py_None;
3855
3856 if (HASTZINFO(time))
3857 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3858 result = PyObject_CallFunction(cls, "iiiiiiiO",
3859 GET_YEAR(date),
3860 GET_MONTH(date),
3861 GET_DAY(date),
3862 TIME_GET_HOUR(time),
3863 TIME_GET_MINUTE(time),
3864 TIME_GET_SECOND(time),
3865 TIME_GET_MICROSECOND(time),
3866 tzinfo);
3867 }
3868 return result;
3869}
Tim Peters2a799bf2002-12-16 20:18:38 +00003870
3871/*
3872 * Destructor.
3873 */
3874
3875static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003876datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003877{
Tim Petersa9bc1682003-01-11 03:39:11 +00003878 if (HASTZINFO(self)) {
3879 Py_XDECREF(self->tzinfo);
3880 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003881 self->ob_type->tp_free((PyObject *)self);
3882}
3883
3884/*
3885 * Indirect access to tzinfo methods.
3886 */
3887
Tim Peters2a799bf2002-12-16 20:18:38 +00003888/* These are all METH_NOARGS, so don't need to check the arglist. */
3889static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003890datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3891 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3892 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003893}
3894
3895static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003896datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3897 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3898 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003899}
3900
3901static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003902datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3903 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3904 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003905}
3906
3907/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003908 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003909 */
3910
Tim Petersa9bc1682003-01-11 03:39:11 +00003911/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3912 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003913 */
3914static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003915add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3916 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003917{
Tim Petersa9bc1682003-01-11 03:39:11 +00003918 /* Note that the C-level additions can't overflow, because of
3919 * invariant bounds on the member values.
3920 */
3921 int year = GET_YEAR(date);
3922 int month = GET_MONTH(date);
3923 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3924 int hour = DATE_GET_HOUR(date);
3925 int minute = DATE_GET_MINUTE(date);
3926 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3927 int microsecond = DATE_GET_MICROSECOND(date) +
3928 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003929
Tim Petersa9bc1682003-01-11 03:39:11 +00003930 assert(factor == 1 || factor == -1);
3931 if (normalize_datetime(&year, &month, &day,
3932 &hour, &minute, &second, &microsecond) < 0)
3933 return NULL;
3934 else
3935 return new_datetime(year, month, day,
3936 hour, minute, second, microsecond,
3937 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003938}
3939
3940static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003941datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003942{
Tim Petersa9bc1682003-01-11 03:39:11 +00003943 if (PyDateTime_Check(left)) {
3944 /* datetime + ??? */
3945 if (PyDelta_Check(right))
3946 /* datetime + delta */
3947 return add_datetime_timedelta(
3948 (PyDateTime_DateTime *)left,
3949 (PyDateTime_Delta *)right,
3950 1);
3951 }
3952 else if (PyDelta_Check(left)) {
3953 /* delta + datetime */
3954 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3955 (PyDateTime_Delta *) left,
3956 1);
3957 }
3958 Py_INCREF(Py_NotImplemented);
3959 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003960}
3961
3962static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003963datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003964{
3965 PyObject *result = Py_NotImplemented;
3966
3967 if (PyDateTime_Check(left)) {
3968 /* datetime - ??? */
3969 if (PyDateTime_Check(right)) {
3970 /* datetime - datetime */
3971 naivety n1, n2;
3972 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003973 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003974
Tim Peterse39a80c2002-12-30 21:28:52 +00003975 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3976 right, &offset2, &n2,
3977 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003978 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003979 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003980 if (n1 != n2) {
3981 PyErr_SetString(PyExc_TypeError,
3982 "can't subtract offset-naive and "
3983 "offset-aware datetimes");
3984 return NULL;
3985 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003986 delta_d = ymd_to_ord(GET_YEAR(left),
3987 GET_MONTH(left),
3988 GET_DAY(left)) -
3989 ymd_to_ord(GET_YEAR(right),
3990 GET_MONTH(right),
3991 GET_DAY(right));
3992 /* These can't overflow, since the values are
3993 * normalized. At most this gives the number of
3994 * seconds in one day.
3995 */
3996 delta_s = (DATE_GET_HOUR(left) -
3997 DATE_GET_HOUR(right)) * 3600 +
3998 (DATE_GET_MINUTE(left) -
3999 DATE_GET_MINUTE(right)) * 60 +
4000 (DATE_GET_SECOND(left) -
4001 DATE_GET_SECOND(right));
4002 delta_us = DATE_GET_MICROSECOND(left) -
4003 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004004 /* (left - offset1) - (right - offset2) =
4005 * (left - right) + (offset2 - offset1)
4006 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004007 delta_s += (offset2 - offset1) * 60;
4008 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004009 }
4010 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004011 /* datetime - delta */
4012 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004013 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004014 (PyDateTime_Delta *)right,
4015 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004016 }
4017 }
4018
4019 if (result == Py_NotImplemented)
4020 Py_INCREF(result);
4021 return result;
4022}
4023
4024/* Various ways to turn a datetime into a string. */
4025
4026static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004027datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004028{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004029 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004030 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004031
Tim Petersa9bc1682003-01-11 03:39:11 +00004032 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004033 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004034 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004035 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004036 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4037 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4038 DATE_GET_SECOND(self),
4039 DATE_GET_MICROSECOND(self));
4040 }
4041 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004042 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004043 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004044 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004045 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4046 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4047 DATE_GET_SECOND(self));
4048 }
4049 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004050 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004051 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004052 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004053 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4054 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4055 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004056 if (baserepr == NULL || ! HASTZINFO(self))
4057 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004058 return append_keyword_tzinfo(baserepr, self->tzinfo);
4059}
4060
Tim Petersa9bc1682003-01-11 03:39:11 +00004061static PyObject *
4062datetime_str(PyDateTime_DateTime *self)
4063{
4064 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4065}
Tim Peters2a799bf2002-12-16 20:18:38 +00004066
4067static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004068datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004069{
Tim Petersa9bc1682003-01-11 03:39:11 +00004070 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004071 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004072 char buffer[100];
4073 char *cp;
4074 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004075
Tim Petersa9bc1682003-01-11 03:39:11 +00004076 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4077 &sep))
4078 return NULL;
4079 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4080 assert(cp != NULL);
4081 *cp++ = sep;
4082 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4083 result = PyString_FromString(buffer);
4084 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004085 return result;
4086
4087 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004088 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004089 (PyObject *)self) < 0) {
4090 Py_DECREF(result);
4091 return NULL;
4092 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004093 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004094 return result;
4095}
4096
Tim Petersa9bc1682003-01-11 03:39:11 +00004097static PyObject *
4098datetime_ctime(PyDateTime_DateTime *self)
4099{
4100 return format_ctime((PyDateTime_Date *)self,
4101 DATE_GET_HOUR(self),
4102 DATE_GET_MINUTE(self),
4103 DATE_GET_SECOND(self));
4104}
4105
Tim Peters2a799bf2002-12-16 20:18:38 +00004106/* Miscellaneous methods. */
4107
Tim Petersa9bc1682003-01-11 03:39:11 +00004108static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004109datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004110{
4111 int diff;
4112 naivety n1, n2;
4113 int offset1, offset2;
4114
4115 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004116 if (PyDate_Check(other)) {
4117 /* Prevent invocation of date_richcompare. We want to
4118 return NotImplemented here to give the other object
4119 a chance. But since DateTime is a subclass of
4120 Date, if the other object is a Date, it would
4121 compute an ordering based on the date part alone,
4122 and we don't want that. So force unequal or
4123 uncomparable here in that case. */
4124 if (op == Py_EQ)
4125 Py_RETURN_FALSE;
4126 if (op == Py_NE)
4127 Py_RETURN_TRUE;
4128 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004129 }
Guido van Rossum19960592006-08-24 17:29:38 +00004130 Py_INCREF(Py_NotImplemented);
4131 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004132 }
4133
Guido van Rossum19960592006-08-24 17:29:38 +00004134 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4135 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004136 return NULL;
4137 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4138 /* If they're both naive, or both aware and have the same offsets,
4139 * we get off cheap. Note that if they're both naive, offset1 ==
4140 * offset2 == 0 at this point.
4141 */
4142 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004143 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4144 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004145 _PyDateTime_DATETIME_DATASIZE);
4146 return diff_to_bool(diff, op);
4147 }
4148
4149 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4150 PyDateTime_Delta *delta;
4151
4152 assert(offset1 != offset2); /* else last "if" handled it */
4153 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4154 other);
4155 if (delta == NULL)
4156 return NULL;
4157 diff = GET_TD_DAYS(delta);
4158 if (diff == 0)
4159 diff = GET_TD_SECONDS(delta) |
4160 GET_TD_MICROSECONDS(delta);
4161 Py_DECREF(delta);
4162 return diff_to_bool(diff, op);
4163 }
4164
4165 assert(n1 != n2);
4166 PyErr_SetString(PyExc_TypeError,
4167 "can't compare offset-naive and "
4168 "offset-aware datetimes");
4169 return NULL;
4170}
4171
4172static long
4173datetime_hash(PyDateTime_DateTime *self)
4174{
4175 if (self->hashcode == -1) {
4176 naivety n;
4177 int offset;
4178 PyObject *temp;
4179
4180 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4181 &offset);
4182 assert(n != OFFSET_UNKNOWN);
4183 if (n == OFFSET_ERROR)
4184 return -1;
4185
4186 /* Reduce this to a hash of another object. */
4187 if (n == OFFSET_NAIVE)
4188 temp = PyString_FromStringAndSize(
4189 (char *)self->data,
4190 _PyDateTime_DATETIME_DATASIZE);
4191 else {
4192 int days;
4193 int seconds;
4194
4195 assert(n == OFFSET_AWARE);
4196 assert(HASTZINFO(self));
4197 days = ymd_to_ord(GET_YEAR(self),
4198 GET_MONTH(self),
4199 GET_DAY(self));
4200 seconds = DATE_GET_HOUR(self) * 3600 +
4201 (DATE_GET_MINUTE(self) - offset) * 60 +
4202 DATE_GET_SECOND(self);
4203 temp = new_delta(days,
4204 seconds,
4205 DATE_GET_MICROSECOND(self),
4206 1);
4207 }
4208 if (temp != NULL) {
4209 self->hashcode = PyObject_Hash(temp);
4210 Py_DECREF(temp);
4211 }
4212 }
4213 return self->hashcode;
4214}
Tim Peters2a799bf2002-12-16 20:18:38 +00004215
4216static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004217datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004218{
4219 PyObject *clone;
4220 PyObject *tuple;
4221 int y = GET_YEAR(self);
4222 int m = GET_MONTH(self);
4223 int d = GET_DAY(self);
4224 int hh = DATE_GET_HOUR(self);
4225 int mm = DATE_GET_MINUTE(self);
4226 int ss = DATE_GET_SECOND(self);
4227 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004228 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004229
4230 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004231 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004232 &y, &m, &d, &hh, &mm, &ss, &us,
4233 &tzinfo))
4234 return NULL;
4235 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4236 if (tuple == NULL)
4237 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004238 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004239 Py_DECREF(tuple);
4240 return clone;
4241}
4242
4243static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004244datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004245{
Tim Peters52dcce22003-01-23 16:36:11 +00004246 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004247 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004248 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004249
Tim Peters80475bb2002-12-25 07:40:55 +00004250 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004251 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004252
Tim Peters52dcce22003-01-23 16:36:11 +00004253 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4254 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004255 return NULL;
4256
Tim Peters52dcce22003-01-23 16:36:11 +00004257 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4258 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004259
Tim Peters52dcce22003-01-23 16:36:11 +00004260 /* Conversion to self's own time zone is a NOP. */
4261 if (self->tzinfo == tzinfo) {
4262 Py_INCREF(self);
4263 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004264 }
Tim Peters521fc152002-12-31 17:36:56 +00004265
Tim Peters52dcce22003-01-23 16:36:11 +00004266 /* Convert self to UTC. */
4267 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4268 if (offset == -1 && PyErr_Occurred())
4269 return NULL;
4270 if (none)
4271 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004272
Tim Peters52dcce22003-01-23 16:36:11 +00004273 y = GET_YEAR(self);
4274 m = GET_MONTH(self);
4275 d = GET_DAY(self);
4276 hh = DATE_GET_HOUR(self);
4277 mm = DATE_GET_MINUTE(self);
4278 ss = DATE_GET_SECOND(self);
4279 us = DATE_GET_MICROSECOND(self);
4280
4281 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004282 if ((mm < 0 || mm >= 60) &&
4283 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004284 return NULL;
4285
4286 /* Attach new tzinfo and let fromutc() do the rest. */
4287 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4288 if (result != NULL) {
4289 PyObject *temp = result;
4290
4291 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4292 Py_DECREF(temp);
4293 }
Tim Petersadf64202003-01-04 06:03:15 +00004294 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004295
Tim Peters52dcce22003-01-23 16:36:11 +00004296NeedAware:
4297 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4298 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004299 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004300}
4301
4302static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004303datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004304{
4305 int dstflag = -1;
4306
Tim Petersa9bc1682003-01-11 03:39:11 +00004307 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004308 int none;
4309
4310 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4311 if (dstflag == -1 && PyErr_Occurred())
4312 return NULL;
4313
4314 if (none)
4315 dstflag = -1;
4316 else if (dstflag != 0)
4317 dstflag = 1;
4318
4319 }
4320 return build_struct_time(GET_YEAR(self),
4321 GET_MONTH(self),
4322 GET_DAY(self),
4323 DATE_GET_HOUR(self),
4324 DATE_GET_MINUTE(self),
4325 DATE_GET_SECOND(self),
4326 dstflag);
4327}
4328
4329static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004330datetime_getdate(PyDateTime_DateTime *self)
4331{
4332 return new_date(GET_YEAR(self),
4333 GET_MONTH(self),
4334 GET_DAY(self));
4335}
4336
4337static PyObject *
4338datetime_gettime(PyDateTime_DateTime *self)
4339{
4340 return new_time(DATE_GET_HOUR(self),
4341 DATE_GET_MINUTE(self),
4342 DATE_GET_SECOND(self),
4343 DATE_GET_MICROSECOND(self),
4344 Py_None);
4345}
4346
4347static PyObject *
4348datetime_gettimetz(PyDateTime_DateTime *self)
4349{
4350 return new_time(DATE_GET_HOUR(self),
4351 DATE_GET_MINUTE(self),
4352 DATE_GET_SECOND(self),
4353 DATE_GET_MICROSECOND(self),
4354 HASTZINFO(self) ? self->tzinfo : Py_None);
4355}
4356
4357static PyObject *
4358datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004359{
4360 int y = GET_YEAR(self);
4361 int m = GET_MONTH(self);
4362 int d = GET_DAY(self);
4363 int hh = DATE_GET_HOUR(self);
4364 int mm = DATE_GET_MINUTE(self);
4365 int ss = DATE_GET_SECOND(self);
4366 int us = 0; /* microseconds are ignored in a timetuple */
4367 int offset = 0;
4368
Tim Petersa9bc1682003-01-11 03:39:11 +00004369 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004370 int none;
4371
4372 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4373 if (offset == -1 && PyErr_Occurred())
4374 return NULL;
4375 }
4376 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4377 * 0 in a UTC timetuple regardless of what dst() says.
4378 */
4379 if (offset) {
4380 /* Subtract offset minutes & normalize. */
4381 int stat;
4382
4383 mm -= offset;
4384 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4385 if (stat < 0) {
4386 /* At the edges, it's possible we overflowed
4387 * beyond MINYEAR or MAXYEAR.
4388 */
4389 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4390 PyErr_Clear();
4391 else
4392 return NULL;
4393 }
4394 }
4395 return build_struct_time(y, m, d, hh, mm, ss, 0);
4396}
4397
Tim Peters371935f2003-02-01 01:52:50 +00004398/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004399
Tim Petersa9bc1682003-01-11 03:39:11 +00004400/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004401 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4402 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004403 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004404 */
4405static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004406datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004407{
4408 PyObject *basestate;
4409 PyObject *result = NULL;
4410
Tim Peters33e0f382003-01-10 02:05:14 +00004411 basestate = PyString_FromStringAndSize((char *)self->data,
4412 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004413 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004414 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004415 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004416 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004417 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004418 Py_DECREF(basestate);
4419 }
4420 return result;
4421}
4422
4423static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004424datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004425{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004426 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004427}
4428
Tim Petersa9bc1682003-01-11 03:39:11 +00004429static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004430
Tim Peters2a799bf2002-12-16 20:18:38 +00004431 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004432
Tim Petersa9bc1682003-01-11 03:39:11 +00004433 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004434 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004435 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004436
Tim Petersa9bc1682003-01-11 03:39:11 +00004437 {"utcnow", (PyCFunction)datetime_utcnow,
4438 METH_NOARGS | METH_CLASS,
4439 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4440
4441 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004442 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004443 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004444
Tim Petersa9bc1682003-01-11 03:39:11 +00004445 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4446 METH_VARARGS | METH_CLASS,
4447 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4448 "(like time.time()).")},
4449
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004450 {"strptime", (PyCFunction)datetime_strptime,
4451 METH_VARARGS | METH_CLASS,
4452 PyDoc_STR("string, format -> new datetime parsed from a string "
4453 "(like time.strptime()).")},
4454
Tim Petersa9bc1682003-01-11 03:39:11 +00004455 {"combine", (PyCFunction)datetime_combine,
4456 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4457 PyDoc_STR("date, time -> datetime with same date and time fields")},
4458
Tim Peters2a799bf2002-12-16 20:18:38 +00004459 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004460
Tim Petersa9bc1682003-01-11 03:39:11 +00004461 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4462 PyDoc_STR("Return date object with same year, month and day.")},
4463
4464 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4465 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4466
4467 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4468 PyDoc_STR("Return time object with same time and tzinfo.")},
4469
4470 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4471 PyDoc_STR("Return ctime() style string.")},
4472
4473 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004474 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4475
Tim Petersa9bc1682003-01-11 03:39:11 +00004476 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004477 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4478
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004479 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004480 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4481 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4482 "sep is used to separate the year from the time, and "
4483 "defaults to 'T'.")},
4484
Tim Petersa9bc1682003-01-11 03:39:11 +00004485 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004486 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4487
Tim Petersa9bc1682003-01-11 03:39:11 +00004488 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004489 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4490
Tim Petersa9bc1682003-01-11 03:39:11 +00004491 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004492 PyDoc_STR("Return self.tzinfo.dst(self).")},
4493
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004494 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004495 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004496
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004497 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004498 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4499
Guido van Rossum177e41a2003-01-30 22:06:23 +00004500 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4501 PyDoc_STR("__reduce__() -> (cls, state)")},
4502
Tim Peters2a799bf2002-12-16 20:18:38 +00004503 {NULL, NULL}
4504};
4505
Tim Petersa9bc1682003-01-11 03:39:11 +00004506static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004507PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4508\n\
4509The year, month and day arguments are required. tzinfo may be None, or an\n\
4510instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004511
Tim Petersa9bc1682003-01-11 03:39:11 +00004512static PyNumberMethods datetime_as_number = {
4513 datetime_add, /* nb_add */
4514 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004515 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004516 0, /* nb_remainder */
4517 0, /* nb_divmod */
4518 0, /* nb_power */
4519 0, /* nb_negative */
4520 0, /* nb_positive */
4521 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004522 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004523};
4524
Neal Norwitz227b5332006-03-22 09:28:35 +00004525static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004526 PyObject_HEAD_INIT(NULL)
4527 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004528 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004529 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004530 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004531 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004532 0, /* tp_print */
4533 0, /* tp_getattr */
4534 0, /* tp_setattr */
4535 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004536 (reprfunc)datetime_repr, /* tp_repr */
4537 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004538 0, /* tp_as_sequence */
4539 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004540 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004541 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004542 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004543 PyObject_GenericGetAttr, /* tp_getattro */
4544 0, /* tp_setattro */
4545 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004546 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004547 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004548 0, /* tp_traverse */
4549 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004550 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004551 0, /* tp_weaklistoffset */
4552 0, /* tp_iter */
4553 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004554 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004555 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004556 datetime_getset, /* tp_getset */
4557 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004558 0, /* tp_dict */
4559 0, /* tp_descr_get */
4560 0, /* tp_descr_set */
4561 0, /* tp_dictoffset */
4562 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004563 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004564 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004565 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004566};
4567
4568/* ---------------------------------------------------------------------------
4569 * Module methods and initialization.
4570 */
4571
4572static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004573 {NULL, NULL}
4574};
4575
Tim Peters9ddf40b2004-06-20 22:41:32 +00004576/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4577 * datetime.h.
4578 */
4579static PyDateTime_CAPI CAPI = {
4580 &PyDateTime_DateType,
4581 &PyDateTime_DateTimeType,
4582 &PyDateTime_TimeType,
4583 &PyDateTime_DeltaType,
4584 &PyDateTime_TZInfoType,
4585 new_date_ex,
4586 new_datetime_ex,
4587 new_time_ex,
4588 new_delta_ex,
4589 datetime_fromtimestamp,
4590 date_fromtimestamp
4591};
4592
4593
Tim Peters2a799bf2002-12-16 20:18:38 +00004594PyMODINIT_FUNC
4595initdatetime(void)
4596{
4597 PyObject *m; /* a module object */
4598 PyObject *d; /* its dict */
4599 PyObject *x;
4600
Tim Peters2a799bf2002-12-16 20:18:38 +00004601 m = Py_InitModule3("datetime", module_methods,
4602 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004603 if (m == NULL)
4604 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004605
4606 if (PyType_Ready(&PyDateTime_DateType) < 0)
4607 return;
4608 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4609 return;
4610 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4611 return;
4612 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4613 return;
4614 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4615 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004616
Tim Peters2a799bf2002-12-16 20:18:38 +00004617 /* timedelta values */
4618 d = PyDateTime_DeltaType.tp_dict;
4619
Tim Peters2a799bf2002-12-16 20:18:38 +00004620 x = new_delta(0, 0, 1, 0);
4621 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4622 return;
4623 Py_DECREF(x);
4624
4625 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4626 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4627 return;
4628 Py_DECREF(x);
4629
4630 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4631 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4632 return;
4633 Py_DECREF(x);
4634
4635 /* date values */
4636 d = PyDateTime_DateType.tp_dict;
4637
4638 x = new_date(1, 1, 1);
4639 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4640 return;
4641 Py_DECREF(x);
4642
4643 x = new_date(MAXYEAR, 12, 31);
4644 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4645 return;
4646 Py_DECREF(x);
4647
4648 x = new_delta(1, 0, 0, 0);
4649 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4650 return;
4651 Py_DECREF(x);
4652
Tim Peters37f39822003-01-10 03:49:02 +00004653 /* time values */
4654 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004655
Tim Peters37f39822003-01-10 03:49:02 +00004656 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004657 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4658 return;
4659 Py_DECREF(x);
4660
Tim Peters37f39822003-01-10 03:49:02 +00004661 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004662 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4663 return;
4664 Py_DECREF(x);
4665
4666 x = new_delta(0, 0, 1, 0);
4667 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4668 return;
4669 Py_DECREF(x);
4670
Tim Petersa9bc1682003-01-11 03:39:11 +00004671 /* datetime values */
4672 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004673
Tim Petersa9bc1682003-01-11 03:39:11 +00004674 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004675 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4676 return;
4677 Py_DECREF(x);
4678
Tim Petersa9bc1682003-01-11 03:39:11 +00004679 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004680 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4681 return;
4682 Py_DECREF(x);
4683
4684 x = new_delta(0, 0, 1, 0);
4685 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4686 return;
4687 Py_DECREF(x);
4688
Tim Peters2a799bf2002-12-16 20:18:38 +00004689 /* module initialization */
4690 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4691 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4692
4693 Py_INCREF(&PyDateTime_DateType);
4694 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4695
Tim Petersa9bc1682003-01-11 03:39:11 +00004696 Py_INCREF(&PyDateTime_DateTimeType);
4697 PyModule_AddObject(m, "datetime",
4698 (PyObject *)&PyDateTime_DateTimeType);
4699
4700 Py_INCREF(&PyDateTime_TimeType);
4701 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4702
Tim Peters2a799bf2002-12-16 20:18:38 +00004703 Py_INCREF(&PyDateTime_DeltaType);
4704 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4705
Tim Peters2a799bf2002-12-16 20:18:38 +00004706 Py_INCREF(&PyDateTime_TZInfoType);
4707 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4708
Tim Peters9ddf40b2004-06-20 22:41:32 +00004709 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4710 NULL);
4711 if (x == NULL)
4712 return;
4713 PyModule_AddObject(m, "datetime_CAPI", x);
4714
Tim Peters2a799bf2002-12-16 20:18:38 +00004715 /* A 4-year cycle has an extra leap day over what we'd get from
4716 * pasting together 4 single years.
4717 */
4718 assert(DI4Y == 4 * 365 + 1);
4719 assert(DI4Y == days_before_year(4+1));
4720
4721 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4722 * get from pasting together 4 100-year cycles.
4723 */
4724 assert(DI400Y == 4 * DI100Y + 1);
4725 assert(DI400Y == days_before_year(400+1));
4726
4727 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4728 * pasting together 25 4-year cycles.
4729 */
4730 assert(DI100Y == 25 * DI4Y - 1);
4731 assert(DI100Y == days_before_year(100+1));
4732
4733 us_per_us = PyInt_FromLong(1);
4734 us_per_ms = PyInt_FromLong(1000);
4735 us_per_second = PyInt_FromLong(1000000);
4736 us_per_minute = PyInt_FromLong(60000000);
4737 seconds_per_day = PyInt_FromLong(24 * 3600);
4738 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4739 us_per_minute == NULL || seconds_per_day == NULL)
4740 return;
4741
4742 /* The rest are too big for 32-bit ints, but even
4743 * us_per_week fits in 40 bits, so doubles should be exact.
4744 */
4745 us_per_hour = PyLong_FromDouble(3600000000.0);
4746 us_per_day = PyLong_FromDouble(86400000000.0);
4747 us_per_week = PyLong_FromDouble(604800000000.0);
4748 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4749 return;
4750}
Tim Petersf3615152003-01-01 21:51:37 +00004751
4752/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004753Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004754 x.n = x stripped of its timezone -- its naive time.
4755 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4756 return None
4757 x.d = x.dst(), and assuming that doesn't raise an exception or
4758 return None
4759 x.s = x's standard offset, x.o - x.d
4760
4761Now some derived rules, where k is a duration (timedelta).
4762
47631. x.o = x.s + x.d
4764 This follows from the definition of x.s.
4765
Tim Petersc5dc4da2003-01-02 17:55:03 +000047662. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004767 This is actually a requirement, an assumption we need to make about
4768 sane tzinfo classes.
4769
47703. The naive UTC time corresponding to x is x.n - x.o.
4771 This is again a requirement for a sane tzinfo class.
4772
47734. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004774 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004775
Tim Petersc5dc4da2003-01-02 17:55:03 +000047765. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004777 Again follows from how arithmetic is defined.
4778
Tim Peters8bb5ad22003-01-24 02:44:45 +00004779Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004780(meaning that the various tzinfo methods exist, and don't blow up or return
4781None when called).
4782
Tim Petersa9bc1682003-01-11 03:39:11 +00004783The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004784x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004785
4786By #3, we want
4787
Tim Peters8bb5ad22003-01-24 02:44:45 +00004788 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004789
4790The algorithm starts by attaching tz to x.n, and calling that y. So
4791x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4792becomes true; in effect, we want to solve [2] for k:
4793
Tim Peters8bb5ad22003-01-24 02:44:45 +00004794 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004795
4796By #1, this is the same as
4797
Tim Peters8bb5ad22003-01-24 02:44:45 +00004798 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004799
4800By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4801Substituting that into [3],
4802
Tim Peters8bb5ad22003-01-24 02:44:45 +00004803 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4804 k - (y+k).s - (y+k).d = 0; rearranging,
4805 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4806 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004807
Tim Peters8bb5ad22003-01-24 02:44:45 +00004808On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4809approximate k by ignoring the (y+k).d term at first. Note that k can't be
4810very large, since all offset-returning methods return a duration of magnitude
4811less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4812be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004813
4814In any case, the new value is
4815
Tim Peters8bb5ad22003-01-24 02:44:45 +00004816 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004817
Tim Peters8bb5ad22003-01-24 02:44:45 +00004818It's helpful to step back at look at [4] from a higher level: it's simply
4819mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004820
4821At this point, if
4822
Tim Peters8bb5ad22003-01-24 02:44:45 +00004823 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004824
4825we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004826at the start of daylight time. Picture US Eastern for concreteness. The wall
4827time 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 +00004828sense then. The docs ask that an Eastern tzinfo class consider such a time to
4829be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4830on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004831the only spelling that makes sense on the local wall clock.
4832
Tim Petersc5dc4da2003-01-02 17:55:03 +00004833In fact, if [5] holds at this point, we do have the standard-time spelling,
4834but that takes a bit of proof. We first prove a stronger result. What's the
4835difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004836
Tim Peters8bb5ad22003-01-24 02:44:45 +00004837 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004838
Tim Petersc5dc4da2003-01-02 17:55:03 +00004839Now
4840 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004841 (y + y.s).n = by #5
4842 y.n + y.s = since y.n = x.n
4843 x.n + y.s = since z and y are have the same tzinfo member,
4844 y.s = z.s by #2
4845 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004846
Tim Petersc5dc4da2003-01-02 17:55:03 +00004847Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004848
Tim Petersc5dc4da2003-01-02 17:55:03 +00004849 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004850 x.n - ((x.n + z.s) - z.o) = expanding
4851 x.n - x.n - z.s + z.o = cancelling
4852 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004853 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004854
Tim Petersc5dc4da2003-01-02 17:55:03 +00004855So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004856
Tim Petersc5dc4da2003-01-02 17:55:03 +00004857If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004858spelling we wanted in the endcase described above. We're done. Contrarily,
4859if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004860
Tim Petersc5dc4da2003-01-02 17:55:03 +00004861If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4862add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004863local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004864
Tim Petersc5dc4da2003-01-02 17:55:03 +00004865Let
Tim Petersf3615152003-01-01 21:51:37 +00004866
Tim Peters4fede1a2003-01-04 00:26:59 +00004867 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004868
Tim Peters4fede1a2003-01-04 00:26:59 +00004869and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004870
Tim Peters8bb5ad22003-01-24 02:44:45 +00004871 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004872
Tim Peters8bb5ad22003-01-24 02:44:45 +00004873If so, we're done. If not, the tzinfo class is insane, according to the
4874assumptions we've made. This also requires a bit of proof. As before, let's
4875compute the difference between the LHS and RHS of [8] (and skipping some of
4876the justifications for the kinds of substitutions we've done several times
4877already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004878
Tim Peters8bb5ad22003-01-24 02:44:45 +00004879 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4880 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4881 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4882 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4883 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004884 - z.o + z'.o = #1 twice
4885 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4886 z'.d - z.d
4887
4888So 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 +00004889we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4890return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004891
Tim Peters8bb5ad22003-01-24 02:44:45 +00004892How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4893a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4894would have to change the result dst() returns: we start in DST, and moving
4895a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004896
Tim Peters8bb5ad22003-01-24 02:44:45 +00004897There isn't a sane case where this can happen. The closest it gets is at
4898the end of DST, where there's an hour in UTC with no spelling in a hybrid
4899tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4900that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4901UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4902time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4903clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4904standard time. Since that's what the local clock *does*, we want to map both
4905UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004906in local time, but so it goes -- it's the way the local clock works.
4907
Tim Peters8bb5ad22003-01-24 02:44:45 +00004908When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4909so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4910z' = 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 +00004911(correctly) concludes that z' is not UTC-equivalent to x.
4912
4913Because we know z.d said z was in daylight time (else [5] would have held and
4914we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004915and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004916return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4917but the reasoning doesn't depend on the example -- it depends on there being
4918two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004919z' must be in standard time, and is the spelling we want in this case.
4920
4921Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4922concerned (because it takes z' as being in standard time rather than the
4923daylight time we intend here), but returning it gives the real-life "local
4924clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4925tz.
4926
4927When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4928the 1:MM standard time spelling we want.
4929
4930So how can this break? One of the assumptions must be violated. Two
4931possibilities:
4932
49331) [2] effectively says that y.s is invariant across all y belong to a given
4934 time zone. This isn't true if, for political reasons or continental drift,
4935 a region decides to change its base offset from UTC.
4936
49372) There may be versions of "double daylight" time where the tail end of
4938 the analysis gives up a step too early. I haven't thought about that
4939 enough to say.
4940
4941In any case, it's clear that the default fromutc() is strong enough to handle
4942"almost all" time zones: so long as the standard offset is invariant, it
4943doesn't matter if daylight time transition points change from year to year, or
4944if daylight time is skipped in some years; it doesn't matter how large or
4945small dst() may get within its bounds; and it doesn't even matter if some
4946perverse time zone returns a negative dst()). So a breaking case must be
4947pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004948--------------------------------------------------------------------------- */