blob: 4cc941208c5930077f62212dac336740dacbee25 [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
1086 char buffer[128];
1087 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1088
1089 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1090 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1091 GET_DAY(date), hours, minutes, seconds,
1092 GET_YEAR(date));
1093 return PyString_FromString(buffer);
1094}
1095
1096/* Add an hours & minutes UTC offset string to buf. buf has no more than
1097 * buflen bytes remaining. The UTC offset is gotten by calling
1098 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1099 * *buf, and that's all. Else the returned value is checked for sanity (an
1100 * integer in range), and if that's OK it's converted to an hours & minutes
1101 * string of the form
1102 * sign HH sep MM
1103 * Returns 0 if everything is OK. If the return value from utcoffset() is
1104 * bogus, an appropriate exception is set and -1 is returned.
1105 */
1106static int
Tim Peters328fff72002-12-20 01:31:27 +00001107format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001108 PyObject *tzinfo, PyObject *tzinfoarg)
1109{
1110 int offset;
1111 int hours;
1112 int minutes;
1113 char sign;
1114 int none;
1115
1116 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1117 if (offset == -1 && PyErr_Occurred())
1118 return -1;
1119 if (none) {
1120 *buf = '\0';
1121 return 0;
1122 }
1123 sign = '+';
1124 if (offset < 0) {
1125 sign = '-';
1126 offset = - offset;
1127 }
1128 hours = divmod(offset, 60, &minutes);
1129 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1130 return 0;
1131}
1132
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001133static PyObject *
1134make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1135{
1136 PyObject *tzinfo = get_tzinfo_member(object);
1137 PyObject *Zreplacement = PyString_FromString("");
1138 if (Zreplacement == NULL)
1139 return NULL;
1140 if (tzinfo != Py_None && tzinfo != NULL) {
1141 PyObject *temp;
1142 assert(tzinfoarg != NULL);
1143 temp = call_tzname(tzinfo, tzinfoarg);
1144 if (temp == NULL)
1145 goto Error;
1146 if (temp != Py_None) {
1147 assert(PyUnicode_Check(temp));
1148 /* Since the tzname is getting stuffed into the
1149 * format, we have to double any % signs so that
1150 * strftime doesn't treat them as format codes.
1151 */
1152 Py_DECREF(Zreplacement);
1153 Zreplacement = PyObject_CallMethod(temp, "replace",
1154 "ss", "%", "%%");
1155 Py_DECREF(temp);
1156 if (Zreplacement == NULL)
1157 return NULL;
1158 if (PyUnicode_Check(Zreplacement)) {
1159 Zreplacement =
1160 _PyUnicode_AsDefaultEncodedString(
1161 Zreplacement, NULL);
1162 if (Zreplacement == NULL)
1163 return NULL;
1164 }
1165 if (!PyString_Check(Zreplacement)) {
1166 PyErr_SetString(PyExc_TypeError,
1167 "tzname.replace() did not return a string");
1168 goto Error;
1169 }
1170 }
1171 else
1172 Py_DECREF(temp);
1173 }
1174 return Zreplacement;
1175
1176 Error:
1177 Py_DECREF(Zreplacement);
1178 return NULL;
1179}
1180
Tim Peters2a799bf2002-12-16 20:18:38 +00001181/* I sure don't want to reproduce the strftime code from the time module,
1182 * so this imports the module and calls it. All the hair is due to
1183 * giving special meanings to the %z and %Z format codes via a preprocessing
1184 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001185 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1186 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001187 */
1188static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001189wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1190 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001191{
1192 PyObject *result = NULL; /* guilty until proved innocent */
1193
1194 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1195 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1196
Guido van Rossumbce56a62007-05-10 18:04:33 +00001197 const char *pin;/* pointer to next char in input format */
1198 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001199 char ch; /* next char in input format */
1200
1201 PyObject *newfmt = NULL; /* py string, the output format */
1202 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001203 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001204 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001205 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001206
Guido van Rossumbce56a62007-05-10 18:04:33 +00001207 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001208 int ntoappend; /* # of bytes to append to output buffer */
1209
Tim Peters2a799bf2002-12-16 20:18:38 +00001210 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001211 assert(PyString_Check(format) || PyUnicode_Check(format));
1212
1213 /* Convert the input format to a C string and size */
1214 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1215 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001216
Tim Petersd6844152002-12-22 20:58:42 +00001217 /* Give up if the year is before 1900.
1218 * Python strftime() plays games with the year, and different
1219 * games depending on whether envar PYTHON2K is set. This makes
1220 * years before 1900 a nightmare, even if the platform strftime
1221 * supports them (and not all do).
1222 * We could get a lot farther here by avoiding Python's strftime
1223 * wrapper and calling the C strftime() directly, but that isn't
1224 * an option in the Python implementation of this module.
1225 */
1226 {
1227 long year;
1228 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1229 if (pyyear == NULL) return NULL;
1230 assert(PyInt_Check(pyyear));
1231 year = PyInt_AsLong(pyyear);
1232 Py_DECREF(pyyear);
1233 if (year < 1900) {
1234 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1235 "1900; the datetime strftime() "
1236 "methods require year >= 1900",
1237 year);
1238 return NULL;
1239 }
1240 }
1241
Tim Peters2a799bf2002-12-16 20:18:38 +00001242 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001243 * a new format. Since computing the replacements for those codes
1244 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001245 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001246 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001247 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1248 if (newfmt == NULL) goto Done;
1249 pnew = PyString_AsString(newfmt);
1250 usednew = 0;
1251
Tim Peters2a799bf2002-12-16 20:18:38 +00001252 while ((ch = *pin++) != '\0') {
1253 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001254 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001255 ntoappend = 1;
1256 }
1257 else if ((ch = *pin++) == '\0') {
1258 /* There's a lone trailing %; doesn't make sense. */
1259 PyErr_SetString(PyExc_ValueError, "strftime format "
1260 "ends with raw %");
1261 goto Done;
1262 }
1263 /* A % has been seen and ch is the character after it. */
1264 else if (ch == 'z') {
1265 if (zreplacement == NULL) {
1266 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001267 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001268 PyObject *tzinfo = get_tzinfo_member(object);
1269 zreplacement = PyString_FromString("");
1270 if (zreplacement == NULL) goto Done;
1271 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001272 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001273 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001274 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001275 "",
1276 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001277 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001278 goto Done;
1279 Py_DECREF(zreplacement);
1280 zreplacement = PyString_FromString(buf);
1281 if (zreplacement == NULL) goto Done;
1282 }
1283 }
1284 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001285 ptoappend = PyString_AS_STRING(zreplacement);
1286 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001287 }
1288 else if (ch == 'Z') {
1289 /* format tzname */
1290 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001291 Zreplacement = make_Zreplacement(object,
1292 tzinfoarg);
1293 if (Zreplacement == NULL)
1294 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001295 }
1296 assert(Zreplacement != NULL);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001297 assert(PyString_Check(Zreplacement));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001298 ptoappend = PyString_AS_STRING(Zreplacement);
1299 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001300 }
1301 else {
Tim Peters328fff72002-12-20 01:31:27 +00001302 /* percent followed by neither z nor Z */
1303 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001304 ntoappend = 2;
1305 }
1306
1307 /* Append the ntoappend chars starting at ptoappend to
1308 * the new format.
1309 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001310 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001311 assert(ntoappend >= 0);
1312 if (ntoappend == 0)
1313 continue;
1314 while (usednew + ntoappend > totalnew) {
1315 int bigger = totalnew << 1;
1316 if ((bigger >> 1) != totalnew) { /* overflow */
1317 PyErr_NoMemory();
1318 goto Done;
1319 }
1320 if (_PyString_Resize(&newfmt, bigger) < 0)
1321 goto Done;
1322 totalnew = bigger;
1323 pnew = PyString_AsString(newfmt) + usednew;
1324 }
1325 memcpy(pnew, ptoappend, ntoappend);
1326 pnew += ntoappend;
1327 usednew += ntoappend;
1328 assert(usednew <= totalnew);
1329 } /* end while() */
1330
1331 if (_PyString_Resize(&newfmt, usednew) < 0)
1332 goto Done;
1333 {
1334 PyObject *time = PyImport_ImportModule("time");
1335 if (time == NULL)
1336 goto Done;
1337 result = PyObject_CallMethod(time, "strftime", "OO",
1338 newfmt, timetuple);
1339 Py_DECREF(time);
1340 }
1341 Done:
1342 Py_XDECREF(zreplacement);
1343 Py_XDECREF(Zreplacement);
1344 Py_XDECREF(newfmt);
1345 return result;
1346}
1347
1348static char *
1349isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1350{
1351 int x;
1352 x = PyOS_snprintf(buffer, bufflen,
1353 "%04d-%02d-%02d",
1354 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1355 return buffer + x;
1356}
1357
1358static void
1359isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1360{
1361 int us = DATE_GET_MICROSECOND(dt);
1362
1363 PyOS_snprintf(buffer, bufflen,
1364 "%02d:%02d:%02d", /* 8 characters */
1365 DATE_GET_HOUR(dt),
1366 DATE_GET_MINUTE(dt),
1367 DATE_GET_SECOND(dt));
1368 if (us)
1369 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1370}
1371
1372/* ---------------------------------------------------------------------------
1373 * Wrap functions from the time module. These aren't directly available
1374 * from C. Perhaps they should be.
1375 */
1376
1377/* Call time.time() and return its result (a Python float). */
1378static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001379time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001380{
1381 PyObject *result = NULL;
1382 PyObject *time = PyImport_ImportModule("time");
1383
1384 if (time != NULL) {
1385 result = PyObject_CallMethod(time, "time", "()");
1386 Py_DECREF(time);
1387 }
1388 return result;
1389}
1390
1391/* Build a time.struct_time. The weekday and day number are automatically
1392 * computed from the y,m,d args.
1393 */
1394static PyObject *
1395build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1396{
1397 PyObject *time;
1398 PyObject *result = NULL;
1399
1400 time = PyImport_ImportModule("time");
1401 if (time != NULL) {
1402 result = PyObject_CallMethod(time, "struct_time",
1403 "((iiiiiiiii))",
1404 y, m, d,
1405 hh, mm, ss,
1406 weekday(y, m, d),
1407 days_before_month(y, m) + d,
1408 dstflag);
1409 Py_DECREF(time);
1410 }
1411 return result;
1412}
1413
1414/* ---------------------------------------------------------------------------
1415 * Miscellaneous helpers.
1416 */
1417
Guido van Rossum19960592006-08-24 17:29:38 +00001418/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001419 * The comparisons here all most naturally compute a cmp()-like result.
1420 * This little helper turns that into a bool result for rich comparisons.
1421 */
1422static PyObject *
1423diff_to_bool(int diff, int op)
1424{
1425 PyObject *result;
1426 int istrue;
1427
1428 switch (op) {
1429 case Py_EQ: istrue = diff == 0; break;
1430 case Py_NE: istrue = diff != 0; break;
1431 case Py_LE: istrue = diff <= 0; break;
1432 case Py_GE: istrue = diff >= 0; break;
1433 case Py_LT: istrue = diff < 0; break;
1434 case Py_GT: istrue = diff > 0; break;
1435 default:
1436 assert(! "op unknown");
1437 istrue = 0; /* To shut up compiler */
1438 }
1439 result = istrue ? Py_True : Py_False;
1440 Py_INCREF(result);
1441 return result;
1442}
1443
Tim Peters07534a62003-02-07 22:50:28 +00001444/* Raises a "can't compare" TypeError and returns NULL. */
1445static PyObject *
1446cmperror(PyObject *a, PyObject *b)
1447{
1448 PyErr_Format(PyExc_TypeError,
1449 "can't compare %s to %s",
1450 a->ob_type->tp_name, b->ob_type->tp_name);
1451 return NULL;
1452}
1453
Tim Peters2a799bf2002-12-16 20:18:38 +00001454/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001455 * Cached Python objects; these are set by the module init function.
1456 */
1457
1458/* Conversion factors. */
1459static PyObject *us_per_us = NULL; /* 1 */
1460static PyObject *us_per_ms = NULL; /* 1000 */
1461static PyObject *us_per_second = NULL; /* 1000000 */
1462static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1463static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1464static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1465static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1466static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1467
Tim Peters2a799bf2002-12-16 20:18:38 +00001468/* ---------------------------------------------------------------------------
1469 * Class implementations.
1470 */
1471
1472/*
1473 * PyDateTime_Delta implementation.
1474 */
1475
1476/* Convert a timedelta to a number of us,
1477 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1478 * as a Python int or long.
1479 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1480 * due to ubiquitous overflow possibilities.
1481 */
1482static PyObject *
1483delta_to_microseconds(PyDateTime_Delta *self)
1484{
1485 PyObject *x1 = NULL;
1486 PyObject *x2 = NULL;
1487 PyObject *x3 = NULL;
1488 PyObject *result = NULL;
1489
1490 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1491 if (x1 == NULL)
1492 goto Done;
1493 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1494 if (x2 == NULL)
1495 goto Done;
1496 Py_DECREF(x1);
1497 x1 = NULL;
1498
1499 /* x2 has days in seconds */
1500 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1501 if (x1 == NULL)
1502 goto Done;
1503 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1504 if (x3 == NULL)
1505 goto Done;
1506 Py_DECREF(x1);
1507 Py_DECREF(x2);
1508 x1 = x2 = NULL;
1509
1510 /* x3 has days+seconds in seconds */
1511 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1512 if (x1 == NULL)
1513 goto Done;
1514 Py_DECREF(x3);
1515 x3 = NULL;
1516
1517 /* x1 has days+seconds in us */
1518 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1519 if (x2 == NULL)
1520 goto Done;
1521 result = PyNumber_Add(x1, x2);
1522
1523Done:
1524 Py_XDECREF(x1);
1525 Py_XDECREF(x2);
1526 Py_XDECREF(x3);
1527 return result;
1528}
1529
1530/* Convert a number of us (as a Python int or long) to a timedelta.
1531 */
1532static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001533microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001534{
1535 int us;
1536 int s;
1537 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001538 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001539
1540 PyObject *tuple = NULL;
1541 PyObject *num = NULL;
1542 PyObject *result = NULL;
1543
1544 tuple = PyNumber_Divmod(pyus, us_per_second);
1545 if (tuple == NULL)
1546 goto Done;
1547
1548 num = PyTuple_GetItem(tuple, 1); /* us */
1549 if (num == NULL)
1550 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001551 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001552 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001553 if (temp == -1 && PyErr_Occurred())
1554 goto Done;
1555 assert(0 <= temp && temp < 1000000);
1556 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001557 if (us < 0) {
1558 /* The divisor was positive, so this must be an error. */
1559 assert(PyErr_Occurred());
1560 goto Done;
1561 }
1562
1563 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1564 if (num == NULL)
1565 goto Done;
1566 Py_INCREF(num);
1567 Py_DECREF(tuple);
1568
1569 tuple = PyNumber_Divmod(num, seconds_per_day);
1570 if (tuple == NULL)
1571 goto Done;
1572 Py_DECREF(num);
1573
1574 num = PyTuple_GetItem(tuple, 1); /* seconds */
1575 if (num == NULL)
1576 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001577 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001578 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001579 if (temp == -1 && PyErr_Occurred())
1580 goto Done;
1581 assert(0 <= temp && temp < 24*3600);
1582 s = (int)temp;
1583
Tim Peters2a799bf2002-12-16 20:18:38 +00001584 if (s < 0) {
1585 /* The divisor was positive, so this must be an error. */
1586 assert(PyErr_Occurred());
1587 goto Done;
1588 }
1589
1590 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1591 if (num == NULL)
1592 goto Done;
1593 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001594 temp = PyLong_AsLong(num);
1595 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001596 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001597 d = (int)temp;
1598 if ((long)d != temp) {
1599 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1600 "large to fit in a C int");
1601 goto Done;
1602 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001603 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001604
1605Done:
1606 Py_XDECREF(tuple);
1607 Py_XDECREF(num);
1608 return result;
1609}
1610
Tim Petersb0c854d2003-05-17 15:57:00 +00001611#define microseconds_to_delta(pymicros) \
1612 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1613
Tim Peters2a799bf2002-12-16 20:18:38 +00001614static PyObject *
1615multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1616{
1617 PyObject *pyus_in;
1618 PyObject *pyus_out;
1619 PyObject *result;
1620
1621 pyus_in = delta_to_microseconds(delta);
1622 if (pyus_in == NULL)
1623 return NULL;
1624
1625 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1626 Py_DECREF(pyus_in);
1627 if (pyus_out == NULL)
1628 return NULL;
1629
1630 result = microseconds_to_delta(pyus_out);
1631 Py_DECREF(pyus_out);
1632 return result;
1633}
1634
1635static PyObject *
1636divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1637{
1638 PyObject *pyus_in;
1639 PyObject *pyus_out;
1640 PyObject *result;
1641
1642 pyus_in = delta_to_microseconds(delta);
1643 if (pyus_in == NULL)
1644 return NULL;
1645
1646 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1647 Py_DECREF(pyus_in);
1648 if (pyus_out == NULL)
1649 return NULL;
1650
1651 result = microseconds_to_delta(pyus_out);
1652 Py_DECREF(pyus_out);
1653 return result;
1654}
1655
1656static PyObject *
1657delta_add(PyObject *left, PyObject *right)
1658{
1659 PyObject *result = Py_NotImplemented;
1660
1661 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1662 /* delta + delta */
1663 /* The C-level additions can't overflow because of the
1664 * invariant bounds.
1665 */
1666 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1667 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1668 int microseconds = GET_TD_MICROSECONDS(left) +
1669 GET_TD_MICROSECONDS(right);
1670 result = new_delta(days, seconds, microseconds, 1);
1671 }
1672
1673 if (result == Py_NotImplemented)
1674 Py_INCREF(result);
1675 return result;
1676}
1677
1678static PyObject *
1679delta_negative(PyDateTime_Delta *self)
1680{
1681 return new_delta(-GET_TD_DAYS(self),
1682 -GET_TD_SECONDS(self),
1683 -GET_TD_MICROSECONDS(self),
1684 1);
1685}
1686
1687static PyObject *
1688delta_positive(PyDateTime_Delta *self)
1689{
1690 /* Could optimize this (by returning self) if this isn't a
1691 * subclass -- but who uses unary + ? Approximately nobody.
1692 */
1693 return new_delta(GET_TD_DAYS(self),
1694 GET_TD_SECONDS(self),
1695 GET_TD_MICROSECONDS(self),
1696 0);
1697}
1698
1699static PyObject *
1700delta_abs(PyDateTime_Delta *self)
1701{
1702 PyObject *result;
1703
1704 assert(GET_TD_MICROSECONDS(self) >= 0);
1705 assert(GET_TD_SECONDS(self) >= 0);
1706
1707 if (GET_TD_DAYS(self) < 0)
1708 result = delta_negative(self);
1709 else
1710 result = delta_positive(self);
1711
1712 return result;
1713}
1714
1715static PyObject *
1716delta_subtract(PyObject *left, PyObject *right)
1717{
1718 PyObject *result = Py_NotImplemented;
1719
1720 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1721 /* delta - delta */
1722 PyObject *minus_right = PyNumber_Negative(right);
1723 if (minus_right) {
1724 result = delta_add(left, minus_right);
1725 Py_DECREF(minus_right);
1726 }
1727 else
1728 result = NULL;
1729 }
1730
1731 if (result == Py_NotImplemented)
1732 Py_INCREF(result);
1733 return result;
1734}
1735
Tim Peters2a799bf2002-12-16 20:18:38 +00001736static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001737delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001738{
Tim Petersaa7d8492003-02-08 03:28:59 +00001739 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001740 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001741 if (diff == 0) {
1742 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1743 if (diff == 0)
1744 diff = GET_TD_MICROSECONDS(self) -
1745 GET_TD_MICROSECONDS(other);
1746 }
Guido van Rossum19960592006-08-24 17:29:38 +00001747 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001748 }
Guido van Rossum19960592006-08-24 17:29:38 +00001749 else {
1750 Py_INCREF(Py_NotImplemented);
1751 return Py_NotImplemented;
1752 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001753}
1754
1755static PyObject *delta_getstate(PyDateTime_Delta *self);
1756
1757static long
1758delta_hash(PyDateTime_Delta *self)
1759{
1760 if (self->hashcode == -1) {
1761 PyObject *temp = delta_getstate(self);
1762 if (temp != NULL) {
1763 self->hashcode = PyObject_Hash(temp);
1764 Py_DECREF(temp);
1765 }
1766 }
1767 return self->hashcode;
1768}
1769
1770static PyObject *
1771delta_multiply(PyObject *left, PyObject *right)
1772{
1773 PyObject *result = Py_NotImplemented;
1774
1775 if (PyDelta_Check(left)) {
1776 /* delta * ??? */
1777 if (PyInt_Check(right) || PyLong_Check(right))
1778 result = multiply_int_timedelta(right,
1779 (PyDateTime_Delta *) left);
1780 }
1781 else if (PyInt_Check(left) || PyLong_Check(left))
1782 result = multiply_int_timedelta(left,
1783 (PyDateTime_Delta *) right);
1784
1785 if (result == Py_NotImplemented)
1786 Py_INCREF(result);
1787 return result;
1788}
1789
1790static PyObject *
1791delta_divide(PyObject *left, PyObject *right)
1792{
1793 PyObject *result = Py_NotImplemented;
1794
1795 if (PyDelta_Check(left)) {
1796 /* delta * ??? */
1797 if (PyInt_Check(right) || PyLong_Check(right))
1798 result = divide_timedelta_int(
1799 (PyDateTime_Delta *)left,
1800 right);
1801 }
1802
1803 if (result == Py_NotImplemented)
1804 Py_INCREF(result);
1805 return result;
1806}
1807
1808/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1809 * timedelta constructor. sofar is the # of microseconds accounted for
1810 * so far, and there are factor microseconds per current unit, the number
1811 * of which is given by num. num * factor is added to sofar in a
1812 * numerically careful way, and that's the result. Any fractional
1813 * microseconds left over (this can happen if num is a float type) are
1814 * added into *leftover.
1815 * Note that there are many ways this can give an error (NULL) return.
1816 */
1817static PyObject *
1818accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1819 double *leftover)
1820{
1821 PyObject *prod;
1822 PyObject *sum;
1823
1824 assert(num != NULL);
1825
1826 if (PyInt_Check(num) || PyLong_Check(num)) {
1827 prod = PyNumber_Multiply(num, factor);
1828 if (prod == NULL)
1829 return NULL;
1830 sum = PyNumber_Add(sofar, prod);
1831 Py_DECREF(prod);
1832 return sum;
1833 }
1834
1835 if (PyFloat_Check(num)) {
1836 double dnum;
1837 double fracpart;
1838 double intpart;
1839 PyObject *x;
1840 PyObject *y;
1841
1842 /* The Plan: decompose num into an integer part and a
1843 * fractional part, num = intpart + fracpart.
1844 * Then num * factor ==
1845 * intpart * factor + fracpart * factor
1846 * and the LHS can be computed exactly in long arithmetic.
1847 * The RHS is again broken into an int part and frac part.
1848 * and the frac part is added into *leftover.
1849 */
1850 dnum = PyFloat_AsDouble(num);
1851 if (dnum == -1.0 && PyErr_Occurred())
1852 return NULL;
1853 fracpart = modf(dnum, &intpart);
1854 x = PyLong_FromDouble(intpart);
1855 if (x == NULL)
1856 return NULL;
1857
1858 prod = PyNumber_Multiply(x, factor);
1859 Py_DECREF(x);
1860 if (prod == NULL)
1861 return NULL;
1862
1863 sum = PyNumber_Add(sofar, prod);
1864 Py_DECREF(prod);
1865 if (sum == NULL)
1866 return NULL;
1867
1868 if (fracpart == 0.0)
1869 return sum;
1870 /* So far we've lost no information. Dealing with the
1871 * fractional part requires float arithmetic, and may
1872 * lose a little info.
1873 */
1874 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001875 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001876
1877 dnum *= fracpart;
1878 fracpart = modf(dnum, &intpart);
1879 x = PyLong_FromDouble(intpart);
1880 if (x == NULL) {
1881 Py_DECREF(sum);
1882 return NULL;
1883 }
1884
1885 y = PyNumber_Add(sum, x);
1886 Py_DECREF(sum);
1887 Py_DECREF(x);
1888 *leftover += fracpart;
1889 return y;
1890 }
1891
1892 PyErr_Format(PyExc_TypeError,
1893 "unsupported type for timedelta %s component: %s",
1894 tag, num->ob_type->tp_name);
1895 return NULL;
1896}
1897
1898static PyObject *
1899delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1900{
1901 PyObject *self = NULL;
1902
1903 /* Argument objects. */
1904 PyObject *day = NULL;
1905 PyObject *second = NULL;
1906 PyObject *us = NULL;
1907 PyObject *ms = NULL;
1908 PyObject *minute = NULL;
1909 PyObject *hour = NULL;
1910 PyObject *week = NULL;
1911
1912 PyObject *x = NULL; /* running sum of microseconds */
1913 PyObject *y = NULL; /* temp sum of microseconds */
1914 double leftover_us = 0.0;
1915
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001916 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001917 "days", "seconds", "microseconds", "milliseconds",
1918 "minutes", "hours", "weeks", NULL
1919 };
1920
1921 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1922 keywords,
1923 &day, &second, &us,
1924 &ms, &minute, &hour, &week) == 0)
1925 goto Done;
1926
1927 x = PyInt_FromLong(0);
1928 if (x == NULL)
1929 goto Done;
1930
1931#define CLEANUP \
1932 Py_DECREF(x); \
1933 x = y; \
1934 if (x == NULL) \
1935 goto Done
1936
1937 if (us) {
1938 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1939 CLEANUP;
1940 }
1941 if (ms) {
1942 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1943 CLEANUP;
1944 }
1945 if (second) {
1946 y = accum("seconds", x, second, us_per_second, &leftover_us);
1947 CLEANUP;
1948 }
1949 if (minute) {
1950 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1951 CLEANUP;
1952 }
1953 if (hour) {
1954 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1955 CLEANUP;
1956 }
1957 if (day) {
1958 y = accum("days", x, day, us_per_day, &leftover_us);
1959 CLEANUP;
1960 }
1961 if (week) {
1962 y = accum("weeks", x, week, us_per_week, &leftover_us);
1963 CLEANUP;
1964 }
1965 if (leftover_us) {
1966 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001967 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001968 if (temp == NULL) {
1969 Py_DECREF(x);
1970 goto Done;
1971 }
1972 y = PyNumber_Add(x, temp);
1973 Py_DECREF(temp);
1974 CLEANUP;
1975 }
1976
Tim Petersb0c854d2003-05-17 15:57:00 +00001977 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001978 Py_DECREF(x);
1979Done:
1980 return self;
1981
1982#undef CLEANUP
1983}
1984
1985static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001986delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001987{
1988 return (GET_TD_DAYS(self) != 0
1989 || GET_TD_SECONDS(self) != 0
1990 || GET_TD_MICROSECONDS(self) != 0);
1991}
1992
1993static PyObject *
1994delta_repr(PyDateTime_Delta *self)
1995{
1996 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001997 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001998 self->ob_type->tp_name,
1999 GET_TD_DAYS(self),
2000 GET_TD_SECONDS(self),
2001 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002002 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00002003 return PyUnicode_FromFormat("%s(%d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002004 self->ob_type->tp_name,
2005 GET_TD_DAYS(self),
2006 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002007
Walter Dörwald1ab83302007-05-18 17:15:44 +00002008 return PyUnicode_FromFormat("%s(%d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002009 self->ob_type->tp_name,
2010 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002011}
2012
2013static PyObject *
2014delta_str(PyDateTime_Delta *self)
2015{
2016 int days = GET_TD_DAYS(self);
2017 int seconds = GET_TD_SECONDS(self);
2018 int us = GET_TD_MICROSECONDS(self);
2019 int hours;
2020 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00002021 char buf[100];
2022 char *pbuf = buf;
2023 size_t buflen = sizeof(buf);
2024 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002025
2026 minutes = divmod(seconds, 60, &seconds);
2027 hours = divmod(minutes, 60, &minutes);
2028
2029 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002030 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2031 (days == 1 || days == -1) ? "" : "s");
2032 if (n < 0 || (size_t)n >= buflen)
2033 goto Fail;
2034 pbuf += n;
2035 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002036 }
2037
Tim Petersba873472002-12-18 20:19:21 +00002038 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2039 hours, minutes, seconds);
2040 if (n < 0 || (size_t)n >= buflen)
2041 goto Fail;
2042 pbuf += n;
2043 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002044
2045 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002046 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2047 if (n < 0 || (size_t)n >= buflen)
2048 goto Fail;
2049 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002050 }
2051
Tim Petersba873472002-12-18 20:19:21 +00002052 return PyString_FromStringAndSize(buf, pbuf - buf);
2053
2054 Fail:
2055 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2056 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002057}
2058
Tim Peters371935f2003-02-01 01:52:50 +00002059/* Pickle support, a simple use of __reduce__. */
2060
Tim Petersb57f8f02003-02-01 02:54:15 +00002061/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002062static PyObject *
2063delta_getstate(PyDateTime_Delta *self)
2064{
2065 return Py_BuildValue("iii", GET_TD_DAYS(self),
2066 GET_TD_SECONDS(self),
2067 GET_TD_MICROSECONDS(self));
2068}
2069
Tim Peters2a799bf2002-12-16 20:18:38 +00002070static PyObject *
2071delta_reduce(PyDateTime_Delta* self)
2072{
Tim Peters8a60c222003-02-01 01:47:29 +00002073 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002074}
2075
2076#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2077
2078static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002079
Neal Norwitzdfb80862002-12-19 02:30:56 +00002080 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002081 PyDoc_STR("Number of days.")},
2082
Neal Norwitzdfb80862002-12-19 02:30:56 +00002083 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002084 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2085
Neal Norwitzdfb80862002-12-19 02:30:56 +00002086 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002087 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2088 {NULL}
2089};
2090
2091static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002092 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2093 PyDoc_STR("__reduce__() -> (cls, state)")},
2094
Tim Peters2a799bf2002-12-16 20:18:38 +00002095 {NULL, NULL},
2096};
2097
2098static char delta_doc[] =
2099PyDoc_STR("Difference between two datetime values.");
2100
2101static PyNumberMethods delta_as_number = {
2102 delta_add, /* nb_add */
2103 delta_subtract, /* nb_subtract */
2104 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002105 0, /* nb_remainder */
2106 0, /* nb_divmod */
2107 0, /* nb_power */
2108 (unaryfunc)delta_negative, /* nb_negative */
2109 (unaryfunc)delta_positive, /* nb_positive */
2110 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002111 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002112 0, /*nb_invert*/
2113 0, /*nb_lshift*/
2114 0, /*nb_rshift*/
2115 0, /*nb_and*/
2116 0, /*nb_xor*/
2117 0, /*nb_or*/
2118 0, /*nb_coerce*/
2119 0, /*nb_int*/
2120 0, /*nb_long*/
2121 0, /*nb_float*/
2122 0, /*nb_oct*/
2123 0, /*nb_hex*/
2124 0, /*nb_inplace_add*/
2125 0, /*nb_inplace_subtract*/
2126 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002127 0, /*nb_inplace_remainder*/
2128 0, /*nb_inplace_power*/
2129 0, /*nb_inplace_lshift*/
2130 0, /*nb_inplace_rshift*/
2131 0, /*nb_inplace_and*/
2132 0, /*nb_inplace_xor*/
2133 0, /*nb_inplace_or*/
2134 delta_divide, /* nb_floor_divide */
2135 0, /* nb_true_divide */
2136 0, /* nb_inplace_floor_divide */
2137 0, /* nb_inplace_true_divide */
2138};
2139
2140static PyTypeObject PyDateTime_DeltaType = {
2141 PyObject_HEAD_INIT(NULL)
2142 0, /* ob_size */
2143 "datetime.timedelta", /* tp_name */
2144 sizeof(PyDateTime_Delta), /* tp_basicsize */
2145 0, /* tp_itemsize */
2146 0, /* tp_dealloc */
2147 0, /* tp_print */
2148 0, /* tp_getattr */
2149 0, /* tp_setattr */
2150 0, /* tp_compare */
2151 (reprfunc)delta_repr, /* tp_repr */
2152 &delta_as_number, /* tp_as_number */
2153 0, /* tp_as_sequence */
2154 0, /* tp_as_mapping */
2155 (hashfunc)delta_hash, /* tp_hash */
2156 0, /* tp_call */
2157 (reprfunc)delta_str, /* tp_str */
2158 PyObject_GenericGetAttr, /* tp_getattro */
2159 0, /* tp_setattro */
2160 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002161 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002162 delta_doc, /* tp_doc */
2163 0, /* tp_traverse */
2164 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002165 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002166 0, /* tp_weaklistoffset */
2167 0, /* tp_iter */
2168 0, /* tp_iternext */
2169 delta_methods, /* tp_methods */
2170 delta_members, /* tp_members */
2171 0, /* tp_getset */
2172 0, /* tp_base */
2173 0, /* tp_dict */
2174 0, /* tp_descr_get */
2175 0, /* tp_descr_set */
2176 0, /* tp_dictoffset */
2177 0, /* tp_init */
2178 0, /* tp_alloc */
2179 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002180 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002181};
2182
2183/*
2184 * PyDateTime_Date implementation.
2185 */
2186
2187/* Accessor properties. */
2188
2189static PyObject *
2190date_year(PyDateTime_Date *self, void *unused)
2191{
2192 return PyInt_FromLong(GET_YEAR(self));
2193}
2194
2195static PyObject *
2196date_month(PyDateTime_Date *self, void *unused)
2197{
2198 return PyInt_FromLong(GET_MONTH(self));
2199}
2200
2201static PyObject *
2202date_day(PyDateTime_Date *self, void *unused)
2203{
2204 return PyInt_FromLong(GET_DAY(self));
2205}
2206
2207static PyGetSetDef date_getset[] = {
2208 {"year", (getter)date_year},
2209 {"month", (getter)date_month},
2210 {"day", (getter)date_day},
2211 {NULL}
2212};
2213
2214/* Constructors. */
2215
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002216static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002217
Tim Peters2a799bf2002-12-16 20:18:38 +00002218static PyObject *
2219date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2220{
2221 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002222 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002223 int year;
2224 int month;
2225 int day;
2226
Guido van Rossum177e41a2003-01-30 22:06:23 +00002227 /* Check for invocation from pickle with __getstate__ state */
2228 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002229 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002230 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2231 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002232 {
Tim Peters70533e22003-02-01 04:40:04 +00002233 PyDateTime_Date *me;
2234
Tim Peters604c0132004-06-07 23:04:33 +00002235 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002236 if (me != NULL) {
2237 char *pdata = PyString_AS_STRING(state);
2238 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2239 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002240 }
Tim Peters70533e22003-02-01 04:40:04 +00002241 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002242 }
2243
Tim Peters12bf3392002-12-24 05:41:27 +00002244 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002245 &year, &month, &day)) {
2246 if (check_date_args(year, month, day) < 0)
2247 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002248 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002249 }
2250 return self;
2251}
2252
2253/* Return new date from localtime(t). */
2254static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002255date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002256{
2257 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002258 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002259 PyObject *result = NULL;
2260
Tim Peters1b6f7a92004-06-20 02:50:16 +00002261 t = _PyTime_DoubleToTimet(ts);
2262 if (t == (time_t)-1 && PyErr_Occurred())
2263 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002264 tm = localtime(&t);
2265 if (tm)
2266 result = PyObject_CallFunction(cls, "iii",
2267 tm->tm_year + 1900,
2268 tm->tm_mon + 1,
2269 tm->tm_mday);
2270 else
2271 PyErr_SetString(PyExc_ValueError,
2272 "timestamp out of range for "
2273 "platform localtime() function");
2274 return result;
2275}
2276
2277/* Return new date from current time.
2278 * We say this is equivalent to fromtimestamp(time.time()), and the
2279 * only way to be sure of that is to *call* time.time(). That's not
2280 * generally the same as calling C's time.
2281 */
2282static PyObject *
2283date_today(PyObject *cls, PyObject *dummy)
2284{
2285 PyObject *time;
2286 PyObject *result;
2287
2288 time = time_time();
2289 if (time == NULL)
2290 return NULL;
2291
2292 /* Note well: today() is a class method, so this may not call
2293 * date.fromtimestamp. For example, it may call
2294 * datetime.fromtimestamp. That's why we need all the accuracy
2295 * time.time() delivers; if someone were gonzo about optimization,
2296 * date.today() could get away with plain C time().
2297 */
2298 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2299 Py_DECREF(time);
2300 return result;
2301}
2302
2303/* Return new date from given timestamp (Python timestamp -- a double). */
2304static PyObject *
2305date_fromtimestamp(PyObject *cls, PyObject *args)
2306{
2307 double timestamp;
2308 PyObject *result = NULL;
2309
2310 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002311 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002312 return result;
2313}
2314
2315/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2316 * the ordinal is out of range.
2317 */
2318static PyObject *
2319date_fromordinal(PyObject *cls, PyObject *args)
2320{
2321 PyObject *result = NULL;
2322 int ordinal;
2323
2324 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2325 int year;
2326 int month;
2327 int day;
2328
2329 if (ordinal < 1)
2330 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2331 ">= 1");
2332 else {
2333 ord_to_ymd(ordinal, &year, &month, &day);
2334 result = PyObject_CallFunction(cls, "iii",
2335 year, month, day);
2336 }
2337 }
2338 return result;
2339}
2340
2341/*
2342 * Date arithmetic.
2343 */
2344
2345/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2346 * instead.
2347 */
2348static PyObject *
2349add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2350{
2351 PyObject *result = NULL;
2352 int year = GET_YEAR(date);
2353 int month = GET_MONTH(date);
2354 int deltadays = GET_TD_DAYS(delta);
2355 /* C-level overflow is impossible because |deltadays| < 1e9. */
2356 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2357
2358 if (normalize_date(&year, &month, &day) >= 0)
2359 result = new_date(year, month, day);
2360 return result;
2361}
2362
2363static PyObject *
2364date_add(PyObject *left, PyObject *right)
2365{
2366 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2367 Py_INCREF(Py_NotImplemented);
2368 return Py_NotImplemented;
2369 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002370 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002371 /* date + ??? */
2372 if (PyDelta_Check(right))
2373 /* date + delta */
2374 return add_date_timedelta((PyDateTime_Date *) left,
2375 (PyDateTime_Delta *) right,
2376 0);
2377 }
2378 else {
2379 /* ??? + date
2380 * 'right' must be one of us, or we wouldn't have been called
2381 */
2382 if (PyDelta_Check(left))
2383 /* delta + date */
2384 return add_date_timedelta((PyDateTime_Date *) right,
2385 (PyDateTime_Delta *) left,
2386 0);
2387 }
2388 Py_INCREF(Py_NotImplemented);
2389 return Py_NotImplemented;
2390}
2391
2392static PyObject *
2393date_subtract(PyObject *left, PyObject *right)
2394{
2395 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2396 Py_INCREF(Py_NotImplemented);
2397 return Py_NotImplemented;
2398 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002399 if (PyDate_Check(left)) {
2400 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002401 /* date - date */
2402 int left_ord = ymd_to_ord(GET_YEAR(left),
2403 GET_MONTH(left),
2404 GET_DAY(left));
2405 int right_ord = ymd_to_ord(GET_YEAR(right),
2406 GET_MONTH(right),
2407 GET_DAY(right));
2408 return new_delta(left_ord - right_ord, 0, 0, 0);
2409 }
2410 if (PyDelta_Check(right)) {
2411 /* date - delta */
2412 return add_date_timedelta((PyDateTime_Date *) left,
2413 (PyDateTime_Delta *) right,
2414 1);
2415 }
2416 }
2417 Py_INCREF(Py_NotImplemented);
2418 return Py_NotImplemented;
2419}
2420
2421
2422/* Various ways to turn a date into a string. */
2423
2424static PyObject *
2425date_repr(PyDateTime_Date *self)
2426{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002427 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2428 self->ob_type->tp_name,
2429 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002430}
2431
2432static PyObject *
2433date_isoformat(PyDateTime_Date *self)
2434{
2435 char buffer[128];
2436
2437 isoformat_date(self, buffer, sizeof(buffer));
2438 return PyString_FromString(buffer);
2439}
2440
Tim Peterse2df5ff2003-05-02 18:39:55 +00002441/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002442static PyObject *
2443date_str(PyDateTime_Date *self)
2444{
2445 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2446}
2447
2448
2449static PyObject *
2450date_ctime(PyDateTime_Date *self)
2451{
2452 return format_ctime(self, 0, 0, 0);
2453}
2454
2455static PyObject *
2456date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2457{
2458 /* This method can be inherited, and needs to call the
2459 * timetuple() method appropriate to self's class.
2460 */
2461 PyObject *result;
2462 PyObject *format;
2463 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002464 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002465
Guido van Rossumbce56a62007-05-10 18:04:33 +00002466 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2467 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002468 return NULL;
2469
2470 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2471 if (tuple == NULL)
2472 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002473 result = wrap_strftime((PyObject *)self, format, tuple,
2474 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002475 Py_DECREF(tuple);
2476 return result;
2477}
2478
2479/* ISO methods. */
2480
2481static PyObject *
2482date_isoweekday(PyDateTime_Date *self)
2483{
2484 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2485
2486 return PyInt_FromLong(dow + 1);
2487}
2488
2489static PyObject *
2490date_isocalendar(PyDateTime_Date *self)
2491{
2492 int year = GET_YEAR(self);
2493 int week1_monday = iso_week1_monday(year);
2494 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2495 int week;
2496 int day;
2497
2498 week = divmod(today - week1_monday, 7, &day);
2499 if (week < 0) {
2500 --year;
2501 week1_monday = iso_week1_monday(year);
2502 week = divmod(today - week1_monday, 7, &day);
2503 }
2504 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2505 ++year;
2506 week = 0;
2507 }
2508 return Py_BuildValue("iii", year, week + 1, day + 1);
2509}
2510
2511/* Miscellaneous methods. */
2512
Tim Peters2a799bf2002-12-16 20:18:38 +00002513static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002514date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002515{
Guido van Rossum19960592006-08-24 17:29:38 +00002516 if (PyDate_Check(other)) {
2517 int diff = memcmp(((PyDateTime_Date *)self)->data,
2518 ((PyDateTime_Date *)other)->data,
2519 _PyDateTime_DATE_DATASIZE);
2520 return diff_to_bool(diff, op);
2521 }
2522 else {
Tim Peters07534a62003-02-07 22:50:28 +00002523 Py_INCREF(Py_NotImplemented);
2524 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002525 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002526}
2527
2528static PyObject *
2529date_timetuple(PyDateTime_Date *self)
2530{
2531 return build_struct_time(GET_YEAR(self),
2532 GET_MONTH(self),
2533 GET_DAY(self),
2534 0, 0, 0, -1);
2535}
2536
Tim Peters12bf3392002-12-24 05:41:27 +00002537static PyObject *
2538date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2539{
2540 PyObject *clone;
2541 PyObject *tuple;
2542 int year = GET_YEAR(self);
2543 int month = GET_MONTH(self);
2544 int day = GET_DAY(self);
2545
2546 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2547 &year, &month, &day))
2548 return NULL;
2549 tuple = Py_BuildValue("iii", year, month, day);
2550 if (tuple == NULL)
2551 return NULL;
2552 clone = date_new(self->ob_type, tuple, NULL);
2553 Py_DECREF(tuple);
2554 return clone;
2555}
2556
Tim Peters2a799bf2002-12-16 20:18:38 +00002557static PyObject *date_getstate(PyDateTime_Date *self);
2558
2559static long
2560date_hash(PyDateTime_Date *self)
2561{
2562 if (self->hashcode == -1) {
2563 PyObject *temp = date_getstate(self);
2564 if (temp != NULL) {
2565 self->hashcode = PyObject_Hash(temp);
2566 Py_DECREF(temp);
2567 }
2568 }
2569 return self->hashcode;
2570}
2571
2572static PyObject *
2573date_toordinal(PyDateTime_Date *self)
2574{
2575 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2576 GET_DAY(self)));
2577}
2578
2579static PyObject *
2580date_weekday(PyDateTime_Date *self)
2581{
2582 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2583
2584 return PyInt_FromLong(dow);
2585}
2586
Tim Peters371935f2003-02-01 01:52:50 +00002587/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002588
Tim Petersb57f8f02003-02-01 02:54:15 +00002589/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002590static PyObject *
2591date_getstate(PyDateTime_Date *self)
2592{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002593 return Py_BuildValue(
2594 "(N)",
2595 PyString_FromStringAndSize((char *)self->data,
2596 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002597}
2598
2599static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002600date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002601{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002602 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002603}
2604
2605static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002606
Tim Peters2a799bf2002-12-16 20:18:38 +00002607 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002608
Tim Peters2a799bf2002-12-16 20:18:38 +00002609 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2610 METH_CLASS,
2611 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2612 "time.time()).")},
2613
2614 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2615 METH_CLASS,
2616 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2617 "ordinal.")},
2618
2619 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2620 PyDoc_STR("Current date or datetime: same as "
2621 "self.__class__.fromtimestamp(time.time()).")},
2622
2623 /* Instance methods: */
2624
2625 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2626 PyDoc_STR("Return ctime() style string.")},
2627
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002628 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002629 PyDoc_STR("format -> strftime() style string.")},
2630
2631 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2632 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2633
2634 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2635 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2636 "weekday.")},
2637
2638 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2639 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2640
2641 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2642 PyDoc_STR("Return the day of the week represented by the date.\n"
2643 "Monday == 1 ... Sunday == 7")},
2644
2645 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2646 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2647 "1 is day 1.")},
2648
2649 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2650 PyDoc_STR("Return the day of the week represented by the date.\n"
2651 "Monday == 0 ... Sunday == 6")},
2652
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002653 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002654 PyDoc_STR("Return date with new specified fields.")},
2655
Guido van Rossum177e41a2003-01-30 22:06:23 +00002656 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2657 PyDoc_STR("__reduce__() -> (cls, state)")},
2658
Tim Peters2a799bf2002-12-16 20:18:38 +00002659 {NULL, NULL}
2660};
2661
2662static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002663PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002664
2665static PyNumberMethods date_as_number = {
2666 date_add, /* nb_add */
2667 date_subtract, /* nb_subtract */
2668 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002669 0, /* nb_remainder */
2670 0, /* nb_divmod */
2671 0, /* nb_power */
2672 0, /* nb_negative */
2673 0, /* nb_positive */
2674 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002675 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002676};
2677
2678static PyTypeObject PyDateTime_DateType = {
2679 PyObject_HEAD_INIT(NULL)
2680 0, /* ob_size */
2681 "datetime.date", /* tp_name */
2682 sizeof(PyDateTime_Date), /* tp_basicsize */
2683 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002684 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002685 0, /* tp_print */
2686 0, /* tp_getattr */
2687 0, /* tp_setattr */
2688 0, /* tp_compare */
2689 (reprfunc)date_repr, /* tp_repr */
2690 &date_as_number, /* tp_as_number */
2691 0, /* tp_as_sequence */
2692 0, /* tp_as_mapping */
2693 (hashfunc)date_hash, /* tp_hash */
2694 0, /* tp_call */
2695 (reprfunc)date_str, /* tp_str */
2696 PyObject_GenericGetAttr, /* tp_getattro */
2697 0, /* tp_setattro */
2698 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002699 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002700 date_doc, /* tp_doc */
2701 0, /* tp_traverse */
2702 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002703 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002704 0, /* tp_weaklistoffset */
2705 0, /* tp_iter */
2706 0, /* tp_iternext */
2707 date_methods, /* tp_methods */
2708 0, /* tp_members */
2709 date_getset, /* tp_getset */
2710 0, /* tp_base */
2711 0, /* tp_dict */
2712 0, /* tp_descr_get */
2713 0, /* tp_descr_set */
2714 0, /* tp_dictoffset */
2715 0, /* tp_init */
2716 0, /* tp_alloc */
2717 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002718 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002719};
2720
2721/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002722 * PyDateTime_TZInfo implementation.
2723 */
2724
2725/* This is a pure abstract base class, so doesn't do anything beyond
2726 * raising NotImplemented exceptions. Real tzinfo classes need
2727 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002728 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002729 * be subclasses of this tzinfo class, which is easy and quick to check).
2730 *
2731 * Note: For reasons having to do with pickling of subclasses, we have
2732 * to allow tzinfo objects to be instantiated. This wasn't an issue
2733 * in the Python implementation (__init__() could raise NotImplementedError
2734 * there without ill effect), but doing so in the C implementation hit a
2735 * brick wall.
2736 */
2737
2738static PyObject *
2739tzinfo_nogo(const char* methodname)
2740{
2741 PyErr_Format(PyExc_NotImplementedError,
2742 "a tzinfo subclass must implement %s()",
2743 methodname);
2744 return NULL;
2745}
2746
2747/* Methods. A subclass must implement these. */
2748
Tim Peters52dcce22003-01-23 16:36:11 +00002749static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002750tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2751{
2752 return tzinfo_nogo("tzname");
2753}
2754
Tim Peters52dcce22003-01-23 16:36:11 +00002755static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002756tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2757{
2758 return tzinfo_nogo("utcoffset");
2759}
2760
Tim Peters52dcce22003-01-23 16:36:11 +00002761static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002762tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2763{
2764 return tzinfo_nogo("dst");
2765}
2766
Tim Peters52dcce22003-01-23 16:36:11 +00002767static PyObject *
2768tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2769{
2770 int y, m, d, hh, mm, ss, us;
2771
2772 PyObject *result;
2773 int off, dst;
2774 int none;
2775 int delta;
2776
2777 if (! PyDateTime_Check(dt)) {
2778 PyErr_SetString(PyExc_TypeError,
2779 "fromutc: argument must be a datetime");
2780 return NULL;
2781 }
2782 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2783 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2784 "is not self");
2785 return NULL;
2786 }
2787
2788 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2789 if (off == -1 && PyErr_Occurred())
2790 return NULL;
2791 if (none) {
2792 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2793 "utcoffset() result required");
2794 return NULL;
2795 }
2796
2797 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2798 if (dst == -1 && PyErr_Occurred())
2799 return NULL;
2800 if (none) {
2801 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2802 "dst() result required");
2803 return NULL;
2804 }
2805
2806 y = GET_YEAR(dt);
2807 m = GET_MONTH(dt);
2808 d = GET_DAY(dt);
2809 hh = DATE_GET_HOUR(dt);
2810 mm = DATE_GET_MINUTE(dt);
2811 ss = DATE_GET_SECOND(dt);
2812 us = DATE_GET_MICROSECOND(dt);
2813
2814 delta = off - dst;
2815 mm += delta;
2816 if ((mm < 0 || mm >= 60) &&
2817 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002818 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002819 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2820 if (result == NULL)
2821 return result;
2822
2823 dst = call_dst(dt->tzinfo, result, &none);
2824 if (dst == -1 && PyErr_Occurred())
2825 goto Fail;
2826 if (none)
2827 goto Inconsistent;
2828 if (dst == 0)
2829 return result;
2830
2831 mm += dst;
2832 if ((mm < 0 || mm >= 60) &&
2833 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2834 goto Fail;
2835 Py_DECREF(result);
2836 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2837 return result;
2838
2839Inconsistent:
2840 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2841 "inconsistent results; cannot convert");
2842
2843 /* fall thru to failure */
2844Fail:
2845 Py_DECREF(result);
2846 return NULL;
2847}
2848
Tim Peters2a799bf2002-12-16 20:18:38 +00002849/*
2850 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002851 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002852 */
2853
Guido van Rossum177e41a2003-01-30 22:06:23 +00002854static PyObject *
2855tzinfo_reduce(PyObject *self)
2856{
2857 PyObject *args, *state, *tmp;
2858 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002859
Guido van Rossum177e41a2003-01-30 22:06:23 +00002860 tmp = PyTuple_New(0);
2861 if (tmp == NULL)
2862 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002863
Guido van Rossum177e41a2003-01-30 22:06:23 +00002864 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2865 if (getinitargs != NULL) {
2866 args = PyObject_CallObject(getinitargs, tmp);
2867 Py_DECREF(getinitargs);
2868 if (args == NULL) {
2869 Py_DECREF(tmp);
2870 return NULL;
2871 }
2872 }
2873 else {
2874 PyErr_Clear();
2875 args = tmp;
2876 Py_INCREF(args);
2877 }
2878
2879 getstate = PyObject_GetAttrString(self, "__getstate__");
2880 if (getstate != NULL) {
2881 state = PyObject_CallObject(getstate, tmp);
2882 Py_DECREF(getstate);
2883 if (state == NULL) {
2884 Py_DECREF(args);
2885 Py_DECREF(tmp);
2886 return NULL;
2887 }
2888 }
2889 else {
2890 PyObject **dictptr;
2891 PyErr_Clear();
2892 state = Py_None;
2893 dictptr = _PyObject_GetDictPtr(self);
2894 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2895 state = *dictptr;
2896 Py_INCREF(state);
2897 }
2898
2899 Py_DECREF(tmp);
2900
2901 if (state == Py_None) {
2902 Py_DECREF(state);
2903 return Py_BuildValue("(ON)", self->ob_type, args);
2904 }
2905 else
2906 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2907}
Tim Peters2a799bf2002-12-16 20:18:38 +00002908
2909static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002910
Tim Peters2a799bf2002-12-16 20:18:38 +00002911 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2912 PyDoc_STR("datetime -> string name of time zone.")},
2913
2914 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2915 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2916 "west of UTC).")},
2917
2918 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2919 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2920
Tim Peters52dcce22003-01-23 16:36:11 +00002921 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2922 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2923
Guido van Rossum177e41a2003-01-30 22:06:23 +00002924 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2925 PyDoc_STR("-> (cls, state)")},
2926
Tim Peters2a799bf2002-12-16 20:18:38 +00002927 {NULL, NULL}
2928};
2929
2930static char tzinfo_doc[] =
2931PyDoc_STR("Abstract base class for time zone info objects.");
2932
Neal Norwitz227b5332006-03-22 09:28:35 +00002933static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002934 PyObject_HEAD_INIT(NULL)
2935 0, /* ob_size */
2936 "datetime.tzinfo", /* tp_name */
2937 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2938 0, /* tp_itemsize */
2939 0, /* tp_dealloc */
2940 0, /* tp_print */
2941 0, /* tp_getattr */
2942 0, /* tp_setattr */
2943 0, /* tp_compare */
2944 0, /* tp_repr */
2945 0, /* tp_as_number */
2946 0, /* tp_as_sequence */
2947 0, /* tp_as_mapping */
2948 0, /* tp_hash */
2949 0, /* tp_call */
2950 0, /* tp_str */
2951 PyObject_GenericGetAttr, /* tp_getattro */
2952 0, /* tp_setattro */
2953 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002954 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002955 tzinfo_doc, /* tp_doc */
2956 0, /* tp_traverse */
2957 0, /* tp_clear */
2958 0, /* tp_richcompare */
2959 0, /* tp_weaklistoffset */
2960 0, /* tp_iter */
2961 0, /* tp_iternext */
2962 tzinfo_methods, /* tp_methods */
2963 0, /* tp_members */
2964 0, /* tp_getset */
2965 0, /* tp_base */
2966 0, /* tp_dict */
2967 0, /* tp_descr_get */
2968 0, /* tp_descr_set */
2969 0, /* tp_dictoffset */
2970 0, /* tp_init */
2971 0, /* tp_alloc */
2972 PyType_GenericNew, /* tp_new */
2973 0, /* tp_free */
2974};
2975
2976/*
Tim Peters37f39822003-01-10 03:49:02 +00002977 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002978 */
2979
Tim Peters37f39822003-01-10 03:49:02 +00002980/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002981 */
2982
2983static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002984time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002985{
Tim Peters37f39822003-01-10 03:49:02 +00002986 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002987}
2988
Tim Peters37f39822003-01-10 03:49:02 +00002989static PyObject *
2990time_minute(PyDateTime_Time *self, void *unused)
2991{
2992 return PyInt_FromLong(TIME_GET_MINUTE(self));
2993}
2994
2995/* The name time_second conflicted with some platform header file. */
2996static PyObject *
2997py_time_second(PyDateTime_Time *self, void *unused)
2998{
2999 return PyInt_FromLong(TIME_GET_SECOND(self));
3000}
3001
3002static PyObject *
3003time_microsecond(PyDateTime_Time *self, void *unused)
3004{
3005 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3006}
3007
3008static PyObject *
3009time_tzinfo(PyDateTime_Time *self, void *unused)
3010{
Tim Petersa032d2e2003-01-11 00:15:54 +00003011 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003012 Py_INCREF(result);
3013 return result;
3014}
3015
3016static PyGetSetDef time_getset[] = {
3017 {"hour", (getter)time_hour},
3018 {"minute", (getter)time_minute},
3019 {"second", (getter)py_time_second},
3020 {"microsecond", (getter)time_microsecond},
3021 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003022 {NULL}
3023};
3024
3025/*
3026 * Constructors.
3027 */
3028
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003029static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003030 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003031
Tim Peters2a799bf2002-12-16 20:18:38 +00003032static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003033time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003034{
3035 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003036 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003037 int hour = 0;
3038 int minute = 0;
3039 int second = 0;
3040 int usecond = 0;
3041 PyObject *tzinfo = Py_None;
3042
Guido van Rossum177e41a2003-01-30 22:06:23 +00003043 /* Check for invocation from pickle with __getstate__ state */
3044 if (PyTuple_GET_SIZE(args) >= 1 &&
3045 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003046 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003047 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3048 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003049 {
Tim Peters70533e22003-02-01 04:40:04 +00003050 PyDateTime_Time *me;
3051 char aware;
3052
3053 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003054 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003055 if (check_tzinfo_subclass(tzinfo) < 0) {
3056 PyErr_SetString(PyExc_TypeError, "bad "
3057 "tzinfo state arg");
3058 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003059 }
3060 }
Tim Peters70533e22003-02-01 04:40:04 +00003061 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003062 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003063 if (me != NULL) {
3064 char *pdata = PyString_AS_STRING(state);
3065
3066 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3067 me->hashcode = -1;
3068 me->hastzinfo = aware;
3069 if (aware) {
3070 Py_INCREF(tzinfo);
3071 me->tzinfo = tzinfo;
3072 }
3073 }
3074 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003075 }
3076
Tim Peters37f39822003-01-10 03:49:02 +00003077 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003078 &hour, &minute, &second, &usecond,
3079 &tzinfo)) {
3080 if (check_time_args(hour, minute, second, usecond) < 0)
3081 return NULL;
3082 if (check_tzinfo_subclass(tzinfo) < 0)
3083 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003084 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3085 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003086 }
3087 return self;
3088}
3089
3090/*
3091 * Destructor.
3092 */
3093
3094static void
Tim Peters37f39822003-01-10 03:49:02 +00003095time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003096{
Tim Petersa032d2e2003-01-11 00:15:54 +00003097 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003098 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003099 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003100 self->ob_type->tp_free((PyObject *)self);
3101}
3102
3103/*
Tim Peters855fe882002-12-22 03:43:39 +00003104 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003105 */
3106
Tim Peters2a799bf2002-12-16 20:18:38 +00003107/* These are all METH_NOARGS, so don't need to check the arglist. */
3108static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003109time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003110 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003111 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003112}
3113
3114static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003115time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003116 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003117 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003118}
3119
3120static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003121time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003122 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003123 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003124}
3125
3126/*
Tim Peters37f39822003-01-10 03:49:02 +00003127 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003128 */
3129
3130static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003131time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003132{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003133 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003134 int h = TIME_GET_HOUR(self);
3135 int m = TIME_GET_MINUTE(self);
3136 int s = TIME_GET_SECOND(self);
3137 int us = TIME_GET_MICROSECOND(self);
3138 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003139
Tim Peters37f39822003-01-10 03:49:02 +00003140 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003141 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3142 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003143 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003144 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3145 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003146 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003147 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003148 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003149 result = append_keyword_tzinfo(result, self->tzinfo);
3150 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003151}
3152
Tim Peters37f39822003-01-10 03:49:02 +00003153static PyObject *
3154time_str(PyDateTime_Time *self)
3155{
3156 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3157}
Tim Peters2a799bf2002-12-16 20:18:38 +00003158
3159static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003160time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003161{
3162 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003163 PyObject *result;
3164 /* Reuse the time format code from the datetime type. */
3165 PyDateTime_DateTime datetime;
3166 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003167
Tim Peters37f39822003-01-10 03:49:02 +00003168 /* Copy over just the time bytes. */
3169 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3170 self->data,
3171 _PyDateTime_TIME_DATASIZE);
3172
3173 isoformat_time(pdatetime, buf, sizeof(buf));
3174 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003175 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003176 return result;
3177
3178 /* We need to append the UTC offset. */
3179 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003180 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003181 Py_DECREF(result);
3182 return NULL;
3183 }
3184 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3185 return result;
3186}
3187
Tim Peters37f39822003-01-10 03:49:02 +00003188static PyObject *
3189time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3190{
3191 PyObject *result;
3192 PyObject *format;
3193 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003194 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003195
Guido van Rossumbce56a62007-05-10 18:04:33 +00003196 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3197 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003198 return NULL;
3199
3200 /* Python's strftime does insane things with the year part of the
3201 * timetuple. The year is forced to (the otherwise nonsensical)
3202 * 1900 to worm around that.
3203 */
3204 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003205 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003206 TIME_GET_HOUR(self),
3207 TIME_GET_MINUTE(self),
3208 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003209 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003210 if (tuple == NULL)
3211 return NULL;
3212 assert(PyTuple_Size(tuple) == 9);
3213 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3214 Py_DECREF(tuple);
3215 return result;
3216}
Tim Peters2a799bf2002-12-16 20:18:38 +00003217
3218/*
3219 * Miscellaneous methods.
3220 */
3221
Tim Peters37f39822003-01-10 03:49:02 +00003222static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003223time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003224{
3225 int diff;
3226 naivety n1, n2;
3227 int offset1, offset2;
3228
3229 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003230 Py_INCREF(Py_NotImplemented);
3231 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003232 }
Guido van Rossum19960592006-08-24 17:29:38 +00003233 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3234 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003235 return NULL;
3236 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3237 /* If they're both naive, or both aware and have the same offsets,
3238 * we get off cheap. Note that if they're both naive, offset1 ==
3239 * offset2 == 0 at this point.
3240 */
3241 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003242 diff = memcmp(((PyDateTime_Time *)self)->data,
3243 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003244 _PyDateTime_TIME_DATASIZE);
3245 return diff_to_bool(diff, op);
3246 }
3247
3248 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3249 assert(offset1 != offset2); /* else last "if" handled it */
3250 /* Convert everything except microseconds to seconds. These
3251 * can't overflow (no more than the # of seconds in 2 days).
3252 */
3253 offset1 = TIME_GET_HOUR(self) * 3600 +
3254 (TIME_GET_MINUTE(self) - offset1) * 60 +
3255 TIME_GET_SECOND(self);
3256 offset2 = TIME_GET_HOUR(other) * 3600 +
3257 (TIME_GET_MINUTE(other) - offset2) * 60 +
3258 TIME_GET_SECOND(other);
3259 diff = offset1 - offset2;
3260 if (diff == 0)
3261 diff = TIME_GET_MICROSECOND(self) -
3262 TIME_GET_MICROSECOND(other);
3263 return diff_to_bool(diff, op);
3264 }
3265
3266 assert(n1 != n2);
3267 PyErr_SetString(PyExc_TypeError,
3268 "can't compare offset-naive and "
3269 "offset-aware times");
3270 return NULL;
3271}
3272
3273static long
3274time_hash(PyDateTime_Time *self)
3275{
3276 if (self->hashcode == -1) {
3277 naivety n;
3278 int offset;
3279 PyObject *temp;
3280
3281 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3282 assert(n != OFFSET_UNKNOWN);
3283 if (n == OFFSET_ERROR)
3284 return -1;
3285
3286 /* Reduce this to a hash of another object. */
3287 if (offset == 0)
3288 temp = PyString_FromStringAndSize((char *)self->data,
3289 _PyDateTime_TIME_DATASIZE);
3290 else {
3291 int hour;
3292 int minute;
3293
3294 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003295 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003296 hour = divmod(TIME_GET_HOUR(self) * 60 +
3297 TIME_GET_MINUTE(self) - offset,
3298 60,
3299 &minute);
3300 if (0 <= hour && hour < 24)
3301 temp = new_time(hour, minute,
3302 TIME_GET_SECOND(self),
3303 TIME_GET_MICROSECOND(self),
3304 Py_None);
3305 else
3306 temp = Py_BuildValue("iiii",
3307 hour, minute,
3308 TIME_GET_SECOND(self),
3309 TIME_GET_MICROSECOND(self));
3310 }
3311 if (temp != NULL) {
3312 self->hashcode = PyObject_Hash(temp);
3313 Py_DECREF(temp);
3314 }
3315 }
3316 return self->hashcode;
3317}
Tim Peters2a799bf2002-12-16 20:18:38 +00003318
Tim Peters12bf3392002-12-24 05:41:27 +00003319static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003320time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003321{
3322 PyObject *clone;
3323 PyObject *tuple;
3324 int hh = TIME_GET_HOUR(self);
3325 int mm = TIME_GET_MINUTE(self);
3326 int ss = TIME_GET_SECOND(self);
3327 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003328 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003329
3330 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003331 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003332 &hh, &mm, &ss, &us, &tzinfo))
3333 return NULL;
3334 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3335 if (tuple == NULL)
3336 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003337 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003338 Py_DECREF(tuple);
3339 return clone;
3340}
3341
Tim Peters2a799bf2002-12-16 20:18:38 +00003342static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003343time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003344{
3345 int offset;
3346 int none;
3347
3348 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3349 /* Since utcoffset is in whole minutes, nothing can
3350 * alter the conclusion that this is nonzero.
3351 */
3352 return 1;
3353 }
3354 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003355 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003356 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003357 if (offset == -1 && PyErr_Occurred())
3358 return -1;
3359 }
3360 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3361}
3362
Tim Peters371935f2003-02-01 01:52:50 +00003363/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003364
Tim Peters33e0f382003-01-10 02:05:14 +00003365/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003366 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3367 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003368 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003369 */
3370static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003371time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003372{
3373 PyObject *basestate;
3374 PyObject *result = NULL;
3375
Tim Peters33e0f382003-01-10 02:05:14 +00003376 basestate = PyString_FromStringAndSize((char *)self->data,
3377 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003378 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003379 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003380 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003381 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003382 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003383 Py_DECREF(basestate);
3384 }
3385 return result;
3386}
3387
3388static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003389time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003390{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003391 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003392}
3393
Tim Peters37f39822003-01-10 03:49:02 +00003394static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003395
Thomas Wouterscf297e42007-02-23 15:07:44 +00003396 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003397 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3398 "[+HH:MM].")},
3399
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003400 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003401 PyDoc_STR("format -> strftime() style string.")},
3402
3403 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003404 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3405
Tim Peters37f39822003-01-10 03:49:02 +00003406 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003407 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3408
Tim Peters37f39822003-01-10 03:49:02 +00003409 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003410 PyDoc_STR("Return self.tzinfo.dst(self).")},
3411
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003412 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003413 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003414
Guido van Rossum177e41a2003-01-30 22:06:23 +00003415 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3416 PyDoc_STR("__reduce__() -> (cls, state)")},
3417
Tim Peters2a799bf2002-12-16 20:18:38 +00003418 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003419};
3420
Tim Peters37f39822003-01-10 03:49:02 +00003421static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003422PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3423\n\
3424All arguments are optional. tzinfo may be None, or an instance of\n\
3425a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003426
Tim Peters37f39822003-01-10 03:49:02 +00003427static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 0, /* nb_add */
3429 0, /* nb_subtract */
3430 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003431 0, /* nb_remainder */
3432 0, /* nb_divmod */
3433 0, /* nb_power */
3434 0, /* nb_negative */
3435 0, /* nb_positive */
3436 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003437 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003438};
3439
Neal Norwitz227b5332006-03-22 09:28:35 +00003440static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003441 PyObject_HEAD_INIT(NULL)
3442 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003443 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003444 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003445 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003446 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003447 0, /* tp_print */
3448 0, /* tp_getattr */
3449 0, /* tp_setattr */
3450 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003451 (reprfunc)time_repr, /* tp_repr */
3452 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003453 0, /* tp_as_sequence */
3454 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003455 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003456 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003457 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003458 PyObject_GenericGetAttr, /* tp_getattro */
3459 0, /* tp_setattro */
3460 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003461 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003462 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003463 0, /* tp_traverse */
3464 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003465 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003466 0, /* tp_weaklistoffset */
3467 0, /* tp_iter */
3468 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003469 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003470 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003471 time_getset, /* tp_getset */
3472 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003473 0, /* tp_dict */
3474 0, /* tp_descr_get */
3475 0, /* tp_descr_set */
3476 0, /* tp_dictoffset */
3477 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003478 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003479 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003480 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003481};
3482
3483/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003484 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003485 */
3486
Tim Petersa9bc1682003-01-11 03:39:11 +00003487/* Accessor properties. Properties for day, month, and year are inherited
3488 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003489 */
3490
3491static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003492datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003493{
Tim Petersa9bc1682003-01-11 03:39:11 +00003494 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003495}
3496
Tim Petersa9bc1682003-01-11 03:39:11 +00003497static PyObject *
3498datetime_minute(PyDateTime_DateTime *self, void *unused)
3499{
3500 return PyInt_FromLong(DATE_GET_MINUTE(self));
3501}
3502
3503static PyObject *
3504datetime_second(PyDateTime_DateTime *self, void *unused)
3505{
3506 return PyInt_FromLong(DATE_GET_SECOND(self));
3507}
3508
3509static PyObject *
3510datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3511{
3512 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3513}
3514
3515static PyObject *
3516datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3517{
3518 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3519 Py_INCREF(result);
3520 return result;
3521}
3522
3523static PyGetSetDef datetime_getset[] = {
3524 {"hour", (getter)datetime_hour},
3525 {"minute", (getter)datetime_minute},
3526 {"second", (getter)datetime_second},
3527 {"microsecond", (getter)datetime_microsecond},
3528 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003529 {NULL}
3530};
3531
3532/*
3533 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003534 */
3535
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003536static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003537 "year", "month", "day", "hour", "minute", "second",
3538 "microsecond", "tzinfo", NULL
3539};
3540
Tim Peters2a799bf2002-12-16 20:18:38 +00003541static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003542datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003543{
3544 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003545 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003546 int year;
3547 int month;
3548 int day;
3549 int hour = 0;
3550 int minute = 0;
3551 int second = 0;
3552 int usecond = 0;
3553 PyObject *tzinfo = Py_None;
3554
Guido van Rossum177e41a2003-01-30 22:06:23 +00003555 /* Check for invocation from pickle with __getstate__ state */
3556 if (PyTuple_GET_SIZE(args) >= 1 &&
3557 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003558 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003559 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3560 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003561 {
Tim Peters70533e22003-02-01 04:40:04 +00003562 PyDateTime_DateTime *me;
3563 char aware;
3564
3565 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003566 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003567 if (check_tzinfo_subclass(tzinfo) < 0) {
3568 PyErr_SetString(PyExc_TypeError, "bad "
3569 "tzinfo state arg");
3570 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003571 }
3572 }
Tim Peters70533e22003-02-01 04:40:04 +00003573 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003574 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003575 if (me != NULL) {
3576 char *pdata = PyString_AS_STRING(state);
3577
3578 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3579 me->hashcode = -1;
3580 me->hastzinfo = aware;
3581 if (aware) {
3582 Py_INCREF(tzinfo);
3583 me->tzinfo = tzinfo;
3584 }
3585 }
3586 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003587 }
3588
Tim Petersa9bc1682003-01-11 03:39:11 +00003589 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003590 &year, &month, &day, &hour, &minute,
3591 &second, &usecond, &tzinfo)) {
3592 if (check_date_args(year, month, day) < 0)
3593 return NULL;
3594 if (check_time_args(hour, minute, second, usecond) < 0)
3595 return NULL;
3596 if (check_tzinfo_subclass(tzinfo) < 0)
3597 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003598 self = new_datetime_ex(year, month, day,
3599 hour, minute, second, usecond,
3600 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003601 }
3602 return self;
3603}
3604
Tim Petersa9bc1682003-01-11 03:39:11 +00003605/* TM_FUNC is the shared type of localtime() and gmtime(). */
3606typedef struct tm *(*TM_FUNC)(const time_t *timer);
3607
3608/* Internal helper.
3609 * Build datetime from a time_t and a distinct count of microseconds.
3610 * Pass localtime or gmtime for f, to control the interpretation of timet.
3611 */
3612static PyObject *
3613datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3614 PyObject *tzinfo)
3615{
3616 struct tm *tm;
3617 PyObject *result = NULL;
3618
3619 tm = f(&timet);
3620 if (tm) {
3621 /* The platform localtime/gmtime may insert leap seconds,
3622 * indicated by tm->tm_sec > 59. We don't care about them,
3623 * except to the extent that passing them on to the datetime
3624 * constructor would raise ValueError for a reason that
3625 * made no sense to the user.
3626 */
3627 if (tm->tm_sec > 59)
3628 tm->tm_sec = 59;
3629 result = PyObject_CallFunction(cls, "iiiiiiiO",
3630 tm->tm_year + 1900,
3631 tm->tm_mon + 1,
3632 tm->tm_mday,
3633 tm->tm_hour,
3634 tm->tm_min,
3635 tm->tm_sec,
3636 us,
3637 tzinfo);
3638 }
3639 else
3640 PyErr_SetString(PyExc_ValueError,
3641 "timestamp out of range for "
3642 "platform localtime()/gmtime() function");
3643 return result;
3644}
3645
3646/* Internal helper.
3647 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3648 * to control the interpretation of the timestamp. Since a double doesn't
3649 * have enough bits to cover a datetime's full range of precision, it's
3650 * better to call datetime_from_timet_and_us provided you have a way
3651 * to get that much precision (e.g., C time() isn't good enough).
3652 */
3653static PyObject *
3654datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3655 PyObject *tzinfo)
3656{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003657 time_t timet;
3658 double fraction;
3659 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003660
Tim Peters1b6f7a92004-06-20 02:50:16 +00003661 timet = _PyTime_DoubleToTimet(timestamp);
3662 if (timet == (time_t)-1 && PyErr_Occurred())
3663 return NULL;
3664 fraction = timestamp - (double)timet;
3665 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003666 if (us < 0) {
3667 /* Truncation towards zero is not what we wanted
3668 for negative numbers (Python's mod semantics) */
3669 timet -= 1;
3670 us += 1000000;
3671 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003672 /* If timestamp is less than one microsecond smaller than a
3673 * full second, round up. Otherwise, ValueErrors are raised
3674 * for some floats. */
3675 if (us == 1000000) {
3676 timet += 1;
3677 us = 0;
3678 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003679 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3680}
3681
3682/* Internal helper.
3683 * Build most accurate possible datetime for current time. Pass localtime or
3684 * gmtime for f as appropriate.
3685 */
3686static PyObject *
3687datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3688{
3689#ifdef HAVE_GETTIMEOFDAY
3690 struct timeval t;
3691
3692#ifdef GETTIMEOFDAY_NO_TZ
3693 gettimeofday(&t);
3694#else
3695 gettimeofday(&t, (struct timezone *)NULL);
3696#endif
3697 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3698 tzinfo);
3699
3700#else /* ! HAVE_GETTIMEOFDAY */
3701 /* No flavor of gettimeofday exists on this platform. Python's
3702 * time.time() does a lot of other platform tricks to get the
3703 * best time it can on the platform, and we're not going to do
3704 * better than that (if we could, the better code would belong
3705 * in time.time()!) We're limited by the precision of a double,
3706 * though.
3707 */
3708 PyObject *time;
3709 double dtime;
3710
3711 time = time_time();
3712 if (time == NULL)
3713 return NULL;
3714 dtime = PyFloat_AsDouble(time);
3715 Py_DECREF(time);
3716 if (dtime == -1.0 && PyErr_Occurred())
3717 return NULL;
3718 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3719#endif /* ! HAVE_GETTIMEOFDAY */
3720}
3721
Tim Peters2a799bf2002-12-16 20:18:38 +00003722/* Return best possible local time -- this isn't constrained by the
3723 * precision of a timestamp.
3724 */
3725static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003726datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003727{
Tim Peters10cadce2003-01-23 19:58:02 +00003728 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003729 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003730 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003731
Tim Peters10cadce2003-01-23 19:58:02 +00003732 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3733 &tzinfo))
3734 return NULL;
3735 if (check_tzinfo_subclass(tzinfo) < 0)
3736 return NULL;
3737
3738 self = datetime_best_possible(cls,
3739 tzinfo == Py_None ? localtime : gmtime,
3740 tzinfo);
3741 if (self != NULL && tzinfo != Py_None) {
3742 /* Convert UTC to tzinfo's zone. */
3743 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003744 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003745 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003746 }
3747 return self;
3748}
3749
Tim Petersa9bc1682003-01-11 03:39:11 +00003750/* Return best possible UTC time -- this isn't constrained by the
3751 * precision of a timestamp.
3752 */
3753static PyObject *
3754datetime_utcnow(PyObject *cls, PyObject *dummy)
3755{
3756 return datetime_best_possible(cls, gmtime, Py_None);
3757}
3758
Tim Peters2a799bf2002-12-16 20:18:38 +00003759/* Return new local datetime from timestamp (Python timestamp -- a double). */
3760static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003761datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003762{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003763 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003764 double timestamp;
3765 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003766 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003767
Tim Peters2a44a8d2003-01-23 20:53:10 +00003768 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3769 keywords, &timestamp, &tzinfo))
3770 return NULL;
3771 if (check_tzinfo_subclass(tzinfo) < 0)
3772 return NULL;
3773
3774 self = datetime_from_timestamp(cls,
3775 tzinfo == Py_None ? localtime : gmtime,
3776 timestamp,
3777 tzinfo);
3778 if (self != NULL && tzinfo != Py_None) {
3779 /* Convert UTC to tzinfo's zone. */
3780 PyObject *temp = self;
3781 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3782 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003783 }
3784 return self;
3785}
3786
Tim Petersa9bc1682003-01-11 03:39:11 +00003787/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3788static PyObject *
3789datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3790{
3791 double timestamp;
3792 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003793
Tim Petersa9bc1682003-01-11 03:39:11 +00003794 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3795 result = datetime_from_timestamp(cls, gmtime, timestamp,
3796 Py_None);
3797 return result;
3798}
3799
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003800/* Return new datetime from time.strptime(). */
3801static PyObject *
3802datetime_strptime(PyObject *cls, PyObject *args)
3803{
3804 PyObject *result = NULL, *obj, *module;
3805 const char *string, *format;
3806
3807 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3808 return NULL;
3809
3810 if ((module = PyImport_ImportModule("time")) == NULL)
3811 return NULL;
3812 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3813 Py_DECREF(module);
3814
3815 if (obj != NULL) {
3816 int i, good_timetuple = 1;
3817 long int ia[6];
3818 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3819 for (i=0; i < 6; i++) {
3820 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003821 if (p == NULL) {
3822 Py_DECREF(obj);
3823 return NULL;
3824 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003825 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003826 ia[i] = PyInt_AsLong(p);
3827 else
3828 good_timetuple = 0;
3829 Py_DECREF(p);
3830 }
3831 else
3832 good_timetuple = 0;
3833 if (good_timetuple)
3834 result = PyObject_CallFunction(cls, "iiiiii",
3835 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3836 else
3837 PyErr_SetString(PyExc_ValueError,
3838 "unexpected value from time.strptime");
3839 Py_DECREF(obj);
3840 }
3841 return result;
3842}
3843
Tim Petersa9bc1682003-01-11 03:39:11 +00003844/* Return new datetime from date/datetime and time arguments. */
3845static PyObject *
3846datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3847{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003848 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003849 PyObject *date;
3850 PyObject *time;
3851 PyObject *result = NULL;
3852
3853 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3854 &PyDateTime_DateType, &date,
3855 &PyDateTime_TimeType, &time)) {
3856 PyObject *tzinfo = Py_None;
3857
3858 if (HASTZINFO(time))
3859 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3860 result = PyObject_CallFunction(cls, "iiiiiiiO",
3861 GET_YEAR(date),
3862 GET_MONTH(date),
3863 GET_DAY(date),
3864 TIME_GET_HOUR(time),
3865 TIME_GET_MINUTE(time),
3866 TIME_GET_SECOND(time),
3867 TIME_GET_MICROSECOND(time),
3868 tzinfo);
3869 }
3870 return result;
3871}
Tim Peters2a799bf2002-12-16 20:18:38 +00003872
3873/*
3874 * Destructor.
3875 */
3876
3877static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003878datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003879{
Tim Petersa9bc1682003-01-11 03:39:11 +00003880 if (HASTZINFO(self)) {
3881 Py_XDECREF(self->tzinfo);
3882 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003883 self->ob_type->tp_free((PyObject *)self);
3884}
3885
3886/*
3887 * Indirect access to tzinfo methods.
3888 */
3889
Tim Peters2a799bf2002-12-16 20:18:38 +00003890/* These are all METH_NOARGS, so don't need to check the arglist. */
3891static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003892datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3893 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3894 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003895}
3896
3897static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003898datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3899 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3900 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003901}
3902
3903static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003904datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3905 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3906 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003907}
3908
3909/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003910 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003911 */
3912
Tim Petersa9bc1682003-01-11 03:39:11 +00003913/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3914 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003915 */
3916static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003917add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3918 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003919{
Tim Petersa9bc1682003-01-11 03:39:11 +00003920 /* Note that the C-level additions can't overflow, because of
3921 * invariant bounds on the member values.
3922 */
3923 int year = GET_YEAR(date);
3924 int month = GET_MONTH(date);
3925 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3926 int hour = DATE_GET_HOUR(date);
3927 int minute = DATE_GET_MINUTE(date);
3928 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3929 int microsecond = DATE_GET_MICROSECOND(date) +
3930 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003931
Tim Petersa9bc1682003-01-11 03:39:11 +00003932 assert(factor == 1 || factor == -1);
3933 if (normalize_datetime(&year, &month, &day,
3934 &hour, &minute, &second, &microsecond) < 0)
3935 return NULL;
3936 else
3937 return new_datetime(year, month, day,
3938 hour, minute, second, microsecond,
3939 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003940}
3941
3942static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003943datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003944{
Tim Petersa9bc1682003-01-11 03:39:11 +00003945 if (PyDateTime_Check(left)) {
3946 /* datetime + ??? */
3947 if (PyDelta_Check(right))
3948 /* datetime + delta */
3949 return add_datetime_timedelta(
3950 (PyDateTime_DateTime *)left,
3951 (PyDateTime_Delta *)right,
3952 1);
3953 }
3954 else if (PyDelta_Check(left)) {
3955 /* delta + datetime */
3956 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3957 (PyDateTime_Delta *) left,
3958 1);
3959 }
3960 Py_INCREF(Py_NotImplemented);
3961 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003962}
3963
3964static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003965datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003966{
3967 PyObject *result = Py_NotImplemented;
3968
3969 if (PyDateTime_Check(left)) {
3970 /* datetime - ??? */
3971 if (PyDateTime_Check(right)) {
3972 /* datetime - datetime */
3973 naivety n1, n2;
3974 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003975 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003976
Tim Peterse39a80c2002-12-30 21:28:52 +00003977 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3978 right, &offset2, &n2,
3979 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003980 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003981 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003982 if (n1 != n2) {
3983 PyErr_SetString(PyExc_TypeError,
3984 "can't subtract offset-naive and "
3985 "offset-aware datetimes");
3986 return NULL;
3987 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003988 delta_d = ymd_to_ord(GET_YEAR(left),
3989 GET_MONTH(left),
3990 GET_DAY(left)) -
3991 ymd_to_ord(GET_YEAR(right),
3992 GET_MONTH(right),
3993 GET_DAY(right));
3994 /* These can't overflow, since the values are
3995 * normalized. At most this gives the number of
3996 * seconds in one day.
3997 */
3998 delta_s = (DATE_GET_HOUR(left) -
3999 DATE_GET_HOUR(right)) * 3600 +
4000 (DATE_GET_MINUTE(left) -
4001 DATE_GET_MINUTE(right)) * 60 +
4002 (DATE_GET_SECOND(left) -
4003 DATE_GET_SECOND(right));
4004 delta_us = DATE_GET_MICROSECOND(left) -
4005 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004006 /* (left - offset1) - (right - offset2) =
4007 * (left - right) + (offset2 - offset1)
4008 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004009 delta_s += (offset2 - offset1) * 60;
4010 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004011 }
4012 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004013 /* datetime - delta */
4014 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004015 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004016 (PyDateTime_Delta *)right,
4017 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004018 }
4019 }
4020
4021 if (result == Py_NotImplemented)
4022 Py_INCREF(result);
4023 return result;
4024}
4025
4026/* Various ways to turn a datetime into a string. */
4027
4028static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004029datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004030{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004031 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004032 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004033
Tim Petersa9bc1682003-01-11 03:39:11 +00004034 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004035 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004036 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004037 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004038 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4039 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4040 DATE_GET_SECOND(self),
4041 DATE_GET_MICROSECOND(self));
4042 }
4043 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004044 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004045 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004046 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004047 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4048 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4049 DATE_GET_SECOND(self));
4050 }
4051 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004052 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004053 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004054 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004055 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4056 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4057 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004058 if (baserepr == NULL || ! HASTZINFO(self))
4059 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004060 return append_keyword_tzinfo(baserepr, self->tzinfo);
4061}
4062
Tim Petersa9bc1682003-01-11 03:39:11 +00004063static PyObject *
4064datetime_str(PyDateTime_DateTime *self)
4065{
4066 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4067}
Tim Peters2a799bf2002-12-16 20:18:38 +00004068
4069static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004070datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004071{
Tim Petersa9bc1682003-01-11 03:39:11 +00004072 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004073 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004074 char buffer[100];
4075 char *cp;
4076 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004077
Tim Petersa9bc1682003-01-11 03:39:11 +00004078 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4079 &sep))
4080 return NULL;
4081 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4082 assert(cp != NULL);
4083 *cp++ = sep;
4084 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4085 result = PyString_FromString(buffer);
4086 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004087 return result;
4088
4089 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004090 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004091 (PyObject *)self) < 0) {
4092 Py_DECREF(result);
4093 return NULL;
4094 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004095 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004096 return result;
4097}
4098
Tim Petersa9bc1682003-01-11 03:39:11 +00004099static PyObject *
4100datetime_ctime(PyDateTime_DateTime *self)
4101{
4102 return format_ctime((PyDateTime_Date *)self,
4103 DATE_GET_HOUR(self),
4104 DATE_GET_MINUTE(self),
4105 DATE_GET_SECOND(self));
4106}
4107
Tim Peters2a799bf2002-12-16 20:18:38 +00004108/* Miscellaneous methods. */
4109
Tim Petersa9bc1682003-01-11 03:39:11 +00004110static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004111datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004112{
4113 int diff;
4114 naivety n1, n2;
4115 int offset1, offset2;
4116
4117 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004118 if (PyDate_Check(other)) {
4119 /* Prevent invocation of date_richcompare. We want to
4120 return NotImplemented here to give the other object
4121 a chance. But since DateTime is a subclass of
4122 Date, if the other object is a Date, it would
4123 compute an ordering based on the date part alone,
4124 and we don't want that. So force unequal or
4125 uncomparable here in that case. */
4126 if (op == Py_EQ)
4127 Py_RETURN_FALSE;
4128 if (op == Py_NE)
4129 Py_RETURN_TRUE;
4130 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004131 }
Guido van Rossum19960592006-08-24 17:29:38 +00004132 Py_INCREF(Py_NotImplemented);
4133 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004134 }
4135
Guido van Rossum19960592006-08-24 17:29:38 +00004136 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4137 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004138 return NULL;
4139 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4140 /* If they're both naive, or both aware and have the same offsets,
4141 * we get off cheap. Note that if they're both naive, offset1 ==
4142 * offset2 == 0 at this point.
4143 */
4144 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004145 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4146 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004147 _PyDateTime_DATETIME_DATASIZE);
4148 return diff_to_bool(diff, op);
4149 }
4150
4151 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4152 PyDateTime_Delta *delta;
4153
4154 assert(offset1 != offset2); /* else last "if" handled it */
4155 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4156 other);
4157 if (delta == NULL)
4158 return NULL;
4159 diff = GET_TD_DAYS(delta);
4160 if (diff == 0)
4161 diff = GET_TD_SECONDS(delta) |
4162 GET_TD_MICROSECONDS(delta);
4163 Py_DECREF(delta);
4164 return diff_to_bool(diff, op);
4165 }
4166
4167 assert(n1 != n2);
4168 PyErr_SetString(PyExc_TypeError,
4169 "can't compare offset-naive and "
4170 "offset-aware datetimes");
4171 return NULL;
4172}
4173
4174static long
4175datetime_hash(PyDateTime_DateTime *self)
4176{
4177 if (self->hashcode == -1) {
4178 naivety n;
4179 int offset;
4180 PyObject *temp;
4181
4182 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4183 &offset);
4184 assert(n != OFFSET_UNKNOWN);
4185 if (n == OFFSET_ERROR)
4186 return -1;
4187
4188 /* Reduce this to a hash of another object. */
4189 if (n == OFFSET_NAIVE)
4190 temp = PyString_FromStringAndSize(
4191 (char *)self->data,
4192 _PyDateTime_DATETIME_DATASIZE);
4193 else {
4194 int days;
4195 int seconds;
4196
4197 assert(n == OFFSET_AWARE);
4198 assert(HASTZINFO(self));
4199 days = ymd_to_ord(GET_YEAR(self),
4200 GET_MONTH(self),
4201 GET_DAY(self));
4202 seconds = DATE_GET_HOUR(self) * 3600 +
4203 (DATE_GET_MINUTE(self) - offset) * 60 +
4204 DATE_GET_SECOND(self);
4205 temp = new_delta(days,
4206 seconds,
4207 DATE_GET_MICROSECOND(self),
4208 1);
4209 }
4210 if (temp != NULL) {
4211 self->hashcode = PyObject_Hash(temp);
4212 Py_DECREF(temp);
4213 }
4214 }
4215 return self->hashcode;
4216}
Tim Peters2a799bf2002-12-16 20:18:38 +00004217
4218static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004219datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004220{
4221 PyObject *clone;
4222 PyObject *tuple;
4223 int y = GET_YEAR(self);
4224 int m = GET_MONTH(self);
4225 int d = GET_DAY(self);
4226 int hh = DATE_GET_HOUR(self);
4227 int mm = DATE_GET_MINUTE(self);
4228 int ss = DATE_GET_SECOND(self);
4229 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004230 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004231
4232 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004233 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004234 &y, &m, &d, &hh, &mm, &ss, &us,
4235 &tzinfo))
4236 return NULL;
4237 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4238 if (tuple == NULL)
4239 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004240 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004241 Py_DECREF(tuple);
4242 return clone;
4243}
4244
4245static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004246datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004247{
Tim Peters52dcce22003-01-23 16:36:11 +00004248 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004249 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004250 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004251
Tim Peters80475bb2002-12-25 07:40:55 +00004252 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004253 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004254
Tim Peters52dcce22003-01-23 16:36:11 +00004255 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4256 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004257 return NULL;
4258
Tim Peters52dcce22003-01-23 16:36:11 +00004259 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4260 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004261
Tim Peters52dcce22003-01-23 16:36:11 +00004262 /* Conversion to self's own time zone is a NOP. */
4263 if (self->tzinfo == tzinfo) {
4264 Py_INCREF(self);
4265 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004266 }
Tim Peters521fc152002-12-31 17:36:56 +00004267
Tim Peters52dcce22003-01-23 16:36:11 +00004268 /* Convert self to UTC. */
4269 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4270 if (offset == -1 && PyErr_Occurred())
4271 return NULL;
4272 if (none)
4273 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004274
Tim Peters52dcce22003-01-23 16:36:11 +00004275 y = GET_YEAR(self);
4276 m = GET_MONTH(self);
4277 d = GET_DAY(self);
4278 hh = DATE_GET_HOUR(self);
4279 mm = DATE_GET_MINUTE(self);
4280 ss = DATE_GET_SECOND(self);
4281 us = DATE_GET_MICROSECOND(self);
4282
4283 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004284 if ((mm < 0 || mm >= 60) &&
4285 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004286 return NULL;
4287
4288 /* Attach new tzinfo and let fromutc() do the rest. */
4289 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4290 if (result != NULL) {
4291 PyObject *temp = result;
4292
4293 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4294 Py_DECREF(temp);
4295 }
Tim Petersadf64202003-01-04 06:03:15 +00004296 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004297
Tim Peters52dcce22003-01-23 16:36:11 +00004298NeedAware:
4299 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4300 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004301 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004302}
4303
4304static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004305datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004306{
4307 int dstflag = -1;
4308
Tim Petersa9bc1682003-01-11 03:39:11 +00004309 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004310 int none;
4311
4312 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4313 if (dstflag == -1 && PyErr_Occurred())
4314 return NULL;
4315
4316 if (none)
4317 dstflag = -1;
4318 else if (dstflag != 0)
4319 dstflag = 1;
4320
4321 }
4322 return build_struct_time(GET_YEAR(self),
4323 GET_MONTH(self),
4324 GET_DAY(self),
4325 DATE_GET_HOUR(self),
4326 DATE_GET_MINUTE(self),
4327 DATE_GET_SECOND(self),
4328 dstflag);
4329}
4330
4331static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004332datetime_getdate(PyDateTime_DateTime *self)
4333{
4334 return new_date(GET_YEAR(self),
4335 GET_MONTH(self),
4336 GET_DAY(self));
4337}
4338
4339static PyObject *
4340datetime_gettime(PyDateTime_DateTime *self)
4341{
4342 return new_time(DATE_GET_HOUR(self),
4343 DATE_GET_MINUTE(self),
4344 DATE_GET_SECOND(self),
4345 DATE_GET_MICROSECOND(self),
4346 Py_None);
4347}
4348
4349static PyObject *
4350datetime_gettimetz(PyDateTime_DateTime *self)
4351{
4352 return new_time(DATE_GET_HOUR(self),
4353 DATE_GET_MINUTE(self),
4354 DATE_GET_SECOND(self),
4355 DATE_GET_MICROSECOND(self),
4356 HASTZINFO(self) ? self->tzinfo : Py_None);
4357}
4358
4359static PyObject *
4360datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004361{
4362 int y = GET_YEAR(self);
4363 int m = GET_MONTH(self);
4364 int d = GET_DAY(self);
4365 int hh = DATE_GET_HOUR(self);
4366 int mm = DATE_GET_MINUTE(self);
4367 int ss = DATE_GET_SECOND(self);
4368 int us = 0; /* microseconds are ignored in a timetuple */
4369 int offset = 0;
4370
Tim Petersa9bc1682003-01-11 03:39:11 +00004371 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004372 int none;
4373
4374 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4375 if (offset == -1 && PyErr_Occurred())
4376 return NULL;
4377 }
4378 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4379 * 0 in a UTC timetuple regardless of what dst() says.
4380 */
4381 if (offset) {
4382 /* Subtract offset minutes & normalize. */
4383 int stat;
4384
4385 mm -= offset;
4386 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4387 if (stat < 0) {
4388 /* At the edges, it's possible we overflowed
4389 * beyond MINYEAR or MAXYEAR.
4390 */
4391 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4392 PyErr_Clear();
4393 else
4394 return NULL;
4395 }
4396 }
4397 return build_struct_time(y, m, d, hh, mm, ss, 0);
4398}
4399
Tim Peters371935f2003-02-01 01:52:50 +00004400/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004401
Tim Petersa9bc1682003-01-11 03:39:11 +00004402/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004403 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4404 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004405 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004406 */
4407static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004408datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004409{
4410 PyObject *basestate;
4411 PyObject *result = NULL;
4412
Tim Peters33e0f382003-01-10 02:05:14 +00004413 basestate = PyString_FromStringAndSize((char *)self->data,
4414 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004415 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004416 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004417 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004418 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004419 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004420 Py_DECREF(basestate);
4421 }
4422 return result;
4423}
4424
4425static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004426datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004427{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004428 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004429}
4430
Tim Petersa9bc1682003-01-11 03:39:11 +00004431static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004432
Tim Peters2a799bf2002-12-16 20:18:38 +00004433 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004434
Tim Petersa9bc1682003-01-11 03:39:11 +00004435 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004436 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004437 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004438
Tim Petersa9bc1682003-01-11 03:39:11 +00004439 {"utcnow", (PyCFunction)datetime_utcnow,
4440 METH_NOARGS | METH_CLASS,
4441 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4442
4443 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004444 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004445 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004446
Tim Petersa9bc1682003-01-11 03:39:11 +00004447 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4448 METH_VARARGS | METH_CLASS,
4449 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4450 "(like time.time()).")},
4451
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004452 {"strptime", (PyCFunction)datetime_strptime,
4453 METH_VARARGS | METH_CLASS,
4454 PyDoc_STR("string, format -> new datetime parsed from a string "
4455 "(like time.strptime()).")},
4456
Tim Petersa9bc1682003-01-11 03:39:11 +00004457 {"combine", (PyCFunction)datetime_combine,
4458 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4459 PyDoc_STR("date, time -> datetime with same date and time fields")},
4460
Tim Peters2a799bf2002-12-16 20:18:38 +00004461 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004462
Tim Petersa9bc1682003-01-11 03:39:11 +00004463 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4464 PyDoc_STR("Return date object with same year, month and day.")},
4465
4466 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4467 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4468
4469 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4470 PyDoc_STR("Return time object with same time and tzinfo.")},
4471
4472 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4473 PyDoc_STR("Return ctime() style string.")},
4474
4475 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004476 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4477
Tim Petersa9bc1682003-01-11 03:39:11 +00004478 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004479 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4480
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004481 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004482 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4483 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4484 "sep is used to separate the year from the time, and "
4485 "defaults to 'T'.")},
4486
Tim Petersa9bc1682003-01-11 03:39:11 +00004487 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004488 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4489
Tim Petersa9bc1682003-01-11 03:39:11 +00004490 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004491 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4492
Tim Petersa9bc1682003-01-11 03:39:11 +00004493 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004494 PyDoc_STR("Return self.tzinfo.dst(self).")},
4495
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004496 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004497 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004498
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004499 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004500 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4501
Guido van Rossum177e41a2003-01-30 22:06:23 +00004502 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4503 PyDoc_STR("__reduce__() -> (cls, state)")},
4504
Tim Peters2a799bf2002-12-16 20:18:38 +00004505 {NULL, NULL}
4506};
4507
Tim Petersa9bc1682003-01-11 03:39:11 +00004508static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004509PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4510\n\
4511The year, month and day arguments are required. tzinfo may be None, or an\n\
4512instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004513
Tim Petersa9bc1682003-01-11 03:39:11 +00004514static PyNumberMethods datetime_as_number = {
4515 datetime_add, /* nb_add */
4516 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004517 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004518 0, /* nb_remainder */
4519 0, /* nb_divmod */
4520 0, /* nb_power */
4521 0, /* nb_negative */
4522 0, /* nb_positive */
4523 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004524 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004525};
4526
Neal Norwitz227b5332006-03-22 09:28:35 +00004527static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004528 PyObject_HEAD_INIT(NULL)
4529 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004530 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004531 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004532 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004533 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004534 0, /* tp_print */
4535 0, /* tp_getattr */
4536 0, /* tp_setattr */
4537 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004538 (reprfunc)datetime_repr, /* tp_repr */
4539 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004540 0, /* tp_as_sequence */
4541 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004542 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004543 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004544 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004545 PyObject_GenericGetAttr, /* tp_getattro */
4546 0, /* tp_setattro */
4547 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004548 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004549 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004550 0, /* tp_traverse */
4551 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004552 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004553 0, /* tp_weaklistoffset */
4554 0, /* tp_iter */
4555 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004556 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004557 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004558 datetime_getset, /* tp_getset */
4559 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004560 0, /* tp_dict */
4561 0, /* tp_descr_get */
4562 0, /* tp_descr_set */
4563 0, /* tp_dictoffset */
4564 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004565 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004566 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004567 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004568};
4569
4570/* ---------------------------------------------------------------------------
4571 * Module methods and initialization.
4572 */
4573
4574static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004575 {NULL, NULL}
4576};
4577
Tim Peters9ddf40b2004-06-20 22:41:32 +00004578/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4579 * datetime.h.
4580 */
4581static PyDateTime_CAPI CAPI = {
4582 &PyDateTime_DateType,
4583 &PyDateTime_DateTimeType,
4584 &PyDateTime_TimeType,
4585 &PyDateTime_DeltaType,
4586 &PyDateTime_TZInfoType,
4587 new_date_ex,
4588 new_datetime_ex,
4589 new_time_ex,
4590 new_delta_ex,
4591 datetime_fromtimestamp,
4592 date_fromtimestamp
4593};
4594
4595
Tim Peters2a799bf2002-12-16 20:18:38 +00004596PyMODINIT_FUNC
4597initdatetime(void)
4598{
4599 PyObject *m; /* a module object */
4600 PyObject *d; /* its dict */
4601 PyObject *x;
4602
Tim Peters2a799bf2002-12-16 20:18:38 +00004603 m = Py_InitModule3("datetime", module_methods,
4604 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004605 if (m == NULL)
4606 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004607
4608 if (PyType_Ready(&PyDateTime_DateType) < 0)
4609 return;
4610 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4611 return;
4612 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4613 return;
4614 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4615 return;
4616 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4617 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004618
Tim Peters2a799bf2002-12-16 20:18:38 +00004619 /* timedelta values */
4620 d = PyDateTime_DeltaType.tp_dict;
4621
Tim Peters2a799bf2002-12-16 20:18:38 +00004622 x = new_delta(0, 0, 1, 0);
4623 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4624 return;
4625 Py_DECREF(x);
4626
4627 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4628 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4629 return;
4630 Py_DECREF(x);
4631
4632 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4633 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4634 return;
4635 Py_DECREF(x);
4636
4637 /* date values */
4638 d = PyDateTime_DateType.tp_dict;
4639
4640 x = new_date(1, 1, 1);
4641 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4642 return;
4643 Py_DECREF(x);
4644
4645 x = new_date(MAXYEAR, 12, 31);
4646 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4647 return;
4648 Py_DECREF(x);
4649
4650 x = new_delta(1, 0, 0, 0);
4651 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4652 return;
4653 Py_DECREF(x);
4654
Tim Peters37f39822003-01-10 03:49:02 +00004655 /* time values */
4656 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004657
Tim Peters37f39822003-01-10 03:49:02 +00004658 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004659 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4660 return;
4661 Py_DECREF(x);
4662
Tim Peters37f39822003-01-10 03:49:02 +00004663 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004664 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4665 return;
4666 Py_DECREF(x);
4667
4668 x = new_delta(0, 0, 1, 0);
4669 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4670 return;
4671 Py_DECREF(x);
4672
Tim Petersa9bc1682003-01-11 03:39:11 +00004673 /* datetime values */
4674 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004675
Tim Petersa9bc1682003-01-11 03:39:11 +00004676 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004677 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4678 return;
4679 Py_DECREF(x);
4680
Tim Petersa9bc1682003-01-11 03:39:11 +00004681 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004682 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4683 return;
4684 Py_DECREF(x);
4685
4686 x = new_delta(0, 0, 1, 0);
4687 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4688 return;
4689 Py_DECREF(x);
4690
Tim Peters2a799bf2002-12-16 20:18:38 +00004691 /* module initialization */
4692 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4693 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4694
4695 Py_INCREF(&PyDateTime_DateType);
4696 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4697
Tim Petersa9bc1682003-01-11 03:39:11 +00004698 Py_INCREF(&PyDateTime_DateTimeType);
4699 PyModule_AddObject(m, "datetime",
4700 (PyObject *)&PyDateTime_DateTimeType);
4701
4702 Py_INCREF(&PyDateTime_TimeType);
4703 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4704
Tim Peters2a799bf2002-12-16 20:18:38 +00004705 Py_INCREF(&PyDateTime_DeltaType);
4706 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4707
Tim Peters2a799bf2002-12-16 20:18:38 +00004708 Py_INCREF(&PyDateTime_TZInfoType);
4709 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4710
Tim Peters9ddf40b2004-06-20 22:41:32 +00004711 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4712 NULL);
4713 if (x == NULL)
4714 return;
4715 PyModule_AddObject(m, "datetime_CAPI", x);
4716
Tim Peters2a799bf2002-12-16 20:18:38 +00004717 /* A 4-year cycle has an extra leap day over what we'd get from
4718 * pasting together 4 single years.
4719 */
4720 assert(DI4Y == 4 * 365 + 1);
4721 assert(DI4Y == days_before_year(4+1));
4722
4723 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4724 * get from pasting together 4 100-year cycles.
4725 */
4726 assert(DI400Y == 4 * DI100Y + 1);
4727 assert(DI400Y == days_before_year(400+1));
4728
4729 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4730 * pasting together 25 4-year cycles.
4731 */
4732 assert(DI100Y == 25 * DI4Y - 1);
4733 assert(DI100Y == days_before_year(100+1));
4734
4735 us_per_us = PyInt_FromLong(1);
4736 us_per_ms = PyInt_FromLong(1000);
4737 us_per_second = PyInt_FromLong(1000000);
4738 us_per_minute = PyInt_FromLong(60000000);
4739 seconds_per_day = PyInt_FromLong(24 * 3600);
4740 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4741 us_per_minute == NULL || seconds_per_day == NULL)
4742 return;
4743
4744 /* The rest are too big for 32-bit ints, but even
4745 * us_per_week fits in 40 bits, so doubles should be exact.
4746 */
4747 us_per_hour = PyLong_FromDouble(3600000000.0);
4748 us_per_day = PyLong_FromDouble(86400000000.0);
4749 us_per_week = PyLong_FromDouble(604800000000.0);
4750 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4751 return;
4752}
Tim Petersf3615152003-01-01 21:51:37 +00004753
4754/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004755Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004756 x.n = x stripped of its timezone -- its naive time.
4757 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4758 return None
4759 x.d = x.dst(), and assuming that doesn't raise an exception or
4760 return None
4761 x.s = x's standard offset, x.o - x.d
4762
4763Now some derived rules, where k is a duration (timedelta).
4764
47651. x.o = x.s + x.d
4766 This follows from the definition of x.s.
4767
Tim Petersc5dc4da2003-01-02 17:55:03 +000047682. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004769 This is actually a requirement, an assumption we need to make about
4770 sane tzinfo classes.
4771
47723. The naive UTC time corresponding to x is x.n - x.o.
4773 This is again a requirement for a sane tzinfo class.
4774
47754. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004776 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004777
Tim Petersc5dc4da2003-01-02 17:55:03 +000047785. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004779 Again follows from how arithmetic is defined.
4780
Tim Peters8bb5ad22003-01-24 02:44:45 +00004781Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004782(meaning that the various tzinfo methods exist, and don't blow up or return
4783None when called).
4784
Tim Petersa9bc1682003-01-11 03:39:11 +00004785The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004786x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004787
4788By #3, we want
4789
Tim Peters8bb5ad22003-01-24 02:44:45 +00004790 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004791
4792The algorithm starts by attaching tz to x.n, and calling that y. So
4793x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4794becomes true; in effect, we want to solve [2] for k:
4795
Tim Peters8bb5ad22003-01-24 02:44:45 +00004796 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004797
4798By #1, this is the same as
4799
Tim Peters8bb5ad22003-01-24 02:44:45 +00004800 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004801
4802By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4803Substituting that into [3],
4804
Tim Peters8bb5ad22003-01-24 02:44:45 +00004805 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4806 k - (y+k).s - (y+k).d = 0; rearranging,
4807 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4808 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004809
Tim Peters8bb5ad22003-01-24 02:44:45 +00004810On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4811approximate k by ignoring the (y+k).d term at first. Note that k can't be
4812very large, since all offset-returning methods return a duration of magnitude
4813less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4814be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004815
4816In any case, the new value is
4817
Tim Peters8bb5ad22003-01-24 02:44:45 +00004818 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004819
Tim Peters8bb5ad22003-01-24 02:44:45 +00004820It's helpful to step back at look at [4] from a higher level: it's simply
4821mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004822
4823At this point, if
4824
Tim Peters8bb5ad22003-01-24 02:44:45 +00004825 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004826
4827we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004828at the start of daylight time. Picture US Eastern for concreteness. The wall
4829time 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 +00004830sense then. The docs ask that an Eastern tzinfo class consider such a time to
4831be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4832on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004833the only spelling that makes sense on the local wall clock.
4834
Tim Petersc5dc4da2003-01-02 17:55:03 +00004835In fact, if [5] holds at this point, we do have the standard-time spelling,
4836but that takes a bit of proof. We first prove a stronger result. What's the
4837difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004838
Tim Peters8bb5ad22003-01-24 02:44:45 +00004839 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004840
Tim Petersc5dc4da2003-01-02 17:55:03 +00004841Now
4842 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004843 (y + y.s).n = by #5
4844 y.n + y.s = since y.n = x.n
4845 x.n + y.s = since z and y are have the same tzinfo member,
4846 y.s = z.s by #2
4847 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004848
Tim Petersc5dc4da2003-01-02 17:55:03 +00004849Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004850
Tim Petersc5dc4da2003-01-02 17:55:03 +00004851 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004852 x.n - ((x.n + z.s) - z.o) = expanding
4853 x.n - x.n - z.s + z.o = cancelling
4854 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004855 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004856
Tim Petersc5dc4da2003-01-02 17:55:03 +00004857So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004858
Tim Petersc5dc4da2003-01-02 17:55:03 +00004859If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004860spelling we wanted in the endcase described above. We're done. Contrarily,
4861if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004862
Tim Petersc5dc4da2003-01-02 17:55:03 +00004863If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4864add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004865local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004866
Tim Petersc5dc4da2003-01-02 17:55:03 +00004867Let
Tim Petersf3615152003-01-01 21:51:37 +00004868
Tim Peters4fede1a2003-01-04 00:26:59 +00004869 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004870
Tim Peters4fede1a2003-01-04 00:26:59 +00004871and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004872
Tim Peters8bb5ad22003-01-24 02:44:45 +00004873 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004874
Tim Peters8bb5ad22003-01-24 02:44:45 +00004875If so, we're done. If not, the tzinfo class is insane, according to the
4876assumptions we've made. This also requires a bit of proof. As before, let's
4877compute the difference between the LHS and RHS of [8] (and skipping some of
4878the justifications for the kinds of substitutions we've done several times
4879already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004880
Tim Peters8bb5ad22003-01-24 02:44:45 +00004881 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4882 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4883 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4884 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4885 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004886 - z.o + z'.o = #1 twice
4887 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4888 z'.d - z.d
4889
4890So 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 +00004891we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4892return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004893
Tim Peters8bb5ad22003-01-24 02:44:45 +00004894How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4895a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4896would have to change the result dst() returns: we start in DST, and moving
4897a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004898
Tim Peters8bb5ad22003-01-24 02:44:45 +00004899There isn't a sane case where this can happen. The closest it gets is at
4900the end of DST, where there's an hour in UTC with no spelling in a hybrid
4901tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4902that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4903UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4904time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4905clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4906standard time. Since that's what the local clock *does*, we want to map both
4907UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004908in local time, but so it goes -- it's the way the local clock works.
4909
Tim Peters8bb5ad22003-01-24 02:44:45 +00004910When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4911so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4912z' = 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 +00004913(correctly) concludes that z' is not UTC-equivalent to x.
4914
4915Because we know z.d said z was in daylight time (else [5] would have held and
4916we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004917and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004918return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4919but the reasoning doesn't depend on the example -- it depends on there being
4920two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004921z' must be in standard time, and is the spelling we want in this case.
4922
4923Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4924concerned (because it takes z' as being in standard time rather than the
4925daylight time we intend here), but returning it gives the real-life "local
4926clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4927tz.
4928
4929When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4930the 1:MM standard time spelling we want.
4931
4932So how can this break? One of the assumptions must be violated. Two
4933possibilities:
4934
49351) [2] effectively says that y.s is invariant across all y belong to a given
4936 time zone. This isn't true if, for political reasons or continental drift,
4937 a region decides to change its base offset from UTC.
4938
49392) There may be versions of "double daylight" time where the tail end of
4940 the analysis gives up a step too early. I haven't thought about that
4941 enough to say.
4942
4943In any case, it's clear that the default fromutc() is strong enough to handle
4944"almost all" time zones: so long as the standard offset is invariant, it
4945doesn't matter if daylight time transition points change from year to year, or
4946if daylight time is skipped in some years; it doesn't matter how large or
4947small dst() may get within its bounds; and it doesn't even matter if some
4948perverse time zone returns a negative dst()). So a breaking case must be
4949pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004950--------------------------------------------------------------------------- */