blob: fb11e35cb6c3d2faefc8c4c50b5d279d84d2183a [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 */
Kristján Valur Jónsson7a0da192007-04-30 15:17:46 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Kristján Valur Jónsson7a0da192007-04-30 15:17:46 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
28# error "datetime.c requires that C int have at least 32 bits"
29#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
33
34/* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
38 */
39#define MAX_DELTA_DAYS 999999999
40
41/* Rename the long macros in datetime.h to more reasonable short names. */
42#define GET_YEAR PyDateTime_GET_YEAR
43#define GET_MONTH PyDateTime_GET_MONTH
44#define GET_DAY PyDateTime_GET_DAY
45#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
49
50/* Date accessors for date and datetime. */
51#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
55
56/* Date/Time accessors for datetime. */
57#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60#define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
64
65/* Time accessors for time. */
66#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73#define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
77
78/* Delta accessors for timedelta. */
79#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
82
83#define SET_TD_DAYS(o, v) ((o)->days = (v))
84#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
85#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
86
Tim Petersa032d2e2003-01-11 00:15:54 +000087/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
89 */
90#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
91
Tim Peters3f606292004-03-21 23:38:41 +000092/* M is a char or int claiming to be a valid month. The macro is equivalent
93 * to the two-sided Python test
94 * 1 <= M <= 12
95 */
96#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
97
Tim Peters2a799bf2002-12-16 20:18:38 +000098/* Forward declarations. */
99static PyTypeObject PyDateTime_DateType;
100static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000101static PyTypeObject PyDateTime_DeltaType;
102static PyTypeObject PyDateTime_TimeType;
103static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000104
105/* ---------------------------------------------------------------------------
106 * Math utilities.
107 */
108
109/* k = i+j overflows iff k differs in sign from both inputs,
110 * iff k^i has sign bit set and k^j has sign bit set,
111 * iff (k^i)&(k^j) has sign bit set.
112 */
113#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
114 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
115
116/* Compute Python divmod(x, y), returning the quotient and storing the
117 * remainder into *r. The quotient is the floor of x/y, and that's
118 * the real point of this. C will probably truncate instead (C99
119 * requires truncation; C89 left it implementation-defined).
120 * Simplification: we *require* that y > 0 here. That's appropriate
121 * for all the uses made of it. This simplifies the code and makes
122 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
123 * overflow case).
124 */
125static int
126divmod(int x, int y, int *r)
127{
128 int quo;
129
130 assert(y > 0);
131 quo = x / y;
132 *r = x - quo * y;
133 if (*r < 0) {
134 --quo;
135 *r += y;
136 }
137 assert(0 <= *r && *r < y);
138 return quo;
139}
140
Tim Peters5d644dd2003-01-02 16:32:54 +0000141/* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
143 */
144static long
145round_to_long(double x)
146{
147 if (x >= 0.0)
148 x = floor(x + 0.5);
149 else
150 x = ceil(x - 0.5);
151 return (long)x;
152}
153
Tim Peters2a799bf2002-12-16 20:18:38 +0000154/* ---------------------------------------------------------------------------
155 * General calendrical helper functions
156 */
157
158/* For each month ordinal in 1..12, the number of days in that month,
159 * and the number of days before that month in the same year. These
160 * are correct for non-leap years only.
161 */
162static int _days_in_month[] = {
163 0, /* unused; this vector uses 1-based indexing */
164 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
165};
166
167static int _days_before_month[] = {
168 0, /* unused; this vector uses 1-based indexing */
169 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
170};
171
172/* year -> 1 if leap year, else 0. */
173static int
174is_leap(int year)
175{
176 /* Cast year to unsigned. The result is the same either way, but
177 * C can generate faster code for unsigned mod than for signed
178 * mod (especially for % 4 -- a good compiler should just grab
179 * the last 2 bits when the LHS is unsigned).
180 */
181 const unsigned int ayear = (unsigned int)year;
182 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
183}
184
185/* year, month -> number of days in that month in that year */
186static int
187days_in_month(int year, int month)
188{
189 assert(month >= 1);
190 assert(month <= 12);
191 if (month == 2 && is_leap(year))
192 return 29;
193 else
194 return _days_in_month[month];
195}
196
197/* year, month -> number of days in year preceeding first day of month */
198static int
199days_before_month(int year, int month)
200{
201 int days;
202
203 assert(month >= 1);
204 assert(month <= 12);
205 days = _days_before_month[month];
206 if (month > 2 && is_leap(year))
207 ++days;
208 return days;
209}
210
211/* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
213 */
214static int
215days_before_year(int year)
216{
217 int y = year - 1;
218 /* This is incorrect if year <= 0; we really want the floor
219 * here. But so long as MINYEAR is 1, the smallest year this
220 * can see is 0 (this can happen in some normalization endcases),
221 * so we'll just special-case that.
222 */
223 assert (year >= 0);
224 if (y >= 0)
225 return y*365 + y/4 - y/100 + y/400;
226 else {
227 assert(y == -1);
228 return -366;
229 }
230}
231
232/* Number of days in 4, 100, and 400 year cycles. That these have
233 * the correct values is asserted in the module init function.
234 */
235#define DI4Y 1461 /* days_before_year(5); days in 4 years */
236#define DI100Y 36524 /* days_before_year(101); days in 100 years */
237#define DI400Y 146097 /* days_before_year(401); days in 400 years */
238
239/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
240static void
241ord_to_ymd(int ordinal, int *year, int *month, int *day)
242{
243 int n, n1, n4, n100, n400, leapyear, preceding;
244
245 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
246 * leap years repeats exactly every 400 years. The basic strategy is
247 * to find the closest 400-year boundary at or before ordinal, then
248 * work with the offset from that boundary to ordinal. Life is much
249 * clearer if we subtract 1 from ordinal first -- then the values
250 * of ordinal at 400-year boundaries are exactly those divisible
251 * by DI400Y:
252 *
253 * D M Y n n-1
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
257 * ...
258 * 30 Dec 000 -1 -2
259 * 31 Dec 000 0 -1
260 * 1 Jan 001 1 0 400-year boundary
261 * 2 Jan 001 2 1
262 * 3 Jan 001 3 2
263 * ...
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
266 */
267 assert(ordinal >= 1);
268 --ordinal;
269 n400 = ordinal / DI400Y;
270 n = ordinal % DI400Y;
271 *year = n400 * 400 + 1;
272
273 /* Now n is the (non-negative) offset, in days, from January 1 of
274 * year, to the desired date. Now compute how many 100-year cycles
275 * precede n.
276 * Note that it's possible for n100 to equal 4! In that case 4 full
277 * 100-year cycles precede the desired day, which implies the
278 * desired day is December 31 at the end of a 400-year cycle.
279 */
280 n100 = n / DI100Y;
281 n = n % DI100Y;
282
283 /* Now compute how many 4-year cycles precede it. */
284 n4 = n / DI4Y;
285 n = n % DI4Y;
286
287 /* And now how many single years. Again n1 can be 4, and again
288 * meaning that the desired day is December 31 at the end of the
289 * 4-year cycle.
290 */
291 n1 = n / 365;
292 n = n % 365;
293
294 *year += n100 * 100 + n4 * 4 + n1;
295 if (n1 == 4 || n100 == 4) {
296 assert(n == 0);
297 *year -= 1;
298 *month = 12;
299 *day = 31;
300 return;
301 }
302
303 /* Now the year is correct, and n is the offset from January 1. We
304 * find the month via an estimate that's either exact or one too
305 * large.
306 */
307 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
308 assert(leapyear == is_leap(*year));
309 *month = (n + 50) >> 5;
310 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
311 if (preceding > n) {
312 /* estimate is too large */
313 *month -= 1;
314 preceding -= days_in_month(*year, *month);
315 }
316 n -= preceding;
317 assert(0 <= n);
318 assert(n < days_in_month(*year, *month));
319
320 *day = n + 1;
321}
322
323/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
324static int
325ymd_to_ord(int year, int month, int day)
326{
327 return days_before_year(year) + days_before_month(year, month) + day;
328}
329
330/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
331static int
332weekday(int year, int month, int day)
333{
334 return (ymd_to_ord(year, month, day) + 6) % 7;
335}
336
337/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
338 * first calendar week containing a Thursday.
339 */
340static int
341iso_week1_monday(int year)
342{
343 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
344 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
345 int first_weekday = (first_day + 6) % 7;
346 /* ordinal of closest Monday at or before 1/1 */
347 int week1_monday = first_day - first_weekday;
348
349 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
350 week1_monday += 7;
351 return week1_monday;
352}
353
354/* ---------------------------------------------------------------------------
355 * Range checkers.
356 */
357
358/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
360 */
361static int
362check_delta_day_range(int days)
363{
364 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
365 return 0;
366 PyErr_Format(PyExc_OverflowError,
367 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000368 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000369 return -1;
370}
371
372/* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
374 */
375static int
376check_date_args(int year, int month, int day)
377{
378
379 if (year < MINYEAR || year > MAXYEAR) {
380 PyErr_SetString(PyExc_ValueError,
381 "year is out of range");
382 return -1;
383 }
384 if (month < 1 || month > 12) {
385 PyErr_SetString(PyExc_ValueError,
386 "month must be in 1..12");
387 return -1;
388 }
389 if (day < 1 || day > days_in_month(year, month)) {
390 PyErr_SetString(PyExc_ValueError,
391 "day is out of range for month");
392 return -1;
393 }
394 return 0;
395}
396
397/* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_time_args(int h, int m, int s, int us)
402{
403 if (h < 0 || h > 23) {
404 PyErr_SetString(PyExc_ValueError,
405 "hour must be in 0..23");
406 return -1;
407 }
408 if (m < 0 || m > 59) {
409 PyErr_SetString(PyExc_ValueError,
410 "minute must be in 0..59");
411 return -1;
412 }
413 if (s < 0 || s > 59) {
414 PyErr_SetString(PyExc_ValueError,
415 "second must be in 0..59");
416 return -1;
417 }
418 if (us < 0 || us > 999999) {
419 PyErr_SetString(PyExc_ValueError,
420 "microsecond must be in 0..999999");
421 return -1;
422 }
423 return 0;
424}
425
426/* ---------------------------------------------------------------------------
427 * Normalization utilities.
428 */
429
430/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
431 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
432 * at least factor, enough of *lo is converted into "hi" units so that
433 * 0 <= *lo < factor. The input values must be such that int overflow
434 * is impossible.
435 */
436static void
437normalize_pair(int *hi, int *lo, int factor)
438{
439 assert(factor > 0);
440 assert(lo != hi);
441 if (*lo < 0 || *lo >= factor) {
442 const int num_hi = divmod(*lo, factor, lo);
443 const int new_hi = *hi + num_hi;
444 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
445 *hi = new_hi;
446 }
447 assert(0 <= *lo && *lo < factor);
448}
449
450/* Fiddle days (d), seconds (s), and microseconds (us) so that
451 * 0 <= *s < 24*3600
452 * 0 <= *us < 1000000
453 * The input values must be such that the internals don't overflow.
454 * The way this routine is used, we don't get close.
455 */
456static void
457normalize_d_s_us(int *d, int *s, int *us)
458{
459 if (*us < 0 || *us >= 1000000) {
460 normalize_pair(s, us, 1000000);
461 /* |s| can't be bigger than about
462 * |original s| + |original us|/1000000 now.
463 */
464
465 }
466 if (*s < 0 || *s >= 24*3600) {
467 normalize_pair(d, s, 24*3600);
468 /* |d| can't be bigger than about
469 * |original d| +
470 * (|original s| + |original us|/1000000) / (24*3600) now.
471 */
472 }
473 assert(0 <= *s && *s < 24*3600);
474 assert(0 <= *us && *us < 1000000);
475}
476
477/* Fiddle years (y), months (m), and days (d) so that
478 * 1 <= *m <= 12
479 * 1 <= *d <= days_in_month(*y, *m)
480 * The input values must be such that the internals don't overflow.
481 * The way this routine is used, we don't get close.
482 */
483static void
484normalize_y_m_d(int *y, int *m, int *d)
485{
486 int dim; /* # of days in month */
487
488 /* This gets muddy: the proper range for day can't be determined
489 * without knowing the correct month and year, but if day is, e.g.,
490 * plus or minus a million, the current month and year values make
491 * no sense (and may also be out of bounds themselves).
492 * Saying 12 months == 1 year should be non-controversial.
493 */
494 if (*m < 1 || *m > 12) {
495 --*m;
496 normalize_pair(y, m, 12);
497 ++*m;
498 /* |y| can't be bigger than about
499 * |original y| + |original m|/12 now.
500 */
501 }
502 assert(1 <= *m && *m <= 12);
503
504 /* Now only day can be out of bounds (year may also be out of bounds
505 * for a datetime object, but we don't care about that here).
506 * If day is out of bounds, what to do is arguable, but at least the
507 * method here is principled and explainable.
508 */
509 dim = days_in_month(*y, *m);
510 if (*d < 1 || *d > dim) {
511 /* Move day-1 days from the first of the month. First try to
512 * get off cheap if we're only one day out of range
513 * (adjustments for timezone alone can't be worse than that).
514 */
515 if (*d == 0) {
516 --*m;
517 if (*m > 0)
518 *d = days_in_month(*y, *m);
519 else {
520 --*y;
521 *m = 12;
522 *d = 31;
523 }
524 }
525 else if (*d == dim + 1) {
526 /* move forward a day */
527 ++*m;
528 *d = 1;
529 if (*m > 12) {
530 *m = 1;
531 ++*y;
532 }
533 }
534 else {
535 int ordinal = ymd_to_ord(*y, *m, 1) +
536 *d - 1;
537 ord_to_ymd(ordinal, y, m, d);
538 }
539 }
540 assert(*m > 0);
541 assert(*d > 0);
542}
543
544/* Fiddle out-of-bounds months and days so that the result makes some kind
545 * of sense. The parameters are both inputs and outputs. Returns < 0 on
546 * failure, where failure means the adjusted year is out of bounds.
547 */
548static int
549normalize_date(int *year, int *month, int *day)
550{
551 int result;
552
553 normalize_y_m_d(year, month, day);
554 if (MINYEAR <= *year && *year <= MAXYEAR)
555 result = 0;
556 else {
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 result = -1;
560 }
561 return result;
562}
563
564/* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
566 */
567static int
568normalize_datetime(int *year, int *month, int *day,
569 int *hour, int *minute, int *second,
570 int *microsecond)
571{
572 normalize_pair(second, microsecond, 1000000);
573 normalize_pair(minute, second, 60);
574 normalize_pair(hour, minute, 60);
575 normalize_pair(day, hour, 24);
576 return normalize_date(year, month, day);
577}
578
579/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000580 * Basic object allocation: tp_alloc implementations. These allocate
581 * Python objects of the right size and type, and do the Python object-
582 * initialization bit. If there's not enough memory, they return NULL after
583 * setting MemoryError. All data members remain uninitialized trash.
584 *
585 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000586 * member is needed. This is ugly, imprecise, and possibly insecure.
587 * tp_basicsize for the time and datetime types is set to the size of the
588 * struct that has room for the tzinfo member, so subclasses in Python will
589 * allocate enough space for a tzinfo member whether or not one is actually
590 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
591 * part is that PyType_GenericAlloc() (which subclasses in Python end up
592 * using) just happens today to effectively ignore the nitems argument
593 * when tp_itemsize is 0, which it is for these type objects. If that
594 * changes, perhaps the callers of tp_alloc slots in this file should
595 * be changed to force a 0 nitems argument unless the type being allocated
596 * is a base type implemented in this file (so that tp_alloc is time_alloc
597 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000598 */
599
600static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000601time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000602{
603 PyObject *self;
604
605 self = (PyObject *)
606 PyObject_MALLOC(aware ?
607 sizeof(PyDateTime_Time) :
608 sizeof(_PyDateTime_BaseTime));
609 if (self == NULL)
610 return (PyObject *)PyErr_NoMemory();
611 PyObject_INIT(self, type);
612 return self;
613}
614
615static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000616datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000617{
618 PyObject *self;
619
620 self = (PyObject *)
621 PyObject_MALLOC(aware ?
622 sizeof(PyDateTime_DateTime) :
623 sizeof(_PyDateTime_BaseDateTime));
624 if (self == NULL)
625 return (PyObject *)PyErr_NoMemory();
626 PyObject_INIT(self, type);
627 return self;
628}
629
630/* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
633 */
634
635/* For date and datetime. */
636static void
637set_date_fields(PyDateTime_Date *self, int y, int m, int d)
638{
639 self->hashcode = -1;
640 SET_YEAR(self, y);
641 SET_MONTH(self, m);
642 SET_DAY(self, d);
643}
644
645/* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
647 */
648
649/* Create a date instance with no range checking. */
650static PyObject *
651new_date_ex(int year, int month, int day, PyTypeObject *type)
652{
653 PyDateTime_Date *self;
654
655 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
656 if (self != NULL)
657 set_date_fields(self, year, month, day);
658 return (PyObject *) self;
659}
660
661#define new_date(year, month, day) \
662 new_date_ex(year, month, day, &PyDateTime_DateType)
663
664/* Create a datetime instance with no range checking. */
665static PyObject *
666new_datetime_ex(int year, int month, int day, int hour, int minute,
667 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
668{
669 PyDateTime_DateTime *self;
670 char aware = tzinfo != Py_None;
671
672 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
673 if (self != NULL) {
674 self->hastzinfo = aware;
675 set_date_fields((PyDateTime_Date *)self, year, month, day);
676 DATE_SET_HOUR(self, hour);
677 DATE_SET_MINUTE(self, minute);
678 DATE_SET_SECOND(self, second);
679 DATE_SET_MICROSECOND(self, usecond);
680 if (aware) {
681 Py_INCREF(tzinfo);
682 self->tzinfo = tzinfo;
683 }
684 }
685 return (PyObject *)self;
686}
687
688#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
689 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
690 &PyDateTime_DateTimeType)
691
692/* Create a time instance with no range checking. */
693static PyObject *
694new_time_ex(int hour, int minute, int second, int usecond,
695 PyObject *tzinfo, PyTypeObject *type)
696{
697 PyDateTime_Time *self;
698 char aware = tzinfo != Py_None;
699
700 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
701 if (self != NULL) {
702 self->hastzinfo = aware;
703 self->hashcode = -1;
704 TIME_SET_HOUR(self, hour);
705 TIME_SET_MINUTE(self, minute);
706 TIME_SET_SECOND(self, second);
707 TIME_SET_MICROSECOND(self, usecond);
708 if (aware) {
709 Py_INCREF(tzinfo);
710 self->tzinfo = tzinfo;
711 }
712 }
713 return (PyObject *)self;
714}
715
716#define new_time(hh, mm, ss, us, tzinfo) \
717 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
718
719/* Create a timedelta instance. Normalize the members iff normalize is
720 * true. Passing false is a speed optimization, if you know for sure
721 * that seconds and microseconds are already in their proper ranges. In any
722 * case, raises OverflowError and returns NULL if the normalized days is out
723 * of range).
724 */
725static PyObject *
726new_delta_ex(int days, int seconds, int microseconds, int normalize,
727 PyTypeObject *type)
728{
729 PyDateTime_Delta *self;
730
731 if (normalize)
732 normalize_d_s_us(&days, &seconds, &microseconds);
733 assert(0 <= seconds && seconds < 24*3600);
734 assert(0 <= microseconds && microseconds < 1000000);
735
736 if (check_delta_day_range(days) < 0)
737 return NULL;
738
739 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
740 if (self != NULL) {
741 self->hashcode = -1;
742 SET_TD_DAYS(self, days);
743 SET_TD_SECONDS(self, seconds);
744 SET_TD_MICROSECONDS(self, microseconds);
745 }
746 return (PyObject *) self;
747}
748
749#define new_delta(d, s, us, normalize) \
750 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
751
752/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000753 * tzinfo helpers.
754 */
755
Tim Peters855fe882002-12-22 03:43:39 +0000756/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
758 */
759static int
760check_tzinfo_subclass(PyObject *p)
761{
762 if (p == Py_None || PyTZInfo_Check(p))
763 return 0;
764 PyErr_Format(PyExc_TypeError,
765 "tzinfo argument must be None or of a tzinfo subclass, "
766 "not type '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000767 Py_TYPE(p)->tp_name);
Tim Peters855fe882002-12-22 03:43:39 +0000768 return -1;
769}
770
Tim Petersbad8ff02002-12-30 20:52:32 +0000771/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000772 * If tzinfo is None, returns None.
773 */
774static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000775call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000776{
777 PyObject *result;
778
Tim Petersbad8ff02002-12-30 20:52:32 +0000779 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
784 }
785 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000787 return result;
788}
789
Tim Peters2a799bf2002-12-16 20:18:38 +0000790/* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
793 */
794static PyObject *
795get_tzinfo_member(PyObject *self)
796{
797 PyObject *tzinfo = NULL;
798
Tim Petersa9bc1682003-01-11 03:39:11 +0000799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000801 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
804 return tzinfo;
805}
806
Tim Petersbad8ff02002-12-30 20:52:32 +0000807/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * Else *none is set to 0 and the integer method result is returned.
814 */
815static int
816call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
818{
819 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000820 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000821
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
825
826 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 if (u == NULL)
829 return -1;
830
Tim Peters27362852002-12-23 16:17:39 +0000831 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 result = 0;
833 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000834 }
Tim Peters855fe882002-12-22 03:43:39 +0000835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
842 */
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000851 }
852 }
853 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000854 else {
855 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000856 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000857 "timedelta, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000858 name, Py_TYPE(u)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 }
860
Tim Peters2a799bf2002-12-16 20:18:38 +0000861 Py_DECREF(u);
862 if (result < -1439 || result > 1439) {
863 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000864 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000865 "-1439 .. 1439",
866 name, result);
867 result = -1;
868 }
Tim Peters397301e2003-01-02 21:28:08 +0000869 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000870}
871
872/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
873 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
874 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000875 * doesn't return None or timedelta, TypeError is raised and this returns -1.
876 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
877 * # of minutes), ValueError is raised and this returns -1. Else *none is
878 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000879 */
880static int
881call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
882{
883 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
884}
885
Tim Petersbad8ff02002-12-30 20:52:32 +0000886/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
887 */
Tim Peters855fe882002-12-22 03:43:39 +0000888static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000889offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000890 PyObject *result;
891
Tim Petersbad8ff02002-12-30 20:52:32 +0000892 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000893 if (tzinfo == Py_None) {
894 result = Py_None;
895 Py_INCREF(result);
896 }
897 else {
898 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000899 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
900 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000901 if (offset < 0 && PyErr_Occurred())
902 return NULL;
903 if (none) {
904 result = Py_None;
905 Py_INCREF(result);
906 }
907 else
908 result = new_delta(0, offset * 60, 0, 1);
909 }
910 return result;
911}
912
Tim Peters2a799bf2002-12-16 20:18:38 +0000913/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If dst()
915 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000916 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000917 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000918 * ValueError is raised and this returns -1. Else *none is set to 0 and
919 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000920 */
921static int
922call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
923{
924 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
925}
926
Tim Petersbad8ff02002-12-30 20:52:32 +0000927/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000928 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000929 * tzname() doesn't return None or a string, TypeError is raised and this
Tim Peters855fe882002-12-22 03:43:39 +0000930 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000931 */
932static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000933call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000934{
935 PyObject *result;
936
937 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000938 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000939 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000940
Tim Peters855fe882002-12-22 03:43:39 +0000941 if (tzinfo == Py_None) {
942 result = Py_None;
943 Py_INCREF(result);
944 }
945 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000946 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000947
948 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
949 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
Tim Peters2a799bf2002-12-16 20:18:38 +0000950 "return None or a string, not '%s'",
Christian Heimese93237d2007-12-19 02:37:44 +0000951 Py_TYPE(result)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000952 Py_DECREF(result);
953 result = NULL;
954 }
955 return result;
956}
957
958typedef enum {
959 /* an exception has been set; the caller should pass it on */
960 OFFSET_ERROR,
961
Tim Petersa9bc1682003-01-11 03:39:11 +0000962 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000963 OFFSET_UNKNOWN,
964
965 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000966 * datetime with !hastzinfo
967 * datetime with None tzinfo,
968 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000969 * time with !hastzinfo
970 * time with None tzinfo,
971 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000972 */
973 OFFSET_NAIVE,
974
Tim Petersa9bc1682003-01-11 03:39:11 +0000975 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000976 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000977} naivety;
978
Tim Peters14b69412002-12-22 18:10:22 +0000979/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 * the "naivety" typedef for details. If the type is aware, *offset is set
981 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000982 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000983 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000984 */
985static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000986classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000987{
988 int none;
989 PyObject *tzinfo;
990
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +0000993 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +0000994 if (tzinfo == Py_None)
995 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +0000996 if (tzinfo == NULL) {
997 /* note that a datetime passes the PyDate_Check test */
998 return (PyTime_Check(op) || PyDate_Check(op)) ?
999 OFFSET_NAIVE : OFFSET_UNKNOWN;
1000 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001001 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (*offset == -1 && PyErr_Occurred())
1003 return OFFSET_ERROR;
1004 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1005}
1006
Tim Peters00237032002-12-27 02:21:51 +00001007/* Classify two objects as to whether they're naive or offset-aware.
1008 * This isn't quite the same as calling classify_utcoffset() twice: for
1009 * binary operations (comparison and subtraction), we generally want to
1010 * ignore the tzinfo members if they're identical. This is by design,
1011 * so that results match "naive" expectations when mixing objects from a
1012 * single timezone. So in that case, this sets both offsets to 0 and
1013 * both naiveties to OFFSET_NAIVE.
1014 * The function returns 0 if everything's OK, and -1 on error.
1015 */
1016static int
1017classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001018 PyObject *tzinfoarg1,
1019 PyObject *o2, int *offset2, naivety *n2,
1020 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001021{
1022 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1023 *offset1 = *offset2 = 0;
1024 *n1 = *n2 = OFFSET_NAIVE;
1025 }
1026 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001027 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001028 if (*n1 == OFFSET_ERROR)
1029 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001030 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001031 if (*n2 == OFFSET_ERROR)
1032 return -1;
1033 }
1034 return 0;
1035}
1036
Tim Peters2a799bf2002-12-16 20:18:38 +00001037/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1038 * stuff
1039 * ", tzinfo=" + repr(tzinfo)
1040 * before the closing ")".
1041 */
1042static PyObject *
1043append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1044{
1045 PyObject *temp;
1046
1047 assert(PyString_Check(repr));
1048 assert(tzinfo);
1049 if (tzinfo == Py_None)
1050 return repr;
1051 /* Get rid of the trailing ')'. */
1052 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1053 temp = PyString_FromStringAndSize(PyString_AsString(repr),
1054 PyString_Size(repr) - 1);
1055 Py_DECREF(repr);
1056 if (temp == NULL)
1057 return NULL;
1058 repr = temp;
1059
1060 /* Append ", tzinfo=". */
1061 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
1062
1063 /* Append repr(tzinfo). */
1064 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
1065
1066 /* Add a closing paren. */
1067 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1068 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
1133/* I sure don't want to reproduce the strftime code from the time module,
1134 * so this imports the module and calls it. All the hair is due to
1135 * giving special meanings to the %z and %Z format codes via a preprocessing
1136 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001137 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1138 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001139 */
1140static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001141wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1142 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001143{
1144 PyObject *result = NULL; /* guilty until proved innocent */
1145
1146 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1147 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1148
1149 char *pin; /* pointer to next char in input format */
1150 char ch; /* next char in input format */
1151
1152 PyObject *newfmt = NULL; /* py string, the output format */
1153 char *pnew; /* pointer to available byte in output format */
Georg Brandl4ddfcd32006-09-30 11:17:34 +00001154 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001155 exclusive of trailing \0 */
Georg Brandl4ddfcd32006-09-30 11:17:34 +00001156 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001157
1158 char *ptoappend; /* pointer to string to append to output buffer */
1159 int ntoappend; /* # of bytes to append to output buffer */
1160
Tim Peters2a799bf2002-12-16 20:18:38 +00001161 assert(object && format && timetuple);
1162 assert(PyString_Check(format));
1163
Tim Petersd6844152002-12-22 20:58:42 +00001164 /* Give up if the year is before 1900.
1165 * Python strftime() plays games with the year, and different
1166 * games depending on whether envar PYTHON2K is set. This makes
1167 * years before 1900 a nightmare, even if the platform strftime
1168 * supports them (and not all do).
1169 * We could get a lot farther here by avoiding Python's strftime
1170 * wrapper and calling the C strftime() directly, but that isn't
1171 * an option in the Python implementation of this module.
1172 */
1173 {
1174 long year;
1175 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1176 if (pyyear == NULL) return NULL;
1177 assert(PyInt_Check(pyyear));
1178 year = PyInt_AsLong(pyyear);
1179 Py_DECREF(pyyear);
1180 if (year < 1900) {
1181 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1182 "1900; the datetime strftime() "
1183 "methods require year >= 1900",
1184 year);
1185 return NULL;
1186 }
1187 }
1188
Tim Peters2a799bf2002-12-16 20:18:38 +00001189 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001190 * a new format. Since computing the replacements for those codes
1191 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001192 */
Raymond Hettingerf69d9f62003-06-27 08:14:17 +00001193 totalnew = PyString_Size(format) + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001194 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1195 if (newfmt == NULL) goto Done;
1196 pnew = PyString_AsString(newfmt);
1197 usednew = 0;
1198
1199 pin = PyString_AsString(format);
1200 while ((ch = *pin++) != '\0') {
1201 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001202 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001203 ntoappend = 1;
1204 }
1205 else if ((ch = *pin++) == '\0') {
1206 /* There's a lone trailing %; doesn't make sense. */
1207 PyErr_SetString(PyExc_ValueError, "strftime format "
1208 "ends with raw %");
1209 goto Done;
1210 }
1211 /* A % has been seen and ch is the character after it. */
1212 else if (ch == 'z') {
1213 if (zreplacement == NULL) {
1214 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001215 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001216 PyObject *tzinfo = get_tzinfo_member(object);
1217 zreplacement = PyString_FromString("");
1218 if (zreplacement == NULL) goto Done;
1219 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001220 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001221 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001222 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001223 "",
1224 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001225 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001226 goto Done;
1227 Py_DECREF(zreplacement);
1228 zreplacement = PyString_FromString(buf);
1229 if (zreplacement == NULL) goto Done;
1230 }
1231 }
1232 assert(zreplacement != NULL);
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001233 ptoappend = PyString_AS_STRING(zreplacement);
1234 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001235 }
1236 else if (ch == 'Z') {
1237 /* format tzname */
1238 if (Zreplacement == NULL) {
1239 PyObject *tzinfo = get_tzinfo_member(object);
1240 Zreplacement = PyString_FromString("");
1241 if (Zreplacement == NULL) goto Done;
1242 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001243 PyObject *temp;
1244 assert(tzinfoarg != NULL);
1245 temp = call_tzname(tzinfo, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001246 if (temp == NULL) goto Done;
1247 if (temp != Py_None) {
1248 assert(PyString_Check(temp));
1249 /* Since the tzname is getting
1250 * stuffed into the format, we
1251 * have to double any % signs
1252 * so that strftime doesn't
1253 * treat them as format codes.
1254 */
1255 Py_DECREF(Zreplacement);
1256 Zreplacement = PyObject_CallMethod(
1257 temp, "replace",
1258 "ss", "%", "%%");
1259 Py_DECREF(temp);
1260 if (Zreplacement == NULL)
1261 goto Done;
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001262 if (!PyString_Check(Zreplacement)) {
1263 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1264 goto Done;
1265 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001266 }
1267 else
1268 Py_DECREF(temp);
1269 }
1270 }
1271 assert(Zreplacement != NULL);
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001272 ptoappend = PyString_AS_STRING(Zreplacement);
1273 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001274 }
1275 else {
Tim Peters328fff72002-12-20 01:31:27 +00001276 /* percent followed by neither z nor Z */
1277 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001278 ntoappend = 2;
1279 }
1280
1281 /* Append the ntoappend chars starting at ptoappend to
1282 * the new format.
1283 */
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001284 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001285 assert(ntoappend >= 0);
1286 if (ntoappend == 0)
1287 continue;
1288 while (usednew + ntoappend > totalnew) {
1289 int bigger = totalnew << 1;
1290 if ((bigger >> 1) != totalnew) { /* overflow */
1291 PyErr_NoMemory();
1292 goto Done;
1293 }
1294 if (_PyString_Resize(&newfmt, bigger) < 0)
1295 goto Done;
1296 totalnew = bigger;
1297 pnew = PyString_AsString(newfmt) + usednew;
1298 }
1299 memcpy(pnew, ptoappend, ntoappend);
1300 pnew += ntoappend;
1301 usednew += ntoappend;
1302 assert(usednew <= totalnew);
1303 } /* end while() */
1304
1305 if (_PyString_Resize(&newfmt, usednew) < 0)
1306 goto Done;
1307 {
Christian Heimes000a0742008-01-03 22:16:32 +00001308 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001309 if (time == NULL)
1310 goto Done;
1311 result = PyObject_CallMethod(time, "strftime", "OO",
1312 newfmt, timetuple);
1313 Py_DECREF(time);
1314 }
1315 Done:
1316 Py_XDECREF(zreplacement);
1317 Py_XDECREF(Zreplacement);
1318 Py_XDECREF(newfmt);
1319 return result;
1320}
1321
1322static char *
1323isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1324{
1325 int x;
1326 x = PyOS_snprintf(buffer, bufflen,
1327 "%04d-%02d-%02d",
1328 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1329 return buffer + x;
1330}
1331
1332static void
1333isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1334{
1335 int us = DATE_GET_MICROSECOND(dt);
1336
1337 PyOS_snprintf(buffer, bufflen,
1338 "%02d:%02d:%02d", /* 8 characters */
1339 DATE_GET_HOUR(dt),
1340 DATE_GET_MINUTE(dt),
1341 DATE_GET_SECOND(dt));
1342 if (us)
1343 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1344}
1345
1346/* ---------------------------------------------------------------------------
1347 * Wrap functions from the time module. These aren't directly available
1348 * from C. Perhaps they should be.
1349 */
1350
1351/* Call time.time() and return its result (a Python float). */
1352static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001353time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001354{
1355 PyObject *result = NULL;
Christian Heimes000a0742008-01-03 22:16:32 +00001356 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001357
1358 if (time != NULL) {
1359 result = PyObject_CallMethod(time, "time", "()");
1360 Py_DECREF(time);
1361 }
1362 return result;
1363}
1364
1365/* Build a time.struct_time. The weekday and day number are automatically
1366 * computed from the y,m,d args.
1367 */
1368static PyObject *
1369build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1370{
1371 PyObject *time;
1372 PyObject *result = NULL;
1373
Christian Heimes000a0742008-01-03 22:16:32 +00001374 time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001375 if (time != NULL) {
1376 result = PyObject_CallMethod(time, "struct_time",
1377 "((iiiiiiiii))",
1378 y, m, d,
1379 hh, mm, ss,
1380 weekday(y, m, d),
1381 days_before_month(y, m) + d,
1382 dstflag);
1383 Py_DECREF(time);
1384 }
1385 return result;
1386}
1387
1388/* ---------------------------------------------------------------------------
1389 * Miscellaneous helpers.
1390 */
1391
1392/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1393 * The comparisons here all most naturally compute a cmp()-like result.
1394 * This little helper turns that into a bool result for rich comparisons.
1395 */
1396static PyObject *
1397diff_to_bool(int diff, int op)
1398{
1399 PyObject *result;
1400 int istrue;
1401
1402 switch (op) {
1403 case Py_EQ: istrue = diff == 0; break;
1404 case Py_NE: istrue = diff != 0; break;
1405 case Py_LE: istrue = diff <= 0; break;
1406 case Py_GE: istrue = diff >= 0; break;
1407 case Py_LT: istrue = diff < 0; break;
1408 case Py_GT: istrue = diff > 0; break;
1409 default:
1410 assert(! "op unknown");
1411 istrue = 0; /* To shut up compiler */
1412 }
1413 result = istrue ? Py_True : Py_False;
1414 Py_INCREF(result);
1415 return result;
1416}
1417
Tim Peters07534a62003-02-07 22:50:28 +00001418/* Raises a "can't compare" TypeError and returns NULL. */
1419static PyObject *
1420cmperror(PyObject *a, PyObject *b)
1421{
1422 PyErr_Format(PyExc_TypeError,
1423 "can't compare %s to %s",
Christian Heimese93237d2007-12-19 02:37:44 +00001424 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001425 return NULL;
1426}
1427
Tim Peters2a799bf2002-12-16 20:18:38 +00001428/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001429 * Cached Python objects; these are set by the module init function.
1430 */
1431
1432/* Conversion factors. */
1433static PyObject *us_per_us = NULL; /* 1 */
1434static PyObject *us_per_ms = NULL; /* 1000 */
1435static PyObject *us_per_second = NULL; /* 1000000 */
1436static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1437static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1438static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1439static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1440static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1441
Tim Peters2a799bf2002-12-16 20:18:38 +00001442/* ---------------------------------------------------------------------------
1443 * Class implementations.
1444 */
1445
1446/*
1447 * PyDateTime_Delta implementation.
1448 */
1449
1450/* Convert a timedelta to a number of us,
1451 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1452 * as a Python int or long.
1453 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1454 * due to ubiquitous overflow possibilities.
1455 */
1456static PyObject *
1457delta_to_microseconds(PyDateTime_Delta *self)
1458{
1459 PyObject *x1 = NULL;
1460 PyObject *x2 = NULL;
1461 PyObject *x3 = NULL;
1462 PyObject *result = NULL;
1463
1464 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1465 if (x1 == NULL)
1466 goto Done;
1467 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1468 if (x2 == NULL)
1469 goto Done;
1470 Py_DECREF(x1);
1471 x1 = NULL;
1472
1473 /* x2 has days in seconds */
1474 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1475 if (x1 == NULL)
1476 goto Done;
1477 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1478 if (x3 == NULL)
1479 goto Done;
1480 Py_DECREF(x1);
1481 Py_DECREF(x2);
1482 x1 = x2 = NULL;
1483
1484 /* x3 has days+seconds in seconds */
1485 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1486 if (x1 == NULL)
1487 goto Done;
1488 Py_DECREF(x3);
1489 x3 = NULL;
1490
1491 /* x1 has days+seconds in us */
1492 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1493 if (x2 == NULL)
1494 goto Done;
1495 result = PyNumber_Add(x1, x2);
1496
1497Done:
1498 Py_XDECREF(x1);
1499 Py_XDECREF(x2);
1500 Py_XDECREF(x3);
1501 return result;
1502}
1503
1504/* Convert a number of us (as a Python int or long) to a timedelta.
1505 */
1506static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001507microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001508{
1509 int us;
1510 int s;
1511 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001512 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001513
1514 PyObject *tuple = NULL;
1515 PyObject *num = NULL;
1516 PyObject *result = NULL;
1517
1518 tuple = PyNumber_Divmod(pyus, us_per_second);
1519 if (tuple == NULL)
1520 goto Done;
1521
1522 num = PyTuple_GetItem(tuple, 1); /* us */
1523 if (num == NULL)
1524 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001525 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001526 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001527 if (temp == -1 && PyErr_Occurred())
1528 goto Done;
1529 assert(0 <= temp && temp < 1000000);
1530 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001531 if (us < 0) {
1532 /* The divisor was positive, so this must be an error. */
1533 assert(PyErr_Occurred());
1534 goto Done;
1535 }
1536
1537 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1538 if (num == NULL)
1539 goto Done;
1540 Py_INCREF(num);
1541 Py_DECREF(tuple);
1542
1543 tuple = PyNumber_Divmod(num, seconds_per_day);
1544 if (tuple == NULL)
1545 goto Done;
1546 Py_DECREF(num);
1547
1548 num = PyTuple_GetItem(tuple, 1); /* seconds */
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 < 24*3600);
1556 s = (int)temp;
1557
Tim Peters2a799bf2002-12-16 20:18:38 +00001558 if (s < 0) {
1559 /* The divisor was positive, so this must be an error. */
1560 assert(PyErr_Occurred());
1561 goto Done;
1562 }
1563
1564 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1565 if (num == NULL)
1566 goto Done;
1567 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001568 temp = PyLong_AsLong(num);
1569 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001570 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001571 d = (int)temp;
1572 if ((long)d != temp) {
1573 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1574 "large to fit in a C int");
1575 goto Done;
1576 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001577 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001578
1579Done:
1580 Py_XDECREF(tuple);
1581 Py_XDECREF(num);
1582 return result;
1583}
1584
Tim Petersb0c854d2003-05-17 15:57:00 +00001585#define microseconds_to_delta(pymicros) \
1586 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1587
Tim Peters2a799bf2002-12-16 20:18:38 +00001588static PyObject *
1589multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1590{
1591 PyObject *pyus_in;
1592 PyObject *pyus_out;
1593 PyObject *result;
1594
1595 pyus_in = delta_to_microseconds(delta);
1596 if (pyus_in == NULL)
1597 return NULL;
1598
1599 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1600 Py_DECREF(pyus_in);
1601 if (pyus_out == NULL)
1602 return NULL;
1603
1604 result = microseconds_to_delta(pyus_out);
1605 Py_DECREF(pyus_out);
1606 return result;
1607}
1608
1609static PyObject *
1610divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1611{
1612 PyObject *pyus_in;
1613 PyObject *pyus_out;
1614 PyObject *result;
1615
1616 pyus_in = delta_to_microseconds(delta);
1617 if (pyus_in == NULL)
1618 return NULL;
1619
1620 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1621 Py_DECREF(pyus_in);
1622 if (pyus_out == NULL)
1623 return NULL;
1624
1625 result = microseconds_to_delta(pyus_out);
1626 Py_DECREF(pyus_out);
1627 return result;
1628}
1629
1630static PyObject *
1631delta_add(PyObject *left, PyObject *right)
1632{
1633 PyObject *result = Py_NotImplemented;
1634
1635 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1636 /* delta + delta */
1637 /* The C-level additions can't overflow because of the
1638 * invariant bounds.
1639 */
1640 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1641 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1642 int microseconds = GET_TD_MICROSECONDS(left) +
1643 GET_TD_MICROSECONDS(right);
1644 result = new_delta(days, seconds, microseconds, 1);
1645 }
1646
1647 if (result == Py_NotImplemented)
1648 Py_INCREF(result);
1649 return result;
1650}
1651
1652static PyObject *
1653delta_negative(PyDateTime_Delta *self)
1654{
1655 return new_delta(-GET_TD_DAYS(self),
1656 -GET_TD_SECONDS(self),
1657 -GET_TD_MICROSECONDS(self),
1658 1);
1659}
1660
1661static PyObject *
1662delta_positive(PyDateTime_Delta *self)
1663{
1664 /* Could optimize this (by returning self) if this isn't a
1665 * subclass -- but who uses unary + ? Approximately nobody.
1666 */
1667 return new_delta(GET_TD_DAYS(self),
1668 GET_TD_SECONDS(self),
1669 GET_TD_MICROSECONDS(self),
1670 0);
1671}
1672
1673static PyObject *
1674delta_abs(PyDateTime_Delta *self)
1675{
1676 PyObject *result;
1677
1678 assert(GET_TD_MICROSECONDS(self) >= 0);
1679 assert(GET_TD_SECONDS(self) >= 0);
1680
1681 if (GET_TD_DAYS(self) < 0)
1682 result = delta_negative(self);
1683 else
1684 result = delta_positive(self);
1685
1686 return result;
1687}
1688
1689static PyObject *
1690delta_subtract(PyObject *left, PyObject *right)
1691{
1692 PyObject *result = Py_NotImplemented;
1693
1694 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1695 /* delta - delta */
1696 PyObject *minus_right = PyNumber_Negative(right);
1697 if (minus_right) {
1698 result = delta_add(left, minus_right);
1699 Py_DECREF(minus_right);
1700 }
1701 else
1702 result = NULL;
1703 }
1704
1705 if (result == Py_NotImplemented)
1706 Py_INCREF(result);
1707 return result;
1708}
1709
1710/* This is more natural as a tp_compare, but doesn't work then: for whatever
1711 * reason, Python's try_3way_compare ignores tp_compare unless
1712 * PyInstance_Check returns true, but these aren't old-style classes.
1713 */
1714static PyObject *
1715delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1716{
Tim Peters07534a62003-02-07 22:50:28 +00001717 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00001718
Tim Petersaa7d8492003-02-08 03:28:59 +00001719 if (PyDelta_Check(other)) {
Tim Peters07534a62003-02-07 22:50:28 +00001720 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1721 if (diff == 0) {
1722 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1723 if (diff == 0)
1724 diff = GET_TD_MICROSECONDS(self) -
1725 GET_TD_MICROSECONDS(other);
1726 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001727 }
Tim Peters07534a62003-02-07 22:50:28 +00001728 else if (op == Py_EQ || op == Py_NE)
1729 diff = 1; /* any non-zero value will do */
1730
1731 else /* stop this from falling back to address comparison */
1732 return cmperror((PyObject *)self, other);
1733
Tim Peters2a799bf2002-12-16 20:18:38 +00001734 return diff_to_bool(diff, op);
1735}
1736
1737static PyObject *delta_getstate(PyDateTime_Delta *self);
1738
1739static long
1740delta_hash(PyDateTime_Delta *self)
1741{
1742 if (self->hashcode == -1) {
1743 PyObject *temp = delta_getstate(self);
1744 if (temp != NULL) {
1745 self->hashcode = PyObject_Hash(temp);
1746 Py_DECREF(temp);
1747 }
1748 }
1749 return self->hashcode;
1750}
1751
1752static PyObject *
1753delta_multiply(PyObject *left, PyObject *right)
1754{
1755 PyObject *result = Py_NotImplemented;
1756
1757 if (PyDelta_Check(left)) {
1758 /* delta * ??? */
1759 if (PyInt_Check(right) || PyLong_Check(right))
1760 result = multiply_int_timedelta(right,
1761 (PyDateTime_Delta *) left);
1762 }
1763 else if (PyInt_Check(left) || PyLong_Check(left))
1764 result = multiply_int_timedelta(left,
1765 (PyDateTime_Delta *) right);
1766
1767 if (result == Py_NotImplemented)
1768 Py_INCREF(result);
1769 return result;
1770}
1771
1772static PyObject *
1773delta_divide(PyObject *left, PyObject *right)
1774{
1775 PyObject *result = Py_NotImplemented;
1776
1777 if (PyDelta_Check(left)) {
1778 /* delta * ??? */
1779 if (PyInt_Check(right) || PyLong_Check(right))
1780 result = divide_timedelta_int(
1781 (PyDateTime_Delta *)left,
1782 right);
1783 }
1784
1785 if (result == Py_NotImplemented)
1786 Py_INCREF(result);
1787 return result;
1788}
1789
1790/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1791 * timedelta constructor. sofar is the # of microseconds accounted for
1792 * so far, and there are factor microseconds per current unit, the number
1793 * of which is given by num. num * factor is added to sofar in a
1794 * numerically careful way, and that's the result. Any fractional
1795 * microseconds left over (this can happen if num is a float type) are
1796 * added into *leftover.
1797 * Note that there are many ways this can give an error (NULL) return.
1798 */
1799static PyObject *
1800accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1801 double *leftover)
1802{
1803 PyObject *prod;
1804 PyObject *sum;
1805
1806 assert(num != NULL);
1807
1808 if (PyInt_Check(num) || PyLong_Check(num)) {
1809 prod = PyNumber_Multiply(num, factor);
1810 if (prod == NULL)
1811 return NULL;
1812 sum = PyNumber_Add(sofar, prod);
1813 Py_DECREF(prod);
1814 return sum;
1815 }
1816
1817 if (PyFloat_Check(num)) {
1818 double dnum;
1819 double fracpart;
1820 double intpart;
1821 PyObject *x;
1822 PyObject *y;
1823
1824 /* The Plan: decompose num into an integer part and a
1825 * fractional part, num = intpart + fracpart.
1826 * Then num * factor ==
1827 * intpart * factor + fracpart * factor
1828 * and the LHS can be computed exactly in long arithmetic.
1829 * The RHS is again broken into an int part and frac part.
1830 * and the frac part is added into *leftover.
1831 */
1832 dnum = PyFloat_AsDouble(num);
1833 if (dnum == -1.0 && PyErr_Occurred())
1834 return NULL;
1835 fracpart = modf(dnum, &intpart);
1836 x = PyLong_FromDouble(intpart);
1837 if (x == NULL)
1838 return NULL;
1839
1840 prod = PyNumber_Multiply(x, factor);
1841 Py_DECREF(x);
1842 if (prod == NULL)
1843 return NULL;
1844
1845 sum = PyNumber_Add(sofar, prod);
1846 Py_DECREF(prod);
1847 if (sum == NULL)
1848 return NULL;
1849
1850 if (fracpart == 0.0)
1851 return sum;
1852 /* So far we've lost no information. Dealing with the
1853 * fractional part requires float arithmetic, and may
1854 * lose a little info.
1855 */
1856 assert(PyInt_Check(factor) || PyLong_Check(factor));
1857 if (PyInt_Check(factor))
1858 dnum = (double)PyInt_AsLong(factor);
1859 else
1860 dnum = PyLong_AsDouble(factor);
1861
1862 dnum *= fracpart;
1863 fracpart = modf(dnum, &intpart);
1864 x = PyLong_FromDouble(intpart);
1865 if (x == NULL) {
1866 Py_DECREF(sum);
1867 return NULL;
1868 }
1869
1870 y = PyNumber_Add(sum, x);
1871 Py_DECREF(sum);
1872 Py_DECREF(x);
1873 *leftover += fracpart;
1874 return y;
1875 }
1876
1877 PyErr_Format(PyExc_TypeError,
1878 "unsupported type for timedelta %s component: %s",
Christian Heimese93237d2007-12-19 02:37:44 +00001879 tag, Py_TYPE(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001880 return NULL;
1881}
1882
1883static PyObject *
1884delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1885{
1886 PyObject *self = NULL;
1887
1888 /* Argument objects. */
1889 PyObject *day = NULL;
1890 PyObject *second = NULL;
1891 PyObject *us = NULL;
1892 PyObject *ms = NULL;
1893 PyObject *minute = NULL;
1894 PyObject *hour = NULL;
1895 PyObject *week = NULL;
1896
1897 PyObject *x = NULL; /* running sum of microseconds */
1898 PyObject *y = NULL; /* temp sum of microseconds */
1899 double leftover_us = 0.0;
1900
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001901 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001902 "days", "seconds", "microseconds", "milliseconds",
1903 "minutes", "hours", "weeks", NULL
1904 };
1905
1906 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1907 keywords,
1908 &day, &second, &us,
1909 &ms, &minute, &hour, &week) == 0)
1910 goto Done;
1911
1912 x = PyInt_FromLong(0);
1913 if (x == NULL)
1914 goto Done;
1915
1916#define CLEANUP \
1917 Py_DECREF(x); \
1918 x = y; \
1919 if (x == NULL) \
1920 goto Done
1921
1922 if (us) {
1923 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1924 CLEANUP;
1925 }
1926 if (ms) {
1927 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1928 CLEANUP;
1929 }
1930 if (second) {
1931 y = accum("seconds", x, second, us_per_second, &leftover_us);
1932 CLEANUP;
1933 }
1934 if (minute) {
1935 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1936 CLEANUP;
1937 }
1938 if (hour) {
1939 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1940 CLEANUP;
1941 }
1942 if (day) {
1943 y = accum("days", x, day, us_per_day, &leftover_us);
1944 CLEANUP;
1945 }
1946 if (week) {
1947 y = accum("weeks", x, week, us_per_week, &leftover_us);
1948 CLEANUP;
1949 }
1950 if (leftover_us) {
1951 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001952 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001953 if (temp == NULL) {
1954 Py_DECREF(x);
1955 goto Done;
1956 }
1957 y = PyNumber_Add(x, temp);
1958 Py_DECREF(temp);
1959 CLEANUP;
1960 }
1961
Tim Petersb0c854d2003-05-17 15:57:00 +00001962 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001963 Py_DECREF(x);
1964Done:
1965 return self;
1966
1967#undef CLEANUP
1968}
1969
1970static int
1971delta_nonzero(PyDateTime_Delta *self)
1972{
1973 return (GET_TD_DAYS(self) != 0
1974 || GET_TD_SECONDS(self) != 0
1975 || GET_TD_MICROSECONDS(self) != 0);
1976}
1977
1978static PyObject *
1979delta_repr(PyDateTime_Delta *self)
1980{
1981 if (GET_TD_MICROSECONDS(self) != 0)
1982 return PyString_FromFormat("%s(%d, %d, %d)",
Christian Heimese93237d2007-12-19 02:37:44 +00001983 Py_TYPE(self)->tp_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00001984 GET_TD_DAYS(self),
1985 GET_TD_SECONDS(self),
1986 GET_TD_MICROSECONDS(self));
1987 if (GET_TD_SECONDS(self) != 0)
1988 return PyString_FromFormat("%s(%d, %d)",
Christian Heimese93237d2007-12-19 02:37:44 +00001989 Py_TYPE(self)->tp_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00001990 GET_TD_DAYS(self),
1991 GET_TD_SECONDS(self));
1992
1993 return PyString_FromFormat("%s(%d)",
Christian Heimese93237d2007-12-19 02:37:44 +00001994 Py_TYPE(self)->tp_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00001995 GET_TD_DAYS(self));
1996}
1997
1998static PyObject *
1999delta_str(PyDateTime_Delta *self)
2000{
2001 int days = GET_TD_DAYS(self);
2002 int seconds = GET_TD_SECONDS(self);
2003 int us = GET_TD_MICROSECONDS(self);
2004 int hours;
2005 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00002006 char buf[100];
2007 char *pbuf = buf;
2008 size_t buflen = sizeof(buf);
2009 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002010
2011 minutes = divmod(seconds, 60, &seconds);
2012 hours = divmod(minutes, 60, &minutes);
2013
2014 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002015 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2016 (days == 1 || days == -1) ? "" : "s");
2017 if (n < 0 || (size_t)n >= buflen)
2018 goto Fail;
2019 pbuf += n;
2020 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002021 }
2022
Tim Petersba873472002-12-18 20:19:21 +00002023 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2024 hours, minutes, seconds);
2025 if (n < 0 || (size_t)n >= buflen)
2026 goto Fail;
2027 pbuf += n;
2028 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002029
2030 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002031 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2032 if (n < 0 || (size_t)n >= buflen)
2033 goto Fail;
2034 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002035 }
2036
Tim Petersba873472002-12-18 20:19:21 +00002037 return PyString_FromStringAndSize(buf, pbuf - buf);
2038
2039 Fail:
2040 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2041 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002042}
2043
Tim Peters371935f2003-02-01 01:52:50 +00002044/* Pickle support, a simple use of __reduce__. */
2045
Tim Petersb57f8f02003-02-01 02:54:15 +00002046/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002047static PyObject *
2048delta_getstate(PyDateTime_Delta *self)
2049{
2050 return Py_BuildValue("iii", GET_TD_DAYS(self),
2051 GET_TD_SECONDS(self),
2052 GET_TD_MICROSECONDS(self));
2053}
2054
Tim Peters2a799bf2002-12-16 20:18:38 +00002055static PyObject *
2056delta_reduce(PyDateTime_Delta* self)
2057{
Christian Heimese93237d2007-12-19 02:37:44 +00002058 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002059}
2060
2061#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2062
2063static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002064
Neal Norwitzdfb80862002-12-19 02:30:56 +00002065 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002066 PyDoc_STR("Number of days.")},
2067
Neal Norwitzdfb80862002-12-19 02:30:56 +00002068 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002069 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2070
Neal Norwitzdfb80862002-12-19 02:30:56 +00002071 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002072 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2073 {NULL}
2074};
2075
2076static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002077 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2078 PyDoc_STR("__reduce__() -> (cls, state)")},
2079
Tim Peters2a799bf2002-12-16 20:18:38 +00002080 {NULL, NULL},
2081};
2082
2083static char delta_doc[] =
2084PyDoc_STR("Difference between two datetime values.");
2085
2086static PyNumberMethods delta_as_number = {
2087 delta_add, /* nb_add */
2088 delta_subtract, /* nb_subtract */
2089 delta_multiply, /* nb_multiply */
2090 delta_divide, /* nb_divide */
2091 0, /* nb_remainder */
2092 0, /* nb_divmod */
2093 0, /* nb_power */
2094 (unaryfunc)delta_negative, /* nb_negative */
2095 (unaryfunc)delta_positive, /* nb_positive */
2096 (unaryfunc)delta_abs, /* nb_absolute */
2097 (inquiry)delta_nonzero, /* nb_nonzero */
2098 0, /*nb_invert*/
2099 0, /*nb_lshift*/
2100 0, /*nb_rshift*/
2101 0, /*nb_and*/
2102 0, /*nb_xor*/
2103 0, /*nb_or*/
2104 0, /*nb_coerce*/
2105 0, /*nb_int*/
2106 0, /*nb_long*/
2107 0, /*nb_float*/
2108 0, /*nb_oct*/
2109 0, /*nb_hex*/
2110 0, /*nb_inplace_add*/
2111 0, /*nb_inplace_subtract*/
2112 0, /*nb_inplace_multiply*/
2113 0, /*nb_inplace_divide*/
2114 0, /*nb_inplace_remainder*/
2115 0, /*nb_inplace_power*/
2116 0, /*nb_inplace_lshift*/
2117 0, /*nb_inplace_rshift*/
2118 0, /*nb_inplace_and*/
2119 0, /*nb_inplace_xor*/
2120 0, /*nb_inplace_or*/
2121 delta_divide, /* nb_floor_divide */
2122 0, /* nb_true_divide */
2123 0, /* nb_inplace_floor_divide */
2124 0, /* nb_inplace_true_divide */
2125};
2126
2127static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002128 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002129 "datetime.timedelta", /* tp_name */
2130 sizeof(PyDateTime_Delta), /* tp_basicsize */
2131 0, /* tp_itemsize */
2132 0, /* tp_dealloc */
2133 0, /* tp_print */
2134 0, /* tp_getattr */
2135 0, /* tp_setattr */
2136 0, /* tp_compare */
2137 (reprfunc)delta_repr, /* tp_repr */
2138 &delta_as_number, /* tp_as_number */
2139 0, /* tp_as_sequence */
2140 0, /* tp_as_mapping */
2141 (hashfunc)delta_hash, /* tp_hash */
2142 0, /* tp_call */
2143 (reprfunc)delta_str, /* tp_str */
2144 PyObject_GenericGetAttr, /* tp_getattro */
2145 0, /* tp_setattro */
2146 0, /* tp_as_buffer */
Tim Petersb0c854d2003-05-17 15:57:00 +00002147 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2148 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002149 delta_doc, /* tp_doc */
2150 0, /* tp_traverse */
2151 0, /* tp_clear */
2152 (richcmpfunc)delta_richcompare, /* tp_richcompare */
2153 0, /* tp_weaklistoffset */
2154 0, /* tp_iter */
2155 0, /* tp_iternext */
2156 delta_methods, /* tp_methods */
2157 delta_members, /* tp_members */
2158 0, /* tp_getset */
2159 0, /* tp_base */
2160 0, /* tp_dict */
2161 0, /* tp_descr_get */
2162 0, /* tp_descr_set */
2163 0, /* tp_dictoffset */
2164 0, /* tp_init */
2165 0, /* tp_alloc */
2166 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002167 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002168};
2169
2170/*
2171 * PyDateTime_Date implementation.
2172 */
2173
2174/* Accessor properties. */
2175
2176static PyObject *
2177date_year(PyDateTime_Date *self, void *unused)
2178{
2179 return PyInt_FromLong(GET_YEAR(self));
2180}
2181
2182static PyObject *
2183date_month(PyDateTime_Date *self, void *unused)
2184{
2185 return PyInt_FromLong(GET_MONTH(self));
2186}
2187
2188static PyObject *
2189date_day(PyDateTime_Date *self, void *unused)
2190{
2191 return PyInt_FromLong(GET_DAY(self));
2192}
2193
2194static PyGetSetDef date_getset[] = {
2195 {"year", (getter)date_year},
2196 {"month", (getter)date_month},
2197 {"day", (getter)date_day},
2198 {NULL}
2199};
2200
2201/* Constructors. */
2202
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002203static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002204
Tim Peters2a799bf2002-12-16 20:18:38 +00002205static PyObject *
2206date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2207{
2208 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002209 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002210 int year;
2211 int month;
2212 int day;
2213
Guido van Rossum177e41a2003-01-30 22:06:23 +00002214 /* Check for invocation from pickle with __getstate__ state */
2215 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002216 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002217 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2218 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002219 {
Tim Peters70533e22003-02-01 04:40:04 +00002220 PyDateTime_Date *me;
2221
Tim Peters604c0132004-06-07 23:04:33 +00002222 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002223 if (me != NULL) {
2224 char *pdata = PyString_AS_STRING(state);
2225 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2226 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002227 }
Tim Peters70533e22003-02-01 04:40:04 +00002228 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002229 }
2230
Tim Peters12bf3392002-12-24 05:41:27 +00002231 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002232 &year, &month, &day)) {
2233 if (check_date_args(year, month, day) < 0)
2234 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002235 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002236 }
2237 return self;
2238}
2239
2240/* Return new date from localtime(t). */
2241static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002242date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002243{
2244 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002245 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002246 PyObject *result = NULL;
2247
Tim Peters1b6f7a92004-06-20 02:50:16 +00002248 t = _PyTime_DoubleToTimet(ts);
2249 if (t == (time_t)-1 && PyErr_Occurred())
2250 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002251 tm = localtime(&t);
2252 if (tm)
2253 result = PyObject_CallFunction(cls, "iii",
2254 tm->tm_year + 1900,
2255 tm->tm_mon + 1,
2256 tm->tm_mday);
2257 else
2258 PyErr_SetString(PyExc_ValueError,
2259 "timestamp out of range for "
2260 "platform localtime() function");
2261 return result;
2262}
2263
2264/* Return new date from current time.
2265 * We say this is equivalent to fromtimestamp(time.time()), and the
2266 * only way to be sure of that is to *call* time.time(). That's not
2267 * generally the same as calling C's time.
2268 */
2269static PyObject *
2270date_today(PyObject *cls, PyObject *dummy)
2271{
2272 PyObject *time;
2273 PyObject *result;
2274
2275 time = time_time();
2276 if (time == NULL)
2277 return NULL;
2278
2279 /* Note well: today() is a class method, so this may not call
2280 * date.fromtimestamp. For example, it may call
2281 * datetime.fromtimestamp. That's why we need all the accuracy
2282 * time.time() delivers; if someone were gonzo about optimization,
2283 * date.today() could get away with plain C time().
2284 */
2285 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2286 Py_DECREF(time);
2287 return result;
2288}
2289
2290/* Return new date from given timestamp (Python timestamp -- a double). */
2291static PyObject *
2292date_fromtimestamp(PyObject *cls, PyObject *args)
2293{
2294 double timestamp;
2295 PyObject *result = NULL;
2296
2297 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002298 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002299 return result;
2300}
2301
2302/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2303 * the ordinal is out of range.
2304 */
2305static PyObject *
2306date_fromordinal(PyObject *cls, PyObject *args)
2307{
2308 PyObject *result = NULL;
2309 int ordinal;
2310
2311 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2312 int year;
2313 int month;
2314 int day;
2315
2316 if (ordinal < 1)
2317 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2318 ">= 1");
2319 else {
2320 ord_to_ymd(ordinal, &year, &month, &day);
2321 result = PyObject_CallFunction(cls, "iii",
2322 year, month, day);
2323 }
2324 }
2325 return result;
2326}
2327
2328/*
2329 * Date arithmetic.
2330 */
2331
2332/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2333 * instead.
2334 */
2335static PyObject *
2336add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2337{
2338 PyObject *result = NULL;
2339 int year = GET_YEAR(date);
2340 int month = GET_MONTH(date);
2341 int deltadays = GET_TD_DAYS(delta);
2342 /* C-level overflow is impossible because |deltadays| < 1e9. */
2343 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2344
2345 if (normalize_date(&year, &month, &day) >= 0)
2346 result = new_date(year, month, day);
2347 return result;
2348}
2349
2350static PyObject *
2351date_add(PyObject *left, PyObject *right)
2352{
2353 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2354 Py_INCREF(Py_NotImplemented);
2355 return Py_NotImplemented;
2356 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002357 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002358 /* date + ??? */
2359 if (PyDelta_Check(right))
2360 /* date + delta */
2361 return add_date_timedelta((PyDateTime_Date *) left,
2362 (PyDateTime_Delta *) right,
2363 0);
2364 }
2365 else {
2366 /* ??? + date
2367 * 'right' must be one of us, or we wouldn't have been called
2368 */
2369 if (PyDelta_Check(left))
2370 /* delta + date */
2371 return add_date_timedelta((PyDateTime_Date *) right,
2372 (PyDateTime_Delta *) left,
2373 0);
2374 }
2375 Py_INCREF(Py_NotImplemented);
2376 return Py_NotImplemented;
2377}
2378
2379static PyObject *
2380date_subtract(PyObject *left, PyObject *right)
2381{
2382 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2383 Py_INCREF(Py_NotImplemented);
2384 return Py_NotImplemented;
2385 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002386 if (PyDate_Check(left)) {
2387 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002388 /* date - date */
2389 int left_ord = ymd_to_ord(GET_YEAR(left),
2390 GET_MONTH(left),
2391 GET_DAY(left));
2392 int right_ord = ymd_to_ord(GET_YEAR(right),
2393 GET_MONTH(right),
2394 GET_DAY(right));
2395 return new_delta(left_ord - right_ord, 0, 0, 0);
2396 }
2397 if (PyDelta_Check(right)) {
2398 /* date - delta */
2399 return add_date_timedelta((PyDateTime_Date *) left,
2400 (PyDateTime_Delta *) right,
2401 1);
2402 }
2403 }
2404 Py_INCREF(Py_NotImplemented);
2405 return Py_NotImplemented;
2406}
2407
2408
2409/* Various ways to turn a date into a string. */
2410
2411static PyObject *
2412date_repr(PyDateTime_Date *self)
2413{
2414 char buffer[1028];
Skip Montanaro14f88992006-04-18 19:35:04 +00002415 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002416
Christian Heimese93237d2007-12-19 02:37:44 +00002417 type_name = Py_TYPE(self)->tp_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002418 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00002419 type_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002420 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2421
2422 return PyString_FromString(buffer);
2423}
2424
2425static PyObject *
2426date_isoformat(PyDateTime_Date *self)
2427{
2428 char buffer[128];
2429
2430 isoformat_date(self, buffer, sizeof(buffer));
2431 return PyString_FromString(buffer);
2432}
2433
Tim Peterse2df5ff2003-05-02 18:39:55 +00002434/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002435static PyObject *
2436date_str(PyDateTime_Date *self)
2437{
2438 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2439}
2440
2441
2442static PyObject *
2443date_ctime(PyDateTime_Date *self)
2444{
2445 return format_ctime(self, 0, 0, 0);
2446}
2447
2448static PyObject *
2449date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2450{
2451 /* This method can be inherited, and needs to call the
2452 * timetuple() method appropriate to self's class.
2453 */
2454 PyObject *result;
2455 PyObject *format;
2456 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002457 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002458
2459 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2460 &PyString_Type, &format))
2461 return NULL;
2462
2463 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2464 if (tuple == NULL)
2465 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002466 result = wrap_strftime((PyObject *)self, format, tuple,
2467 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002468 Py_DECREF(tuple);
2469 return result;
2470}
2471
Eric Smitha9f7d622008-02-17 19:46:49 +00002472static PyObject *
2473date_format(PyDateTime_Date *self, PyObject *args)
2474{
2475 PyObject *format;
2476
2477 if (!PyArg_ParseTuple(args, "O:__format__", &format))
2478 return NULL;
2479
2480 /* Check for str or unicode */
2481 if (PyString_Check(format)) {
2482 /* If format is zero length, return str(self) */
2483 if (PyString_GET_SIZE(format) == 0)
2484 return PyObject_Str((PyObject *)self);
2485 } else if (PyUnicode_Check(format)) {
2486 /* If format is zero length, return str(self) */
2487 if (PyUnicode_GET_SIZE(format) == 0)
2488 return PyObject_Unicode((PyObject *)self);
2489 } else {
2490 PyErr_Format(PyExc_ValueError,
2491 "__format__ expects str or unicode, not %.200s",
2492 Py_TYPE(format)->tp_name);
2493 return NULL;
2494 }
2495 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
2496}
2497
Tim Peters2a799bf2002-12-16 20:18:38 +00002498/* ISO methods. */
2499
2500static PyObject *
2501date_isoweekday(PyDateTime_Date *self)
2502{
2503 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2504
2505 return PyInt_FromLong(dow + 1);
2506}
2507
2508static PyObject *
2509date_isocalendar(PyDateTime_Date *self)
2510{
2511 int year = GET_YEAR(self);
2512 int week1_monday = iso_week1_monday(year);
2513 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2514 int week;
2515 int day;
2516
2517 week = divmod(today - week1_monday, 7, &day);
2518 if (week < 0) {
2519 --year;
2520 week1_monday = iso_week1_monday(year);
2521 week = divmod(today - week1_monday, 7, &day);
2522 }
2523 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2524 ++year;
2525 week = 0;
2526 }
2527 return Py_BuildValue("iii", year, week + 1, day + 1);
2528}
2529
2530/* Miscellaneous methods. */
2531
2532/* This is more natural as a tp_compare, but doesn't work then: for whatever
2533 * reason, Python's try_3way_compare ignores tp_compare unless
2534 * PyInstance_Check returns true, but these aren't old-style classes.
2535 */
2536static PyObject *
2537date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2538{
Tim Peters07534a62003-02-07 22:50:28 +00002539 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00002540
Tim Peters07534a62003-02-07 22:50:28 +00002541 if (PyDate_Check(other))
2542 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2543 _PyDateTime_DATE_DATASIZE);
2544
2545 else if (PyObject_HasAttrString(other, "timetuple")) {
2546 /* A hook for other kinds of date objects. */
2547 Py_INCREF(Py_NotImplemented);
2548 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002549 }
Tim Peters07534a62003-02-07 22:50:28 +00002550 else if (op == Py_EQ || op == Py_NE)
2551 diff = 1; /* any non-zero value will do */
2552
2553 else /* stop this from falling back to address comparison */
2554 return cmperror((PyObject *)self, other);
2555
Tim Peters2a799bf2002-12-16 20:18:38 +00002556 return diff_to_bool(diff, op);
2557}
2558
2559static PyObject *
2560date_timetuple(PyDateTime_Date *self)
2561{
2562 return build_struct_time(GET_YEAR(self),
2563 GET_MONTH(self),
2564 GET_DAY(self),
2565 0, 0, 0, -1);
2566}
2567
Tim Peters12bf3392002-12-24 05:41:27 +00002568static PyObject *
2569date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2570{
2571 PyObject *clone;
2572 PyObject *tuple;
2573 int year = GET_YEAR(self);
2574 int month = GET_MONTH(self);
2575 int day = GET_DAY(self);
2576
2577 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2578 &year, &month, &day))
2579 return NULL;
2580 tuple = Py_BuildValue("iii", year, month, day);
2581 if (tuple == NULL)
2582 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002583 clone = date_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002584 Py_DECREF(tuple);
2585 return clone;
2586}
2587
Tim Peters2a799bf2002-12-16 20:18:38 +00002588static PyObject *date_getstate(PyDateTime_Date *self);
2589
2590static long
2591date_hash(PyDateTime_Date *self)
2592{
2593 if (self->hashcode == -1) {
2594 PyObject *temp = date_getstate(self);
2595 if (temp != NULL) {
2596 self->hashcode = PyObject_Hash(temp);
2597 Py_DECREF(temp);
2598 }
2599 }
2600 return self->hashcode;
2601}
2602
2603static PyObject *
2604date_toordinal(PyDateTime_Date *self)
2605{
2606 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2607 GET_DAY(self)));
2608}
2609
2610static PyObject *
2611date_weekday(PyDateTime_Date *self)
2612{
2613 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2614
2615 return PyInt_FromLong(dow);
2616}
2617
Tim Peters371935f2003-02-01 01:52:50 +00002618/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002619
Tim Petersb57f8f02003-02-01 02:54:15 +00002620/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002621static PyObject *
2622date_getstate(PyDateTime_Date *self)
2623{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002624 return Py_BuildValue(
2625 "(N)",
2626 PyString_FromStringAndSize((char *)self->data,
2627 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002628}
2629
2630static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002631date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002632{
Christian Heimese93237d2007-12-19 02:37:44 +00002633 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002634}
2635
2636static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002637
Tim Peters2a799bf2002-12-16 20:18:38 +00002638 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002639
Tim Peters2a799bf2002-12-16 20:18:38 +00002640 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2641 METH_CLASS,
2642 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2643 "time.time()).")},
2644
2645 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2646 METH_CLASS,
2647 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2648 "ordinal.")},
2649
2650 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2651 PyDoc_STR("Current date or datetime: same as "
2652 "self.__class__.fromtimestamp(time.time()).")},
2653
2654 /* Instance methods: */
2655
2656 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2657 PyDoc_STR("Return ctime() style string.")},
2658
Neal Norwitza84dcd72007-05-22 07:16:44 +00002659 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002660 PyDoc_STR("format -> strftime() style string.")},
2661
Eric Smitha9f7d622008-02-17 19:46:49 +00002662 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2663 PyDoc_STR("Formats self with strftime.")},
2664
Tim Peters2a799bf2002-12-16 20:18:38 +00002665 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2666 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2667
2668 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2669 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2670 "weekday.")},
2671
2672 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2673 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2674
2675 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2676 PyDoc_STR("Return the day of the week represented by the date.\n"
2677 "Monday == 1 ... Sunday == 7")},
2678
2679 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2680 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2681 "1 is day 1.")},
2682
2683 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2684 PyDoc_STR("Return the day of the week represented by the date.\n"
2685 "Monday == 0 ... Sunday == 6")},
2686
Neal Norwitza84dcd72007-05-22 07:16:44 +00002687 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002688 PyDoc_STR("Return date with new specified fields.")},
2689
Guido van Rossum177e41a2003-01-30 22:06:23 +00002690 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2691 PyDoc_STR("__reduce__() -> (cls, state)")},
2692
Tim Peters2a799bf2002-12-16 20:18:38 +00002693 {NULL, NULL}
2694};
2695
2696static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002697PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002698
2699static PyNumberMethods date_as_number = {
2700 date_add, /* nb_add */
2701 date_subtract, /* nb_subtract */
2702 0, /* nb_multiply */
2703 0, /* nb_divide */
2704 0, /* nb_remainder */
2705 0, /* nb_divmod */
2706 0, /* nb_power */
2707 0, /* nb_negative */
2708 0, /* nb_positive */
2709 0, /* nb_absolute */
2710 0, /* nb_nonzero */
2711};
2712
2713static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002714 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002715 "datetime.date", /* tp_name */
2716 sizeof(PyDateTime_Date), /* tp_basicsize */
2717 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002718 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002719 0, /* tp_print */
2720 0, /* tp_getattr */
2721 0, /* tp_setattr */
2722 0, /* tp_compare */
2723 (reprfunc)date_repr, /* tp_repr */
2724 &date_as_number, /* tp_as_number */
2725 0, /* tp_as_sequence */
2726 0, /* tp_as_mapping */
2727 (hashfunc)date_hash, /* tp_hash */
2728 0, /* tp_call */
2729 (reprfunc)date_str, /* tp_str */
2730 PyObject_GenericGetAttr, /* tp_getattro */
2731 0, /* tp_setattro */
2732 0, /* tp_as_buffer */
2733 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2734 Py_TPFLAGS_BASETYPE, /* tp_flags */
2735 date_doc, /* tp_doc */
2736 0, /* tp_traverse */
2737 0, /* tp_clear */
2738 (richcmpfunc)date_richcompare, /* tp_richcompare */
2739 0, /* tp_weaklistoffset */
2740 0, /* tp_iter */
2741 0, /* tp_iternext */
2742 date_methods, /* tp_methods */
2743 0, /* tp_members */
2744 date_getset, /* tp_getset */
2745 0, /* tp_base */
2746 0, /* tp_dict */
2747 0, /* tp_descr_get */
2748 0, /* tp_descr_set */
2749 0, /* tp_dictoffset */
2750 0, /* tp_init */
2751 0, /* tp_alloc */
2752 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002753 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002754};
2755
2756/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002757 * PyDateTime_TZInfo implementation.
2758 */
2759
2760/* This is a pure abstract base class, so doesn't do anything beyond
2761 * raising NotImplemented exceptions. Real tzinfo classes need
2762 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002763 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002764 * be subclasses of this tzinfo class, which is easy and quick to check).
2765 *
2766 * Note: For reasons having to do with pickling of subclasses, we have
2767 * to allow tzinfo objects to be instantiated. This wasn't an issue
2768 * in the Python implementation (__init__() could raise NotImplementedError
2769 * there without ill effect), but doing so in the C implementation hit a
2770 * brick wall.
2771 */
2772
2773static PyObject *
2774tzinfo_nogo(const char* methodname)
2775{
2776 PyErr_Format(PyExc_NotImplementedError,
2777 "a tzinfo subclass must implement %s()",
2778 methodname);
2779 return NULL;
2780}
2781
2782/* Methods. A subclass must implement these. */
2783
Tim Peters52dcce22003-01-23 16:36:11 +00002784static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002785tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2786{
2787 return tzinfo_nogo("tzname");
2788}
2789
Tim Peters52dcce22003-01-23 16:36:11 +00002790static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002791tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2792{
2793 return tzinfo_nogo("utcoffset");
2794}
2795
Tim Peters52dcce22003-01-23 16:36:11 +00002796static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002797tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2798{
2799 return tzinfo_nogo("dst");
2800}
2801
Tim Peters52dcce22003-01-23 16:36:11 +00002802static PyObject *
2803tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2804{
2805 int y, m, d, hh, mm, ss, us;
2806
2807 PyObject *result;
2808 int off, dst;
2809 int none;
2810 int delta;
2811
2812 if (! PyDateTime_Check(dt)) {
2813 PyErr_SetString(PyExc_TypeError,
2814 "fromutc: argument must be a datetime");
2815 return NULL;
2816 }
2817 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2818 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2819 "is not self");
2820 return NULL;
2821 }
2822
2823 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2824 if (off == -1 && PyErr_Occurred())
2825 return NULL;
2826 if (none) {
2827 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2828 "utcoffset() result required");
2829 return NULL;
2830 }
2831
2832 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2833 if (dst == -1 && PyErr_Occurred())
2834 return NULL;
2835 if (none) {
2836 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2837 "dst() result required");
2838 return NULL;
2839 }
2840
2841 y = GET_YEAR(dt);
2842 m = GET_MONTH(dt);
2843 d = GET_DAY(dt);
2844 hh = DATE_GET_HOUR(dt);
2845 mm = DATE_GET_MINUTE(dt);
2846 ss = DATE_GET_SECOND(dt);
2847 us = DATE_GET_MICROSECOND(dt);
2848
2849 delta = off - dst;
2850 mm += delta;
2851 if ((mm < 0 || mm >= 60) &&
2852 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002853 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002854 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2855 if (result == NULL)
2856 return result;
2857
2858 dst = call_dst(dt->tzinfo, result, &none);
2859 if (dst == -1 && PyErr_Occurred())
2860 goto Fail;
2861 if (none)
2862 goto Inconsistent;
2863 if (dst == 0)
2864 return result;
2865
2866 mm += dst;
2867 if ((mm < 0 || mm >= 60) &&
2868 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2869 goto Fail;
2870 Py_DECREF(result);
2871 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2872 return result;
2873
2874Inconsistent:
2875 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2876 "inconsistent results; cannot convert");
2877
2878 /* fall thru to failure */
2879Fail:
2880 Py_DECREF(result);
2881 return NULL;
2882}
2883
Tim Peters2a799bf2002-12-16 20:18:38 +00002884/*
2885 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002886 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002887 */
2888
Guido van Rossum177e41a2003-01-30 22:06:23 +00002889static PyObject *
2890tzinfo_reduce(PyObject *self)
2891{
2892 PyObject *args, *state, *tmp;
2893 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002894
Guido van Rossum177e41a2003-01-30 22:06:23 +00002895 tmp = PyTuple_New(0);
2896 if (tmp == NULL)
2897 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002898
Guido van Rossum177e41a2003-01-30 22:06:23 +00002899 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2900 if (getinitargs != NULL) {
2901 args = PyObject_CallObject(getinitargs, tmp);
2902 Py_DECREF(getinitargs);
2903 if (args == NULL) {
2904 Py_DECREF(tmp);
2905 return NULL;
2906 }
2907 }
2908 else {
2909 PyErr_Clear();
2910 args = tmp;
2911 Py_INCREF(args);
2912 }
2913
2914 getstate = PyObject_GetAttrString(self, "__getstate__");
2915 if (getstate != NULL) {
2916 state = PyObject_CallObject(getstate, tmp);
2917 Py_DECREF(getstate);
2918 if (state == NULL) {
2919 Py_DECREF(args);
2920 Py_DECREF(tmp);
2921 return NULL;
2922 }
2923 }
2924 else {
2925 PyObject **dictptr;
2926 PyErr_Clear();
2927 state = Py_None;
2928 dictptr = _PyObject_GetDictPtr(self);
2929 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2930 state = *dictptr;
2931 Py_INCREF(state);
2932 }
2933
2934 Py_DECREF(tmp);
2935
2936 if (state == Py_None) {
2937 Py_DECREF(state);
Christian Heimese93237d2007-12-19 02:37:44 +00002938 return Py_BuildValue("(ON)", Py_TYPE(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002939 }
2940 else
Christian Heimese93237d2007-12-19 02:37:44 +00002941 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002942}
Tim Peters2a799bf2002-12-16 20:18:38 +00002943
2944static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002945
Tim Peters2a799bf2002-12-16 20:18:38 +00002946 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2947 PyDoc_STR("datetime -> string name of time zone.")},
2948
2949 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2950 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2951 "west of UTC).")},
2952
2953 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2954 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2955
Tim Peters52dcce22003-01-23 16:36:11 +00002956 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2957 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2958
Guido van Rossum177e41a2003-01-30 22:06:23 +00002959 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2960 PyDoc_STR("-> (cls, state)")},
2961
Tim Peters2a799bf2002-12-16 20:18:38 +00002962 {NULL, NULL}
2963};
2964
2965static char tzinfo_doc[] =
2966PyDoc_STR("Abstract base class for time zone info objects.");
2967
Neal Norwitzce3d34d2003-02-04 20:45:17 +00002968statichere PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002969 PyObject_HEAD_INIT(NULL)
2970 0, /* ob_size */
2971 "datetime.tzinfo", /* tp_name */
2972 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2973 0, /* tp_itemsize */
2974 0, /* tp_dealloc */
2975 0, /* tp_print */
2976 0, /* tp_getattr */
2977 0, /* tp_setattr */
2978 0, /* tp_compare */
2979 0, /* tp_repr */
2980 0, /* tp_as_number */
2981 0, /* tp_as_sequence */
2982 0, /* tp_as_mapping */
2983 0, /* tp_hash */
2984 0, /* tp_call */
2985 0, /* tp_str */
2986 PyObject_GenericGetAttr, /* tp_getattro */
2987 0, /* tp_setattro */
2988 0, /* tp_as_buffer */
2989 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2990 Py_TPFLAGS_BASETYPE, /* tp_flags */
2991 tzinfo_doc, /* tp_doc */
2992 0, /* tp_traverse */
2993 0, /* tp_clear */
2994 0, /* tp_richcompare */
2995 0, /* tp_weaklistoffset */
2996 0, /* tp_iter */
2997 0, /* tp_iternext */
2998 tzinfo_methods, /* tp_methods */
2999 0, /* tp_members */
3000 0, /* tp_getset */
3001 0, /* tp_base */
3002 0, /* tp_dict */
3003 0, /* tp_descr_get */
3004 0, /* tp_descr_set */
3005 0, /* tp_dictoffset */
3006 0, /* tp_init */
3007 0, /* tp_alloc */
3008 PyType_GenericNew, /* tp_new */
3009 0, /* tp_free */
3010};
3011
3012/*
Tim Peters37f39822003-01-10 03:49:02 +00003013 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003014 */
3015
Tim Peters37f39822003-01-10 03:49:02 +00003016/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003017 */
3018
3019static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003020time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003021{
Tim Peters37f39822003-01-10 03:49:02 +00003022 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003023}
3024
Tim Peters37f39822003-01-10 03:49:02 +00003025static PyObject *
3026time_minute(PyDateTime_Time *self, void *unused)
3027{
3028 return PyInt_FromLong(TIME_GET_MINUTE(self));
3029}
3030
3031/* The name time_second conflicted with some platform header file. */
3032static PyObject *
3033py_time_second(PyDateTime_Time *self, void *unused)
3034{
3035 return PyInt_FromLong(TIME_GET_SECOND(self));
3036}
3037
3038static PyObject *
3039time_microsecond(PyDateTime_Time *self, void *unused)
3040{
3041 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3042}
3043
3044static PyObject *
3045time_tzinfo(PyDateTime_Time *self, void *unused)
3046{
Tim Petersa032d2e2003-01-11 00:15:54 +00003047 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003048 Py_INCREF(result);
3049 return result;
3050}
3051
3052static PyGetSetDef time_getset[] = {
3053 {"hour", (getter)time_hour},
3054 {"minute", (getter)time_minute},
3055 {"second", (getter)py_time_second},
3056 {"microsecond", (getter)time_microsecond},
3057 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003058 {NULL}
3059};
3060
3061/*
3062 * Constructors.
3063 */
3064
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003065static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003066 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003067
Tim Peters2a799bf2002-12-16 20:18:38 +00003068static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003069time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003070{
3071 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003072 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003073 int hour = 0;
3074 int minute = 0;
3075 int second = 0;
3076 int usecond = 0;
3077 PyObject *tzinfo = Py_None;
3078
Guido van Rossum177e41a2003-01-30 22:06:23 +00003079 /* Check for invocation from pickle with __getstate__ state */
3080 if (PyTuple_GET_SIZE(args) >= 1 &&
3081 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003082 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003083 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3084 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003085 {
Tim Peters70533e22003-02-01 04:40:04 +00003086 PyDateTime_Time *me;
3087 char aware;
3088
3089 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003090 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003091 if (check_tzinfo_subclass(tzinfo) < 0) {
3092 PyErr_SetString(PyExc_TypeError, "bad "
3093 "tzinfo state arg");
3094 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003095 }
3096 }
Tim Peters70533e22003-02-01 04:40:04 +00003097 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003098 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003099 if (me != NULL) {
3100 char *pdata = PyString_AS_STRING(state);
3101
3102 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3103 me->hashcode = -1;
3104 me->hastzinfo = aware;
3105 if (aware) {
3106 Py_INCREF(tzinfo);
3107 me->tzinfo = tzinfo;
3108 }
3109 }
3110 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003111 }
3112
Tim Peters37f39822003-01-10 03:49:02 +00003113 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003114 &hour, &minute, &second, &usecond,
3115 &tzinfo)) {
3116 if (check_time_args(hour, minute, second, usecond) < 0)
3117 return NULL;
3118 if (check_tzinfo_subclass(tzinfo) < 0)
3119 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003120 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3121 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003122 }
3123 return self;
3124}
3125
3126/*
3127 * Destructor.
3128 */
3129
3130static void
Tim Peters37f39822003-01-10 03:49:02 +00003131time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003132{
Tim Petersa032d2e2003-01-11 00:15:54 +00003133 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003134 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003135 }
Christian Heimese93237d2007-12-19 02:37:44 +00003136 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003137}
3138
3139/*
Tim Peters855fe882002-12-22 03:43:39 +00003140 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003141 */
3142
Tim Peters2a799bf2002-12-16 20:18:38 +00003143/* These are all METH_NOARGS, so don't need to check the arglist. */
3144static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003145time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003146 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003147 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003148}
3149
3150static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003151time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003152 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003153 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003154}
3155
3156static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003157time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003158 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003159 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003160}
3161
3162/*
Tim Peters37f39822003-01-10 03:49:02 +00003163 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003164 */
3165
3166static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003167time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003168{
Tim Peters37f39822003-01-10 03:49:02 +00003169 char buffer[100];
Christian Heimese93237d2007-12-19 02:37:44 +00003170 const char *type_name = Py_TYPE(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003171 int h = TIME_GET_HOUR(self);
3172 int m = TIME_GET_MINUTE(self);
3173 int s = TIME_GET_SECOND(self);
3174 int us = TIME_GET_MICROSECOND(self);
3175 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003176
Tim Peters37f39822003-01-10 03:49:02 +00003177 if (us)
3178 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003179 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003180 else if (s)
3181 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003182 "%s(%d, %d, %d)", type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003183 else
3184 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003185 "%s(%d, %d)", type_name, h, m);
Tim Peters37f39822003-01-10 03:49:02 +00003186 result = PyString_FromString(buffer);
Tim Petersa032d2e2003-01-11 00:15:54 +00003187 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003188 result = append_keyword_tzinfo(result, self->tzinfo);
3189 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003190}
3191
Tim Peters37f39822003-01-10 03:49:02 +00003192static PyObject *
3193time_str(PyDateTime_Time *self)
3194{
3195 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3196}
Tim Peters2a799bf2002-12-16 20:18:38 +00003197
3198static PyObject *
Martin v. Löwis4c11a922007-02-08 09:13:36 +00003199time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003200{
3201 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003202 PyObject *result;
3203 /* Reuse the time format code from the datetime type. */
3204 PyDateTime_DateTime datetime;
3205 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003206
Tim Peters37f39822003-01-10 03:49:02 +00003207 /* Copy over just the time bytes. */
3208 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3209 self->data,
3210 _PyDateTime_TIME_DATASIZE);
3211
3212 isoformat_time(pdatetime, buf, sizeof(buf));
3213 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003214 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003215 return result;
3216
3217 /* We need to append the UTC offset. */
3218 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003219 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003220 Py_DECREF(result);
3221 return NULL;
3222 }
3223 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3224 return result;
3225}
3226
Tim Peters37f39822003-01-10 03:49:02 +00003227static PyObject *
3228time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3229{
3230 PyObject *result;
3231 PyObject *format;
3232 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003233 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003234
3235 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3236 &PyString_Type, &format))
3237 return NULL;
3238
3239 /* Python's strftime does insane things with the year part of the
3240 * timetuple. The year is forced to (the otherwise nonsensical)
3241 * 1900 to worm around that.
3242 */
3243 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003244 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003245 TIME_GET_HOUR(self),
3246 TIME_GET_MINUTE(self),
3247 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003248 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003249 if (tuple == NULL)
3250 return NULL;
3251 assert(PyTuple_Size(tuple) == 9);
3252 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3253 Py_DECREF(tuple);
3254 return result;
3255}
Tim Peters2a799bf2002-12-16 20:18:38 +00003256
3257/*
3258 * Miscellaneous methods.
3259 */
3260
Tim Peters37f39822003-01-10 03:49:02 +00003261/* This is more natural as a tp_compare, but doesn't work then: for whatever
3262 * reason, Python's try_3way_compare ignores tp_compare unless
3263 * PyInstance_Check returns true, but these aren't old-style classes.
3264 */
3265static PyObject *
3266time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3267{
3268 int diff;
3269 naivety n1, n2;
3270 int offset1, offset2;
3271
3272 if (! PyTime_Check(other)) {
Tim Peters07534a62003-02-07 22:50:28 +00003273 if (op == Py_EQ || op == Py_NE) {
3274 PyObject *result = op == Py_EQ ? Py_False : Py_True;
3275 Py_INCREF(result);
3276 return result;
3277 }
Tim Peters37f39822003-01-10 03:49:02 +00003278 /* Stop this from falling back to address comparison. */
Tim Peters07534a62003-02-07 22:50:28 +00003279 return cmperror((PyObject *)self, other);
Tim Peters37f39822003-01-10 03:49:02 +00003280 }
3281 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
3282 other, &offset2, &n2, Py_None) < 0)
3283 return NULL;
3284 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3285 /* If they're both naive, or both aware and have the same offsets,
3286 * we get off cheap. Note that if they're both naive, offset1 ==
3287 * offset2 == 0 at this point.
3288 */
3289 if (n1 == n2 && offset1 == offset2) {
3290 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3291 _PyDateTime_TIME_DATASIZE);
3292 return diff_to_bool(diff, op);
3293 }
3294
3295 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3296 assert(offset1 != offset2); /* else last "if" handled it */
3297 /* Convert everything except microseconds to seconds. These
3298 * can't overflow (no more than the # of seconds in 2 days).
3299 */
3300 offset1 = TIME_GET_HOUR(self) * 3600 +
3301 (TIME_GET_MINUTE(self) - offset1) * 60 +
3302 TIME_GET_SECOND(self);
3303 offset2 = TIME_GET_HOUR(other) * 3600 +
3304 (TIME_GET_MINUTE(other) - offset2) * 60 +
3305 TIME_GET_SECOND(other);
3306 diff = offset1 - offset2;
3307 if (diff == 0)
3308 diff = TIME_GET_MICROSECOND(self) -
3309 TIME_GET_MICROSECOND(other);
3310 return diff_to_bool(diff, op);
3311 }
3312
3313 assert(n1 != n2);
3314 PyErr_SetString(PyExc_TypeError,
3315 "can't compare offset-naive and "
3316 "offset-aware times");
3317 return NULL;
3318}
3319
3320static long
3321time_hash(PyDateTime_Time *self)
3322{
3323 if (self->hashcode == -1) {
3324 naivety n;
3325 int offset;
3326 PyObject *temp;
3327
3328 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3329 assert(n != OFFSET_UNKNOWN);
3330 if (n == OFFSET_ERROR)
3331 return -1;
3332
3333 /* Reduce this to a hash of another object. */
3334 if (offset == 0)
3335 temp = PyString_FromStringAndSize((char *)self->data,
3336 _PyDateTime_TIME_DATASIZE);
3337 else {
3338 int hour;
3339 int minute;
3340
3341 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003342 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003343 hour = divmod(TIME_GET_HOUR(self) * 60 +
3344 TIME_GET_MINUTE(self) - offset,
3345 60,
3346 &minute);
3347 if (0 <= hour && hour < 24)
3348 temp = new_time(hour, minute,
3349 TIME_GET_SECOND(self),
3350 TIME_GET_MICROSECOND(self),
3351 Py_None);
3352 else
3353 temp = Py_BuildValue("iiii",
3354 hour, minute,
3355 TIME_GET_SECOND(self),
3356 TIME_GET_MICROSECOND(self));
3357 }
3358 if (temp != NULL) {
3359 self->hashcode = PyObject_Hash(temp);
3360 Py_DECREF(temp);
3361 }
3362 }
3363 return self->hashcode;
3364}
Tim Peters2a799bf2002-12-16 20:18:38 +00003365
Tim Peters12bf3392002-12-24 05:41:27 +00003366static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003367time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003368{
3369 PyObject *clone;
3370 PyObject *tuple;
3371 int hh = TIME_GET_HOUR(self);
3372 int mm = TIME_GET_MINUTE(self);
3373 int ss = TIME_GET_SECOND(self);
3374 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003375 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003376
3377 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003378 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003379 &hh, &mm, &ss, &us, &tzinfo))
3380 return NULL;
3381 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3382 if (tuple == NULL)
3383 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00003384 clone = time_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003385 Py_DECREF(tuple);
3386 return clone;
3387}
3388
Tim Peters2a799bf2002-12-16 20:18:38 +00003389static int
Tim Peters37f39822003-01-10 03:49:02 +00003390time_nonzero(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003391{
3392 int offset;
3393 int none;
3394
3395 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3396 /* Since utcoffset is in whole minutes, nothing can
3397 * alter the conclusion that this is nonzero.
3398 */
3399 return 1;
3400 }
3401 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003402 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003403 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003404 if (offset == -1 && PyErr_Occurred())
3405 return -1;
3406 }
3407 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3408}
3409
Tim Peters371935f2003-02-01 01:52:50 +00003410/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003411
Tim Peters33e0f382003-01-10 02:05:14 +00003412/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003413 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3414 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003415 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003416 */
3417static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003418time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003419{
3420 PyObject *basestate;
3421 PyObject *result = NULL;
3422
Tim Peters33e0f382003-01-10 02:05:14 +00003423 basestate = PyString_FromStringAndSize((char *)self->data,
3424 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003425 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003426 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003427 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003429 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003430 Py_DECREF(basestate);
3431 }
3432 return result;
3433}
3434
3435static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003436time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003437{
Christian Heimese93237d2007-12-19 02:37:44 +00003438 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003439}
3440
Tim Peters37f39822003-01-10 03:49:02 +00003441static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003442
Martin v. Löwis4c11a922007-02-08 09:13:36 +00003443 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003444 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3445 "[+HH:MM].")},
3446
Neal Norwitza84dcd72007-05-22 07:16:44 +00003447 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003448 PyDoc_STR("format -> strftime() style string.")},
3449
Eric Smitha9f7d622008-02-17 19:46:49 +00003450 {"__format__", (PyCFunction)date_format, METH_VARARGS,
3451 PyDoc_STR("Formats self with strftime.")},
3452
Tim Peters37f39822003-01-10 03:49:02 +00003453 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003454 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3455
Tim Peters37f39822003-01-10 03:49:02 +00003456 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003457 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3458
Tim Peters37f39822003-01-10 03:49:02 +00003459 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003460 PyDoc_STR("Return self.tzinfo.dst(self).")},
3461
Neal Norwitza84dcd72007-05-22 07:16:44 +00003462 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003463 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003464
Guido van Rossum177e41a2003-01-30 22:06:23 +00003465 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3466 PyDoc_STR("__reduce__() -> (cls, state)")},
3467
Tim Peters2a799bf2002-12-16 20:18:38 +00003468 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003469};
3470
Tim Peters37f39822003-01-10 03:49:02 +00003471static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003472PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3473\n\
3474All arguments are optional. tzinfo may be None, or an instance of\n\
3475a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003476
Tim Peters37f39822003-01-10 03:49:02 +00003477static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003478 0, /* nb_add */
3479 0, /* nb_subtract */
3480 0, /* nb_multiply */
3481 0, /* nb_divide */
3482 0, /* nb_remainder */
3483 0, /* nb_divmod */
3484 0, /* nb_power */
3485 0, /* nb_negative */
3486 0, /* nb_positive */
3487 0, /* nb_absolute */
Tim Peters37f39822003-01-10 03:49:02 +00003488 (inquiry)time_nonzero, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00003489};
3490
Tim Peters37f39822003-01-10 03:49:02 +00003491statichere PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003492 PyObject_HEAD_INIT(NULL)
3493 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003494 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003495 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003496 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003497 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003498 0, /* tp_print */
3499 0, /* tp_getattr */
3500 0, /* tp_setattr */
3501 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003502 (reprfunc)time_repr, /* tp_repr */
3503 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003504 0, /* tp_as_sequence */
3505 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003506 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003507 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003508 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003509 PyObject_GenericGetAttr, /* tp_getattro */
3510 0, /* tp_setattro */
3511 0, /* tp_as_buffer */
3512 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3513 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003514 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003515 0, /* tp_traverse */
3516 0, /* tp_clear */
Tim Peters37f39822003-01-10 03:49:02 +00003517 (richcmpfunc)time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003518 0, /* tp_weaklistoffset */
3519 0, /* tp_iter */
3520 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003521 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003522 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003523 time_getset, /* tp_getset */
3524 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003525 0, /* tp_dict */
3526 0, /* tp_descr_get */
3527 0, /* tp_descr_set */
3528 0, /* tp_dictoffset */
3529 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003530 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003531 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003532 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003533};
3534
3535/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003536 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003537 */
3538
Tim Petersa9bc1682003-01-11 03:39:11 +00003539/* Accessor properties. Properties for day, month, and year are inherited
3540 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003541 */
3542
3543static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003544datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003545{
Tim Petersa9bc1682003-01-11 03:39:11 +00003546 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003547}
3548
Tim Petersa9bc1682003-01-11 03:39:11 +00003549static PyObject *
3550datetime_minute(PyDateTime_DateTime *self, void *unused)
3551{
3552 return PyInt_FromLong(DATE_GET_MINUTE(self));
3553}
3554
3555static PyObject *
3556datetime_second(PyDateTime_DateTime *self, void *unused)
3557{
3558 return PyInt_FromLong(DATE_GET_SECOND(self));
3559}
3560
3561static PyObject *
3562datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3563{
3564 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3565}
3566
3567static PyObject *
3568datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3569{
3570 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3571 Py_INCREF(result);
3572 return result;
3573}
3574
3575static PyGetSetDef datetime_getset[] = {
3576 {"hour", (getter)datetime_hour},
3577 {"minute", (getter)datetime_minute},
3578 {"second", (getter)datetime_second},
3579 {"microsecond", (getter)datetime_microsecond},
3580 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003581 {NULL}
3582};
3583
3584/*
3585 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003586 */
3587
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003588static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003589 "year", "month", "day", "hour", "minute", "second",
3590 "microsecond", "tzinfo", NULL
3591};
3592
Tim Peters2a799bf2002-12-16 20:18:38 +00003593static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003594datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003595{
3596 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003597 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003598 int year;
3599 int month;
3600 int day;
3601 int hour = 0;
3602 int minute = 0;
3603 int second = 0;
3604 int usecond = 0;
3605 PyObject *tzinfo = Py_None;
3606
Guido van Rossum177e41a2003-01-30 22:06:23 +00003607 /* Check for invocation from pickle with __getstate__ state */
3608 if (PyTuple_GET_SIZE(args) >= 1 &&
3609 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003610 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003611 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3612 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003613 {
Tim Peters70533e22003-02-01 04:40:04 +00003614 PyDateTime_DateTime *me;
3615 char aware;
3616
3617 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003618 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003619 if (check_tzinfo_subclass(tzinfo) < 0) {
3620 PyErr_SetString(PyExc_TypeError, "bad "
3621 "tzinfo state arg");
3622 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003623 }
3624 }
Tim Peters70533e22003-02-01 04:40:04 +00003625 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003626 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003627 if (me != NULL) {
3628 char *pdata = PyString_AS_STRING(state);
3629
3630 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3631 me->hashcode = -1;
3632 me->hastzinfo = aware;
3633 if (aware) {
3634 Py_INCREF(tzinfo);
3635 me->tzinfo = tzinfo;
3636 }
3637 }
3638 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003639 }
3640
Tim Petersa9bc1682003-01-11 03:39:11 +00003641 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003642 &year, &month, &day, &hour, &minute,
3643 &second, &usecond, &tzinfo)) {
3644 if (check_date_args(year, month, day) < 0)
3645 return NULL;
3646 if (check_time_args(hour, minute, second, usecond) < 0)
3647 return NULL;
3648 if (check_tzinfo_subclass(tzinfo) < 0)
3649 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003650 self = new_datetime_ex(year, month, day,
3651 hour, minute, second, usecond,
3652 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003653 }
3654 return self;
3655}
3656
Tim Petersa9bc1682003-01-11 03:39:11 +00003657/* TM_FUNC is the shared type of localtime() and gmtime(). */
3658typedef struct tm *(*TM_FUNC)(const time_t *timer);
3659
3660/* Internal helper.
3661 * Build datetime from a time_t and a distinct count of microseconds.
3662 * Pass localtime or gmtime for f, to control the interpretation of timet.
3663 */
3664static PyObject *
3665datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3666 PyObject *tzinfo)
3667{
3668 struct tm *tm;
3669 PyObject *result = NULL;
3670
3671 tm = f(&timet);
3672 if (tm) {
3673 /* The platform localtime/gmtime may insert leap seconds,
3674 * indicated by tm->tm_sec > 59. We don't care about them,
3675 * except to the extent that passing them on to the datetime
3676 * constructor would raise ValueError for a reason that
3677 * made no sense to the user.
3678 */
3679 if (tm->tm_sec > 59)
3680 tm->tm_sec = 59;
3681 result = PyObject_CallFunction(cls, "iiiiiiiO",
3682 tm->tm_year + 1900,
3683 tm->tm_mon + 1,
3684 tm->tm_mday,
3685 tm->tm_hour,
3686 tm->tm_min,
3687 tm->tm_sec,
3688 us,
3689 tzinfo);
3690 }
3691 else
3692 PyErr_SetString(PyExc_ValueError,
3693 "timestamp out of range for "
3694 "platform localtime()/gmtime() function");
3695 return result;
3696}
3697
3698/* Internal helper.
3699 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3700 * to control the interpretation of the timestamp. Since a double doesn't
3701 * have enough bits to cover a datetime's full range of precision, it's
3702 * better to call datetime_from_timet_and_us provided you have a way
3703 * to get that much precision (e.g., C time() isn't good enough).
3704 */
3705static PyObject *
3706datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3707 PyObject *tzinfo)
3708{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003709 time_t timet;
3710 double fraction;
3711 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003712
Tim Peters1b6f7a92004-06-20 02:50:16 +00003713 timet = _PyTime_DoubleToTimet(timestamp);
3714 if (timet == (time_t)-1 && PyErr_Occurred())
3715 return NULL;
3716 fraction = timestamp - (double)timet;
3717 us = (int)round_to_long(fraction * 1e6);
Guido van Rossum2054ee92007-03-06 15:50:01 +00003718 if (us < 0) {
3719 /* Truncation towards zero is not what we wanted
3720 for negative numbers (Python's mod semantics) */
3721 timet -= 1;
3722 us += 1000000;
3723 }
Georg Brandl6d78a582006-04-28 19:09:24 +00003724 /* If timestamp is less than one microsecond smaller than a
3725 * full second, round up. Otherwise, ValueErrors are raised
3726 * for some floats. */
3727 if (us == 1000000) {
3728 timet += 1;
3729 us = 0;
3730 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003731 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3732}
3733
3734/* Internal helper.
3735 * Build most accurate possible datetime for current time. Pass localtime or
3736 * gmtime for f as appropriate.
3737 */
3738static PyObject *
3739datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3740{
3741#ifdef HAVE_GETTIMEOFDAY
3742 struct timeval t;
3743
3744#ifdef GETTIMEOFDAY_NO_TZ
3745 gettimeofday(&t);
3746#else
3747 gettimeofday(&t, (struct timezone *)NULL);
3748#endif
3749 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3750 tzinfo);
3751
3752#else /* ! HAVE_GETTIMEOFDAY */
3753 /* No flavor of gettimeofday exists on this platform. Python's
3754 * time.time() does a lot of other platform tricks to get the
3755 * best time it can on the platform, and we're not going to do
3756 * better than that (if we could, the better code would belong
3757 * in time.time()!) We're limited by the precision of a double,
3758 * though.
3759 */
3760 PyObject *time;
3761 double dtime;
3762
3763 time = time_time();
3764 if (time == NULL)
3765 return NULL;
3766 dtime = PyFloat_AsDouble(time);
3767 Py_DECREF(time);
3768 if (dtime == -1.0 && PyErr_Occurred())
3769 return NULL;
3770 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3771#endif /* ! HAVE_GETTIMEOFDAY */
3772}
3773
Tim Peters2a799bf2002-12-16 20:18:38 +00003774/* Return best possible local time -- this isn't constrained by the
3775 * precision of a timestamp.
3776 */
3777static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003778datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003779{
Tim Peters10cadce2003-01-23 19:58:02 +00003780 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003781 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003782 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003783
Tim Peters10cadce2003-01-23 19:58:02 +00003784 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3785 &tzinfo))
3786 return NULL;
3787 if (check_tzinfo_subclass(tzinfo) < 0)
3788 return NULL;
3789
3790 self = datetime_best_possible(cls,
3791 tzinfo == Py_None ? localtime : gmtime,
3792 tzinfo);
3793 if (self != NULL && tzinfo != Py_None) {
3794 /* Convert UTC to tzinfo's zone. */
3795 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003796 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003797 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003798 }
3799 return self;
3800}
3801
Tim Petersa9bc1682003-01-11 03:39:11 +00003802/* Return best possible UTC time -- this isn't constrained by the
3803 * precision of a timestamp.
3804 */
3805static PyObject *
3806datetime_utcnow(PyObject *cls, PyObject *dummy)
3807{
3808 return datetime_best_possible(cls, gmtime, Py_None);
3809}
3810
Tim Peters2a799bf2002-12-16 20:18:38 +00003811/* Return new local datetime from timestamp (Python timestamp -- a double). */
3812static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003813datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003814{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003815 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003816 double timestamp;
3817 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003818 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003819
Tim Peters2a44a8d2003-01-23 20:53:10 +00003820 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3821 keywords, &timestamp, &tzinfo))
3822 return NULL;
3823 if (check_tzinfo_subclass(tzinfo) < 0)
3824 return NULL;
3825
3826 self = datetime_from_timestamp(cls,
3827 tzinfo == Py_None ? localtime : gmtime,
3828 timestamp,
3829 tzinfo);
3830 if (self != NULL && tzinfo != Py_None) {
3831 /* Convert UTC to tzinfo's zone. */
3832 PyObject *temp = self;
3833 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3834 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003835 }
3836 return self;
3837}
3838
Tim Petersa9bc1682003-01-11 03:39:11 +00003839/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3840static PyObject *
3841datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3842{
3843 double timestamp;
3844 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003845
Tim Petersa9bc1682003-01-11 03:39:11 +00003846 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3847 result = datetime_from_timestamp(cls, gmtime, timestamp,
3848 Py_None);
3849 return result;
3850}
3851
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003852/* Return new datetime from time.strptime(). */
3853static PyObject *
3854datetime_strptime(PyObject *cls, PyObject *args)
3855{
3856 PyObject *result = NULL, *obj, *module;
3857 const char *string, *format;
3858
3859 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3860 return NULL;
3861
Christian Heimes000a0742008-01-03 22:16:32 +00003862 if ((module = PyImport_ImportModuleNoBlock("time")) == NULL)
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003863 return NULL;
3864 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3865 Py_DECREF(module);
3866
3867 if (obj != NULL) {
3868 int i, good_timetuple = 1;
3869 long int ia[6];
3870 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3871 for (i=0; i < 6; i++) {
3872 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters3cfea2d2006-04-14 21:23:42 +00003873 if (p == NULL) {
3874 Py_DECREF(obj);
3875 return NULL;
3876 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003877 if (PyInt_Check(p))
3878 ia[i] = PyInt_AsLong(p);
3879 else
3880 good_timetuple = 0;
3881 Py_DECREF(p);
3882 }
3883 else
3884 good_timetuple = 0;
3885 if (good_timetuple)
3886 result = PyObject_CallFunction(cls, "iiiiii",
3887 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3888 else
3889 PyErr_SetString(PyExc_ValueError,
3890 "unexpected value from time.strptime");
3891 Py_DECREF(obj);
3892 }
3893 return result;
3894}
3895
Tim Petersa9bc1682003-01-11 03:39:11 +00003896/* Return new datetime from date/datetime and time arguments. */
3897static PyObject *
3898datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3899{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003900 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003901 PyObject *date;
3902 PyObject *time;
3903 PyObject *result = NULL;
3904
3905 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3906 &PyDateTime_DateType, &date,
3907 &PyDateTime_TimeType, &time)) {
3908 PyObject *tzinfo = Py_None;
3909
3910 if (HASTZINFO(time))
3911 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3912 result = PyObject_CallFunction(cls, "iiiiiiiO",
3913 GET_YEAR(date),
3914 GET_MONTH(date),
3915 GET_DAY(date),
3916 TIME_GET_HOUR(time),
3917 TIME_GET_MINUTE(time),
3918 TIME_GET_SECOND(time),
3919 TIME_GET_MICROSECOND(time),
3920 tzinfo);
3921 }
3922 return result;
3923}
Tim Peters2a799bf2002-12-16 20:18:38 +00003924
3925/*
3926 * Destructor.
3927 */
3928
3929static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003930datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003931{
Tim Petersa9bc1682003-01-11 03:39:11 +00003932 if (HASTZINFO(self)) {
3933 Py_XDECREF(self->tzinfo);
3934 }
Christian Heimese93237d2007-12-19 02:37:44 +00003935 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003936}
3937
3938/*
3939 * Indirect access to tzinfo methods.
3940 */
3941
Tim Peters2a799bf2002-12-16 20:18:38 +00003942/* These are all METH_NOARGS, so don't need to check the arglist. */
3943static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003944datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3945 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3946 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003947}
3948
3949static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003950datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3951 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3952 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003953}
3954
3955static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003956datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3957 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3958 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003959}
3960
3961/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003962 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003963 */
3964
Tim Petersa9bc1682003-01-11 03:39:11 +00003965/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3966 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003967 */
3968static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003969add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3970 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003971{
Tim Petersa9bc1682003-01-11 03:39:11 +00003972 /* Note that the C-level additions can't overflow, because of
3973 * invariant bounds on the member values.
3974 */
3975 int year = GET_YEAR(date);
3976 int month = GET_MONTH(date);
3977 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3978 int hour = DATE_GET_HOUR(date);
3979 int minute = DATE_GET_MINUTE(date);
3980 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3981 int microsecond = DATE_GET_MICROSECOND(date) +
3982 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003983
Tim Petersa9bc1682003-01-11 03:39:11 +00003984 assert(factor == 1 || factor == -1);
3985 if (normalize_datetime(&year, &month, &day,
3986 &hour, &minute, &second, &microsecond) < 0)
3987 return NULL;
3988 else
3989 return new_datetime(year, month, day,
3990 hour, minute, second, microsecond,
3991 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003992}
3993
3994static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003995datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003996{
Tim Petersa9bc1682003-01-11 03:39:11 +00003997 if (PyDateTime_Check(left)) {
3998 /* datetime + ??? */
3999 if (PyDelta_Check(right))
4000 /* datetime + delta */
4001 return add_datetime_timedelta(
4002 (PyDateTime_DateTime *)left,
4003 (PyDateTime_Delta *)right,
4004 1);
4005 }
4006 else if (PyDelta_Check(left)) {
4007 /* delta + datetime */
4008 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4009 (PyDateTime_Delta *) left,
4010 1);
4011 }
4012 Py_INCREF(Py_NotImplemented);
4013 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004014}
4015
4016static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004017datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004018{
4019 PyObject *result = Py_NotImplemented;
4020
4021 if (PyDateTime_Check(left)) {
4022 /* datetime - ??? */
4023 if (PyDateTime_Check(right)) {
4024 /* datetime - datetime */
4025 naivety n1, n2;
4026 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004027 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004028
Tim Peterse39a80c2002-12-30 21:28:52 +00004029 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4030 right, &offset2, &n2,
4031 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00004032 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00004033 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00004034 if (n1 != n2) {
4035 PyErr_SetString(PyExc_TypeError,
4036 "can't subtract offset-naive and "
4037 "offset-aware datetimes");
4038 return NULL;
4039 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004040 delta_d = ymd_to_ord(GET_YEAR(left),
4041 GET_MONTH(left),
4042 GET_DAY(left)) -
4043 ymd_to_ord(GET_YEAR(right),
4044 GET_MONTH(right),
4045 GET_DAY(right));
4046 /* These can't overflow, since the values are
4047 * normalized. At most this gives the number of
4048 * seconds in one day.
4049 */
4050 delta_s = (DATE_GET_HOUR(left) -
4051 DATE_GET_HOUR(right)) * 3600 +
4052 (DATE_GET_MINUTE(left) -
4053 DATE_GET_MINUTE(right)) * 60 +
4054 (DATE_GET_SECOND(left) -
4055 DATE_GET_SECOND(right));
4056 delta_us = DATE_GET_MICROSECOND(left) -
4057 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004058 /* (left - offset1) - (right - offset2) =
4059 * (left - right) + (offset2 - offset1)
4060 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004061 delta_s += (offset2 - offset1) * 60;
4062 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004063 }
4064 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004065 /* datetime - delta */
4066 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004067 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004068 (PyDateTime_Delta *)right,
4069 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004070 }
4071 }
4072
4073 if (result == Py_NotImplemented)
4074 Py_INCREF(result);
4075 return result;
4076}
4077
4078/* Various ways to turn a datetime into a string. */
4079
4080static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004081datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004082{
Tim Petersa9bc1682003-01-11 03:39:11 +00004083 char buffer[1000];
Christian Heimese93237d2007-12-19 02:37:44 +00004084 const char *type_name = Py_TYPE(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004085 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004086
Tim Petersa9bc1682003-01-11 03:39:11 +00004087 if (DATE_GET_MICROSECOND(self)) {
4088 PyOS_snprintf(buffer, sizeof(buffer),
4089 "%s(%d, %d, %d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004090 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004091 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4092 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4093 DATE_GET_SECOND(self),
4094 DATE_GET_MICROSECOND(self));
4095 }
4096 else if (DATE_GET_SECOND(self)) {
4097 PyOS_snprintf(buffer, sizeof(buffer),
4098 "%s(%d, %d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004099 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004100 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4101 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4102 DATE_GET_SECOND(self));
4103 }
4104 else {
4105 PyOS_snprintf(buffer, sizeof(buffer),
4106 "%s(%d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004107 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004108 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4109 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4110 }
4111 baserepr = PyString_FromString(buffer);
4112 if (baserepr == NULL || ! HASTZINFO(self))
4113 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004114 return append_keyword_tzinfo(baserepr, self->tzinfo);
4115}
4116
Tim Petersa9bc1682003-01-11 03:39:11 +00004117static PyObject *
4118datetime_str(PyDateTime_DateTime *self)
4119{
4120 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4121}
Tim Peters2a799bf2002-12-16 20:18:38 +00004122
4123static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004124datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004125{
Tim Petersa9bc1682003-01-11 03:39:11 +00004126 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004127 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004128 char buffer[100];
4129 char *cp;
4130 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004131
Tim Petersa9bc1682003-01-11 03:39:11 +00004132 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4133 &sep))
4134 return NULL;
4135 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4136 assert(cp != NULL);
4137 *cp++ = sep;
4138 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4139 result = PyString_FromString(buffer);
4140 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004141 return result;
4142
4143 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004144 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004145 (PyObject *)self) < 0) {
4146 Py_DECREF(result);
4147 return NULL;
4148 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004149 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004150 return result;
4151}
4152
Tim Petersa9bc1682003-01-11 03:39:11 +00004153static PyObject *
4154datetime_ctime(PyDateTime_DateTime *self)
4155{
4156 return format_ctime((PyDateTime_Date *)self,
4157 DATE_GET_HOUR(self),
4158 DATE_GET_MINUTE(self),
4159 DATE_GET_SECOND(self));
4160}
4161
Tim Peters2a799bf2002-12-16 20:18:38 +00004162/* Miscellaneous methods. */
4163
Tim Petersa9bc1682003-01-11 03:39:11 +00004164/* This is more natural as a tp_compare, but doesn't work then: for whatever
4165 * reason, Python's try_3way_compare ignores tp_compare unless
4166 * PyInstance_Check returns true, but these aren't old-style classes.
4167 */
4168static PyObject *
4169datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
4170{
4171 int diff;
4172 naivety n1, n2;
4173 int offset1, offset2;
4174
4175 if (! PyDateTime_Check(other)) {
Tim Peters528ca532004-09-16 01:30:50 +00004176 /* If other has a "timetuple" attr, that's an advertised
4177 * hook for other classes to ask to get comparison control.
4178 * However, date instances have a timetuple attr, and we
4179 * don't want to allow that comparison. Because datetime
4180 * is a subclass of date, when mixing date and datetime
4181 * in a comparison, Python gives datetime the first shot
4182 * (it's the more specific subtype). So we can stop that
4183 * combination here reliably.
4184 */
4185 if (PyObject_HasAttrString(other, "timetuple") &&
4186 ! PyDate_Check(other)) {
Tim Peters8d81a012003-01-24 22:36:34 +00004187 /* A hook for other kinds of datetime objects. */
4188 Py_INCREF(Py_NotImplemented);
4189 return Py_NotImplemented;
4190 }
Tim Peters07534a62003-02-07 22:50:28 +00004191 if (op == Py_EQ || op == Py_NE) {
4192 PyObject *result = op == Py_EQ ? Py_False : Py_True;
4193 Py_INCREF(result);
4194 return result;
4195 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004196 /* Stop this from falling back to address comparison. */
Tim Peters07534a62003-02-07 22:50:28 +00004197 return cmperror((PyObject *)self, other);
Tim Petersa9bc1682003-01-11 03:39:11 +00004198 }
4199
4200 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
4201 (PyObject *)self,
4202 other, &offset2, &n2,
4203 other) < 0)
4204 return NULL;
4205 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4206 /* If they're both naive, or both aware and have the same offsets,
4207 * we get off cheap. Note that if they're both naive, offset1 ==
4208 * offset2 == 0 at this point.
4209 */
4210 if (n1 == n2 && offset1 == offset2) {
4211 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
4212 _PyDateTime_DATETIME_DATASIZE);
4213 return diff_to_bool(diff, op);
4214 }
4215
4216 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4217 PyDateTime_Delta *delta;
4218
4219 assert(offset1 != offset2); /* else last "if" handled it */
4220 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4221 other);
4222 if (delta == NULL)
4223 return NULL;
4224 diff = GET_TD_DAYS(delta);
4225 if (diff == 0)
4226 diff = GET_TD_SECONDS(delta) |
4227 GET_TD_MICROSECONDS(delta);
4228 Py_DECREF(delta);
4229 return diff_to_bool(diff, op);
4230 }
4231
4232 assert(n1 != n2);
4233 PyErr_SetString(PyExc_TypeError,
4234 "can't compare offset-naive and "
4235 "offset-aware datetimes");
4236 return NULL;
4237}
4238
4239static long
4240datetime_hash(PyDateTime_DateTime *self)
4241{
4242 if (self->hashcode == -1) {
4243 naivety n;
4244 int offset;
4245 PyObject *temp;
4246
4247 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4248 &offset);
4249 assert(n != OFFSET_UNKNOWN);
4250 if (n == OFFSET_ERROR)
4251 return -1;
4252
4253 /* Reduce this to a hash of another object. */
4254 if (n == OFFSET_NAIVE)
4255 temp = PyString_FromStringAndSize(
4256 (char *)self->data,
4257 _PyDateTime_DATETIME_DATASIZE);
4258 else {
4259 int days;
4260 int seconds;
4261
4262 assert(n == OFFSET_AWARE);
4263 assert(HASTZINFO(self));
4264 days = ymd_to_ord(GET_YEAR(self),
4265 GET_MONTH(self),
4266 GET_DAY(self));
4267 seconds = DATE_GET_HOUR(self) * 3600 +
4268 (DATE_GET_MINUTE(self) - offset) * 60 +
4269 DATE_GET_SECOND(self);
4270 temp = new_delta(days,
4271 seconds,
4272 DATE_GET_MICROSECOND(self),
4273 1);
4274 }
4275 if (temp != NULL) {
4276 self->hashcode = PyObject_Hash(temp);
4277 Py_DECREF(temp);
4278 }
4279 }
4280 return self->hashcode;
4281}
Tim Peters2a799bf2002-12-16 20:18:38 +00004282
4283static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004284datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004285{
4286 PyObject *clone;
4287 PyObject *tuple;
4288 int y = GET_YEAR(self);
4289 int m = GET_MONTH(self);
4290 int d = GET_DAY(self);
4291 int hh = DATE_GET_HOUR(self);
4292 int mm = DATE_GET_MINUTE(self);
4293 int ss = DATE_GET_SECOND(self);
4294 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004295 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004296
4297 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004298 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004299 &y, &m, &d, &hh, &mm, &ss, &us,
4300 &tzinfo))
4301 return NULL;
4302 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4303 if (tuple == NULL)
4304 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00004305 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004306 Py_DECREF(tuple);
4307 return clone;
4308}
4309
4310static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004311datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004312{
Tim Peters52dcce22003-01-23 16:36:11 +00004313 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004314 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004315 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004316
Tim Peters80475bb2002-12-25 07:40:55 +00004317 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004318 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004319
Tim Peters52dcce22003-01-23 16:36:11 +00004320 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4321 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004322 return NULL;
4323
Tim Peters52dcce22003-01-23 16:36:11 +00004324 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4325 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004326
Tim Peters52dcce22003-01-23 16:36:11 +00004327 /* Conversion to self's own time zone is a NOP. */
4328 if (self->tzinfo == tzinfo) {
4329 Py_INCREF(self);
4330 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004331 }
Tim Peters521fc152002-12-31 17:36:56 +00004332
Tim Peters52dcce22003-01-23 16:36:11 +00004333 /* Convert self to UTC. */
4334 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4335 if (offset == -1 && PyErr_Occurred())
4336 return NULL;
4337 if (none)
4338 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004339
Tim Peters52dcce22003-01-23 16:36:11 +00004340 y = GET_YEAR(self);
4341 m = GET_MONTH(self);
4342 d = GET_DAY(self);
4343 hh = DATE_GET_HOUR(self);
4344 mm = DATE_GET_MINUTE(self);
4345 ss = DATE_GET_SECOND(self);
4346 us = DATE_GET_MICROSECOND(self);
4347
4348 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004349 if ((mm < 0 || mm >= 60) &&
4350 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004351 return NULL;
4352
4353 /* Attach new tzinfo and let fromutc() do the rest. */
4354 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4355 if (result != NULL) {
4356 PyObject *temp = result;
4357
4358 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4359 Py_DECREF(temp);
4360 }
Tim Petersadf64202003-01-04 06:03:15 +00004361 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004362
Tim Peters52dcce22003-01-23 16:36:11 +00004363NeedAware:
4364 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4365 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004366 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004367}
4368
4369static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004370datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004371{
4372 int dstflag = -1;
4373
Tim Petersa9bc1682003-01-11 03:39:11 +00004374 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004375 int none;
4376
4377 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4378 if (dstflag == -1 && PyErr_Occurred())
4379 return NULL;
4380
4381 if (none)
4382 dstflag = -1;
4383 else if (dstflag != 0)
4384 dstflag = 1;
4385
4386 }
4387 return build_struct_time(GET_YEAR(self),
4388 GET_MONTH(self),
4389 GET_DAY(self),
4390 DATE_GET_HOUR(self),
4391 DATE_GET_MINUTE(self),
4392 DATE_GET_SECOND(self),
4393 dstflag);
4394}
4395
4396static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004397datetime_getdate(PyDateTime_DateTime *self)
4398{
4399 return new_date(GET_YEAR(self),
4400 GET_MONTH(self),
4401 GET_DAY(self));
4402}
4403
4404static PyObject *
4405datetime_gettime(PyDateTime_DateTime *self)
4406{
4407 return new_time(DATE_GET_HOUR(self),
4408 DATE_GET_MINUTE(self),
4409 DATE_GET_SECOND(self),
4410 DATE_GET_MICROSECOND(self),
4411 Py_None);
4412}
4413
4414static PyObject *
4415datetime_gettimetz(PyDateTime_DateTime *self)
4416{
4417 return new_time(DATE_GET_HOUR(self),
4418 DATE_GET_MINUTE(self),
4419 DATE_GET_SECOND(self),
4420 DATE_GET_MICROSECOND(self),
4421 HASTZINFO(self) ? self->tzinfo : Py_None);
4422}
4423
4424static PyObject *
4425datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004426{
4427 int y = GET_YEAR(self);
4428 int m = GET_MONTH(self);
4429 int d = GET_DAY(self);
4430 int hh = DATE_GET_HOUR(self);
4431 int mm = DATE_GET_MINUTE(self);
4432 int ss = DATE_GET_SECOND(self);
4433 int us = 0; /* microseconds are ignored in a timetuple */
4434 int offset = 0;
4435
Tim Petersa9bc1682003-01-11 03:39:11 +00004436 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004437 int none;
4438
4439 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4440 if (offset == -1 && PyErr_Occurred())
4441 return NULL;
4442 }
4443 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4444 * 0 in a UTC timetuple regardless of what dst() says.
4445 */
4446 if (offset) {
4447 /* Subtract offset minutes & normalize. */
4448 int stat;
4449
4450 mm -= offset;
4451 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4452 if (stat < 0) {
4453 /* At the edges, it's possible we overflowed
4454 * beyond MINYEAR or MAXYEAR.
4455 */
4456 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4457 PyErr_Clear();
4458 else
4459 return NULL;
4460 }
4461 }
4462 return build_struct_time(y, m, d, hh, mm, ss, 0);
4463}
4464
Tim Peters371935f2003-02-01 01:52:50 +00004465/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004466
Tim Petersa9bc1682003-01-11 03:39:11 +00004467/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004468 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4469 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004470 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004471 */
4472static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004473datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004474{
4475 PyObject *basestate;
4476 PyObject *result = NULL;
4477
Tim Peters33e0f382003-01-10 02:05:14 +00004478 basestate = PyString_FromStringAndSize((char *)self->data,
4479 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004480 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004481 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004482 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004483 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004484 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004485 Py_DECREF(basestate);
4486 }
4487 return result;
4488}
4489
4490static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004491datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004492{
Christian Heimese93237d2007-12-19 02:37:44 +00004493 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004494}
4495
Tim Petersa9bc1682003-01-11 03:39:11 +00004496static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004497
Tim Peters2a799bf2002-12-16 20:18:38 +00004498 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004499
Tim Petersa9bc1682003-01-11 03:39:11 +00004500 {"now", (PyCFunction)datetime_now,
Neal Norwitza84dcd72007-05-22 07:16:44 +00004501 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004502 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004503
Tim Petersa9bc1682003-01-11 03:39:11 +00004504 {"utcnow", (PyCFunction)datetime_utcnow,
4505 METH_NOARGS | METH_CLASS,
4506 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4507
4508 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Neal Norwitza84dcd72007-05-22 07:16:44 +00004509 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004510 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004511
Tim Petersa9bc1682003-01-11 03:39:11 +00004512 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4513 METH_VARARGS | METH_CLASS,
4514 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4515 "(like time.time()).")},
4516
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004517 {"strptime", (PyCFunction)datetime_strptime,
4518 METH_VARARGS | METH_CLASS,
4519 PyDoc_STR("string, format -> new datetime parsed from a string "
4520 "(like time.strptime()).")},
4521
Tim Petersa9bc1682003-01-11 03:39:11 +00004522 {"combine", (PyCFunction)datetime_combine,
4523 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4524 PyDoc_STR("date, time -> datetime with same date and time fields")},
4525
Tim Peters2a799bf2002-12-16 20:18:38 +00004526 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004527
Tim Petersa9bc1682003-01-11 03:39:11 +00004528 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4529 PyDoc_STR("Return date object with same year, month and day.")},
4530
4531 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4532 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4533
4534 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4535 PyDoc_STR("Return time object with same time and tzinfo.")},
4536
4537 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4538 PyDoc_STR("Return ctime() style string.")},
4539
4540 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004541 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4542
Tim Petersa9bc1682003-01-11 03:39:11 +00004543 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004544 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4545
Neal Norwitza84dcd72007-05-22 07:16:44 +00004546 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004547 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4548 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4549 "sep is used to separate the year from the time, and "
4550 "defaults to 'T'.")},
4551
Tim Petersa9bc1682003-01-11 03:39:11 +00004552 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004553 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4554
Tim Petersa9bc1682003-01-11 03:39:11 +00004555 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004556 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4557
Tim Petersa9bc1682003-01-11 03:39:11 +00004558 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004559 PyDoc_STR("Return self.tzinfo.dst(self).")},
4560
Neal Norwitza84dcd72007-05-22 07:16:44 +00004561 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004562 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004563
Neal Norwitza84dcd72007-05-22 07:16:44 +00004564 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004565 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4566
Guido van Rossum177e41a2003-01-30 22:06:23 +00004567 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4568 PyDoc_STR("__reduce__() -> (cls, state)")},
4569
Tim Peters2a799bf2002-12-16 20:18:38 +00004570 {NULL, NULL}
4571};
4572
Tim Petersa9bc1682003-01-11 03:39:11 +00004573static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004574PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4575\n\
4576The year, month and day arguments are required. tzinfo may be None, or an\n\
4577instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004578
Tim Petersa9bc1682003-01-11 03:39:11 +00004579static PyNumberMethods datetime_as_number = {
4580 datetime_add, /* nb_add */
4581 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004582 0, /* nb_multiply */
4583 0, /* nb_divide */
4584 0, /* nb_remainder */
4585 0, /* nb_divmod */
4586 0, /* nb_power */
4587 0, /* nb_negative */
4588 0, /* nb_positive */
4589 0, /* nb_absolute */
4590 0, /* nb_nonzero */
4591};
4592
Tim Petersa9bc1682003-01-11 03:39:11 +00004593statichere PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004594 PyObject_HEAD_INIT(NULL)
4595 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004596 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004597 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004598 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004599 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004600 0, /* tp_print */
4601 0, /* tp_getattr */
4602 0, /* tp_setattr */
4603 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004604 (reprfunc)datetime_repr, /* tp_repr */
4605 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004606 0, /* tp_as_sequence */
4607 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004608 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004609 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004610 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004611 PyObject_GenericGetAttr, /* tp_getattro */
4612 0, /* tp_setattro */
4613 0, /* tp_as_buffer */
4614 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4615 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004616 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004617 0, /* tp_traverse */
4618 0, /* tp_clear */
Tim Petersa9bc1682003-01-11 03:39:11 +00004619 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004620 0, /* tp_weaklistoffset */
4621 0, /* tp_iter */
4622 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004623 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004624 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004625 datetime_getset, /* tp_getset */
4626 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004627 0, /* tp_dict */
4628 0, /* tp_descr_get */
4629 0, /* tp_descr_set */
4630 0, /* tp_dictoffset */
4631 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004632 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004633 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004634 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004635};
4636
4637/* ---------------------------------------------------------------------------
4638 * Module methods and initialization.
4639 */
4640
4641static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004642 {NULL, NULL}
4643};
4644
Tim Peters9ddf40b2004-06-20 22:41:32 +00004645/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4646 * datetime.h.
4647 */
4648static PyDateTime_CAPI CAPI = {
4649 &PyDateTime_DateType,
4650 &PyDateTime_DateTimeType,
4651 &PyDateTime_TimeType,
4652 &PyDateTime_DeltaType,
4653 &PyDateTime_TZInfoType,
4654 new_date_ex,
4655 new_datetime_ex,
4656 new_time_ex,
4657 new_delta_ex,
4658 datetime_fromtimestamp,
4659 date_fromtimestamp
4660};
4661
4662
Tim Peters2a799bf2002-12-16 20:18:38 +00004663PyMODINIT_FUNC
4664initdatetime(void)
4665{
4666 PyObject *m; /* a module object */
4667 PyObject *d; /* its dict */
4668 PyObject *x;
4669
Tim Peters2a799bf2002-12-16 20:18:38 +00004670 m = Py_InitModule3("datetime", module_methods,
4671 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004672 if (m == NULL)
4673 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004674
4675 if (PyType_Ready(&PyDateTime_DateType) < 0)
4676 return;
4677 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4678 return;
4679 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4680 return;
4681 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4682 return;
4683 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4684 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004685
Tim Peters2a799bf2002-12-16 20:18:38 +00004686 /* timedelta values */
4687 d = PyDateTime_DeltaType.tp_dict;
4688
Tim Peters2a799bf2002-12-16 20:18:38 +00004689 x = new_delta(0, 0, 1, 0);
4690 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4691 return;
4692 Py_DECREF(x);
4693
4694 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4695 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4696 return;
4697 Py_DECREF(x);
4698
4699 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4700 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4701 return;
4702 Py_DECREF(x);
4703
4704 /* date values */
4705 d = PyDateTime_DateType.tp_dict;
4706
4707 x = new_date(1, 1, 1);
4708 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4709 return;
4710 Py_DECREF(x);
4711
4712 x = new_date(MAXYEAR, 12, 31);
4713 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4714 return;
4715 Py_DECREF(x);
4716
4717 x = new_delta(1, 0, 0, 0);
4718 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4719 return;
4720 Py_DECREF(x);
4721
Tim Peters37f39822003-01-10 03:49:02 +00004722 /* time values */
4723 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004724
Tim Peters37f39822003-01-10 03:49:02 +00004725 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004726 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4727 return;
4728 Py_DECREF(x);
4729
Tim Peters37f39822003-01-10 03:49:02 +00004730 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004731 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4732 return;
4733 Py_DECREF(x);
4734
4735 x = new_delta(0, 0, 1, 0);
4736 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4737 return;
4738 Py_DECREF(x);
4739
Tim Petersa9bc1682003-01-11 03:39:11 +00004740 /* datetime values */
4741 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004742
Tim Petersa9bc1682003-01-11 03:39:11 +00004743 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004744 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4745 return;
4746 Py_DECREF(x);
4747
Tim Petersa9bc1682003-01-11 03:39:11 +00004748 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004749 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4750 return;
4751 Py_DECREF(x);
4752
4753 x = new_delta(0, 0, 1, 0);
4754 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4755 return;
4756 Py_DECREF(x);
4757
Tim Peters2a799bf2002-12-16 20:18:38 +00004758 /* module initialization */
4759 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4760 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4761
4762 Py_INCREF(&PyDateTime_DateType);
4763 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4764
Tim Petersa9bc1682003-01-11 03:39:11 +00004765 Py_INCREF(&PyDateTime_DateTimeType);
4766 PyModule_AddObject(m, "datetime",
4767 (PyObject *)&PyDateTime_DateTimeType);
4768
4769 Py_INCREF(&PyDateTime_TimeType);
4770 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4771
Tim Peters2a799bf2002-12-16 20:18:38 +00004772 Py_INCREF(&PyDateTime_DeltaType);
4773 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4774
Tim Peters2a799bf2002-12-16 20:18:38 +00004775 Py_INCREF(&PyDateTime_TZInfoType);
4776 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4777
Tim Peters9ddf40b2004-06-20 22:41:32 +00004778 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4779 NULL);
4780 if (x == NULL)
4781 return;
4782 PyModule_AddObject(m, "datetime_CAPI", x);
4783
Tim Peters2a799bf2002-12-16 20:18:38 +00004784 /* A 4-year cycle has an extra leap day over what we'd get from
4785 * pasting together 4 single years.
4786 */
4787 assert(DI4Y == 4 * 365 + 1);
4788 assert(DI4Y == days_before_year(4+1));
4789
4790 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4791 * get from pasting together 4 100-year cycles.
4792 */
4793 assert(DI400Y == 4 * DI100Y + 1);
4794 assert(DI400Y == days_before_year(400+1));
4795
4796 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4797 * pasting together 25 4-year cycles.
4798 */
4799 assert(DI100Y == 25 * DI4Y - 1);
4800 assert(DI100Y == days_before_year(100+1));
4801
4802 us_per_us = PyInt_FromLong(1);
4803 us_per_ms = PyInt_FromLong(1000);
4804 us_per_second = PyInt_FromLong(1000000);
4805 us_per_minute = PyInt_FromLong(60000000);
4806 seconds_per_day = PyInt_FromLong(24 * 3600);
4807 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4808 us_per_minute == NULL || seconds_per_day == NULL)
4809 return;
4810
4811 /* The rest are too big for 32-bit ints, but even
4812 * us_per_week fits in 40 bits, so doubles should be exact.
4813 */
4814 us_per_hour = PyLong_FromDouble(3600000000.0);
4815 us_per_day = PyLong_FromDouble(86400000000.0);
4816 us_per_week = PyLong_FromDouble(604800000000.0);
4817 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4818 return;
4819}
Tim Petersf3615152003-01-01 21:51:37 +00004820
4821/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004822Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004823 x.n = x stripped of its timezone -- its naive time.
4824 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4825 return None
4826 x.d = x.dst(), and assuming that doesn't raise an exception or
4827 return None
4828 x.s = x's standard offset, x.o - x.d
4829
4830Now some derived rules, where k is a duration (timedelta).
4831
48321. x.o = x.s + x.d
4833 This follows from the definition of x.s.
4834
Tim Petersc5dc4da2003-01-02 17:55:03 +000048352. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004836 This is actually a requirement, an assumption we need to make about
4837 sane tzinfo classes.
4838
48393. The naive UTC time corresponding to x is x.n - x.o.
4840 This is again a requirement for a sane tzinfo class.
4841
48424. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004843 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004844
Tim Petersc5dc4da2003-01-02 17:55:03 +000048455. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004846 Again follows from how arithmetic is defined.
4847
Tim Peters8bb5ad22003-01-24 02:44:45 +00004848Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004849(meaning that the various tzinfo methods exist, and don't blow up or return
4850None when called).
4851
Tim Petersa9bc1682003-01-11 03:39:11 +00004852The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004853x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004854
4855By #3, we want
4856
Tim Peters8bb5ad22003-01-24 02:44:45 +00004857 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004858
4859The algorithm starts by attaching tz to x.n, and calling that y. So
4860x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4861becomes true; in effect, we want to solve [2] for k:
4862
Tim Peters8bb5ad22003-01-24 02:44:45 +00004863 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004864
4865By #1, this is the same as
4866
Tim Peters8bb5ad22003-01-24 02:44:45 +00004867 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004868
4869By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4870Substituting that into [3],
4871
Tim Peters8bb5ad22003-01-24 02:44:45 +00004872 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4873 k - (y+k).s - (y+k).d = 0; rearranging,
4874 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4875 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004876
Tim Peters8bb5ad22003-01-24 02:44:45 +00004877On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4878approximate k by ignoring the (y+k).d term at first. Note that k can't be
4879very large, since all offset-returning methods return a duration of magnitude
4880less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4881be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004882
4883In any case, the new value is
4884
Tim Peters8bb5ad22003-01-24 02:44:45 +00004885 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004886
Tim Peters8bb5ad22003-01-24 02:44:45 +00004887It's helpful to step back at look at [4] from a higher level: it's simply
4888mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004889
4890At this point, if
4891
Tim Peters8bb5ad22003-01-24 02:44:45 +00004892 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004893
4894we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004895at the start of daylight time. Picture US Eastern for concreteness. The wall
4896time 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 +00004897sense then. The docs ask that an Eastern tzinfo class consider such a time to
4898be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4899on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004900the only spelling that makes sense on the local wall clock.
4901
Tim Petersc5dc4da2003-01-02 17:55:03 +00004902In fact, if [5] holds at this point, we do have the standard-time spelling,
4903but that takes a bit of proof. We first prove a stronger result. What's the
4904difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004905
Tim Peters8bb5ad22003-01-24 02:44:45 +00004906 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004907
Tim Petersc5dc4da2003-01-02 17:55:03 +00004908Now
4909 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004910 (y + y.s).n = by #5
4911 y.n + y.s = since y.n = x.n
4912 x.n + y.s = since z and y are have the same tzinfo member,
4913 y.s = z.s by #2
4914 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004915
Tim Petersc5dc4da2003-01-02 17:55:03 +00004916Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004917
Tim Petersc5dc4da2003-01-02 17:55:03 +00004918 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004919 x.n - ((x.n + z.s) - z.o) = expanding
4920 x.n - x.n - z.s + z.o = cancelling
4921 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004922 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004923
Tim Petersc5dc4da2003-01-02 17:55:03 +00004924So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004925
Tim Petersc5dc4da2003-01-02 17:55:03 +00004926If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004927spelling we wanted in the endcase described above. We're done. Contrarily,
4928if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004929
Tim Petersc5dc4da2003-01-02 17:55:03 +00004930If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4931add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004932local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004933
Tim Petersc5dc4da2003-01-02 17:55:03 +00004934Let
Tim Petersf3615152003-01-01 21:51:37 +00004935
Tim Peters4fede1a2003-01-04 00:26:59 +00004936 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004937
Tim Peters4fede1a2003-01-04 00:26:59 +00004938and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004939
Tim Peters8bb5ad22003-01-24 02:44:45 +00004940 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004941
Tim Peters8bb5ad22003-01-24 02:44:45 +00004942If so, we're done. If not, the tzinfo class is insane, according to the
4943assumptions we've made. This also requires a bit of proof. As before, let's
4944compute the difference between the LHS and RHS of [8] (and skipping some of
4945the justifications for the kinds of substitutions we've done several times
4946already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004947
Tim Peters8bb5ad22003-01-24 02:44:45 +00004948 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4949 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4950 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4951 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4952 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004953 - z.o + z'.o = #1 twice
4954 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4955 z'.d - z.d
4956
4957So 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 +00004958we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4959return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004960
Tim Peters8bb5ad22003-01-24 02:44:45 +00004961How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4962a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4963would have to change the result dst() returns: we start in DST, and moving
4964a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004965
Tim Peters8bb5ad22003-01-24 02:44:45 +00004966There isn't a sane case where this can happen. The closest it gets is at
4967the end of DST, where there's an hour in UTC with no spelling in a hybrid
4968tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4969that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4970UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4971time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4972clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4973standard time. Since that's what the local clock *does*, we want to map both
4974UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004975in local time, but so it goes -- it's the way the local clock works.
4976
Tim Peters8bb5ad22003-01-24 02:44:45 +00004977When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4978so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4979z' = 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 +00004980(correctly) concludes that z' is not UTC-equivalent to x.
4981
4982Because we know z.d said z was in daylight time (else [5] would have held and
4983we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004984and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004985return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4986but the reasoning doesn't depend on the example -- it depends on there being
4987two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004988z' must be in standard time, and is the spelling we want in this case.
4989
4990Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4991concerned (because it takes z' as being in standard time rather than the
4992daylight time we intend here), but returning it gives the real-life "local
4993clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4994tz.
4995
4996When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4997the 1:MM standard time spelling we want.
4998
4999So how can this break? One of the assumptions must be violated. Two
5000possibilities:
5001
50021) [2] effectively says that y.s is invariant across all y belong to a given
5003 time zone. This isn't true if, for political reasons or continental drift,
5004 a region decides to change its base offset from UTC.
5005
50062) There may be versions of "double daylight" time where the tail end of
5007 the analysis gives up a step too early. I haven't thought about that
5008 enough to say.
5009
5010In any case, it's clear that the default fromutc() is strong enough to handle
5011"almost all" time zones: so long as the standard offset is invariant, it
5012doesn't matter if daylight time transition points change from year to year, or
5013if daylight time is skipped in some years; it doesn't matter how large or
5014small dst() may get within its bounds; and it doesn't even matter if some
5015perverse time zone returns a negative dst()). So a breaking case must be
5016pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005017--------------------------------------------------------------------------- */