blob: 83dab2c93508b899c98325e68f94cbc028d8d707 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
28# error "datetime.c requires that C int have at least 32 bits"
29#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
33
34/* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
38 */
39#define MAX_DELTA_DAYS 999999999
40
41/* Rename the long macros in datetime.h to more reasonable short names. */
42#define GET_YEAR PyDateTime_GET_YEAR
43#define GET_MONTH PyDateTime_GET_MONTH
44#define GET_DAY PyDateTime_GET_DAY
45#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
49
50/* Date accessors for date and datetime. */
51#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
55
56/* Date/Time accessors for datetime. */
57#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60#define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
64
65/* Time accessors for time. */
66#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73#define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
77
78/* Delta accessors for timedelta. */
79#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
82
83#define SET_TD_DAYS(o, v) ((o)->days = (v))
84#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
85#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
86
Tim Petersa032d2e2003-01-11 00:15:54 +000087/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
89 */
90#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
91
Tim Peters3f606292004-03-21 23:38:41 +000092/* M is a char or int claiming to be a valid month. The macro is equivalent
93 * to the two-sided Python test
94 * 1 <= M <= 12
95 */
96#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
97
Tim Peters2a799bf2002-12-16 20:18:38 +000098/* Forward declarations. */
99static PyTypeObject PyDateTime_DateType;
100static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000101static PyTypeObject PyDateTime_DeltaType;
102static PyTypeObject PyDateTime_TimeType;
103static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000104
105/* ---------------------------------------------------------------------------
106 * Math utilities.
107 */
108
109/* k = i+j overflows iff k differs in sign from both inputs,
110 * iff k^i has sign bit set and k^j has sign bit set,
111 * iff (k^i)&(k^j) has sign bit set.
112 */
113#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
114 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
115
116/* Compute Python divmod(x, y), returning the quotient and storing the
117 * remainder into *r. The quotient is the floor of x/y, and that's
118 * the real point of this. C will probably truncate instead (C99
119 * requires truncation; C89 left it implementation-defined).
120 * Simplification: we *require* that y > 0 here. That's appropriate
121 * for all the uses made of it. This simplifies the code and makes
122 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
123 * overflow case).
124 */
125static int
126divmod(int x, int y, int *r)
127{
128 int quo;
129
130 assert(y > 0);
131 quo = x / y;
132 *r = x - quo * y;
133 if (*r < 0) {
134 --quo;
135 *r += y;
136 }
137 assert(0 <= *r && *r < y);
138 return quo;
139}
140
Tim Peters5d644dd2003-01-02 16:32:54 +0000141/* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
143 */
144static long
145round_to_long(double x)
146{
147 if (x >= 0.0)
148 x = floor(x + 0.5);
149 else
150 x = ceil(x - 0.5);
151 return (long)x;
152}
153
Tim Peters2a799bf2002-12-16 20:18:38 +0000154/* ---------------------------------------------------------------------------
155 * General calendrical helper functions
156 */
157
158/* For each month ordinal in 1..12, the number of days in that month,
159 * and the number of days before that month in the same year. These
160 * are correct for non-leap years only.
161 */
162static int _days_in_month[] = {
163 0, /* unused; this vector uses 1-based indexing */
164 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
165};
166
167static int _days_before_month[] = {
168 0, /* unused; this vector uses 1-based indexing */
169 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
170};
171
172/* year -> 1 if leap year, else 0. */
173static int
174is_leap(int year)
175{
176 /* Cast year to unsigned. The result is the same either way, but
177 * C can generate faster code for unsigned mod than for signed
178 * mod (especially for % 4 -- a good compiler should just grab
179 * the last 2 bits when the LHS is unsigned).
180 */
181 const unsigned int ayear = (unsigned int)year;
182 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
183}
184
185/* year, month -> number of days in that month in that year */
186static int
187days_in_month(int year, int month)
188{
189 assert(month >= 1);
190 assert(month <= 12);
191 if (month == 2 && is_leap(year))
192 return 29;
193 else
194 return _days_in_month[month];
195}
196
197/* year, month -> number of days in year preceeding first day of month */
198static int
199days_before_month(int year, int month)
200{
201 int days;
202
203 assert(month >= 1);
204 assert(month <= 12);
205 days = _days_before_month[month];
206 if (month > 2 && is_leap(year))
207 ++days;
208 return days;
209}
210
211/* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
213 */
214static int
215days_before_year(int year)
216{
217 int y = year - 1;
218 /* This is incorrect if year <= 0; we really want the floor
219 * here. But so long as MINYEAR is 1, the smallest year this
220 * can see is 0 (this can happen in some normalization endcases),
221 * so we'll just special-case that.
222 */
223 assert (year >= 0);
224 if (y >= 0)
225 return y*365 + y/4 - y/100 + y/400;
226 else {
227 assert(y == -1);
228 return -366;
229 }
230}
231
232/* Number of days in 4, 100, and 400 year cycles. That these have
233 * the correct values is asserted in the module init function.
234 */
235#define DI4Y 1461 /* days_before_year(5); days in 4 years */
236#define DI100Y 36524 /* days_before_year(101); days in 100 years */
237#define DI400Y 146097 /* days_before_year(401); days in 400 years */
238
239/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
240static void
241ord_to_ymd(int ordinal, int *year, int *month, int *day)
242{
243 int n, n1, n4, n100, n400, leapyear, preceding;
244
245 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
246 * leap years repeats exactly every 400 years. The basic strategy is
247 * to find the closest 400-year boundary at or before ordinal, then
248 * work with the offset from that boundary to ordinal. Life is much
249 * clearer if we subtract 1 from ordinal first -- then the values
250 * of ordinal at 400-year boundaries are exactly those divisible
251 * by DI400Y:
252 *
253 * D M Y n n-1
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
257 * ...
258 * 30 Dec 000 -1 -2
259 * 31 Dec 000 0 -1
260 * 1 Jan 001 1 0 400-year boundary
261 * 2 Jan 001 2 1
262 * 3 Jan 001 3 2
263 * ...
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
266 */
267 assert(ordinal >= 1);
268 --ordinal;
269 n400 = ordinal / DI400Y;
270 n = ordinal % DI400Y;
271 *year = n400 * 400 + 1;
272
273 /* Now n is the (non-negative) offset, in days, from January 1 of
274 * year, to the desired date. Now compute how many 100-year cycles
275 * precede n.
276 * Note that it's possible for n100 to equal 4! In that case 4 full
277 * 100-year cycles precede the desired day, which implies the
278 * desired day is December 31 at the end of a 400-year cycle.
279 */
280 n100 = n / DI100Y;
281 n = n % DI100Y;
282
283 /* Now compute how many 4-year cycles precede it. */
284 n4 = n / DI4Y;
285 n = n % DI4Y;
286
287 /* And now how many single years. Again n1 can be 4, and again
288 * meaning that the desired day is December 31 at the end of the
289 * 4-year cycle.
290 */
291 n1 = n / 365;
292 n = n % 365;
293
294 *year += n100 * 100 + n4 * 4 + n1;
295 if (n1 == 4 || n100 == 4) {
296 assert(n == 0);
297 *year -= 1;
298 *month = 12;
299 *day = 31;
300 return;
301 }
302
303 /* Now the year is correct, and n is the offset from January 1. We
304 * find the month via an estimate that's either exact or one too
305 * large.
306 */
307 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
308 assert(leapyear == is_leap(*year));
309 *month = (n + 50) >> 5;
310 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
311 if (preceding > n) {
312 /* estimate is too large */
313 *month -= 1;
314 preceding -= days_in_month(*year, *month);
315 }
316 n -= preceding;
317 assert(0 <= n);
318 assert(n < days_in_month(*year, *month));
319
320 *day = n + 1;
321}
322
323/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
324static int
325ymd_to_ord(int year, int month, int day)
326{
327 return days_before_year(year) + days_before_month(year, month) + day;
328}
329
330/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
331static int
332weekday(int year, int month, int day)
333{
334 return (ymd_to_ord(year, month, day) + 6) % 7;
335}
336
337/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
338 * first calendar week containing a Thursday.
339 */
340static int
341iso_week1_monday(int year)
342{
343 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
344 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
345 int first_weekday = (first_day + 6) % 7;
346 /* ordinal of closest Monday at or before 1/1 */
347 int week1_monday = first_day - first_weekday;
348
349 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
350 week1_monday += 7;
351 return week1_monday;
352}
353
354/* ---------------------------------------------------------------------------
355 * Range checkers.
356 */
357
358/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
360 */
361static int
362check_delta_day_range(int days)
363{
364 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
365 return 0;
366 PyErr_Format(PyExc_OverflowError,
367 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000368 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000369 return -1;
370}
371
372/* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
374 */
375static int
376check_date_args(int year, int month, int day)
377{
378
379 if (year < MINYEAR || year > MAXYEAR) {
380 PyErr_SetString(PyExc_ValueError,
381 "year is out of range");
382 return -1;
383 }
384 if (month < 1 || month > 12) {
385 PyErr_SetString(PyExc_ValueError,
386 "month must be in 1..12");
387 return -1;
388 }
389 if (day < 1 || day > days_in_month(year, month)) {
390 PyErr_SetString(PyExc_ValueError,
391 "day is out of range for month");
392 return -1;
393 }
394 return 0;
395}
396
397/* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_time_args(int h, int m, int s, int us)
402{
403 if (h < 0 || h > 23) {
404 PyErr_SetString(PyExc_ValueError,
405 "hour must be in 0..23");
406 return -1;
407 }
408 if (m < 0 || m > 59) {
409 PyErr_SetString(PyExc_ValueError,
410 "minute must be in 0..59");
411 return -1;
412 }
413 if (s < 0 || s > 59) {
414 PyErr_SetString(PyExc_ValueError,
415 "second must be in 0..59");
416 return -1;
417 }
418 if (us < 0 || us > 999999) {
419 PyErr_SetString(PyExc_ValueError,
420 "microsecond must be in 0..999999");
421 return -1;
422 }
423 return 0;
424}
425
426/* ---------------------------------------------------------------------------
427 * Normalization utilities.
428 */
429
430/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
431 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
432 * at least factor, enough of *lo is converted into "hi" units so that
433 * 0 <= *lo < factor. The input values must be such that int overflow
434 * is impossible.
435 */
436static void
437normalize_pair(int *hi, int *lo, int factor)
438{
439 assert(factor > 0);
440 assert(lo != hi);
441 if (*lo < 0 || *lo >= factor) {
442 const int num_hi = divmod(*lo, factor, lo);
443 const int new_hi = *hi + num_hi;
444 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
445 *hi = new_hi;
446 }
447 assert(0 <= *lo && *lo < factor);
448}
449
450/* Fiddle days (d), seconds (s), and microseconds (us) so that
451 * 0 <= *s < 24*3600
452 * 0 <= *us < 1000000
453 * The input values must be such that the internals don't overflow.
454 * The way this routine is used, we don't get close.
455 */
456static void
457normalize_d_s_us(int *d, int *s, int *us)
458{
459 if (*us < 0 || *us >= 1000000) {
460 normalize_pair(s, us, 1000000);
461 /* |s| can't be bigger than about
462 * |original s| + |original us|/1000000 now.
463 */
464
465 }
466 if (*s < 0 || *s >= 24*3600) {
467 normalize_pair(d, s, 24*3600);
468 /* |d| can't be bigger than about
469 * |original d| +
470 * (|original s| + |original us|/1000000) / (24*3600) now.
471 */
472 }
473 assert(0 <= *s && *s < 24*3600);
474 assert(0 <= *us && *us < 1000000);
475}
476
477/* Fiddle years (y), months (m), and days (d) so that
478 * 1 <= *m <= 12
479 * 1 <= *d <= days_in_month(*y, *m)
480 * The input values must be such that the internals don't overflow.
481 * The way this routine is used, we don't get close.
482 */
483static void
484normalize_y_m_d(int *y, int *m, int *d)
485{
486 int dim; /* # of days in month */
487
488 /* This gets muddy: the proper range for day can't be determined
489 * without knowing the correct month and year, but if day is, e.g.,
490 * plus or minus a million, the current month and year values make
491 * no sense (and may also be out of bounds themselves).
492 * Saying 12 months == 1 year should be non-controversial.
493 */
494 if (*m < 1 || *m > 12) {
495 --*m;
496 normalize_pair(y, m, 12);
497 ++*m;
498 /* |y| can't be bigger than about
499 * |original y| + |original m|/12 now.
500 */
501 }
502 assert(1 <= *m && *m <= 12);
503
504 /* Now only day can be out of bounds (year may also be out of bounds
505 * for a datetime object, but we don't care about that here).
506 * If day is out of bounds, what to do is arguable, but at least the
507 * method here is principled and explainable.
508 */
509 dim = days_in_month(*y, *m);
510 if (*d < 1 || *d > dim) {
511 /* Move day-1 days from the first of the month. First try to
512 * get off cheap if we're only one day out of range
513 * (adjustments for timezone alone can't be worse than that).
514 */
515 if (*d == 0) {
516 --*m;
517 if (*m > 0)
518 *d = days_in_month(*y, *m);
519 else {
520 --*y;
521 *m = 12;
522 *d = 31;
523 }
524 }
525 else if (*d == dim + 1) {
526 /* move forward a day */
527 ++*m;
528 *d = 1;
529 if (*m > 12) {
530 *m = 1;
531 ++*y;
532 }
533 }
534 else {
535 int ordinal = ymd_to_ord(*y, *m, 1) +
536 *d - 1;
537 ord_to_ymd(ordinal, y, m, d);
538 }
539 }
540 assert(*m > 0);
541 assert(*d > 0);
542}
543
544/* Fiddle out-of-bounds months and days so that the result makes some kind
545 * of sense. The parameters are both inputs and outputs. Returns < 0 on
546 * failure, where failure means the adjusted year is out of bounds.
547 */
548static int
549normalize_date(int *year, int *month, int *day)
550{
551 int result;
552
553 normalize_y_m_d(year, month, day);
554 if (MINYEAR <= *year && *year <= MAXYEAR)
555 result = 0;
556 else {
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 result = -1;
560 }
561 return result;
562}
563
564/* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
566 */
567static int
568normalize_datetime(int *year, int *month, int *day,
569 int *hour, int *minute, int *second,
570 int *microsecond)
571{
572 normalize_pair(second, microsecond, 1000000);
573 normalize_pair(minute, second, 60);
574 normalize_pair(hour, minute, 60);
575 normalize_pair(day, hour, 24);
576 return normalize_date(year, month, day);
577}
578
579/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000580 * Basic object allocation: tp_alloc implementations. These allocate
581 * Python objects of the right size and type, and do the Python object-
582 * initialization bit. If there's not enough memory, they return NULL after
583 * setting MemoryError. All data members remain uninitialized trash.
584 *
585 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000586 * member is needed. This is ugly, imprecise, and possibly insecure.
587 * tp_basicsize for the time and datetime types is set to the size of the
588 * struct that has room for the tzinfo member, so subclasses in Python will
589 * allocate enough space for a tzinfo member whether or not one is actually
590 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
591 * part is that PyType_GenericAlloc() (which subclasses in Python end up
592 * using) just happens today to effectively ignore the nitems argument
593 * when tp_itemsize is 0, which it is for these type objects. If that
594 * changes, perhaps the callers of tp_alloc slots in this file should
595 * be changed to force a 0 nitems argument unless the type being allocated
596 * is a base type implemented in this file (so that tp_alloc is time_alloc
597 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000598 */
599
600static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000601time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000602{
603 PyObject *self;
604
605 self = (PyObject *)
606 PyObject_MALLOC(aware ?
607 sizeof(PyDateTime_Time) :
608 sizeof(_PyDateTime_BaseTime));
609 if (self == NULL)
610 return (PyObject *)PyErr_NoMemory();
611 PyObject_INIT(self, type);
612 return self;
613}
614
615static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000616datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000617{
618 PyObject *self;
619
620 self = (PyObject *)
621 PyObject_MALLOC(aware ?
622 sizeof(PyDateTime_DateTime) :
623 sizeof(_PyDateTime_BaseDateTime));
624 if (self == NULL)
625 return (PyObject *)PyErr_NoMemory();
626 PyObject_INIT(self, type);
627 return self;
628}
629
630/* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
633 */
634
635/* For date and datetime. */
636static void
637set_date_fields(PyDateTime_Date *self, int y, int m, int d)
638{
639 self->hashcode = -1;
640 SET_YEAR(self, y);
641 SET_MONTH(self, m);
642 SET_DAY(self, d);
643}
644
645/* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
647 */
648
649/* Create a date instance with no range checking. */
650static PyObject *
651new_date_ex(int year, int month, int day, PyTypeObject *type)
652{
653 PyDateTime_Date *self;
654
655 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
656 if (self != NULL)
657 set_date_fields(self, year, month, day);
658 return (PyObject *) self;
659}
660
661#define new_date(year, month, day) \
662 new_date_ex(year, month, day, &PyDateTime_DateType)
663
664/* Create a datetime instance with no range checking. */
665static PyObject *
666new_datetime_ex(int year, int month, int day, int hour, int minute,
667 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
668{
669 PyDateTime_DateTime *self;
670 char aware = tzinfo != Py_None;
671
672 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
673 if (self != NULL) {
674 self->hastzinfo = aware;
675 set_date_fields((PyDateTime_Date *)self, year, month, day);
676 DATE_SET_HOUR(self, hour);
677 DATE_SET_MINUTE(self, minute);
678 DATE_SET_SECOND(self, second);
679 DATE_SET_MICROSECOND(self, usecond);
680 if (aware) {
681 Py_INCREF(tzinfo);
682 self->tzinfo = tzinfo;
683 }
684 }
685 return (PyObject *)self;
686}
687
688#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
689 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
690 &PyDateTime_DateTimeType)
691
692/* Create a time instance with no range checking. */
693static PyObject *
694new_time_ex(int hour, int minute, int second, int usecond,
695 PyObject *tzinfo, PyTypeObject *type)
696{
697 PyDateTime_Time *self;
698 char aware = tzinfo != Py_None;
699
700 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
701 if (self != NULL) {
702 self->hastzinfo = aware;
703 self->hashcode = -1;
704 TIME_SET_HOUR(self, hour);
705 TIME_SET_MINUTE(self, minute);
706 TIME_SET_SECOND(self, second);
707 TIME_SET_MICROSECOND(self, usecond);
708 if (aware) {
709 Py_INCREF(tzinfo);
710 self->tzinfo = tzinfo;
711 }
712 }
713 return (PyObject *)self;
714}
715
716#define new_time(hh, mm, ss, us, tzinfo) \
717 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
718
719/* Create a timedelta instance. Normalize the members iff normalize is
720 * true. Passing false is a speed optimization, if you know for sure
721 * that seconds and microseconds are already in their proper ranges. In any
722 * case, raises OverflowError and returns NULL if the normalized days is out
723 * of range).
724 */
725static PyObject *
726new_delta_ex(int days, int seconds, int microseconds, int normalize,
727 PyTypeObject *type)
728{
729 PyDateTime_Delta *self;
730
731 if (normalize)
732 normalize_d_s_us(&days, &seconds, &microseconds);
733 assert(0 <= seconds && seconds < 24*3600);
734 assert(0 <= microseconds && microseconds < 1000000);
735
736 if (check_delta_day_range(days) < 0)
737 return NULL;
738
739 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
740 if (self != NULL) {
741 self->hashcode = -1;
742 SET_TD_DAYS(self, days);
743 SET_TD_SECONDS(self, seconds);
744 SET_TD_MICROSECONDS(self, microseconds);
745 }
746 return (PyObject *) self;
747}
748
749#define new_delta(d, s, us, normalize) \
750 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
751
752/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000753 * tzinfo helpers.
754 */
755
Tim Peters855fe882002-12-22 03:43:39 +0000756/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
758 */
759static int
760check_tzinfo_subclass(PyObject *p)
761{
762 if (p == Py_None || PyTZInfo_Check(p))
763 return 0;
764 PyErr_Format(PyExc_TypeError,
765 "tzinfo argument must be None or of a tzinfo subclass, "
766 "not type '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000767 Py_TYPE(p)->tp_name);
Tim Peters855fe882002-12-22 03:43:39 +0000768 return -1;
769}
770
Tim Petersbad8ff02002-12-30 20:52:32 +0000771/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000772 * If tzinfo is None, returns None.
773 */
774static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000775call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000776{
777 PyObject *result;
778
Tim Petersbad8ff02002-12-30 20:52:32 +0000779 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
784 }
785 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000787 return result;
788}
789
Tim Peters2a799bf2002-12-16 20:18:38 +0000790/* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
793 */
794static PyObject *
795get_tzinfo_member(PyObject *self)
796{
797 PyObject *tzinfo = NULL;
798
Tim Petersa9bc1682003-01-11 03:39:11 +0000799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000801 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
804 return tzinfo;
805}
806
Tim Petersbad8ff02002-12-30 20:52:32 +0000807/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * Else *none is set to 0 and the integer method result is returned.
814 */
815static int
816call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
818{
819 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000820 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000821
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
825
826 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 if (u == NULL)
829 return -1;
830
Tim Peters27362852002-12-23 16:17:39 +0000831 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 result = 0;
833 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000834 }
Tim Peters855fe882002-12-22 03:43:39 +0000835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
842 */
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000851 }
852 }
853 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000854 else {
855 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000856 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000857 "timedelta, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000858 name, Py_TYPE(u)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 }
860
Tim Peters2a799bf2002-12-16 20:18:38 +0000861 Py_DECREF(u);
862 if (result < -1439 || result > 1439) {
863 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000864 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000865 "-1439 .. 1439",
866 name, result);
867 result = -1;
868 }
Tim Peters397301e2003-01-02 21:28:08 +0000869 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000870}
871
872/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
873 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
874 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000875 * doesn't return None or timedelta, TypeError is raised and this returns -1.
876 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
877 * # of minutes), ValueError is raised and this returns -1. Else *none is
878 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000879 */
880static int
881call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
882{
883 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
884}
885
Tim Petersbad8ff02002-12-30 20:52:32 +0000886/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
887 */
Tim Peters855fe882002-12-22 03:43:39 +0000888static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000889offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000890 PyObject *result;
891
Tim Petersbad8ff02002-12-30 20:52:32 +0000892 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000893 if (tzinfo == Py_None) {
894 result = Py_None;
895 Py_INCREF(result);
896 }
897 else {
898 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000899 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
900 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000901 if (offset < 0 && PyErr_Occurred())
902 return NULL;
903 if (none) {
904 result = Py_None;
905 Py_INCREF(result);
906 }
907 else
908 result = new_delta(0, offset * 60, 0, 1);
909 }
910 return result;
911}
912
Tim Peters2a799bf2002-12-16 20:18:38 +0000913/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If dst()
915 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000916 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000917 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000918 * ValueError is raised and this returns -1. Else *none is set to 0 and
919 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000920 */
921static int
922call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
923{
924 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
925}
926
Tim Petersbad8ff02002-12-30 20:52:32 +0000927/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000928 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000929 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000930 * returns NULL. If the result is a string, we ensure it is a Unicode
931 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000932 */
933static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000934call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000935{
936 PyObject *result;
937
938 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000939 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000940 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000941
Tim Peters855fe882002-12-22 03:43:39 +0000942 if (tzinfo == Py_None) {
943 result = Py_None;
944 Py_INCREF(result);
945 }
946 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000947 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000948
Guido van Rossume3d1d412007-05-23 21:24:35 +0000949 if (result != NULL && result != Py_None) {
Guido van Rossumfd53fd62007-08-24 04:05:13 +0000950 if (!PyUnicode_Check(result)) {
Guido van Rossume3d1d412007-05-23 21:24:35 +0000951 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
952 "return None or a string, not '%s'",
Christian Heimes90aa7642007-12-19 02:45:37 +0000953 Py_TYPE(result)->tp_name);
Guido van Rossume3d1d412007-05-23 21:24:35 +0000954 Py_DECREF(result);
955 result = NULL;
956 }
957 else if (!PyUnicode_Check(result)) {
958 PyObject *temp = PyUnicode_FromObject(result);
959 Py_DECREF(result);
960 result = temp;
961 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000962 }
963 return result;
964}
965
966typedef enum {
967 /* an exception has been set; the caller should pass it on */
968 OFFSET_ERROR,
969
Tim Petersa9bc1682003-01-11 03:39:11 +0000970 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000971 OFFSET_UNKNOWN,
972
973 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000974 * datetime with !hastzinfo
975 * datetime with None tzinfo,
976 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000977 * time with !hastzinfo
978 * time with None tzinfo,
979 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 */
981 OFFSET_NAIVE,
982
Tim Petersa9bc1682003-01-11 03:39:11 +0000983 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000984 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000985} naivety;
986
Tim Peters14b69412002-12-22 18:10:22 +0000987/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000988 * the "naivety" typedef for details. If the type is aware, *offset is set
989 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000990 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 */
993static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000994classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000995{
996 int none;
997 PyObject *tzinfo;
998
Tim Peterse39a80c2002-12-30 21:28:52 +0000999 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001000 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +00001001 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (tzinfo == Py_None)
1003 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +00001004 if (tzinfo == NULL) {
1005 /* note that a datetime passes the PyDate_Check test */
1006 return (PyTime_Check(op) || PyDate_Check(op)) ?
1007 OFFSET_NAIVE : OFFSET_UNKNOWN;
1008 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001009 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001010 if (*offset == -1 && PyErr_Occurred())
1011 return OFFSET_ERROR;
1012 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1013}
1014
Tim Peters00237032002-12-27 02:21:51 +00001015/* Classify two objects as to whether they're naive or offset-aware.
1016 * This isn't quite the same as calling classify_utcoffset() twice: for
1017 * binary operations (comparison and subtraction), we generally want to
1018 * ignore the tzinfo members if they're identical. This is by design,
1019 * so that results match "naive" expectations when mixing objects from a
1020 * single timezone. So in that case, this sets both offsets to 0 and
1021 * both naiveties to OFFSET_NAIVE.
1022 * The function returns 0 if everything's OK, and -1 on error.
1023 */
1024static int
1025classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001026 PyObject *tzinfoarg1,
1027 PyObject *o2, int *offset2, naivety *n2,
1028 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001029{
1030 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1031 *offset1 = *offset2 = 0;
1032 *n1 = *n2 = OFFSET_NAIVE;
1033 }
1034 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001035 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001036 if (*n1 == OFFSET_ERROR)
1037 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001038 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001039 if (*n2 == OFFSET_ERROR)
1040 return -1;
1041 }
1042 return 0;
1043}
1044
Tim Peters2a799bf2002-12-16 20:18:38 +00001045/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1046 * stuff
1047 * ", tzinfo=" + repr(tzinfo)
1048 * before the closing ")".
1049 */
1050static PyObject *
1051append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1052{
1053 PyObject *temp;
1054
Walter Dörwald1ab83302007-05-18 17:15:44 +00001055 assert(PyUnicode_Check(repr));
Tim Peters2a799bf2002-12-16 20:18:38 +00001056 assert(tzinfo);
1057 if (tzinfo == Py_None)
1058 return repr;
1059 /* Get rid of the trailing ')'. */
Walter Dörwald1ab83302007-05-18 17:15:44 +00001060 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1061 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1062 PyUnicode_GET_SIZE(repr) - 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001063 Py_DECREF(repr);
1064 if (temp == NULL)
1065 return NULL;
Walter Dörwald517bcfe2007-05-23 20:45:05 +00001066 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1067 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00001068 return repr;
1069}
1070
1071/* ---------------------------------------------------------------------------
1072 * String format helpers.
1073 */
1074
1075static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001076format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001077{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001078 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001079 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1080 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001081 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001082 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1083 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1084 };
1085
Tim Peters2a799bf2002-12-16 20:18:38 +00001086 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1087
Walter Dörwald4af32b32007-05-31 16:19:50 +00001088 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1089 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1090 GET_DAY(date), hours, minutes, seconds,
1091 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001092}
1093
1094/* Add an hours & minutes UTC offset string to buf. buf has no more than
1095 * buflen bytes remaining. The UTC offset is gotten by calling
1096 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1097 * *buf, and that's all. Else the returned value is checked for sanity (an
1098 * integer in range), and if that's OK it's converted to an hours & minutes
1099 * string of the form
1100 * sign HH sep MM
1101 * Returns 0 if everything is OK. If the return value from utcoffset() is
1102 * bogus, an appropriate exception is set and -1 is returned.
1103 */
1104static int
Tim Peters328fff72002-12-20 01:31:27 +00001105format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001106 PyObject *tzinfo, PyObject *tzinfoarg)
1107{
1108 int offset;
1109 int hours;
1110 int minutes;
1111 char sign;
1112 int none;
1113
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001114 assert(buflen >= 1);
1115
Tim Peters2a799bf2002-12-16 20:18:38 +00001116 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1117 if (offset == -1 && PyErr_Occurred())
1118 return -1;
1119 if (none) {
1120 *buf = '\0';
1121 return 0;
1122 }
1123 sign = '+';
1124 if (offset < 0) {
1125 sign = '-';
1126 offset = - offset;
1127 }
1128 hours = divmod(offset, 60, &minutes);
1129 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1130 return 0;
1131}
1132
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001133static PyObject *
1134make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1135{
Neal Norwitzaea70e02007-08-12 04:32:26 +00001136 PyObject *temp;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001137 PyObject *tzinfo = get_tzinfo_member(object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001138 PyObject *Zreplacement = PyUnicode_FromStringAndSize(NULL, 0);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001139 if (Zreplacement == NULL)
1140 return NULL;
Neal Norwitzaea70e02007-08-12 04:32:26 +00001141 if (tzinfo == Py_None || tzinfo == NULL)
1142 return Zreplacement;
1143
1144 assert(tzinfoarg != NULL);
1145 temp = call_tzname(tzinfo, tzinfoarg);
1146 if (temp == NULL)
1147 goto Error;
1148 if (temp == Py_None) {
1149 Py_DECREF(temp);
1150 return Zreplacement;
1151 }
1152
1153 assert(PyUnicode_Check(temp));
1154 /* Since the tzname is getting stuffed into the
1155 * format, we have to double any % signs so that
1156 * strftime doesn't treat them as format codes.
1157 */
1158 Py_DECREF(Zreplacement);
1159 Zreplacement = PyObject_CallMethod(temp, "replace", "ss", "%", "%%");
1160 Py_DECREF(temp);
1161 if (Zreplacement == NULL)
1162 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001163 if (!PyUnicode_Check(Zreplacement)) {
Neal Norwitzaea70e02007-08-12 04:32:26 +00001164 PyErr_SetString(PyExc_TypeError,
1165 "tzname.replace() did not return a string");
1166 goto Error;
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001167 }
1168 return Zreplacement;
1169
1170 Error:
1171 Py_DECREF(Zreplacement);
1172 return NULL;
1173}
1174
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001175static PyObject *
1176make_freplacement(PyObject *object)
1177{
Christian Heimesb186d002008-03-18 15:15:01 +00001178 char freplacement[64];
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001179 if (PyTime_Check(object))
1180 sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1181 else if (PyDateTime_Check(object))
1182 sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1183 else
1184 sprintf(freplacement, "%06d", 0);
1185
Christian Heimes72b710a2008-05-26 13:28:38 +00001186 return PyBytes_FromStringAndSize(freplacement, strlen(freplacement));
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001187}
1188
Tim Peters2a799bf2002-12-16 20:18:38 +00001189/* I sure don't want to reproduce the strftime code from the time module,
1190 * so this imports the module and calls it. All the hair is due to
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001191 * giving special meanings to the %z, %Z and %f format codes via a
1192 * preprocessing step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001193 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1194 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001195 */
1196static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001197wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1198 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001199{
1200 PyObject *result = NULL; /* guilty until proved innocent */
1201
1202 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1203 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001204 PyObject *freplacement = NULL; /* py string, replacement for %f */
Tim Peters2a799bf2002-12-16 20:18:38 +00001205
Georg Brandlf78e02b2008-06-10 17:40:04 +00001206 const char *pin; /* pointer to next char in input format */
1207 Py_ssize_t flen; /* length of input format */
1208 char ch; /* next char in input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001209
1210 PyObject *newfmt = NULL; /* py string, the output format */
1211 char *pnew; /* pointer to available byte in output format */
Georg Brandlf78e02b2008-06-10 17:40:04 +00001212 size_t totalnew; /* number bytes total in output format buffer,
1213 exclusive of trailing \0 */
1214 size_t usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001215
Georg Brandlf78e02b2008-06-10 17:40:04 +00001216 const char *ptoappend; /* ptr to string to append to output buffer */
Brett Cannon27da8122007-11-06 23:15:11 +00001217 Py_ssize_t ntoappend; /* # of bytes to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001218
Tim Peters2a799bf2002-12-16 20:18:38 +00001219 assert(object && format && timetuple);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001220 assert(PyUnicode_Check(format));
Neal Norwitz908c8712007-08-27 04:58:38 +00001221 /* Convert the input format to a C string and size */
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001222 pin = _PyUnicode_AsStringAndSize(format, &flen);
Neal Norwitz908c8712007-08-27 04:58:38 +00001223 if (!pin)
1224 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001225
Tim Petersd6844152002-12-22 20:58:42 +00001226 /* Give up if the year is before 1900.
1227 * Python strftime() plays games with the year, and different
1228 * games depending on whether envar PYTHON2K is set. This makes
1229 * years before 1900 a nightmare, even if the platform strftime
1230 * supports them (and not all do).
1231 * We could get a lot farther here by avoiding Python's strftime
1232 * wrapper and calling the C strftime() directly, but that isn't
1233 * an option in the Python implementation of this module.
1234 */
1235 {
1236 long year;
1237 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1238 if (pyyear == NULL) return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +00001239 assert(PyLong_Check(pyyear));
1240 year = PyLong_AsLong(pyyear);
Tim Petersd6844152002-12-22 20:58:42 +00001241 Py_DECREF(pyyear);
1242 if (year < 1900) {
1243 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1244 "1900; the datetime strftime() "
1245 "methods require year >= 1900",
1246 year);
1247 return NULL;
1248 }
1249 }
1250
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001251 /* Scan the input format, looking for %z/%Z/%f escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001252 * a new format. Since computing the replacements for those codes
1253 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001254 */
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001255 if (flen > INT_MAX - 1) {
1256 PyErr_NoMemory();
1257 goto Done;
1258 }
1259
Guido van Rossumbce56a62007-05-10 18:04:33 +00001260 totalnew = flen + 1; /* realistic if no %z/%Z */
Christian Heimes72b710a2008-05-26 13:28:38 +00001261 newfmt = PyBytes_FromStringAndSize(NULL, totalnew);
Tim Peters2a799bf2002-12-16 20:18:38 +00001262 if (newfmt == NULL) goto Done;
Christian Heimes72b710a2008-05-26 13:28:38 +00001263 pnew = PyBytes_AsString(newfmt);
Tim Peters2a799bf2002-12-16 20:18:38 +00001264 usednew = 0;
1265
Tim Peters2a799bf2002-12-16 20:18:38 +00001266 while ((ch = *pin++) != '\0') {
1267 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001268 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001269 ntoappend = 1;
1270 }
1271 else if ((ch = *pin++) == '\0') {
1272 /* There's a lone trailing %; doesn't make sense. */
1273 PyErr_SetString(PyExc_ValueError, "strftime format "
1274 "ends with raw %");
1275 goto Done;
1276 }
1277 /* A % has been seen and ch is the character after it. */
1278 else if (ch == 'z') {
1279 if (zreplacement == NULL) {
1280 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001281 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001282 PyObject *tzinfo = get_tzinfo_member(object);
Christian Heimes72b710a2008-05-26 13:28:38 +00001283 zreplacement = PyBytes_FromStringAndSize("", 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001284 if (zreplacement == NULL) goto Done;
1285 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001286 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001287 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001288 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001289 "",
1290 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001291 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001292 goto Done;
1293 Py_DECREF(zreplacement);
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001294 zreplacement =
Christian Heimes72b710a2008-05-26 13:28:38 +00001295 PyBytes_FromStringAndSize(buf,
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001296 strlen(buf));
1297 if (zreplacement == NULL)
1298 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001299 }
1300 }
1301 assert(zreplacement != NULL);
Christian Heimes72b710a2008-05-26 13:28:38 +00001302 ptoappend = PyBytes_AS_STRING(zreplacement);
1303 ntoappend = PyBytes_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001304 }
1305 else if (ch == 'Z') {
1306 /* format tzname */
1307 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001308 Zreplacement = make_Zreplacement(object,
1309 tzinfoarg);
1310 if (Zreplacement == NULL)
1311 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001312 }
1313 assert(Zreplacement != NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001314 assert(PyUnicode_Check(Zreplacement));
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001315 ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
Guido van Rossum98297ee2007-11-06 21:34:58 +00001316 &ntoappend);
Christian Heimes90aa7642007-12-19 02:45:37 +00001317 ntoappend = Py_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001318 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001319 else if (ch == 'f') {
1320 /* format microseconds */
1321 if (freplacement == NULL) {
1322 freplacement = make_freplacement(object);
1323 if (freplacement == NULL)
1324 goto Done;
1325 }
1326 assert(freplacement != NULL);
Christian Heimes72b710a2008-05-26 13:28:38 +00001327 assert(PyBytes_Check(freplacement));
1328 ptoappend = PyBytes_AS_STRING(freplacement);
1329 ntoappend = PyBytes_GET_SIZE(freplacement);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001330 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001331 else {
Tim Peters328fff72002-12-20 01:31:27 +00001332 /* percent followed by neither z nor Z */
1333 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001334 ntoappend = 2;
1335 }
1336
1337 /* Append the ntoappend chars starting at ptoappend to
1338 * the new format.
1339 */
Tim Peters2a799bf2002-12-16 20:18:38 +00001340 if (ntoappend == 0)
1341 continue;
Guido van Rossumfd53fd62007-08-24 04:05:13 +00001342 assert(ptoappend != NULL);
1343 assert(ntoappend > 0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001344 while (usednew + ntoappend > totalnew) {
Georg Brandlf78e02b2008-06-10 17:40:04 +00001345 size_t bigger = totalnew << 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001346 if ((bigger >> 1) != totalnew) { /* overflow */
1347 PyErr_NoMemory();
1348 goto Done;
1349 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001350 if (_PyBytes_Resize(&newfmt, bigger) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001351 goto Done;
1352 totalnew = bigger;
Christian Heimes72b710a2008-05-26 13:28:38 +00001353 pnew = PyBytes_AsString(newfmt) + usednew;
Tim Peters2a799bf2002-12-16 20:18:38 +00001354 }
1355 memcpy(pnew, ptoappend, ntoappend);
1356 pnew += ntoappend;
1357 usednew += ntoappend;
1358 assert(usednew <= totalnew);
1359 } /* end while() */
1360
Christian Heimes72b710a2008-05-26 13:28:38 +00001361 if (_PyBytes_Resize(&newfmt, usednew) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001362 goto Done;
1363 {
Neal Norwitz908c8712007-08-27 04:58:38 +00001364 PyObject *format;
Christian Heimes072c0f12008-01-03 23:01:04 +00001365 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001366 if (time == NULL)
1367 goto Done;
Christian Heimes72b710a2008-05-26 13:28:38 +00001368 format = PyUnicode_FromString(PyBytes_AS_STRING(newfmt));
Neal Norwitz908c8712007-08-27 04:58:38 +00001369 if (format != NULL) {
1370 result = PyObject_CallMethod(time, "strftime", "OO",
1371 format, timetuple);
1372 Py_DECREF(format);
1373 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001374 Py_DECREF(time);
1375 }
1376 Done:
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001377 Py_XDECREF(freplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001378 Py_XDECREF(zreplacement);
1379 Py_XDECREF(Zreplacement);
1380 Py_XDECREF(newfmt);
1381 return result;
1382}
1383
Tim Peters2a799bf2002-12-16 20:18:38 +00001384/* ---------------------------------------------------------------------------
1385 * Wrap functions from the time module. These aren't directly available
1386 * from C. Perhaps they should be.
1387 */
1388
1389/* Call time.time() and return its result (a Python float). */
1390static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001391time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001392{
1393 PyObject *result = NULL;
Christian Heimes072c0f12008-01-03 23:01:04 +00001394 PyObject *time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001395
1396 if (time != NULL) {
1397 result = PyObject_CallMethod(time, "time", "()");
1398 Py_DECREF(time);
1399 }
1400 return result;
1401}
1402
1403/* Build a time.struct_time. The weekday and day number are automatically
1404 * computed from the y,m,d args.
1405 */
1406static PyObject *
1407build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1408{
1409 PyObject *time;
1410 PyObject *result = NULL;
1411
Christian Heimes072c0f12008-01-03 23:01:04 +00001412 time = PyImport_ImportModuleNoBlock("time");
Tim Peters2a799bf2002-12-16 20:18:38 +00001413 if (time != NULL) {
1414 result = PyObject_CallMethod(time, "struct_time",
1415 "((iiiiiiiii))",
1416 y, m, d,
1417 hh, mm, ss,
1418 weekday(y, m, d),
1419 days_before_month(y, m) + d,
1420 dstflag);
1421 Py_DECREF(time);
1422 }
1423 return result;
1424}
1425
1426/* ---------------------------------------------------------------------------
1427 * Miscellaneous helpers.
1428 */
1429
Mark Dickinsone94c6792009-02-02 20:36:42 +00001430/* For various reasons, we need to use tp_richcompare instead of tp_reserved.
Tim Peters2a799bf2002-12-16 20:18:38 +00001431 * The comparisons here all most naturally compute a cmp()-like result.
1432 * This little helper turns that into a bool result for rich comparisons.
1433 */
1434static PyObject *
1435diff_to_bool(int diff, int op)
1436{
1437 PyObject *result;
1438 int istrue;
1439
1440 switch (op) {
1441 case Py_EQ: istrue = diff == 0; break;
1442 case Py_NE: istrue = diff != 0; break;
1443 case Py_LE: istrue = diff <= 0; break;
1444 case Py_GE: istrue = diff >= 0; break;
1445 case Py_LT: istrue = diff < 0; break;
1446 case Py_GT: istrue = diff > 0; break;
1447 default:
1448 assert(! "op unknown");
1449 istrue = 0; /* To shut up compiler */
1450 }
1451 result = istrue ? Py_True : Py_False;
1452 Py_INCREF(result);
1453 return result;
1454}
1455
Tim Peters07534a62003-02-07 22:50:28 +00001456/* Raises a "can't compare" TypeError and returns NULL. */
1457static PyObject *
1458cmperror(PyObject *a, PyObject *b)
1459{
1460 PyErr_Format(PyExc_TypeError,
1461 "can't compare %s to %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001462 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
Tim Peters07534a62003-02-07 22:50:28 +00001463 return NULL;
1464}
1465
Tim Peters2a799bf2002-12-16 20:18:38 +00001466/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001467 * Cached Python objects; these are set by the module init function.
1468 */
1469
1470/* Conversion factors. */
1471static PyObject *us_per_us = NULL; /* 1 */
1472static PyObject *us_per_ms = NULL; /* 1000 */
1473static PyObject *us_per_second = NULL; /* 1000000 */
1474static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1475static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1476static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1477static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1478static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1479
Tim Peters2a799bf2002-12-16 20:18:38 +00001480/* ---------------------------------------------------------------------------
1481 * Class implementations.
1482 */
1483
1484/*
1485 * PyDateTime_Delta implementation.
1486 */
1487
1488/* Convert a timedelta to a number of us,
1489 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1490 * as a Python int or long.
1491 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1492 * due to ubiquitous overflow possibilities.
1493 */
1494static PyObject *
1495delta_to_microseconds(PyDateTime_Delta *self)
1496{
1497 PyObject *x1 = NULL;
1498 PyObject *x2 = NULL;
1499 PyObject *x3 = NULL;
1500 PyObject *result = NULL;
1501
Christian Heimes217cfd12007-12-02 14:31:20 +00001502 x1 = PyLong_FromLong(GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001503 if (x1 == NULL)
1504 goto Done;
1505 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1506 if (x2 == NULL)
1507 goto Done;
1508 Py_DECREF(x1);
1509 x1 = NULL;
1510
1511 /* x2 has days in seconds */
Christian Heimes217cfd12007-12-02 14:31:20 +00001512 x1 = PyLong_FromLong(GET_TD_SECONDS(self)); /* seconds */
Tim Peters2a799bf2002-12-16 20:18:38 +00001513 if (x1 == NULL)
1514 goto Done;
1515 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1516 if (x3 == NULL)
1517 goto Done;
1518 Py_DECREF(x1);
1519 Py_DECREF(x2);
1520 x1 = x2 = NULL;
1521
1522 /* x3 has days+seconds in seconds */
1523 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1524 if (x1 == NULL)
1525 goto Done;
1526 Py_DECREF(x3);
1527 x3 = NULL;
1528
1529 /* x1 has days+seconds in us */
Christian Heimes217cfd12007-12-02 14:31:20 +00001530 x2 = PyLong_FromLong(GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001531 if (x2 == NULL)
1532 goto Done;
1533 result = PyNumber_Add(x1, x2);
1534
1535Done:
1536 Py_XDECREF(x1);
1537 Py_XDECREF(x2);
1538 Py_XDECREF(x3);
1539 return result;
1540}
1541
1542/* Convert a number of us (as a Python int or long) to a timedelta.
1543 */
1544static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001545microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001546{
1547 int us;
1548 int s;
1549 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001550 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001551
1552 PyObject *tuple = NULL;
1553 PyObject *num = NULL;
1554 PyObject *result = NULL;
1555
1556 tuple = PyNumber_Divmod(pyus, us_per_second);
1557 if (tuple == NULL)
1558 goto Done;
1559
1560 num = PyTuple_GetItem(tuple, 1); /* us */
1561 if (num == NULL)
1562 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001563 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001564 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001565 if (temp == -1 && PyErr_Occurred())
1566 goto Done;
1567 assert(0 <= temp && temp < 1000000);
1568 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001569 if (us < 0) {
1570 /* The divisor was positive, so this must be an error. */
1571 assert(PyErr_Occurred());
1572 goto Done;
1573 }
1574
1575 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1576 if (num == NULL)
1577 goto Done;
1578 Py_INCREF(num);
1579 Py_DECREF(tuple);
1580
1581 tuple = PyNumber_Divmod(num, seconds_per_day);
1582 if (tuple == NULL)
1583 goto Done;
1584 Py_DECREF(num);
1585
1586 num = PyTuple_GetItem(tuple, 1); /* seconds */
1587 if (num == NULL)
1588 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001589 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001590 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001591 if (temp == -1 && PyErr_Occurred())
1592 goto Done;
1593 assert(0 <= temp && temp < 24*3600);
1594 s = (int)temp;
1595
Tim Peters2a799bf2002-12-16 20:18:38 +00001596 if (s < 0) {
1597 /* The divisor was positive, so this must be an error. */
1598 assert(PyErr_Occurred());
1599 goto Done;
1600 }
1601
1602 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1603 if (num == NULL)
1604 goto Done;
1605 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001606 temp = PyLong_AsLong(num);
1607 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001608 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001609 d = (int)temp;
1610 if ((long)d != temp) {
1611 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1612 "large to fit in a C int");
1613 goto Done;
1614 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001615 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001616
1617Done:
1618 Py_XDECREF(tuple);
1619 Py_XDECREF(num);
1620 return result;
1621}
1622
Tim Petersb0c854d2003-05-17 15:57:00 +00001623#define microseconds_to_delta(pymicros) \
1624 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1625
Tim Peters2a799bf2002-12-16 20:18:38 +00001626static PyObject *
1627multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1628{
1629 PyObject *pyus_in;
1630 PyObject *pyus_out;
1631 PyObject *result;
1632
1633 pyus_in = delta_to_microseconds(delta);
1634 if (pyus_in == NULL)
1635 return NULL;
1636
1637 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1638 Py_DECREF(pyus_in);
1639 if (pyus_out == NULL)
1640 return NULL;
1641
1642 result = microseconds_to_delta(pyus_out);
1643 Py_DECREF(pyus_out);
1644 return result;
1645}
1646
1647static PyObject *
1648divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1649{
1650 PyObject *pyus_in;
1651 PyObject *pyus_out;
1652 PyObject *result;
1653
1654 pyus_in = delta_to_microseconds(delta);
1655 if (pyus_in == NULL)
1656 return NULL;
1657
1658 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1659 Py_DECREF(pyus_in);
1660 if (pyus_out == NULL)
1661 return NULL;
1662
1663 result = microseconds_to_delta(pyus_out);
1664 Py_DECREF(pyus_out);
1665 return result;
1666}
1667
1668static PyObject *
Mark Dickinson7c186e22010-04-20 22:32:49 +00001669divide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1670{
1671 PyObject *pyus_left;
1672 PyObject *pyus_right;
1673 PyObject *result;
1674
1675 pyus_left = delta_to_microseconds(left);
1676 if (pyus_left == NULL)
1677 return NULL;
1678
1679 pyus_right = delta_to_microseconds(right);
1680 if (pyus_right == NULL) {
1681 Py_DECREF(pyus_left);
1682 return NULL;
1683 }
1684
1685 result = PyNumber_FloorDivide(pyus_left, pyus_right);
1686 Py_DECREF(pyus_left);
1687 Py_DECREF(pyus_right);
1688 return result;
1689}
1690
1691static PyObject *
1692truedivide_timedelta_timedelta(PyDateTime_Delta *left, PyDateTime_Delta *right)
1693{
1694 PyObject *pyus_left;
1695 PyObject *pyus_right;
1696 PyObject *result;
1697
1698 pyus_left = delta_to_microseconds(left);
1699 if (pyus_left == NULL)
1700 return NULL;
1701
1702 pyus_right = delta_to_microseconds(right);
1703 if (pyus_right == NULL) {
1704 Py_DECREF(pyus_left);
1705 return NULL;
1706 }
1707
1708 result = PyNumber_TrueDivide(pyus_left, pyus_right);
1709 Py_DECREF(pyus_left);
1710 Py_DECREF(pyus_right);
1711 return result;
1712}
1713
1714static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00001715delta_add(PyObject *left, PyObject *right)
1716{
1717 PyObject *result = Py_NotImplemented;
1718
1719 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1720 /* delta + delta */
1721 /* The C-level additions can't overflow because of the
1722 * invariant bounds.
1723 */
1724 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1725 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1726 int microseconds = GET_TD_MICROSECONDS(left) +
1727 GET_TD_MICROSECONDS(right);
1728 result = new_delta(days, seconds, microseconds, 1);
1729 }
1730
1731 if (result == Py_NotImplemented)
1732 Py_INCREF(result);
1733 return result;
1734}
1735
1736static PyObject *
1737delta_negative(PyDateTime_Delta *self)
1738{
1739 return new_delta(-GET_TD_DAYS(self),
1740 -GET_TD_SECONDS(self),
1741 -GET_TD_MICROSECONDS(self),
1742 1);
1743}
1744
1745static PyObject *
1746delta_positive(PyDateTime_Delta *self)
1747{
1748 /* Could optimize this (by returning self) if this isn't a
1749 * subclass -- but who uses unary + ? Approximately nobody.
1750 */
1751 return new_delta(GET_TD_DAYS(self),
1752 GET_TD_SECONDS(self),
1753 GET_TD_MICROSECONDS(self),
1754 0);
1755}
1756
1757static PyObject *
1758delta_abs(PyDateTime_Delta *self)
1759{
1760 PyObject *result;
1761
1762 assert(GET_TD_MICROSECONDS(self) >= 0);
1763 assert(GET_TD_SECONDS(self) >= 0);
1764
1765 if (GET_TD_DAYS(self) < 0)
1766 result = delta_negative(self);
1767 else
1768 result = delta_positive(self);
1769
1770 return result;
1771}
1772
1773static PyObject *
1774delta_subtract(PyObject *left, PyObject *right)
1775{
1776 PyObject *result = Py_NotImplemented;
1777
1778 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1779 /* delta - delta */
1780 PyObject *minus_right = PyNumber_Negative(right);
1781 if (minus_right) {
1782 result = delta_add(left, minus_right);
1783 Py_DECREF(minus_right);
1784 }
1785 else
1786 result = NULL;
1787 }
1788
1789 if (result == Py_NotImplemented)
1790 Py_INCREF(result);
1791 return result;
1792}
1793
Tim Peters2a799bf2002-12-16 20:18:38 +00001794static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001795delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001796{
Tim Petersaa7d8492003-02-08 03:28:59 +00001797 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001798 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001799 if (diff == 0) {
1800 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1801 if (diff == 0)
1802 diff = GET_TD_MICROSECONDS(self) -
1803 GET_TD_MICROSECONDS(other);
1804 }
Guido van Rossum19960592006-08-24 17:29:38 +00001805 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001806 }
Guido van Rossum19960592006-08-24 17:29:38 +00001807 else {
1808 Py_INCREF(Py_NotImplemented);
1809 return Py_NotImplemented;
1810 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001811}
1812
1813static PyObject *delta_getstate(PyDateTime_Delta *self);
1814
1815static long
1816delta_hash(PyDateTime_Delta *self)
1817{
1818 if (self->hashcode == -1) {
1819 PyObject *temp = delta_getstate(self);
1820 if (temp != NULL) {
1821 self->hashcode = PyObject_Hash(temp);
1822 Py_DECREF(temp);
1823 }
1824 }
1825 return self->hashcode;
1826}
1827
1828static PyObject *
1829delta_multiply(PyObject *left, PyObject *right)
1830{
1831 PyObject *result = Py_NotImplemented;
1832
1833 if (PyDelta_Check(left)) {
1834 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001835 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001836 result = multiply_int_timedelta(right,
1837 (PyDateTime_Delta *) left);
1838 }
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001839 else if (PyLong_Check(left))
Tim Peters2a799bf2002-12-16 20:18:38 +00001840 result = multiply_int_timedelta(left,
1841 (PyDateTime_Delta *) right);
1842
1843 if (result == Py_NotImplemented)
1844 Py_INCREF(result);
1845 return result;
1846}
1847
1848static PyObject *
1849delta_divide(PyObject *left, PyObject *right)
1850{
1851 PyObject *result = Py_NotImplemented;
1852
1853 if (PyDelta_Check(left)) {
1854 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001855 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001856 result = divide_timedelta_int(
1857 (PyDateTime_Delta *)left,
1858 right);
Mark Dickinson7c186e22010-04-20 22:32:49 +00001859 else if (PyDelta_Check(right))
1860 result = divide_timedelta_timedelta(
1861 (PyDateTime_Delta *)left,
1862 (PyDateTime_Delta *)right);
Tim Peters2a799bf2002-12-16 20:18:38 +00001863 }
1864
1865 if (result == Py_NotImplemented)
1866 Py_INCREF(result);
1867 return result;
1868}
1869
Mark Dickinson7c186e22010-04-20 22:32:49 +00001870static PyObject *
1871delta_truedivide(PyObject *left, PyObject *right)
1872{
1873 PyObject *result = Py_NotImplemented;
1874
1875 if (PyDelta_Check(left)) {
1876 if (PyDelta_Check(right))
1877 result = truedivide_timedelta_timedelta(
1878 (PyDateTime_Delta *)left,
1879 (PyDateTime_Delta *)right);
1880 }
1881
1882 if (result == Py_NotImplemented)
1883 Py_INCREF(result);
1884 return result;
1885}
1886
1887static PyObject *
1888delta_remainder(PyObject *left, PyObject *right)
1889{
1890 PyObject *pyus_left;
1891 PyObject *pyus_right;
1892 PyObject *pyus_remainder;
1893 PyObject *remainder;
1894
1895 if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
1896 Py_INCREF(Py_NotImplemented);
1897 return Py_NotImplemented;
1898 }
1899
1900 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1901 if (pyus_left == NULL)
1902 return NULL;
1903
1904 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1905 if (pyus_right == NULL) {
1906 Py_DECREF(pyus_left);
1907 return NULL;
1908 }
1909
1910 pyus_remainder = PyNumber_Remainder(pyus_left, pyus_right);
1911 Py_DECREF(pyus_left);
1912 Py_DECREF(pyus_right);
1913 if (pyus_remainder == NULL)
1914 return NULL;
1915
1916 remainder = microseconds_to_delta(pyus_remainder);
Mark Dickinson56a60872010-04-20 22:39:53 +00001917 Py_DECREF(pyus_remainder);
1918 if (remainder == NULL)
Mark Dickinson7c186e22010-04-20 22:32:49 +00001919 return NULL;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001920
1921 return remainder;
1922}
1923
1924static PyObject *
1925delta_divmod(PyObject *left, PyObject *right)
1926{
1927 PyObject *pyus_left;
1928 PyObject *pyus_right;
1929 PyObject *divmod;
Mark Dickinsona03e5342010-04-20 23:24:25 +00001930 PyObject *delta;
1931 PyObject *result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001932
1933 if (!PyDelta_Check(left) || !PyDelta_Check(right)) {
1934 Py_INCREF(Py_NotImplemented);
1935 return Py_NotImplemented;
1936 }
1937
1938 pyus_left = delta_to_microseconds((PyDateTime_Delta *)left);
1939 if (pyus_left == NULL)
1940 return NULL;
1941
1942 pyus_right = delta_to_microseconds((PyDateTime_Delta *)right);
1943 if (pyus_right == NULL) {
1944 Py_DECREF(pyus_left);
1945 return NULL;
1946 }
1947
1948 divmod = PyNumber_Divmod(pyus_left, pyus_right);
1949 Py_DECREF(pyus_left);
1950 Py_DECREF(pyus_right);
1951 if (divmod == NULL)
1952 return NULL;
1953
Mark Dickinsona03e5342010-04-20 23:24:25 +00001954 assert(PyTuple_Size(divmod) == 2);
1955 delta = microseconds_to_delta(PyTuple_GET_ITEM(divmod, 1));
Mark Dickinson7c186e22010-04-20 22:32:49 +00001956 if (delta == NULL) {
1957 Py_DECREF(divmod);
1958 return NULL;
1959 }
Mark Dickinsona03e5342010-04-20 23:24:25 +00001960 result = PyTuple_Pack(2, PyTuple_GET_ITEM(divmod, 0), delta);
1961 Py_DECREF(delta);
1962 Py_DECREF(divmod);
1963 return result;
Mark Dickinson7c186e22010-04-20 22:32:49 +00001964}
1965
Tim Peters2a799bf2002-12-16 20:18:38 +00001966/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1967 * timedelta constructor. sofar is the # of microseconds accounted for
1968 * so far, and there are factor microseconds per current unit, the number
1969 * of which is given by num. num * factor is added to sofar in a
1970 * numerically careful way, and that's the result. Any fractional
1971 * microseconds left over (this can happen if num is a float type) are
1972 * added into *leftover.
1973 * Note that there are many ways this can give an error (NULL) return.
1974 */
1975static PyObject *
1976accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1977 double *leftover)
1978{
1979 PyObject *prod;
1980 PyObject *sum;
1981
1982 assert(num != NULL);
1983
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001984 if (PyLong_Check(num)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00001985 prod = PyNumber_Multiply(num, factor);
1986 if (prod == NULL)
1987 return NULL;
1988 sum = PyNumber_Add(sofar, prod);
1989 Py_DECREF(prod);
1990 return sum;
1991 }
1992
1993 if (PyFloat_Check(num)) {
1994 double dnum;
1995 double fracpart;
1996 double intpart;
1997 PyObject *x;
1998 PyObject *y;
1999
2000 /* The Plan: decompose num into an integer part and a
2001 * fractional part, num = intpart + fracpart.
2002 * Then num * factor ==
2003 * intpart * factor + fracpart * factor
2004 * and the LHS can be computed exactly in long arithmetic.
2005 * The RHS is again broken into an int part and frac part.
2006 * and the frac part is added into *leftover.
2007 */
2008 dnum = PyFloat_AsDouble(num);
2009 if (dnum == -1.0 && PyErr_Occurred())
2010 return NULL;
2011 fracpart = modf(dnum, &intpart);
2012 x = PyLong_FromDouble(intpart);
2013 if (x == NULL)
2014 return NULL;
2015
2016 prod = PyNumber_Multiply(x, factor);
2017 Py_DECREF(x);
2018 if (prod == NULL)
2019 return NULL;
2020
2021 sum = PyNumber_Add(sofar, prod);
2022 Py_DECREF(prod);
2023 if (sum == NULL)
2024 return NULL;
2025
2026 if (fracpart == 0.0)
2027 return sum;
2028 /* So far we've lost no information. Dealing with the
2029 * fractional part requires float arithmetic, and may
2030 * lose a little info.
2031 */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00002032 assert(PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00002033 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00002034
2035 dnum *= fracpart;
2036 fracpart = modf(dnum, &intpart);
2037 x = PyLong_FromDouble(intpart);
2038 if (x == NULL) {
2039 Py_DECREF(sum);
2040 return NULL;
2041 }
2042
2043 y = PyNumber_Add(sum, x);
2044 Py_DECREF(sum);
2045 Py_DECREF(x);
2046 *leftover += fracpart;
2047 return y;
2048 }
2049
2050 PyErr_Format(PyExc_TypeError,
2051 "unsupported type for timedelta %s component: %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00002052 tag, Py_TYPE(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00002053 return NULL;
2054}
2055
2056static PyObject *
2057delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2058{
2059 PyObject *self = NULL;
2060
2061 /* Argument objects. */
2062 PyObject *day = NULL;
2063 PyObject *second = NULL;
2064 PyObject *us = NULL;
2065 PyObject *ms = NULL;
2066 PyObject *minute = NULL;
2067 PyObject *hour = NULL;
2068 PyObject *week = NULL;
2069
2070 PyObject *x = NULL; /* running sum of microseconds */
2071 PyObject *y = NULL; /* temp sum of microseconds */
2072 double leftover_us = 0.0;
2073
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002074 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002075 "days", "seconds", "microseconds", "milliseconds",
2076 "minutes", "hours", "weeks", NULL
2077 };
2078
2079 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
2080 keywords,
2081 &day, &second, &us,
2082 &ms, &minute, &hour, &week) == 0)
2083 goto Done;
2084
Christian Heimes217cfd12007-12-02 14:31:20 +00002085 x = PyLong_FromLong(0);
Tim Peters2a799bf2002-12-16 20:18:38 +00002086 if (x == NULL)
2087 goto Done;
2088
2089#define CLEANUP \
2090 Py_DECREF(x); \
2091 x = y; \
2092 if (x == NULL) \
2093 goto Done
2094
2095 if (us) {
2096 y = accum("microseconds", x, us, us_per_us, &leftover_us);
2097 CLEANUP;
2098 }
2099 if (ms) {
2100 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
2101 CLEANUP;
2102 }
2103 if (second) {
2104 y = accum("seconds", x, second, us_per_second, &leftover_us);
2105 CLEANUP;
2106 }
2107 if (minute) {
2108 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
2109 CLEANUP;
2110 }
2111 if (hour) {
2112 y = accum("hours", x, hour, us_per_hour, &leftover_us);
2113 CLEANUP;
2114 }
2115 if (day) {
2116 y = accum("days", x, day, us_per_day, &leftover_us);
2117 CLEANUP;
2118 }
2119 if (week) {
2120 y = accum("weeks", x, week, us_per_week, &leftover_us);
2121 CLEANUP;
2122 }
2123 if (leftover_us) {
2124 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00002125 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00002126 if (temp == NULL) {
2127 Py_DECREF(x);
2128 goto Done;
2129 }
2130 y = PyNumber_Add(x, temp);
2131 Py_DECREF(temp);
2132 CLEANUP;
2133 }
2134
Tim Petersb0c854d2003-05-17 15:57:00 +00002135 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002136 Py_DECREF(x);
2137Done:
2138 return self;
2139
2140#undef CLEANUP
2141}
2142
2143static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00002144delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002145{
2146 return (GET_TD_DAYS(self) != 0
2147 || GET_TD_SECONDS(self) != 0
2148 || GET_TD_MICROSECONDS(self) != 0);
2149}
2150
2151static PyObject *
2152delta_repr(PyDateTime_Delta *self)
2153{
2154 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00002155 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002156 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002157 GET_TD_DAYS(self),
2158 GET_TD_SECONDS(self),
2159 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002160 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00002161 return PyUnicode_FromFormat("%s(%d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002162 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002163 GET_TD_DAYS(self),
2164 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002165
Walter Dörwald1ab83302007-05-18 17:15:44 +00002166 return PyUnicode_FromFormat("%s(%d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002167 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002168 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002169}
2170
2171static PyObject *
2172delta_str(PyDateTime_Delta *self)
2173{
Tim Peters2a799bf2002-12-16 20:18:38 +00002174 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002175 int seconds = GET_TD_SECONDS(self);
2176 int minutes = divmod(seconds, 60, &seconds);
2177 int hours = divmod(minutes, 60, &minutes);
2178 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002179
2180 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002181 if (us)
2182 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2183 days, (days == 1 || days == -1) ? "" : "s",
2184 hours, minutes, seconds, us);
2185 else
2186 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2187 days, (days == 1 || days == -1) ? "" : "s",
2188 hours, minutes, seconds);
2189 } else {
2190 if (us)
2191 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2192 hours, minutes, seconds, us);
2193 else
2194 return PyUnicode_FromFormat("%d:%02d:%02d",
2195 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002196 }
2197
Tim Peters2a799bf2002-12-16 20:18:38 +00002198}
2199
Tim Peters371935f2003-02-01 01:52:50 +00002200/* Pickle support, a simple use of __reduce__. */
2201
Tim Petersb57f8f02003-02-01 02:54:15 +00002202/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002203static PyObject *
2204delta_getstate(PyDateTime_Delta *self)
2205{
2206 return Py_BuildValue("iii", GET_TD_DAYS(self),
2207 GET_TD_SECONDS(self),
2208 GET_TD_MICROSECONDS(self));
2209}
2210
Tim Peters2a799bf2002-12-16 20:18:38 +00002211static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002212delta_total_seconds(PyObject *self)
2213{
2214 return PyFloat_FromDouble(GET_TD_MICROSECONDS(self) / 1000000.0 +
2215 GET_TD_SECONDS(self) +
2216 GET_TD_DAYS(self) * 24.0 * 3600.0);
2217}
2218
2219static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002220delta_reduce(PyDateTime_Delta* self)
2221{
Christian Heimes90aa7642007-12-19 02:45:37 +00002222 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002223}
2224
2225#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2226
2227static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002228
Neal Norwitzdfb80862002-12-19 02:30:56 +00002229 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002230 PyDoc_STR("Number of days.")},
2231
Neal Norwitzdfb80862002-12-19 02:30:56 +00002232 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002233 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2234
Neal Norwitzdfb80862002-12-19 02:30:56 +00002235 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002236 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2237 {NULL}
2238};
2239
2240static PyMethodDef delta_methods[] = {
Antoine Pitroube6859d2009-11-25 23:02:32 +00002241 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2242 PyDoc_STR("Total seconds in the duration.")},
2243
2244 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
Guido van Rossum177e41a2003-01-30 22:06:23 +00002245 PyDoc_STR("__reduce__() -> (cls, state)")},
2246
Tim Peters2a799bf2002-12-16 20:18:38 +00002247 {NULL, NULL},
2248};
2249
2250static char delta_doc[] =
2251PyDoc_STR("Difference between two datetime values.");
2252
2253static PyNumberMethods delta_as_number = {
2254 delta_add, /* nb_add */
2255 delta_subtract, /* nb_subtract */
2256 delta_multiply, /* nb_multiply */
Mark Dickinson7c186e22010-04-20 22:32:49 +00002257 delta_remainder, /* nb_remainder */
2258 delta_divmod, /* nb_divmod */
Tim Peters2a799bf2002-12-16 20:18:38 +00002259 0, /* nb_power */
2260 (unaryfunc)delta_negative, /* nb_negative */
2261 (unaryfunc)delta_positive, /* nb_positive */
2262 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002263 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002264 0, /*nb_invert*/
2265 0, /*nb_lshift*/
2266 0, /*nb_rshift*/
2267 0, /*nb_and*/
2268 0, /*nb_xor*/
2269 0, /*nb_or*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002270 0, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00002271 0, /*nb_reserved*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002272 0, /*nb_float*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002273 0, /*nb_inplace_add*/
2274 0, /*nb_inplace_subtract*/
2275 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002276 0, /*nb_inplace_remainder*/
2277 0, /*nb_inplace_power*/
2278 0, /*nb_inplace_lshift*/
2279 0, /*nb_inplace_rshift*/
2280 0, /*nb_inplace_and*/
2281 0, /*nb_inplace_xor*/
2282 0, /*nb_inplace_or*/
2283 delta_divide, /* nb_floor_divide */
Mark Dickinson7c186e22010-04-20 22:32:49 +00002284 delta_truedivide, /* nb_true_divide */
Tim Peters2a799bf2002-12-16 20:18:38 +00002285 0, /* nb_inplace_floor_divide */
2286 0, /* nb_inplace_true_divide */
2287};
2288
2289static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002290 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002291 "datetime.timedelta", /* tp_name */
2292 sizeof(PyDateTime_Delta), /* tp_basicsize */
2293 0, /* tp_itemsize */
2294 0, /* tp_dealloc */
2295 0, /* tp_print */
2296 0, /* tp_getattr */
2297 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002298 0, /* tp_reserved */
Tim Peters2a799bf2002-12-16 20:18:38 +00002299 (reprfunc)delta_repr, /* tp_repr */
2300 &delta_as_number, /* tp_as_number */
2301 0, /* tp_as_sequence */
2302 0, /* tp_as_mapping */
2303 (hashfunc)delta_hash, /* tp_hash */
2304 0, /* tp_call */
2305 (reprfunc)delta_str, /* tp_str */
2306 PyObject_GenericGetAttr, /* tp_getattro */
2307 0, /* tp_setattro */
2308 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002309 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002310 delta_doc, /* tp_doc */
2311 0, /* tp_traverse */
2312 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002313 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002314 0, /* tp_weaklistoffset */
2315 0, /* tp_iter */
2316 0, /* tp_iternext */
2317 delta_methods, /* tp_methods */
2318 delta_members, /* tp_members */
2319 0, /* tp_getset */
2320 0, /* tp_base */
2321 0, /* tp_dict */
2322 0, /* tp_descr_get */
2323 0, /* tp_descr_set */
2324 0, /* tp_dictoffset */
2325 0, /* tp_init */
2326 0, /* tp_alloc */
2327 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002328 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002329};
2330
2331/*
2332 * PyDateTime_Date implementation.
2333 */
2334
2335/* Accessor properties. */
2336
2337static PyObject *
2338date_year(PyDateTime_Date *self, void *unused)
2339{
Christian Heimes217cfd12007-12-02 14:31:20 +00002340 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002341}
2342
2343static PyObject *
2344date_month(PyDateTime_Date *self, void *unused)
2345{
Christian Heimes217cfd12007-12-02 14:31:20 +00002346 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002347}
2348
2349static PyObject *
2350date_day(PyDateTime_Date *self, void *unused)
2351{
Christian Heimes217cfd12007-12-02 14:31:20 +00002352 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002353}
2354
2355static PyGetSetDef date_getset[] = {
2356 {"year", (getter)date_year},
2357 {"month", (getter)date_month},
2358 {"day", (getter)date_day},
2359 {NULL}
2360};
2361
2362/* Constructors. */
2363
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002364static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002365
Tim Peters2a799bf2002-12-16 20:18:38 +00002366static PyObject *
2367date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2368{
2369 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002370 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002371 int year;
2372 int month;
2373 int day;
2374
Guido van Rossum177e41a2003-01-30 22:06:23 +00002375 /* Check for invocation from pickle with __getstate__ state */
2376 if (PyTuple_GET_SIZE(args) == 1 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00002377 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2378 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2379 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002380 {
Tim Peters70533e22003-02-01 04:40:04 +00002381 PyDateTime_Date *me;
2382
Tim Peters604c0132004-06-07 23:04:33 +00002383 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002384 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00002385 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002386 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2387 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002388 }
Tim Peters70533e22003-02-01 04:40:04 +00002389 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002390 }
2391
Tim Peters12bf3392002-12-24 05:41:27 +00002392 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002393 &year, &month, &day)) {
2394 if (check_date_args(year, month, day) < 0)
2395 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002396 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002397 }
2398 return self;
2399}
2400
2401/* Return new date from localtime(t). */
2402static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002403date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002404{
2405 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002406 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002407 PyObject *result = NULL;
2408
Tim Peters1b6f7a92004-06-20 02:50:16 +00002409 t = _PyTime_DoubleToTimet(ts);
2410 if (t == (time_t)-1 && PyErr_Occurred())
2411 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002412 tm = localtime(&t);
2413 if (tm)
2414 result = PyObject_CallFunction(cls, "iii",
2415 tm->tm_year + 1900,
2416 tm->tm_mon + 1,
2417 tm->tm_mday);
2418 else
2419 PyErr_SetString(PyExc_ValueError,
2420 "timestamp out of range for "
2421 "platform localtime() function");
2422 return result;
2423}
2424
2425/* Return new date from current time.
2426 * We say this is equivalent to fromtimestamp(time.time()), and the
2427 * only way to be sure of that is to *call* time.time(). That's not
2428 * generally the same as calling C's time.
2429 */
2430static PyObject *
2431date_today(PyObject *cls, PyObject *dummy)
2432{
2433 PyObject *time;
2434 PyObject *result;
2435
2436 time = time_time();
2437 if (time == NULL)
2438 return NULL;
2439
2440 /* Note well: today() is a class method, so this may not call
2441 * date.fromtimestamp. For example, it may call
2442 * datetime.fromtimestamp. That's why we need all the accuracy
2443 * time.time() delivers; if someone were gonzo about optimization,
2444 * date.today() could get away with plain C time().
2445 */
2446 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2447 Py_DECREF(time);
2448 return result;
2449}
2450
2451/* Return new date from given timestamp (Python timestamp -- a double). */
2452static PyObject *
2453date_fromtimestamp(PyObject *cls, PyObject *args)
2454{
2455 double timestamp;
2456 PyObject *result = NULL;
2457
2458 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002459 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002460 return result;
2461}
2462
2463/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2464 * the ordinal is out of range.
2465 */
2466static PyObject *
2467date_fromordinal(PyObject *cls, PyObject *args)
2468{
2469 PyObject *result = NULL;
2470 int ordinal;
2471
2472 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2473 int year;
2474 int month;
2475 int day;
2476
2477 if (ordinal < 1)
2478 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2479 ">= 1");
2480 else {
2481 ord_to_ymd(ordinal, &year, &month, &day);
2482 result = PyObject_CallFunction(cls, "iii",
2483 year, month, day);
2484 }
2485 }
2486 return result;
2487}
2488
2489/*
2490 * Date arithmetic.
2491 */
2492
2493/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2494 * instead.
2495 */
2496static PyObject *
2497add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2498{
2499 PyObject *result = NULL;
2500 int year = GET_YEAR(date);
2501 int month = GET_MONTH(date);
2502 int deltadays = GET_TD_DAYS(delta);
2503 /* C-level overflow is impossible because |deltadays| < 1e9. */
2504 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2505
2506 if (normalize_date(&year, &month, &day) >= 0)
2507 result = new_date(year, month, day);
2508 return result;
2509}
2510
2511static PyObject *
2512date_add(PyObject *left, PyObject *right)
2513{
2514 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2515 Py_INCREF(Py_NotImplemented);
2516 return Py_NotImplemented;
2517 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002518 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002519 /* date + ??? */
2520 if (PyDelta_Check(right))
2521 /* date + delta */
2522 return add_date_timedelta((PyDateTime_Date *) left,
2523 (PyDateTime_Delta *) right,
2524 0);
2525 }
2526 else {
2527 /* ??? + date
2528 * 'right' must be one of us, or we wouldn't have been called
2529 */
2530 if (PyDelta_Check(left))
2531 /* delta + date */
2532 return add_date_timedelta((PyDateTime_Date *) right,
2533 (PyDateTime_Delta *) left,
2534 0);
2535 }
2536 Py_INCREF(Py_NotImplemented);
2537 return Py_NotImplemented;
2538}
2539
2540static PyObject *
2541date_subtract(PyObject *left, PyObject *right)
2542{
2543 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2544 Py_INCREF(Py_NotImplemented);
2545 return Py_NotImplemented;
2546 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002547 if (PyDate_Check(left)) {
2548 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002549 /* date - date */
2550 int left_ord = ymd_to_ord(GET_YEAR(left),
2551 GET_MONTH(left),
2552 GET_DAY(left));
2553 int right_ord = ymd_to_ord(GET_YEAR(right),
2554 GET_MONTH(right),
2555 GET_DAY(right));
2556 return new_delta(left_ord - right_ord, 0, 0, 0);
2557 }
2558 if (PyDelta_Check(right)) {
2559 /* date - delta */
2560 return add_date_timedelta((PyDateTime_Date *) left,
2561 (PyDateTime_Delta *) right,
2562 1);
2563 }
2564 }
2565 Py_INCREF(Py_NotImplemented);
2566 return Py_NotImplemented;
2567}
2568
2569
2570/* Various ways to turn a date into a string. */
2571
2572static PyObject *
2573date_repr(PyDateTime_Date *self)
2574{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002575 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002576 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002577 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002578}
2579
2580static PyObject *
2581date_isoformat(PyDateTime_Date *self)
2582{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002583 return PyUnicode_FromFormat("%04d-%02d-%02d",
2584 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002585}
2586
Tim Peterse2df5ff2003-05-02 18:39:55 +00002587/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002588static PyObject *
2589date_str(PyDateTime_Date *self)
2590{
2591 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2592}
2593
2594
2595static PyObject *
2596date_ctime(PyDateTime_Date *self)
2597{
2598 return format_ctime(self, 0, 0, 0);
2599}
2600
2601static PyObject *
2602date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2603{
2604 /* This method can be inherited, and needs to call the
2605 * timetuple() method appropriate to self's class.
2606 */
2607 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002608 PyObject *tuple;
Georg Brandlf78e02b2008-06-10 17:40:04 +00002609 PyObject *format;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002610 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002611
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002612 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00002613 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002614 return NULL;
2615
2616 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2617 if (tuple == NULL)
2618 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002619 result = wrap_strftime((PyObject *)self, format, tuple,
2620 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002621 Py_DECREF(tuple);
2622 return result;
2623}
2624
Eric Smith1ba31142007-09-11 18:06:02 +00002625static PyObject *
2626date_format(PyDateTime_Date *self, PyObject *args)
2627{
2628 PyObject *format;
2629
2630 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2631 return NULL;
2632
2633 /* if the format is zero length, return str(self) */
2634 if (PyUnicode_GetSize(format) == 0)
Thomas Heller519a0422007-11-15 20:48:54 +00002635 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002636
2637 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
2638}
2639
Tim Peters2a799bf2002-12-16 20:18:38 +00002640/* ISO methods. */
2641
2642static PyObject *
2643date_isoweekday(PyDateTime_Date *self)
2644{
2645 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2646
Christian Heimes217cfd12007-12-02 14:31:20 +00002647 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002648}
2649
2650static PyObject *
2651date_isocalendar(PyDateTime_Date *self)
2652{
2653 int year = GET_YEAR(self);
2654 int week1_monday = iso_week1_monday(year);
2655 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2656 int week;
2657 int day;
2658
2659 week = divmod(today - week1_monday, 7, &day);
2660 if (week < 0) {
2661 --year;
2662 week1_monday = iso_week1_monday(year);
2663 week = divmod(today - week1_monday, 7, &day);
2664 }
2665 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2666 ++year;
2667 week = 0;
2668 }
2669 return Py_BuildValue("iii", year, week + 1, day + 1);
2670}
2671
2672/* Miscellaneous methods. */
2673
Tim Peters2a799bf2002-12-16 20:18:38 +00002674static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002675date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002676{
Guido van Rossum19960592006-08-24 17:29:38 +00002677 if (PyDate_Check(other)) {
2678 int diff = memcmp(((PyDateTime_Date *)self)->data,
2679 ((PyDateTime_Date *)other)->data,
2680 _PyDateTime_DATE_DATASIZE);
2681 return diff_to_bool(diff, op);
2682 }
2683 else {
Tim Peters07534a62003-02-07 22:50:28 +00002684 Py_INCREF(Py_NotImplemented);
2685 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002686 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002687}
2688
2689static PyObject *
2690date_timetuple(PyDateTime_Date *self)
2691{
2692 return build_struct_time(GET_YEAR(self),
2693 GET_MONTH(self),
2694 GET_DAY(self),
2695 0, 0, 0, -1);
2696}
2697
Tim Peters12bf3392002-12-24 05:41:27 +00002698static PyObject *
2699date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2700{
2701 PyObject *clone;
2702 PyObject *tuple;
2703 int year = GET_YEAR(self);
2704 int month = GET_MONTH(self);
2705 int day = GET_DAY(self);
2706
2707 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2708 &year, &month, &day))
2709 return NULL;
2710 tuple = Py_BuildValue("iii", year, month, day);
2711 if (tuple == NULL)
2712 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002713 clone = date_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002714 Py_DECREF(tuple);
2715 return clone;
2716}
2717
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002718/*
2719 Borrowed from stringobject.c, originally it was string_hash()
2720*/
2721static long
2722generic_hash(unsigned char *data, int len)
2723{
2724 register unsigned char *p;
2725 register long x;
2726
2727 p = (unsigned char *) data;
2728 x = *p << 7;
2729 while (--len >= 0)
2730 x = (1000003*x) ^ *p++;
2731 x ^= len;
2732 if (x == -1)
2733 x = -2;
2734
2735 return x;
2736}
2737
2738
2739static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002740
2741static long
2742date_hash(PyDateTime_Date *self)
2743{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002744 if (self->hashcode == -1)
2745 self->hashcode = generic_hash(
2746 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002747
Tim Peters2a799bf2002-12-16 20:18:38 +00002748 return self->hashcode;
2749}
2750
2751static PyObject *
2752date_toordinal(PyDateTime_Date *self)
2753{
Christian Heimes217cfd12007-12-02 14:31:20 +00002754 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
Tim Peters2a799bf2002-12-16 20:18:38 +00002755 GET_DAY(self)));
2756}
2757
2758static PyObject *
2759date_weekday(PyDateTime_Date *self)
2760{
2761 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2762
Christian Heimes217cfd12007-12-02 14:31:20 +00002763 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002764}
2765
Tim Peters371935f2003-02-01 01:52:50 +00002766/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002767
Tim Petersb57f8f02003-02-01 02:54:15 +00002768/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002769static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002770date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002771{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002772 PyObject* field;
Christian Heimes72b710a2008-05-26 13:28:38 +00002773 field = PyBytes_FromStringAndSize((char*)self->data,
Guido van Rossum254348e2007-11-21 19:29:53 +00002774 _PyDateTime_DATE_DATASIZE);
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002775 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002776}
2777
2778static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002779date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002780{
Christian Heimes90aa7642007-12-19 02:45:37 +00002781 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002782}
2783
2784static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002785
Tim Peters2a799bf2002-12-16 20:18:38 +00002786 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002787
Tim Peters2a799bf2002-12-16 20:18:38 +00002788 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2789 METH_CLASS,
2790 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2791 "time.time()).")},
2792
2793 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2794 METH_CLASS,
2795 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2796 "ordinal.")},
2797
2798 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2799 PyDoc_STR("Current date or datetime: same as "
2800 "self.__class__.fromtimestamp(time.time()).")},
2801
2802 /* Instance methods: */
2803
2804 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2805 PyDoc_STR("Return ctime() style string.")},
2806
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002807 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002808 PyDoc_STR("format -> strftime() style string.")},
2809
Eric Smith1ba31142007-09-11 18:06:02 +00002810 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2811 PyDoc_STR("Formats self with strftime.")},
2812
Tim Peters2a799bf2002-12-16 20:18:38 +00002813 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2814 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2815
2816 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2817 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2818 "weekday.")},
2819
2820 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2821 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2822
2823 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2824 PyDoc_STR("Return the day of the week represented by the date.\n"
2825 "Monday == 1 ... Sunday == 7")},
2826
2827 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2828 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2829 "1 is day 1.")},
2830
2831 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2832 PyDoc_STR("Return the day of the week represented by the date.\n"
2833 "Monday == 0 ... Sunday == 6")},
2834
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002835 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002836 PyDoc_STR("Return date with new specified fields.")},
2837
Guido van Rossum177e41a2003-01-30 22:06:23 +00002838 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2839 PyDoc_STR("__reduce__() -> (cls, state)")},
2840
Tim Peters2a799bf2002-12-16 20:18:38 +00002841 {NULL, NULL}
2842};
2843
2844static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002845PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002846
2847static PyNumberMethods date_as_number = {
2848 date_add, /* nb_add */
2849 date_subtract, /* nb_subtract */
2850 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002851 0, /* nb_remainder */
2852 0, /* nb_divmod */
2853 0, /* nb_power */
2854 0, /* nb_negative */
2855 0, /* nb_positive */
2856 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002857 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002858};
2859
2860static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002861 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002862 "datetime.date", /* tp_name */
2863 sizeof(PyDateTime_Date), /* tp_basicsize */
2864 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002865 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002866 0, /* tp_print */
2867 0, /* tp_getattr */
2868 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002869 0, /* tp_reserved */
Tim Peters2a799bf2002-12-16 20:18:38 +00002870 (reprfunc)date_repr, /* tp_repr */
2871 &date_as_number, /* tp_as_number */
2872 0, /* tp_as_sequence */
2873 0, /* tp_as_mapping */
2874 (hashfunc)date_hash, /* tp_hash */
2875 0, /* tp_call */
2876 (reprfunc)date_str, /* tp_str */
2877 PyObject_GenericGetAttr, /* tp_getattro */
2878 0, /* tp_setattro */
2879 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002880 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002881 date_doc, /* tp_doc */
2882 0, /* tp_traverse */
2883 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002884 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002885 0, /* tp_weaklistoffset */
2886 0, /* tp_iter */
2887 0, /* tp_iternext */
2888 date_methods, /* tp_methods */
2889 0, /* tp_members */
2890 date_getset, /* tp_getset */
2891 0, /* tp_base */
2892 0, /* tp_dict */
2893 0, /* tp_descr_get */
2894 0, /* tp_descr_set */
2895 0, /* tp_dictoffset */
2896 0, /* tp_init */
2897 0, /* tp_alloc */
2898 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002899 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002900};
2901
2902/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002903 * PyDateTime_TZInfo implementation.
2904 */
2905
2906/* This is a pure abstract base class, so doesn't do anything beyond
2907 * raising NotImplemented exceptions. Real tzinfo classes need
2908 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002909 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002910 * be subclasses of this tzinfo class, which is easy and quick to check).
2911 *
2912 * Note: For reasons having to do with pickling of subclasses, we have
2913 * to allow tzinfo objects to be instantiated. This wasn't an issue
2914 * in the Python implementation (__init__() could raise NotImplementedError
2915 * there without ill effect), but doing so in the C implementation hit a
2916 * brick wall.
2917 */
2918
2919static PyObject *
2920tzinfo_nogo(const char* methodname)
2921{
2922 PyErr_Format(PyExc_NotImplementedError,
2923 "a tzinfo subclass must implement %s()",
2924 methodname);
2925 return NULL;
2926}
2927
2928/* Methods. A subclass must implement these. */
2929
Tim Peters52dcce22003-01-23 16:36:11 +00002930static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002931tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2932{
2933 return tzinfo_nogo("tzname");
2934}
2935
Tim Peters52dcce22003-01-23 16:36:11 +00002936static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002937tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2938{
2939 return tzinfo_nogo("utcoffset");
2940}
2941
Tim Peters52dcce22003-01-23 16:36:11 +00002942static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002943tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2944{
2945 return tzinfo_nogo("dst");
2946}
2947
Tim Peters52dcce22003-01-23 16:36:11 +00002948static PyObject *
2949tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2950{
2951 int y, m, d, hh, mm, ss, us;
2952
2953 PyObject *result;
2954 int off, dst;
2955 int none;
2956 int delta;
2957
2958 if (! PyDateTime_Check(dt)) {
2959 PyErr_SetString(PyExc_TypeError,
2960 "fromutc: argument must be a datetime");
2961 return NULL;
2962 }
2963 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2964 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2965 "is not self");
2966 return NULL;
2967 }
2968
2969 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2970 if (off == -1 && PyErr_Occurred())
2971 return NULL;
2972 if (none) {
2973 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2974 "utcoffset() result required");
2975 return NULL;
2976 }
2977
2978 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2979 if (dst == -1 && PyErr_Occurred())
2980 return NULL;
2981 if (none) {
2982 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2983 "dst() result required");
2984 return NULL;
2985 }
2986
2987 y = GET_YEAR(dt);
2988 m = GET_MONTH(dt);
2989 d = GET_DAY(dt);
2990 hh = DATE_GET_HOUR(dt);
2991 mm = DATE_GET_MINUTE(dt);
2992 ss = DATE_GET_SECOND(dt);
2993 us = DATE_GET_MICROSECOND(dt);
2994
2995 delta = off - dst;
2996 mm += delta;
2997 if ((mm < 0 || mm >= 60) &&
2998 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002999 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00003000 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
3001 if (result == NULL)
3002 return result;
3003
3004 dst = call_dst(dt->tzinfo, result, &none);
3005 if (dst == -1 && PyErr_Occurred())
3006 goto Fail;
3007 if (none)
3008 goto Inconsistent;
3009 if (dst == 0)
3010 return result;
3011
3012 mm += dst;
3013 if ((mm < 0 || mm >= 60) &&
3014 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
3015 goto Fail;
3016 Py_DECREF(result);
3017 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
3018 return result;
3019
3020Inconsistent:
3021 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
3022 "inconsistent results; cannot convert");
3023
3024 /* fall thru to failure */
3025Fail:
3026 Py_DECREF(result);
3027 return NULL;
3028}
3029
Tim Peters2a799bf2002-12-16 20:18:38 +00003030/*
3031 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00003032 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00003033 */
3034
Guido van Rossum177e41a2003-01-30 22:06:23 +00003035static PyObject *
3036tzinfo_reduce(PyObject *self)
3037{
3038 PyObject *args, *state, *tmp;
3039 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00003040
Guido van Rossum177e41a2003-01-30 22:06:23 +00003041 tmp = PyTuple_New(0);
3042 if (tmp == NULL)
3043 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003044
Guido van Rossum177e41a2003-01-30 22:06:23 +00003045 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
3046 if (getinitargs != NULL) {
3047 args = PyObject_CallObject(getinitargs, tmp);
3048 Py_DECREF(getinitargs);
3049 if (args == NULL) {
3050 Py_DECREF(tmp);
3051 return NULL;
3052 }
3053 }
3054 else {
3055 PyErr_Clear();
3056 args = tmp;
3057 Py_INCREF(args);
3058 }
3059
3060 getstate = PyObject_GetAttrString(self, "__getstate__");
3061 if (getstate != NULL) {
3062 state = PyObject_CallObject(getstate, tmp);
3063 Py_DECREF(getstate);
3064 if (state == NULL) {
3065 Py_DECREF(args);
3066 Py_DECREF(tmp);
3067 return NULL;
3068 }
3069 }
3070 else {
3071 PyObject **dictptr;
3072 PyErr_Clear();
3073 state = Py_None;
3074 dictptr = _PyObject_GetDictPtr(self);
3075 if (dictptr && *dictptr && PyDict_Size(*dictptr))
3076 state = *dictptr;
3077 Py_INCREF(state);
3078 }
3079
3080 Py_DECREF(tmp);
3081
3082 if (state == Py_None) {
3083 Py_DECREF(state);
Christian Heimes90aa7642007-12-19 02:45:37 +00003084 return Py_BuildValue("(ON)", Py_TYPE(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003085 }
3086 else
Christian Heimes90aa7642007-12-19 02:45:37 +00003087 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00003088}
Tim Peters2a799bf2002-12-16 20:18:38 +00003089
3090static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003091
Tim Peters2a799bf2002-12-16 20:18:38 +00003092 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
3093 PyDoc_STR("datetime -> string name of time zone.")},
3094
3095 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
3096 PyDoc_STR("datetime -> minutes east of UTC (negative for "
3097 "west of UTC).")},
3098
3099 {"dst", (PyCFunction)tzinfo_dst, METH_O,
3100 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
3101
Tim Peters52dcce22003-01-23 16:36:11 +00003102 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
3103 PyDoc_STR("datetime in UTC -> datetime in local time.")},
3104
Guido van Rossum177e41a2003-01-30 22:06:23 +00003105 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
3106 PyDoc_STR("-> (cls, state)")},
3107
Tim Peters2a799bf2002-12-16 20:18:38 +00003108 {NULL, NULL}
3109};
3110
3111static char tzinfo_doc[] =
3112PyDoc_STR("Abstract base class for time zone info objects.");
3113
Neal Norwitz227b5332006-03-22 09:28:35 +00003114static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003115 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00003116 "datetime.tzinfo", /* tp_name */
3117 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
3118 0, /* tp_itemsize */
3119 0, /* tp_dealloc */
3120 0, /* tp_print */
3121 0, /* tp_getattr */
3122 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003123 0, /* tp_reserved */
Tim Peters2a799bf2002-12-16 20:18:38 +00003124 0, /* tp_repr */
3125 0, /* tp_as_number */
3126 0, /* tp_as_sequence */
3127 0, /* tp_as_mapping */
3128 0, /* tp_hash */
3129 0, /* tp_call */
3130 0, /* tp_str */
3131 PyObject_GenericGetAttr, /* tp_getattro */
3132 0, /* tp_setattro */
3133 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003134 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00003135 tzinfo_doc, /* tp_doc */
3136 0, /* tp_traverse */
3137 0, /* tp_clear */
3138 0, /* tp_richcompare */
3139 0, /* tp_weaklistoffset */
3140 0, /* tp_iter */
3141 0, /* tp_iternext */
3142 tzinfo_methods, /* tp_methods */
3143 0, /* tp_members */
3144 0, /* tp_getset */
3145 0, /* tp_base */
3146 0, /* tp_dict */
3147 0, /* tp_descr_get */
3148 0, /* tp_descr_set */
3149 0, /* tp_dictoffset */
3150 0, /* tp_init */
3151 0, /* tp_alloc */
3152 PyType_GenericNew, /* tp_new */
3153 0, /* tp_free */
3154};
3155
3156/*
Tim Peters37f39822003-01-10 03:49:02 +00003157 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003158 */
3159
Tim Peters37f39822003-01-10 03:49:02 +00003160/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003161 */
3162
3163static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003164time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003165{
Christian Heimes217cfd12007-12-02 14:31:20 +00003166 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003167}
3168
Tim Peters37f39822003-01-10 03:49:02 +00003169static PyObject *
3170time_minute(PyDateTime_Time *self, void *unused)
3171{
Christian Heimes217cfd12007-12-02 14:31:20 +00003172 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003173}
3174
3175/* The name time_second conflicted with some platform header file. */
3176static PyObject *
3177py_time_second(PyDateTime_Time *self, void *unused)
3178{
Christian Heimes217cfd12007-12-02 14:31:20 +00003179 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003180}
3181
3182static PyObject *
3183time_microsecond(PyDateTime_Time *self, void *unused)
3184{
Christian Heimes217cfd12007-12-02 14:31:20 +00003185 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003186}
3187
3188static PyObject *
3189time_tzinfo(PyDateTime_Time *self, void *unused)
3190{
Tim Petersa032d2e2003-01-11 00:15:54 +00003191 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003192 Py_INCREF(result);
3193 return result;
3194}
3195
3196static PyGetSetDef time_getset[] = {
3197 {"hour", (getter)time_hour},
3198 {"minute", (getter)time_minute},
3199 {"second", (getter)py_time_second},
3200 {"microsecond", (getter)time_microsecond},
3201 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003202 {NULL}
3203};
3204
3205/*
3206 * Constructors.
3207 */
3208
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003209static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003210 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003211
Tim Peters2a799bf2002-12-16 20:18:38 +00003212static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003213time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003214{
3215 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003216 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003217 int hour = 0;
3218 int minute = 0;
3219 int second = 0;
3220 int usecond = 0;
3221 PyObject *tzinfo = Py_None;
3222
Guido van Rossum177e41a2003-01-30 22:06:23 +00003223 /* Check for invocation from pickle with __getstate__ state */
3224 if (PyTuple_GET_SIZE(args) >= 1 &&
3225 PyTuple_GET_SIZE(args) <= 2 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00003226 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3227 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3228 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003229 {
Tim Peters70533e22003-02-01 04:40:04 +00003230 PyDateTime_Time *me;
3231 char aware;
3232
3233 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003234 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003235 if (check_tzinfo_subclass(tzinfo) < 0) {
3236 PyErr_SetString(PyExc_TypeError, "bad "
3237 "tzinfo state arg");
3238 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003239 }
3240 }
Tim Peters70533e22003-02-01 04:40:04 +00003241 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003242 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003243 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003244 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003245
3246 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3247 me->hashcode = -1;
3248 me->hastzinfo = aware;
3249 if (aware) {
3250 Py_INCREF(tzinfo);
3251 me->tzinfo = tzinfo;
3252 }
3253 }
3254 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003255 }
3256
Tim Peters37f39822003-01-10 03:49:02 +00003257 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003258 &hour, &minute, &second, &usecond,
3259 &tzinfo)) {
3260 if (check_time_args(hour, minute, second, usecond) < 0)
3261 return NULL;
3262 if (check_tzinfo_subclass(tzinfo) < 0)
3263 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003264 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3265 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003266 }
3267 return self;
3268}
3269
3270/*
3271 * Destructor.
3272 */
3273
3274static void
Tim Peters37f39822003-01-10 03:49:02 +00003275time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003276{
Tim Petersa032d2e2003-01-11 00:15:54 +00003277 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003278 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003279 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003280 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003281}
3282
3283/*
Tim Peters855fe882002-12-22 03:43:39 +00003284 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003285 */
3286
Tim Peters2a799bf2002-12-16 20:18:38 +00003287/* These are all METH_NOARGS, so don't need to check the arglist. */
3288static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003289time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003290 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003291 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003292}
3293
3294static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003295time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003296 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003297 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003298}
3299
3300static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003301time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003302 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003303 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003304}
3305
3306/*
Tim Peters37f39822003-01-10 03:49:02 +00003307 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003308 */
3309
3310static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003311time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003312{
Christian Heimes90aa7642007-12-19 02:45:37 +00003313 const char *type_name = Py_TYPE(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003314 int h = TIME_GET_HOUR(self);
3315 int m = TIME_GET_MINUTE(self);
3316 int s = TIME_GET_SECOND(self);
3317 int us = TIME_GET_MICROSECOND(self);
3318 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003319
Tim Peters37f39822003-01-10 03:49:02 +00003320 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003321 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3322 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003323 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003324 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3325 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003326 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003327 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003328 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003329 result = append_keyword_tzinfo(result, self->tzinfo);
3330 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003331}
3332
Tim Peters37f39822003-01-10 03:49:02 +00003333static PyObject *
3334time_str(PyDateTime_Time *self)
3335{
3336 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3337}
Tim Peters2a799bf2002-12-16 20:18:38 +00003338
3339static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003340time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003341{
3342 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003343 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003344 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003345
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003346 if (us)
3347 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3348 TIME_GET_HOUR(self),
3349 TIME_GET_MINUTE(self),
3350 TIME_GET_SECOND(self),
3351 us);
3352 else
3353 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3354 TIME_GET_HOUR(self),
3355 TIME_GET_MINUTE(self),
3356 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003357
Tim Petersa032d2e2003-01-11 00:15:54 +00003358 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003359 return result;
3360
3361 /* We need to append the UTC offset. */
3362 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003363 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003364 Py_DECREF(result);
3365 return NULL;
3366 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003367 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003368 return result;
3369}
3370
Tim Peters37f39822003-01-10 03:49:02 +00003371static PyObject *
3372time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3373{
3374 PyObject *result;
Tim Peters37f39822003-01-10 03:49:02 +00003375 PyObject *tuple;
Georg Brandlf78e02b2008-06-10 17:40:04 +00003376 PyObject *format;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003377 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003378
Guido van Rossum98297ee2007-11-06 21:34:58 +00003379 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00003380 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003381 return NULL;
3382
3383 /* Python's strftime does insane things with the year part of the
3384 * timetuple. The year is forced to (the otherwise nonsensical)
3385 * 1900 to worm around that.
3386 */
3387 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003388 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003389 TIME_GET_HOUR(self),
3390 TIME_GET_MINUTE(self),
3391 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003392 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003393 if (tuple == NULL)
3394 return NULL;
3395 assert(PyTuple_Size(tuple) == 9);
Georg Brandlf78e02b2008-06-10 17:40:04 +00003396 result = wrap_strftime((PyObject *)self, format, tuple,
3397 Py_None);
Tim Peters37f39822003-01-10 03:49:02 +00003398 Py_DECREF(tuple);
3399 return result;
3400}
Tim Peters2a799bf2002-12-16 20:18:38 +00003401
3402/*
3403 * Miscellaneous methods.
3404 */
3405
Tim Peters37f39822003-01-10 03:49:02 +00003406static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003407time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003408{
3409 int diff;
3410 naivety n1, n2;
3411 int offset1, offset2;
3412
3413 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003414 Py_INCREF(Py_NotImplemented);
3415 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003416 }
Guido van Rossum19960592006-08-24 17:29:38 +00003417 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3418 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003419 return NULL;
3420 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3421 /* If they're both naive, or both aware and have the same offsets,
3422 * we get off cheap. Note that if they're both naive, offset1 ==
3423 * offset2 == 0 at this point.
3424 */
3425 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003426 diff = memcmp(((PyDateTime_Time *)self)->data,
3427 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003428 _PyDateTime_TIME_DATASIZE);
3429 return diff_to_bool(diff, op);
3430 }
3431
3432 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3433 assert(offset1 != offset2); /* else last "if" handled it */
3434 /* Convert everything except microseconds to seconds. These
3435 * can't overflow (no more than the # of seconds in 2 days).
3436 */
3437 offset1 = TIME_GET_HOUR(self) * 3600 +
3438 (TIME_GET_MINUTE(self) - offset1) * 60 +
3439 TIME_GET_SECOND(self);
3440 offset2 = TIME_GET_HOUR(other) * 3600 +
3441 (TIME_GET_MINUTE(other) - offset2) * 60 +
3442 TIME_GET_SECOND(other);
3443 diff = offset1 - offset2;
3444 if (diff == 0)
3445 diff = TIME_GET_MICROSECOND(self) -
3446 TIME_GET_MICROSECOND(other);
3447 return diff_to_bool(diff, op);
3448 }
3449
3450 assert(n1 != n2);
3451 PyErr_SetString(PyExc_TypeError,
3452 "can't compare offset-naive and "
3453 "offset-aware times");
3454 return NULL;
3455}
3456
3457static long
3458time_hash(PyDateTime_Time *self)
3459{
3460 if (self->hashcode == -1) {
3461 naivety n;
3462 int offset;
3463 PyObject *temp;
3464
3465 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3466 assert(n != OFFSET_UNKNOWN);
3467 if (n == OFFSET_ERROR)
3468 return -1;
3469
3470 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003471 if (offset == 0) {
3472 self->hashcode = generic_hash(
3473 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3474 return self->hashcode;
3475 }
Tim Peters37f39822003-01-10 03:49:02 +00003476 else {
3477 int hour;
3478 int minute;
3479
3480 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003481 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003482 hour = divmod(TIME_GET_HOUR(self) * 60 +
3483 TIME_GET_MINUTE(self) - offset,
3484 60,
3485 &minute);
3486 if (0 <= hour && hour < 24)
3487 temp = new_time(hour, minute,
3488 TIME_GET_SECOND(self),
3489 TIME_GET_MICROSECOND(self),
3490 Py_None);
3491 else
3492 temp = Py_BuildValue("iiii",
3493 hour, minute,
3494 TIME_GET_SECOND(self),
3495 TIME_GET_MICROSECOND(self));
3496 }
3497 if (temp != NULL) {
3498 self->hashcode = PyObject_Hash(temp);
3499 Py_DECREF(temp);
3500 }
3501 }
3502 return self->hashcode;
3503}
Tim Peters2a799bf2002-12-16 20:18:38 +00003504
Tim Peters12bf3392002-12-24 05:41:27 +00003505static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003506time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003507{
3508 PyObject *clone;
3509 PyObject *tuple;
3510 int hh = TIME_GET_HOUR(self);
3511 int mm = TIME_GET_MINUTE(self);
3512 int ss = TIME_GET_SECOND(self);
3513 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003514 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003515
3516 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003517 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003518 &hh, &mm, &ss, &us, &tzinfo))
3519 return NULL;
3520 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3521 if (tuple == NULL)
3522 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003523 clone = time_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003524 Py_DECREF(tuple);
3525 return clone;
3526}
3527
Tim Peters2a799bf2002-12-16 20:18:38 +00003528static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003529time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003530{
3531 int offset;
3532 int none;
3533
3534 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3535 /* Since utcoffset is in whole minutes, nothing can
3536 * alter the conclusion that this is nonzero.
3537 */
3538 return 1;
3539 }
3540 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003541 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003542 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003543 if (offset == -1 && PyErr_Occurred())
3544 return -1;
3545 }
3546 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3547}
3548
Tim Peters371935f2003-02-01 01:52:50 +00003549/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003550
Tim Peters33e0f382003-01-10 02:05:14 +00003551/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003552 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3553 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003554 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003555 */
3556static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003557time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003558{
3559 PyObject *basestate;
3560 PyObject *result = NULL;
3561
Christian Heimes72b710a2008-05-26 13:28:38 +00003562 basestate = PyBytes_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003563 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003564 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003565 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003566 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003567 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003568 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003569 Py_DECREF(basestate);
3570 }
3571 return result;
3572}
3573
3574static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003575time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003576{
Christian Heimes90aa7642007-12-19 02:45:37 +00003577 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003578}
3579
Tim Peters37f39822003-01-10 03:49:02 +00003580static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003581
Thomas Wouterscf297e42007-02-23 15:07:44 +00003582 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003583 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3584 "[+HH:MM].")},
3585
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003586 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003587 PyDoc_STR("format -> strftime() style string.")},
3588
Eric Smith8fd3eba2008-02-17 19:48:00 +00003589 {"__format__", (PyCFunction)date_format, METH_VARARGS,
Eric Smith1ba31142007-09-11 18:06:02 +00003590 PyDoc_STR("Formats self with strftime.")},
3591
Tim Peters37f39822003-01-10 03:49:02 +00003592 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003593 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3594
Tim Peters37f39822003-01-10 03:49:02 +00003595 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003596 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3597
Tim Peters37f39822003-01-10 03:49:02 +00003598 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003599 PyDoc_STR("Return self.tzinfo.dst(self).")},
3600
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003601 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003602 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003603
Guido van Rossum177e41a2003-01-30 22:06:23 +00003604 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3605 PyDoc_STR("__reduce__() -> (cls, state)")},
3606
Tim Peters2a799bf2002-12-16 20:18:38 +00003607 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003608};
3609
Tim Peters37f39822003-01-10 03:49:02 +00003610static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003611PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3612\n\
3613All arguments are optional. tzinfo may be None, or an instance of\n\
3614a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003615
Tim Peters37f39822003-01-10 03:49:02 +00003616static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003617 0, /* nb_add */
3618 0, /* nb_subtract */
3619 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003620 0, /* nb_remainder */
3621 0, /* nb_divmod */
3622 0, /* nb_power */
3623 0, /* nb_negative */
3624 0, /* nb_positive */
3625 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003626 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003627};
3628
Neal Norwitz227b5332006-03-22 09:28:35 +00003629static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003630 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003631 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003632 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003633 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003634 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003635 0, /* tp_print */
3636 0, /* tp_getattr */
3637 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003638 0, /* tp_reserved */
Tim Peters37f39822003-01-10 03:49:02 +00003639 (reprfunc)time_repr, /* tp_repr */
3640 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003641 0, /* tp_as_sequence */
3642 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003643 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003644 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003645 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003646 PyObject_GenericGetAttr, /* tp_getattro */
3647 0, /* tp_setattro */
3648 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003649 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003650 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003651 0, /* tp_traverse */
3652 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003653 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003654 0, /* tp_weaklistoffset */
3655 0, /* tp_iter */
3656 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003657 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003658 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003659 time_getset, /* tp_getset */
3660 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003661 0, /* tp_dict */
3662 0, /* tp_descr_get */
3663 0, /* tp_descr_set */
3664 0, /* tp_dictoffset */
3665 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003666 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003667 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003668 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003669};
3670
3671/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003672 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003673 */
3674
Tim Petersa9bc1682003-01-11 03:39:11 +00003675/* Accessor properties. Properties for day, month, and year are inherited
3676 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003677 */
3678
3679static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003680datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003681{
Christian Heimes217cfd12007-12-02 14:31:20 +00003682 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003683}
3684
Tim Petersa9bc1682003-01-11 03:39:11 +00003685static PyObject *
3686datetime_minute(PyDateTime_DateTime *self, void *unused)
3687{
Christian Heimes217cfd12007-12-02 14:31:20 +00003688 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003689}
3690
3691static PyObject *
3692datetime_second(PyDateTime_DateTime *self, void *unused)
3693{
Christian Heimes217cfd12007-12-02 14:31:20 +00003694 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003695}
3696
3697static PyObject *
3698datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3699{
Christian Heimes217cfd12007-12-02 14:31:20 +00003700 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003701}
3702
3703static PyObject *
3704datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3705{
3706 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3707 Py_INCREF(result);
3708 return result;
3709}
3710
3711static PyGetSetDef datetime_getset[] = {
3712 {"hour", (getter)datetime_hour},
3713 {"minute", (getter)datetime_minute},
3714 {"second", (getter)datetime_second},
3715 {"microsecond", (getter)datetime_microsecond},
3716 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003717 {NULL}
3718};
3719
3720/*
3721 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003722 */
3723
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003724static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003725 "year", "month", "day", "hour", "minute", "second",
3726 "microsecond", "tzinfo", NULL
3727};
3728
Tim Peters2a799bf2002-12-16 20:18:38 +00003729static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003730datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003731{
3732 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003733 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003734 int year;
3735 int month;
3736 int day;
3737 int hour = 0;
3738 int minute = 0;
3739 int second = 0;
3740 int usecond = 0;
3741 PyObject *tzinfo = Py_None;
3742
Guido van Rossum177e41a2003-01-30 22:06:23 +00003743 /* Check for invocation from pickle with __getstate__ state */
3744 if (PyTuple_GET_SIZE(args) >= 1 &&
3745 PyTuple_GET_SIZE(args) <= 2 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00003746 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3747 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3748 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003749 {
Tim Peters70533e22003-02-01 04:40:04 +00003750 PyDateTime_DateTime *me;
3751 char aware;
3752
3753 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003754 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003755 if (check_tzinfo_subclass(tzinfo) < 0) {
3756 PyErr_SetString(PyExc_TypeError, "bad "
3757 "tzinfo state arg");
3758 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003759 }
3760 }
Tim Peters70533e22003-02-01 04:40:04 +00003761 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003762 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003763 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003764 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003765
3766 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3767 me->hashcode = -1;
3768 me->hastzinfo = aware;
3769 if (aware) {
3770 Py_INCREF(tzinfo);
3771 me->tzinfo = tzinfo;
3772 }
3773 }
3774 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003775 }
3776
Tim Petersa9bc1682003-01-11 03:39:11 +00003777 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003778 &year, &month, &day, &hour, &minute,
3779 &second, &usecond, &tzinfo)) {
3780 if (check_date_args(year, month, day) < 0)
3781 return NULL;
3782 if (check_time_args(hour, minute, second, usecond) < 0)
3783 return NULL;
3784 if (check_tzinfo_subclass(tzinfo) < 0)
3785 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003786 self = new_datetime_ex(year, month, day,
3787 hour, minute, second, usecond,
3788 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003789 }
3790 return self;
3791}
3792
Tim Petersa9bc1682003-01-11 03:39:11 +00003793/* TM_FUNC is the shared type of localtime() and gmtime(). */
3794typedef struct tm *(*TM_FUNC)(const time_t *timer);
3795
3796/* Internal helper.
3797 * Build datetime from a time_t and a distinct count of microseconds.
3798 * Pass localtime or gmtime for f, to control the interpretation of timet.
3799 */
3800static PyObject *
3801datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3802 PyObject *tzinfo)
3803{
3804 struct tm *tm;
3805 PyObject *result = NULL;
3806
3807 tm = f(&timet);
3808 if (tm) {
3809 /* The platform localtime/gmtime may insert leap seconds,
3810 * indicated by tm->tm_sec > 59. We don't care about them,
3811 * except to the extent that passing them on to the datetime
3812 * constructor would raise ValueError for a reason that
3813 * made no sense to the user.
3814 */
3815 if (tm->tm_sec > 59)
3816 tm->tm_sec = 59;
3817 result = PyObject_CallFunction(cls, "iiiiiiiO",
3818 tm->tm_year + 1900,
3819 tm->tm_mon + 1,
3820 tm->tm_mday,
3821 tm->tm_hour,
3822 tm->tm_min,
3823 tm->tm_sec,
3824 us,
3825 tzinfo);
3826 }
3827 else
3828 PyErr_SetString(PyExc_ValueError,
3829 "timestamp out of range for "
3830 "platform localtime()/gmtime() function");
3831 return result;
3832}
3833
3834/* Internal helper.
3835 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3836 * to control the interpretation of the timestamp. Since a double doesn't
3837 * have enough bits to cover a datetime's full range of precision, it's
3838 * better to call datetime_from_timet_and_us provided you have a way
3839 * to get that much precision (e.g., C time() isn't good enough).
3840 */
3841static PyObject *
3842datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3843 PyObject *tzinfo)
3844{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003845 time_t timet;
3846 double fraction;
3847 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003848
Tim Peters1b6f7a92004-06-20 02:50:16 +00003849 timet = _PyTime_DoubleToTimet(timestamp);
3850 if (timet == (time_t)-1 && PyErr_Occurred())
3851 return NULL;
3852 fraction = timestamp - (double)timet;
3853 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003854 if (us < 0) {
3855 /* Truncation towards zero is not what we wanted
3856 for negative numbers (Python's mod semantics) */
3857 timet -= 1;
3858 us += 1000000;
3859 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003860 /* If timestamp is less than one microsecond smaller than a
3861 * full second, round up. Otherwise, ValueErrors are raised
3862 * for some floats. */
3863 if (us == 1000000) {
3864 timet += 1;
3865 us = 0;
3866 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003867 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3868}
3869
3870/* Internal helper.
3871 * Build most accurate possible datetime for current time. Pass localtime or
3872 * gmtime for f as appropriate.
3873 */
3874static PyObject *
3875datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3876{
3877#ifdef HAVE_GETTIMEOFDAY
3878 struct timeval t;
3879
3880#ifdef GETTIMEOFDAY_NO_TZ
3881 gettimeofday(&t);
3882#else
3883 gettimeofday(&t, (struct timezone *)NULL);
3884#endif
3885 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3886 tzinfo);
3887
3888#else /* ! HAVE_GETTIMEOFDAY */
3889 /* No flavor of gettimeofday exists on this platform. Python's
3890 * time.time() does a lot of other platform tricks to get the
3891 * best time it can on the platform, and we're not going to do
3892 * better than that (if we could, the better code would belong
3893 * in time.time()!) We're limited by the precision of a double,
3894 * though.
3895 */
3896 PyObject *time;
3897 double dtime;
3898
3899 time = time_time();
3900 if (time == NULL)
3901 return NULL;
3902 dtime = PyFloat_AsDouble(time);
3903 Py_DECREF(time);
3904 if (dtime == -1.0 && PyErr_Occurred())
3905 return NULL;
3906 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3907#endif /* ! HAVE_GETTIMEOFDAY */
3908}
3909
Tim Peters2a799bf2002-12-16 20:18:38 +00003910/* Return best possible local time -- this isn't constrained by the
3911 * precision of a timestamp.
3912 */
3913static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003914datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003915{
Tim Peters10cadce2003-01-23 19:58:02 +00003916 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003917 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003918 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003919
Tim Peters10cadce2003-01-23 19:58:02 +00003920 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3921 &tzinfo))
3922 return NULL;
3923 if (check_tzinfo_subclass(tzinfo) < 0)
3924 return NULL;
3925
3926 self = datetime_best_possible(cls,
3927 tzinfo == Py_None ? localtime : gmtime,
3928 tzinfo);
3929 if (self != NULL && tzinfo != Py_None) {
3930 /* Convert UTC to tzinfo's zone. */
3931 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003932 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003933 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003934 }
3935 return self;
3936}
3937
Tim Petersa9bc1682003-01-11 03:39:11 +00003938/* Return best possible UTC time -- this isn't constrained by the
3939 * precision of a timestamp.
3940 */
3941static PyObject *
3942datetime_utcnow(PyObject *cls, PyObject *dummy)
3943{
3944 return datetime_best_possible(cls, gmtime, Py_None);
3945}
3946
Tim Peters2a799bf2002-12-16 20:18:38 +00003947/* Return new local datetime from timestamp (Python timestamp -- a double). */
3948static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003949datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003950{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003951 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003952 double timestamp;
3953 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003954 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003955
Tim Peters2a44a8d2003-01-23 20:53:10 +00003956 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3957 keywords, &timestamp, &tzinfo))
3958 return NULL;
3959 if (check_tzinfo_subclass(tzinfo) < 0)
3960 return NULL;
3961
3962 self = datetime_from_timestamp(cls,
3963 tzinfo == Py_None ? localtime : gmtime,
3964 timestamp,
3965 tzinfo);
3966 if (self != NULL && tzinfo != Py_None) {
3967 /* Convert UTC to tzinfo's zone. */
3968 PyObject *temp = self;
3969 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3970 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003971 }
3972 return self;
3973}
3974
Tim Petersa9bc1682003-01-11 03:39:11 +00003975/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3976static PyObject *
3977datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3978{
3979 double timestamp;
3980 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003981
Tim Petersa9bc1682003-01-11 03:39:11 +00003982 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3983 result = datetime_from_timestamp(cls, gmtime, timestamp,
3984 Py_None);
3985 return result;
3986}
3987
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003988/* Return new datetime from time.strptime(). */
3989static PyObject *
3990datetime_strptime(PyObject *cls, PyObject *args)
3991{
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003992 static PyObject *module = NULL;
3993 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
Guido van Rossume8a17aa2007-08-29 17:28:42 +00003994 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003995
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003996 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003997 return NULL;
3998
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003999 if (module == NULL &&
4000 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004001 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004002
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004003 /* _strptime._strptime returns a two-element tuple. The first
4004 element is a time.struct_time object. The second is the
4005 microseconds (which are not defined for time.struct_time). */
Mark Dickinsonfc689dd2008-03-16 03:45:34 +00004006 obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004007 if (obj != NULL) {
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004008 int i, good_timetuple = 1;
4009 long int ia[7];
4010 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
4011 st = PySequence_GetItem(obj, 0);
4012 frac = PySequence_GetItem(obj, 1);
4013 if (st == NULL || frac == NULL)
4014 good_timetuple = 0;
4015 /* copy y/m/d/h/m/s values out of the
4016 time.struct_time */
4017 if (good_timetuple &&
4018 PySequence_Check(st) &&
4019 PySequence_Size(st) >= 6) {
4020 for (i=0; i < 6; i++) {
4021 PyObject *p = PySequence_GetItem(st, i);
4022 if (p == NULL) {
4023 good_timetuple = 0;
4024 break;
4025 }
4026 if (PyLong_Check(p))
4027 ia[i] = PyLong_AsLong(p);
4028 else
4029 good_timetuple = 0;
4030 Py_DECREF(p);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004031 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004032/* if (PyLong_CheckExact(p)) {
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00004033 ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
4034 if (overflow)
4035 good_timetuple = 0;
4036 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004037 else
4038 good_timetuple = 0;
4039 Py_DECREF(p);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004040*/ }
4041 else
4042 good_timetuple = 0;
4043 /* follow that up with a little dose of microseconds */
4044 if (PyLong_Check(frac))
4045 ia[6] = PyLong_AsLong(frac);
4046 else
4047 good_timetuple = 0;
4048 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004049 else
4050 good_timetuple = 0;
4051 if (good_timetuple)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004052 result = PyObject_CallFunction(cls, "iiiiiii",
4053 ia[0], ia[1], ia[2],
4054 ia[3], ia[4], ia[5],
4055 ia[6]);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004056 else
4057 PyErr_SetString(PyExc_ValueError,
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004058 "unexpected value from _strptime._strptime");
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004059 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00004060 Py_XDECREF(obj);
4061 Py_XDECREF(st);
4062 Py_XDECREF(frac);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004063 return result;
4064}
4065
Tim Petersa9bc1682003-01-11 03:39:11 +00004066/* Return new datetime from date/datetime and time arguments. */
4067static PyObject *
4068datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4069{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004070 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004071 PyObject *date;
4072 PyObject *time;
4073 PyObject *result = NULL;
4074
4075 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4076 &PyDateTime_DateType, &date,
4077 &PyDateTime_TimeType, &time)) {
4078 PyObject *tzinfo = Py_None;
4079
4080 if (HASTZINFO(time))
4081 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4082 result = PyObject_CallFunction(cls, "iiiiiiiO",
4083 GET_YEAR(date),
4084 GET_MONTH(date),
4085 GET_DAY(date),
4086 TIME_GET_HOUR(time),
4087 TIME_GET_MINUTE(time),
4088 TIME_GET_SECOND(time),
4089 TIME_GET_MICROSECOND(time),
4090 tzinfo);
4091 }
4092 return result;
4093}
Tim Peters2a799bf2002-12-16 20:18:38 +00004094
4095/*
4096 * Destructor.
4097 */
4098
4099static void
Tim Petersa9bc1682003-01-11 03:39:11 +00004100datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004101{
Tim Petersa9bc1682003-01-11 03:39:11 +00004102 if (HASTZINFO(self)) {
4103 Py_XDECREF(self->tzinfo);
4104 }
Christian Heimes90aa7642007-12-19 02:45:37 +00004105 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004106}
4107
4108/*
4109 * Indirect access to tzinfo methods.
4110 */
4111
Tim Peters2a799bf2002-12-16 20:18:38 +00004112/* These are all METH_NOARGS, so don't need to check the arglist. */
4113static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004114datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
4115 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4116 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004117}
4118
4119static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004120datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
4121 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4122 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00004123}
4124
4125static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004126datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
4127 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
4128 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004129}
4130
4131/*
Tim Petersa9bc1682003-01-11 03:39:11 +00004132 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00004133 */
4134
Tim Petersa9bc1682003-01-11 03:39:11 +00004135/* factor must be 1 (to add) or -1 (to subtract). The result inherits
4136 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00004137 */
4138static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004139add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
4140 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00004141{
Tim Petersa9bc1682003-01-11 03:39:11 +00004142 /* Note that the C-level additions can't overflow, because of
4143 * invariant bounds on the member values.
4144 */
4145 int year = GET_YEAR(date);
4146 int month = GET_MONTH(date);
4147 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4148 int hour = DATE_GET_HOUR(date);
4149 int minute = DATE_GET_MINUTE(date);
4150 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4151 int microsecond = DATE_GET_MICROSECOND(date) +
4152 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004153
Tim Petersa9bc1682003-01-11 03:39:11 +00004154 assert(factor == 1 || factor == -1);
4155 if (normalize_datetime(&year, &month, &day,
4156 &hour, &minute, &second, &microsecond) < 0)
4157 return NULL;
4158 else
4159 return new_datetime(year, month, day,
4160 hour, minute, second, microsecond,
4161 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004162}
4163
4164static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004165datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004166{
Tim Petersa9bc1682003-01-11 03:39:11 +00004167 if (PyDateTime_Check(left)) {
4168 /* datetime + ??? */
4169 if (PyDelta_Check(right))
4170 /* datetime + delta */
4171 return add_datetime_timedelta(
4172 (PyDateTime_DateTime *)left,
4173 (PyDateTime_Delta *)right,
4174 1);
4175 }
4176 else if (PyDelta_Check(left)) {
4177 /* delta + datetime */
4178 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4179 (PyDateTime_Delta *) left,
4180 1);
4181 }
4182 Py_INCREF(Py_NotImplemented);
4183 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004184}
4185
4186static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004187datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004188{
4189 PyObject *result = Py_NotImplemented;
4190
4191 if (PyDateTime_Check(left)) {
4192 /* datetime - ??? */
4193 if (PyDateTime_Check(right)) {
4194 /* datetime - datetime */
4195 naivety n1, n2;
4196 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004197 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004198
Tim Peterse39a80c2002-12-30 21:28:52 +00004199 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4200 right, &offset2, &n2,
4201 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00004202 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00004203 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00004204 if (n1 != n2) {
4205 PyErr_SetString(PyExc_TypeError,
4206 "can't subtract offset-naive and "
4207 "offset-aware datetimes");
4208 return NULL;
4209 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004210 delta_d = ymd_to_ord(GET_YEAR(left),
4211 GET_MONTH(left),
4212 GET_DAY(left)) -
4213 ymd_to_ord(GET_YEAR(right),
4214 GET_MONTH(right),
4215 GET_DAY(right));
4216 /* These can't overflow, since the values are
4217 * normalized. At most this gives the number of
4218 * seconds in one day.
4219 */
4220 delta_s = (DATE_GET_HOUR(left) -
4221 DATE_GET_HOUR(right)) * 3600 +
4222 (DATE_GET_MINUTE(left) -
4223 DATE_GET_MINUTE(right)) * 60 +
4224 (DATE_GET_SECOND(left) -
4225 DATE_GET_SECOND(right));
4226 delta_us = DATE_GET_MICROSECOND(left) -
4227 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004228 /* (left - offset1) - (right - offset2) =
4229 * (left - right) + (offset2 - offset1)
4230 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004231 delta_s += (offset2 - offset1) * 60;
4232 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004233 }
4234 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004235 /* datetime - delta */
4236 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004237 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004238 (PyDateTime_Delta *)right,
4239 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004240 }
4241 }
4242
4243 if (result == Py_NotImplemented)
4244 Py_INCREF(result);
4245 return result;
4246}
4247
4248/* Various ways to turn a datetime into a string. */
4249
4250static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004251datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004252{
Christian Heimes90aa7642007-12-19 02:45:37 +00004253 const char *type_name = Py_TYPE(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004254 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004255
Tim Petersa9bc1682003-01-11 03:39:11 +00004256 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004257 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004258 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004259 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004260 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4261 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4262 DATE_GET_SECOND(self),
4263 DATE_GET_MICROSECOND(self));
4264 }
4265 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004266 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004267 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004268 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004269 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4270 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4271 DATE_GET_SECOND(self));
4272 }
4273 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004274 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004275 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004276 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004277 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4278 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4279 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004280 if (baserepr == NULL || ! HASTZINFO(self))
4281 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004282 return append_keyword_tzinfo(baserepr, self->tzinfo);
4283}
4284
Tim Petersa9bc1682003-01-11 03:39:11 +00004285static PyObject *
4286datetime_str(PyDateTime_DateTime *self)
4287{
4288 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4289}
Tim Peters2a799bf2002-12-16 20:18:38 +00004290
4291static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004292datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004293{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004294 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004295 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004296 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004297 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004298 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004299
Walter Dörwaldd0941302007-07-01 21:58:22 +00004300 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004301 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004302 if (us)
4303 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4304 GET_YEAR(self), GET_MONTH(self),
4305 GET_DAY(self), (int)sep,
4306 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4307 DATE_GET_SECOND(self), us);
4308 else
4309 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4310 GET_YEAR(self), GET_MONTH(self),
4311 GET_DAY(self), (int)sep,
4312 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4313 DATE_GET_SECOND(self));
4314
4315 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004316 return result;
4317
4318 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004319 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004320 (PyObject *)self) < 0) {
4321 Py_DECREF(result);
4322 return NULL;
4323 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004324 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004325 return result;
4326}
4327
Tim Petersa9bc1682003-01-11 03:39:11 +00004328static PyObject *
4329datetime_ctime(PyDateTime_DateTime *self)
4330{
4331 return format_ctime((PyDateTime_Date *)self,
4332 DATE_GET_HOUR(self),
4333 DATE_GET_MINUTE(self),
4334 DATE_GET_SECOND(self));
4335}
4336
Tim Peters2a799bf2002-12-16 20:18:38 +00004337/* Miscellaneous methods. */
4338
Tim Petersa9bc1682003-01-11 03:39:11 +00004339static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004340datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004341{
4342 int diff;
4343 naivety n1, n2;
4344 int offset1, offset2;
4345
4346 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004347 if (PyDate_Check(other)) {
4348 /* Prevent invocation of date_richcompare. We want to
4349 return NotImplemented here to give the other object
4350 a chance. But since DateTime is a subclass of
4351 Date, if the other object is a Date, it would
4352 compute an ordering based on the date part alone,
4353 and we don't want that. So force unequal or
4354 uncomparable here in that case. */
4355 if (op == Py_EQ)
4356 Py_RETURN_FALSE;
4357 if (op == Py_NE)
4358 Py_RETURN_TRUE;
4359 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004360 }
Guido van Rossum19960592006-08-24 17:29:38 +00004361 Py_INCREF(Py_NotImplemented);
4362 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004363 }
4364
Guido van Rossum19960592006-08-24 17:29:38 +00004365 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4366 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004367 return NULL;
4368 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4369 /* If they're both naive, or both aware and have the same offsets,
4370 * we get off cheap. Note that if they're both naive, offset1 ==
4371 * offset2 == 0 at this point.
4372 */
4373 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004374 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4375 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004376 _PyDateTime_DATETIME_DATASIZE);
4377 return diff_to_bool(diff, op);
4378 }
4379
4380 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4381 PyDateTime_Delta *delta;
4382
4383 assert(offset1 != offset2); /* else last "if" handled it */
4384 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4385 other);
4386 if (delta == NULL)
4387 return NULL;
4388 diff = GET_TD_DAYS(delta);
4389 if (diff == 0)
4390 diff = GET_TD_SECONDS(delta) |
4391 GET_TD_MICROSECONDS(delta);
4392 Py_DECREF(delta);
4393 return diff_to_bool(diff, op);
4394 }
4395
4396 assert(n1 != n2);
4397 PyErr_SetString(PyExc_TypeError,
4398 "can't compare offset-naive and "
4399 "offset-aware datetimes");
4400 return NULL;
4401}
4402
4403static long
4404datetime_hash(PyDateTime_DateTime *self)
4405{
4406 if (self->hashcode == -1) {
4407 naivety n;
4408 int offset;
4409 PyObject *temp;
4410
4411 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4412 &offset);
4413 assert(n != OFFSET_UNKNOWN);
4414 if (n == OFFSET_ERROR)
4415 return -1;
4416
4417 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00004418 if (n == OFFSET_NAIVE) {
4419 self->hashcode = generic_hash(
4420 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4421 return self->hashcode;
4422 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004423 else {
4424 int days;
4425 int seconds;
4426
4427 assert(n == OFFSET_AWARE);
4428 assert(HASTZINFO(self));
4429 days = ymd_to_ord(GET_YEAR(self),
4430 GET_MONTH(self),
4431 GET_DAY(self));
4432 seconds = DATE_GET_HOUR(self) * 3600 +
4433 (DATE_GET_MINUTE(self) - offset) * 60 +
4434 DATE_GET_SECOND(self);
4435 temp = new_delta(days,
4436 seconds,
4437 DATE_GET_MICROSECOND(self),
4438 1);
4439 }
4440 if (temp != NULL) {
4441 self->hashcode = PyObject_Hash(temp);
4442 Py_DECREF(temp);
4443 }
4444 }
4445 return self->hashcode;
4446}
Tim Peters2a799bf2002-12-16 20:18:38 +00004447
4448static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004449datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004450{
4451 PyObject *clone;
4452 PyObject *tuple;
4453 int y = GET_YEAR(self);
4454 int m = GET_MONTH(self);
4455 int d = GET_DAY(self);
4456 int hh = DATE_GET_HOUR(self);
4457 int mm = DATE_GET_MINUTE(self);
4458 int ss = DATE_GET_SECOND(self);
4459 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004460 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004461
4462 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004463 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004464 &y, &m, &d, &hh, &mm, &ss, &us,
4465 &tzinfo))
4466 return NULL;
4467 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4468 if (tuple == NULL)
4469 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00004470 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004471 Py_DECREF(tuple);
4472 return clone;
4473}
4474
4475static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004476datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004477{
Tim Peters52dcce22003-01-23 16:36:11 +00004478 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004479 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004480 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004481
Tim Peters80475bb2002-12-25 07:40:55 +00004482 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004483 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004484
Tim Peters52dcce22003-01-23 16:36:11 +00004485 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4486 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004487 return NULL;
4488
Tim Peters52dcce22003-01-23 16:36:11 +00004489 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4490 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004491
Tim Peters52dcce22003-01-23 16:36:11 +00004492 /* Conversion to self's own time zone is a NOP. */
4493 if (self->tzinfo == tzinfo) {
4494 Py_INCREF(self);
4495 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004496 }
Tim Peters521fc152002-12-31 17:36:56 +00004497
Tim Peters52dcce22003-01-23 16:36:11 +00004498 /* Convert self to UTC. */
4499 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4500 if (offset == -1 && PyErr_Occurred())
4501 return NULL;
4502 if (none)
4503 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004504
Tim Peters52dcce22003-01-23 16:36:11 +00004505 y = GET_YEAR(self);
4506 m = GET_MONTH(self);
4507 d = GET_DAY(self);
4508 hh = DATE_GET_HOUR(self);
4509 mm = DATE_GET_MINUTE(self);
4510 ss = DATE_GET_SECOND(self);
4511 us = DATE_GET_MICROSECOND(self);
4512
4513 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004514 if ((mm < 0 || mm >= 60) &&
4515 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004516 return NULL;
4517
4518 /* Attach new tzinfo and let fromutc() do the rest. */
4519 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4520 if (result != NULL) {
4521 PyObject *temp = result;
4522
4523 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4524 Py_DECREF(temp);
4525 }
Tim Petersadf64202003-01-04 06:03:15 +00004526 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004527
Tim Peters52dcce22003-01-23 16:36:11 +00004528NeedAware:
4529 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4530 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004531 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004532}
4533
4534static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004535datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004536{
4537 int dstflag = -1;
4538
Tim Petersa9bc1682003-01-11 03:39:11 +00004539 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004540 int none;
4541
4542 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4543 if (dstflag == -1 && PyErr_Occurred())
4544 return NULL;
4545
4546 if (none)
4547 dstflag = -1;
4548 else if (dstflag != 0)
4549 dstflag = 1;
4550
4551 }
4552 return build_struct_time(GET_YEAR(self),
4553 GET_MONTH(self),
4554 GET_DAY(self),
4555 DATE_GET_HOUR(self),
4556 DATE_GET_MINUTE(self),
4557 DATE_GET_SECOND(self),
4558 dstflag);
4559}
4560
4561static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004562datetime_getdate(PyDateTime_DateTime *self)
4563{
4564 return new_date(GET_YEAR(self),
4565 GET_MONTH(self),
4566 GET_DAY(self));
4567}
4568
4569static PyObject *
4570datetime_gettime(PyDateTime_DateTime *self)
4571{
4572 return new_time(DATE_GET_HOUR(self),
4573 DATE_GET_MINUTE(self),
4574 DATE_GET_SECOND(self),
4575 DATE_GET_MICROSECOND(self),
4576 Py_None);
4577}
4578
4579static PyObject *
4580datetime_gettimetz(PyDateTime_DateTime *self)
4581{
4582 return new_time(DATE_GET_HOUR(self),
4583 DATE_GET_MINUTE(self),
4584 DATE_GET_SECOND(self),
4585 DATE_GET_MICROSECOND(self),
4586 HASTZINFO(self) ? self->tzinfo : Py_None);
4587}
4588
4589static PyObject *
4590datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004591{
4592 int y = GET_YEAR(self);
4593 int m = GET_MONTH(self);
4594 int d = GET_DAY(self);
4595 int hh = DATE_GET_HOUR(self);
4596 int mm = DATE_GET_MINUTE(self);
4597 int ss = DATE_GET_SECOND(self);
4598 int us = 0; /* microseconds are ignored in a timetuple */
4599 int offset = 0;
4600
Tim Petersa9bc1682003-01-11 03:39:11 +00004601 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004602 int none;
4603
4604 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4605 if (offset == -1 && PyErr_Occurred())
4606 return NULL;
4607 }
4608 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4609 * 0 in a UTC timetuple regardless of what dst() says.
4610 */
4611 if (offset) {
4612 /* Subtract offset minutes & normalize. */
4613 int stat;
4614
4615 mm -= offset;
4616 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4617 if (stat < 0) {
4618 /* At the edges, it's possible we overflowed
4619 * beyond MINYEAR or MAXYEAR.
4620 */
4621 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4622 PyErr_Clear();
4623 else
4624 return NULL;
4625 }
4626 }
4627 return build_struct_time(y, m, d, hh, mm, ss, 0);
4628}
4629
Tim Peters371935f2003-02-01 01:52:50 +00004630/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004631
Tim Petersa9bc1682003-01-11 03:39:11 +00004632/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004633 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4634 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004635 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004636 */
4637static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004638datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004639{
4640 PyObject *basestate;
4641 PyObject *result = NULL;
4642
Christian Heimes72b710a2008-05-26 13:28:38 +00004643 basestate = PyBytes_FromStringAndSize((char *)self->data,
Guido van Rossum254348e2007-11-21 19:29:53 +00004644 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004645 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004646 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004647 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004648 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004649 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004650 Py_DECREF(basestate);
4651 }
4652 return result;
4653}
4654
4655static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004656datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004657{
Christian Heimes90aa7642007-12-19 02:45:37 +00004658 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004659}
4660
Tim Petersa9bc1682003-01-11 03:39:11 +00004661static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004662
Tim Peters2a799bf2002-12-16 20:18:38 +00004663 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004664
Tim Petersa9bc1682003-01-11 03:39:11 +00004665 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004666 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004667 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004668
Tim Petersa9bc1682003-01-11 03:39:11 +00004669 {"utcnow", (PyCFunction)datetime_utcnow,
4670 METH_NOARGS | METH_CLASS,
4671 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4672
4673 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004674 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004675 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004676
Tim Petersa9bc1682003-01-11 03:39:11 +00004677 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4678 METH_VARARGS | METH_CLASS,
4679 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4680 "(like time.time()).")},
4681
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004682 {"strptime", (PyCFunction)datetime_strptime,
4683 METH_VARARGS | METH_CLASS,
4684 PyDoc_STR("string, format -> new datetime parsed from a string "
4685 "(like time.strptime()).")},
4686
Tim Petersa9bc1682003-01-11 03:39:11 +00004687 {"combine", (PyCFunction)datetime_combine,
4688 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4689 PyDoc_STR("date, time -> datetime with same date and time fields")},
4690
Tim Peters2a799bf2002-12-16 20:18:38 +00004691 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004692
Tim Petersa9bc1682003-01-11 03:39:11 +00004693 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4694 PyDoc_STR("Return date object with same year, month and day.")},
4695
4696 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4697 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4698
4699 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4700 PyDoc_STR("Return time object with same time and tzinfo.")},
4701
4702 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4703 PyDoc_STR("Return ctime() style string.")},
4704
4705 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004706 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4707
Tim Petersa9bc1682003-01-11 03:39:11 +00004708 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004709 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4710
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004711 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004712 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4713 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4714 "sep is used to separate the year from the time, and "
4715 "defaults to 'T'.")},
4716
Tim Petersa9bc1682003-01-11 03:39:11 +00004717 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004718 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4719
Tim Petersa9bc1682003-01-11 03:39:11 +00004720 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004721 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4722
Tim Petersa9bc1682003-01-11 03:39:11 +00004723 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004724 PyDoc_STR("Return self.tzinfo.dst(self).")},
4725
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004726 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004727 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004728
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004729 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004730 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4731
Guido van Rossum177e41a2003-01-30 22:06:23 +00004732 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4733 PyDoc_STR("__reduce__() -> (cls, state)")},
4734
Tim Peters2a799bf2002-12-16 20:18:38 +00004735 {NULL, NULL}
4736};
4737
Tim Petersa9bc1682003-01-11 03:39:11 +00004738static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004739PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4740\n\
4741The year, month and day arguments are required. tzinfo may be None, or an\n\
4742instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004743
Tim Petersa9bc1682003-01-11 03:39:11 +00004744static PyNumberMethods datetime_as_number = {
4745 datetime_add, /* nb_add */
4746 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004747 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004748 0, /* nb_remainder */
4749 0, /* nb_divmod */
4750 0, /* nb_power */
4751 0, /* nb_negative */
4752 0, /* nb_positive */
4753 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004754 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004755};
4756
Neal Norwitz227b5332006-03-22 09:28:35 +00004757static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004758 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004759 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004760 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004761 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004762 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004763 0, /* tp_print */
4764 0, /* tp_getattr */
4765 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00004766 0, /* tp_reserved */
Tim Petersa9bc1682003-01-11 03:39:11 +00004767 (reprfunc)datetime_repr, /* tp_repr */
4768 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004769 0, /* tp_as_sequence */
4770 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004771 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004772 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004773 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004774 PyObject_GenericGetAttr, /* tp_getattro */
4775 0, /* tp_setattro */
4776 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004777 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004778 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004779 0, /* tp_traverse */
4780 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004781 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004782 0, /* tp_weaklistoffset */
4783 0, /* tp_iter */
4784 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004785 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004786 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004787 datetime_getset, /* tp_getset */
4788 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004789 0, /* tp_dict */
4790 0, /* tp_descr_get */
4791 0, /* tp_descr_set */
4792 0, /* tp_dictoffset */
4793 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004794 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004795 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004796 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004797};
4798
4799/* ---------------------------------------------------------------------------
4800 * Module methods and initialization.
4801 */
4802
4803static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004804 {NULL, NULL}
4805};
4806
Tim Peters9ddf40b2004-06-20 22:41:32 +00004807/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4808 * datetime.h.
4809 */
4810static PyDateTime_CAPI CAPI = {
4811 &PyDateTime_DateType,
4812 &PyDateTime_DateTimeType,
4813 &PyDateTime_TimeType,
4814 &PyDateTime_DeltaType,
4815 &PyDateTime_TZInfoType,
4816 new_date_ex,
4817 new_datetime_ex,
4818 new_time_ex,
4819 new_delta_ex,
4820 datetime_fromtimestamp,
4821 date_fromtimestamp
4822};
4823
4824
Martin v. Löwis1a214512008-06-11 05:26:20 +00004825
4826static struct PyModuleDef datetimemodule = {
4827 PyModuleDef_HEAD_INIT,
4828 "datetime",
4829 "Fast implementation of the datetime type.",
4830 -1,
4831 module_methods,
4832 NULL,
4833 NULL,
4834 NULL,
4835 NULL
4836};
4837
Tim Peters2a799bf2002-12-16 20:18:38 +00004838PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004839PyInit_datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00004840{
4841 PyObject *m; /* a module object */
4842 PyObject *d; /* its dict */
4843 PyObject *x;
4844
Martin v. Löwis1a214512008-06-11 05:26:20 +00004845 m = PyModule_Create(&datetimemodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004846 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004847 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004848
4849 if (PyType_Ready(&PyDateTime_DateType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004850 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004851 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004852 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004853 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004854 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004855 if (PyType_Ready(&PyDateTime_TimeType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004856 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004857 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004858 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004859
Tim Peters2a799bf2002-12-16 20:18:38 +00004860 /* timedelta values */
4861 d = PyDateTime_DeltaType.tp_dict;
4862
Tim Peters2a799bf2002-12-16 20:18:38 +00004863 x = new_delta(0, 0, 1, 0);
4864 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004865 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004866 Py_DECREF(x);
4867
4868 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4869 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004870 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004871 Py_DECREF(x);
4872
4873 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4874 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004875 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004876 Py_DECREF(x);
4877
4878 /* date values */
4879 d = PyDateTime_DateType.tp_dict;
4880
4881 x = new_date(1, 1, 1);
4882 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004883 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004884 Py_DECREF(x);
4885
4886 x = new_date(MAXYEAR, 12, 31);
4887 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004888 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004889 Py_DECREF(x);
4890
4891 x = new_delta(1, 0, 0, 0);
4892 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004893 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004894 Py_DECREF(x);
4895
Tim Peters37f39822003-01-10 03:49:02 +00004896 /* time values */
4897 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004898
Tim Peters37f39822003-01-10 03:49:02 +00004899 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004900 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004901 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004902 Py_DECREF(x);
4903
Tim Peters37f39822003-01-10 03:49:02 +00004904 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004905 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004906 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004907 Py_DECREF(x);
4908
4909 x = new_delta(0, 0, 1, 0);
4910 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004911 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004912 Py_DECREF(x);
4913
Tim Petersa9bc1682003-01-11 03:39:11 +00004914 /* datetime values */
4915 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004916
Tim Petersa9bc1682003-01-11 03:39:11 +00004917 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004918 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004919 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004920 Py_DECREF(x);
4921
Tim Petersa9bc1682003-01-11 03:39:11 +00004922 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004923 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004924 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004925 Py_DECREF(x);
4926
4927 x = new_delta(0, 0, 1, 0);
4928 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004929 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004930 Py_DECREF(x);
4931
Tim Peters2a799bf2002-12-16 20:18:38 +00004932 /* module initialization */
4933 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4934 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4935
4936 Py_INCREF(&PyDateTime_DateType);
4937 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4938
Tim Petersa9bc1682003-01-11 03:39:11 +00004939 Py_INCREF(&PyDateTime_DateTimeType);
4940 PyModule_AddObject(m, "datetime",
4941 (PyObject *)&PyDateTime_DateTimeType);
4942
4943 Py_INCREF(&PyDateTime_TimeType);
4944 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4945
Tim Peters2a799bf2002-12-16 20:18:38 +00004946 Py_INCREF(&PyDateTime_DeltaType);
4947 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4948
Tim Peters2a799bf2002-12-16 20:18:38 +00004949 Py_INCREF(&PyDateTime_TZInfoType);
4950 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4951
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00004952 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
4953 if (x == NULL)
4954 return NULL;
4955 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00004956
Tim Peters2a799bf2002-12-16 20:18:38 +00004957 /* A 4-year cycle has an extra leap day over what we'd get from
4958 * pasting together 4 single years.
4959 */
4960 assert(DI4Y == 4 * 365 + 1);
4961 assert(DI4Y == days_before_year(4+1));
4962
4963 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4964 * get from pasting together 4 100-year cycles.
4965 */
4966 assert(DI400Y == 4 * DI100Y + 1);
4967 assert(DI400Y == days_before_year(400+1));
4968
4969 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4970 * pasting together 25 4-year cycles.
4971 */
4972 assert(DI100Y == 25 * DI4Y - 1);
4973 assert(DI100Y == days_before_year(100+1));
4974
Christian Heimes217cfd12007-12-02 14:31:20 +00004975 us_per_us = PyLong_FromLong(1);
4976 us_per_ms = PyLong_FromLong(1000);
4977 us_per_second = PyLong_FromLong(1000000);
4978 us_per_minute = PyLong_FromLong(60000000);
4979 seconds_per_day = PyLong_FromLong(24 * 3600);
Tim Peters2a799bf2002-12-16 20:18:38 +00004980 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4981 us_per_minute == NULL || seconds_per_day == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004982 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004983
4984 /* The rest are too big for 32-bit ints, but even
4985 * us_per_week fits in 40 bits, so doubles should be exact.
4986 */
4987 us_per_hour = PyLong_FromDouble(3600000000.0);
4988 us_per_day = PyLong_FromDouble(86400000000.0);
4989 us_per_week = PyLong_FromDouble(604800000000.0);
4990 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004991 return NULL;
4992 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00004993}
Tim Petersf3615152003-01-01 21:51:37 +00004994
4995/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004996Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004997 x.n = x stripped of its timezone -- its naive time.
4998 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4999 return None
5000 x.d = x.dst(), and assuming that doesn't raise an exception or
5001 return None
5002 x.s = x's standard offset, x.o - x.d
5003
5004Now some derived rules, where k is a duration (timedelta).
5005
50061. x.o = x.s + x.d
5007 This follows from the definition of x.s.
5008
Tim Petersc5dc4da2003-01-02 17:55:03 +000050092. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00005010 This is actually a requirement, an assumption we need to make about
5011 sane tzinfo classes.
5012
50133. The naive UTC time corresponding to x is x.n - x.o.
5014 This is again a requirement for a sane tzinfo class.
5015
50164. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00005017 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00005018
Tim Petersc5dc4da2003-01-02 17:55:03 +000050195. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00005020 Again follows from how arithmetic is defined.
5021
Tim Peters8bb5ad22003-01-24 02:44:45 +00005022Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00005023(meaning that the various tzinfo methods exist, and don't blow up or return
5024None when called).
5025
Tim Petersa9bc1682003-01-11 03:39:11 +00005026The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00005027x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00005028
5029By #3, we want
5030
Tim Peters8bb5ad22003-01-24 02:44:45 +00005031 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00005032
5033The algorithm starts by attaching tz to x.n, and calling that y. So
5034x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
5035becomes true; in effect, we want to solve [2] for k:
5036
Tim Peters8bb5ad22003-01-24 02:44:45 +00005037 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00005038
5039By #1, this is the same as
5040
Tim Peters8bb5ad22003-01-24 02:44:45 +00005041 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00005042
5043By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
5044Substituting that into [3],
5045
Tim Peters8bb5ad22003-01-24 02:44:45 +00005046 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
5047 k - (y+k).s - (y+k).d = 0; rearranging,
5048 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
5049 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00005050
Tim Peters8bb5ad22003-01-24 02:44:45 +00005051On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
5052approximate k by ignoring the (y+k).d term at first. Note that k can't be
5053very large, since all offset-returning methods return a duration of magnitude
5054less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
5055be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00005056
5057In any case, the new value is
5058
Tim Peters8bb5ad22003-01-24 02:44:45 +00005059 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00005060
Tim Peters8bb5ad22003-01-24 02:44:45 +00005061It's helpful to step back at look at [4] from a higher level: it's simply
5062mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00005063
5064At this point, if
5065
Tim Peters8bb5ad22003-01-24 02:44:45 +00005066 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00005067
5068we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00005069at the start of daylight time. Picture US Eastern for concreteness. The wall
5070time 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 +00005071sense then. The docs ask that an Eastern tzinfo class consider such a time to
5072be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5073on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00005074the only spelling that makes sense on the local wall clock.
5075
Tim Petersc5dc4da2003-01-02 17:55:03 +00005076In fact, if [5] holds at this point, we do have the standard-time spelling,
5077but that takes a bit of proof. We first prove a stronger result. What's the
5078difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00005079
Tim Peters8bb5ad22003-01-24 02:44:45 +00005080 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00005081
Tim Petersc5dc4da2003-01-02 17:55:03 +00005082Now
5083 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00005084 (y + y.s).n = by #5
5085 y.n + y.s = since y.n = x.n
5086 x.n + y.s = since z and y are have the same tzinfo member,
5087 y.s = z.s by #2
5088 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00005089
Tim Petersc5dc4da2003-01-02 17:55:03 +00005090Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00005091
Tim Petersc5dc4da2003-01-02 17:55:03 +00005092 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00005093 x.n - ((x.n + z.s) - z.o) = expanding
5094 x.n - x.n - z.s + z.o = cancelling
5095 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00005096 z.d
Tim Petersf3615152003-01-01 21:51:37 +00005097
Tim Petersc5dc4da2003-01-02 17:55:03 +00005098So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00005099
Tim Petersc5dc4da2003-01-02 17:55:03 +00005100If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00005101spelling we wanted in the endcase described above. We're done. Contrarily,
5102if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00005103
Tim Petersc5dc4da2003-01-02 17:55:03 +00005104If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5105add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00005106local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00005107
Tim Petersc5dc4da2003-01-02 17:55:03 +00005108Let
Tim Petersf3615152003-01-01 21:51:37 +00005109
Tim Peters4fede1a2003-01-04 00:26:59 +00005110 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005111
Tim Peters4fede1a2003-01-04 00:26:59 +00005112and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00005113
Tim Peters8bb5ad22003-01-24 02:44:45 +00005114 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00005115
Tim Peters8bb5ad22003-01-24 02:44:45 +00005116If so, we're done. If not, the tzinfo class is insane, according to the
5117assumptions we've made. This also requires a bit of proof. As before, let's
5118compute the difference between the LHS and RHS of [8] (and skipping some of
5119the justifications for the kinds of substitutions we've done several times
5120already):
Tim Peters4fede1a2003-01-04 00:26:59 +00005121
Tim Peters8bb5ad22003-01-24 02:44:45 +00005122 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
5123 x.n - (z.n + diff - z'.o) = replacing diff via [6]
5124 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5125 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
5126 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00005127 - z.o + z'.o = #1 twice
5128 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
5129 z'.d - z.d
5130
5131So 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 +00005132we've found the UTC-equivalent so are done. In fact, we stop with [7] and
5133return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00005134
Tim Peters8bb5ad22003-01-24 02:44:45 +00005135How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
5136a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5137would have to change the result dst() returns: we start in DST, and moving
5138a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00005139
Tim Peters8bb5ad22003-01-24 02:44:45 +00005140There isn't a sane case where this can happen. The closest it gets is at
5141the end of DST, where there's an hour in UTC with no spelling in a hybrid
5142tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
5143that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5144UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5145time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5146clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5147standard time. Since that's what the local clock *does*, we want to map both
5148UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005149in local time, but so it goes -- it's the way the local clock works.
5150
Tim Peters8bb5ad22003-01-24 02:44:45 +00005151When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5152so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5153z' = 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 +00005154(correctly) concludes that z' is not UTC-equivalent to x.
5155
5156Because we know z.d said z was in daylight time (else [5] would have held and
5157we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005158and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005159return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5160but the reasoning doesn't depend on the example -- it depends on there being
5161two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005162z' must be in standard time, and is the spelling we want in this case.
5163
5164Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5165concerned (because it takes z' as being in standard time rather than the
5166daylight time we intend here), but returning it gives the real-life "local
5167clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5168tz.
5169
5170When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5171the 1:MM standard time spelling we want.
5172
5173So how can this break? One of the assumptions must be violated. Two
5174possibilities:
5175
51761) [2] effectively says that y.s is invariant across all y belong to a given
5177 time zone. This isn't true if, for political reasons or continental drift,
5178 a region decides to change its base offset from UTC.
5179
51802) There may be versions of "double daylight" time where the tail end of
5181 the analysis gives up a step too early. I haven't thought about that
5182 enough to say.
5183
5184In any case, it's clear that the default fromutc() is strong enough to handle
5185"almost all" time zones: so long as the standard offset is invariant, it
5186doesn't matter if daylight time transition points change from year to year, or
5187if daylight time is skipped in some years; it doesn't matter how large or
5188small dst() may get within its bounds; and it doesn't even matter if some
5189perverse time zone returns a negative dst()). So a breaking case must be
5190pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005191--------------------------------------------------------------------------- */