blob: 764de34c367dc6467d9e60420fa812aaf86b0618 [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 *
1669delta_add(PyObject *left, PyObject *right)
1670{
1671 PyObject *result = Py_NotImplemented;
1672
1673 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1674 /* delta + delta */
1675 /* The C-level additions can't overflow because of the
1676 * invariant bounds.
1677 */
1678 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1679 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1680 int microseconds = GET_TD_MICROSECONDS(left) +
1681 GET_TD_MICROSECONDS(right);
1682 result = new_delta(days, seconds, microseconds, 1);
1683 }
1684
1685 if (result == Py_NotImplemented)
1686 Py_INCREF(result);
1687 return result;
1688}
1689
1690static PyObject *
1691delta_negative(PyDateTime_Delta *self)
1692{
1693 return new_delta(-GET_TD_DAYS(self),
1694 -GET_TD_SECONDS(self),
1695 -GET_TD_MICROSECONDS(self),
1696 1);
1697}
1698
1699static PyObject *
1700delta_positive(PyDateTime_Delta *self)
1701{
1702 /* Could optimize this (by returning self) if this isn't a
1703 * subclass -- but who uses unary + ? Approximately nobody.
1704 */
1705 return new_delta(GET_TD_DAYS(self),
1706 GET_TD_SECONDS(self),
1707 GET_TD_MICROSECONDS(self),
1708 0);
1709}
1710
1711static PyObject *
1712delta_abs(PyDateTime_Delta *self)
1713{
1714 PyObject *result;
1715
1716 assert(GET_TD_MICROSECONDS(self) >= 0);
1717 assert(GET_TD_SECONDS(self) >= 0);
1718
1719 if (GET_TD_DAYS(self) < 0)
1720 result = delta_negative(self);
1721 else
1722 result = delta_positive(self);
1723
1724 return result;
1725}
1726
1727static PyObject *
1728delta_subtract(PyObject *left, PyObject *right)
1729{
1730 PyObject *result = Py_NotImplemented;
1731
1732 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1733 /* delta - delta */
1734 PyObject *minus_right = PyNumber_Negative(right);
1735 if (minus_right) {
1736 result = delta_add(left, minus_right);
1737 Py_DECREF(minus_right);
1738 }
1739 else
1740 result = NULL;
1741 }
1742
1743 if (result == Py_NotImplemented)
1744 Py_INCREF(result);
1745 return result;
1746}
1747
Tim Peters2a799bf2002-12-16 20:18:38 +00001748static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001749delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001750{
Tim Petersaa7d8492003-02-08 03:28:59 +00001751 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001752 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001753 if (diff == 0) {
1754 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1755 if (diff == 0)
1756 diff = GET_TD_MICROSECONDS(self) -
1757 GET_TD_MICROSECONDS(other);
1758 }
Guido van Rossum19960592006-08-24 17:29:38 +00001759 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001760 }
Guido van Rossum19960592006-08-24 17:29:38 +00001761 else {
1762 Py_INCREF(Py_NotImplemented);
1763 return Py_NotImplemented;
1764 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001765}
1766
1767static PyObject *delta_getstate(PyDateTime_Delta *self);
1768
1769static long
1770delta_hash(PyDateTime_Delta *self)
1771{
1772 if (self->hashcode == -1) {
1773 PyObject *temp = delta_getstate(self);
1774 if (temp != NULL) {
1775 self->hashcode = PyObject_Hash(temp);
1776 Py_DECREF(temp);
1777 }
1778 }
1779 return self->hashcode;
1780}
1781
1782static PyObject *
1783delta_multiply(PyObject *left, PyObject *right)
1784{
1785 PyObject *result = Py_NotImplemented;
1786
1787 if (PyDelta_Check(left)) {
1788 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001789 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001790 result = multiply_int_timedelta(right,
1791 (PyDateTime_Delta *) left);
1792 }
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001793 else if (PyLong_Check(left))
Tim Peters2a799bf2002-12-16 20:18:38 +00001794 result = multiply_int_timedelta(left,
1795 (PyDateTime_Delta *) right);
1796
1797 if (result == Py_NotImplemented)
1798 Py_INCREF(result);
1799 return result;
1800}
1801
1802static PyObject *
1803delta_divide(PyObject *left, PyObject *right)
1804{
1805 PyObject *result = Py_NotImplemented;
1806
1807 if (PyDelta_Check(left)) {
1808 /* delta * ??? */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001809 if (PyLong_Check(right))
Tim Peters2a799bf2002-12-16 20:18:38 +00001810 result = divide_timedelta_int(
1811 (PyDateTime_Delta *)left,
1812 right);
1813 }
1814
1815 if (result == Py_NotImplemented)
1816 Py_INCREF(result);
1817 return result;
1818}
1819
1820/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1821 * timedelta constructor. sofar is the # of microseconds accounted for
1822 * so far, and there are factor microseconds per current unit, the number
1823 * of which is given by num. num * factor is added to sofar in a
1824 * numerically careful way, and that's the result. Any fractional
1825 * microseconds left over (this can happen if num is a float type) are
1826 * added into *leftover.
1827 * Note that there are many ways this can give an error (NULL) return.
1828 */
1829static PyObject *
1830accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1831 double *leftover)
1832{
1833 PyObject *prod;
1834 PyObject *sum;
1835
1836 assert(num != NULL);
1837
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001838 if (PyLong_Check(num)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00001839 prod = PyNumber_Multiply(num, factor);
1840 if (prod == NULL)
1841 return NULL;
1842 sum = PyNumber_Add(sofar, prod);
1843 Py_DECREF(prod);
1844 return sum;
1845 }
1846
1847 if (PyFloat_Check(num)) {
1848 double dnum;
1849 double fracpart;
1850 double intpart;
1851 PyObject *x;
1852 PyObject *y;
1853
1854 /* The Plan: decompose num into an integer part and a
1855 * fractional part, num = intpart + fracpart.
1856 * Then num * factor ==
1857 * intpart * factor + fracpart * factor
1858 * and the LHS can be computed exactly in long arithmetic.
1859 * The RHS is again broken into an int part and frac part.
1860 * and the frac part is added into *leftover.
1861 */
1862 dnum = PyFloat_AsDouble(num);
1863 if (dnum == -1.0 && PyErr_Occurred())
1864 return NULL;
1865 fracpart = modf(dnum, &intpart);
1866 x = PyLong_FromDouble(intpart);
1867 if (x == NULL)
1868 return NULL;
1869
1870 prod = PyNumber_Multiply(x, factor);
1871 Py_DECREF(x);
1872 if (prod == NULL)
1873 return NULL;
1874
1875 sum = PyNumber_Add(sofar, prod);
1876 Py_DECREF(prod);
1877 if (sum == NULL)
1878 return NULL;
1879
1880 if (fracpart == 0.0)
1881 return sum;
1882 /* So far we've lost no information. Dealing with the
1883 * fractional part requires float arithmetic, and may
1884 * lose a little info.
1885 */
Neal Norwitz1fe5f382007-08-31 04:32:55 +00001886 assert(PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001887 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001888
1889 dnum *= fracpart;
1890 fracpart = modf(dnum, &intpart);
1891 x = PyLong_FromDouble(intpart);
1892 if (x == NULL) {
1893 Py_DECREF(sum);
1894 return NULL;
1895 }
1896
1897 y = PyNumber_Add(sum, x);
1898 Py_DECREF(sum);
1899 Py_DECREF(x);
1900 *leftover += fracpart;
1901 return y;
1902 }
1903
1904 PyErr_Format(PyExc_TypeError,
1905 "unsupported type for timedelta %s component: %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001906 tag, Py_TYPE(num)->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +00001907 return NULL;
1908}
1909
1910static PyObject *
1911delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1912{
1913 PyObject *self = NULL;
1914
1915 /* Argument objects. */
1916 PyObject *day = NULL;
1917 PyObject *second = NULL;
1918 PyObject *us = NULL;
1919 PyObject *ms = NULL;
1920 PyObject *minute = NULL;
1921 PyObject *hour = NULL;
1922 PyObject *week = NULL;
1923
1924 PyObject *x = NULL; /* running sum of microseconds */
1925 PyObject *y = NULL; /* temp sum of microseconds */
1926 double leftover_us = 0.0;
1927
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001928 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001929 "days", "seconds", "microseconds", "milliseconds",
1930 "minutes", "hours", "weeks", NULL
1931 };
1932
1933 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1934 keywords,
1935 &day, &second, &us,
1936 &ms, &minute, &hour, &week) == 0)
1937 goto Done;
1938
Christian Heimes217cfd12007-12-02 14:31:20 +00001939 x = PyLong_FromLong(0);
Tim Peters2a799bf2002-12-16 20:18:38 +00001940 if (x == NULL)
1941 goto Done;
1942
1943#define CLEANUP \
1944 Py_DECREF(x); \
1945 x = y; \
1946 if (x == NULL) \
1947 goto Done
1948
1949 if (us) {
1950 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1951 CLEANUP;
1952 }
1953 if (ms) {
1954 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1955 CLEANUP;
1956 }
1957 if (second) {
1958 y = accum("seconds", x, second, us_per_second, &leftover_us);
1959 CLEANUP;
1960 }
1961 if (minute) {
1962 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1963 CLEANUP;
1964 }
1965 if (hour) {
1966 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1967 CLEANUP;
1968 }
1969 if (day) {
1970 y = accum("days", x, day, us_per_day, &leftover_us);
1971 CLEANUP;
1972 }
1973 if (week) {
1974 y = accum("weeks", x, week, us_per_week, &leftover_us);
1975 CLEANUP;
1976 }
1977 if (leftover_us) {
1978 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001979 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001980 if (temp == NULL) {
1981 Py_DECREF(x);
1982 goto Done;
1983 }
1984 y = PyNumber_Add(x, temp);
1985 Py_DECREF(temp);
1986 CLEANUP;
1987 }
1988
Tim Petersb0c854d2003-05-17 15:57:00 +00001989 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001990 Py_DECREF(x);
1991Done:
1992 return self;
1993
1994#undef CLEANUP
1995}
1996
1997static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001998delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001999{
2000 return (GET_TD_DAYS(self) != 0
2001 || GET_TD_SECONDS(self) != 0
2002 || GET_TD_MICROSECONDS(self) != 0);
2003}
2004
2005static PyObject *
2006delta_repr(PyDateTime_Delta *self)
2007{
2008 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00002009 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002010 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002011 GET_TD_DAYS(self),
2012 GET_TD_SECONDS(self),
2013 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002014 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00002015 return PyUnicode_FromFormat("%s(%d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002016 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002017 GET_TD_DAYS(self),
2018 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002019
Walter Dörwald1ab83302007-05-18 17:15:44 +00002020 return PyUnicode_FromFormat("%s(%d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002021 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002022 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002023}
2024
2025static PyObject *
2026delta_str(PyDateTime_Delta *self)
2027{
Tim Peters2a799bf2002-12-16 20:18:38 +00002028 int us = GET_TD_MICROSECONDS(self);
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002029 int seconds = GET_TD_SECONDS(self);
2030 int minutes = divmod(seconds, 60, &seconds);
2031 int hours = divmod(minutes, 60, &minutes);
2032 int days = GET_TD_DAYS(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002033
2034 if (days) {
Walter Dörwaldbaf853c2007-05-31 18:42:47 +00002035 if (us)
2036 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d.%06d",
2037 days, (days == 1 || days == -1) ? "" : "s",
2038 hours, minutes, seconds, us);
2039 else
2040 return PyUnicode_FromFormat("%d day%s, %d:%02d:%02d",
2041 days, (days == 1 || days == -1) ? "" : "s",
2042 hours, minutes, seconds);
2043 } else {
2044 if (us)
2045 return PyUnicode_FromFormat("%d:%02d:%02d.%06d",
2046 hours, minutes, seconds, us);
2047 else
2048 return PyUnicode_FromFormat("%d:%02d:%02d",
2049 hours, minutes, seconds);
Tim Peters2a799bf2002-12-16 20:18:38 +00002050 }
2051
Tim Peters2a799bf2002-12-16 20:18:38 +00002052}
2053
Tim Peters371935f2003-02-01 01:52:50 +00002054/* Pickle support, a simple use of __reduce__. */
2055
Tim Petersb57f8f02003-02-01 02:54:15 +00002056/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002057static PyObject *
2058delta_getstate(PyDateTime_Delta *self)
2059{
2060 return Py_BuildValue("iii", GET_TD_DAYS(self),
2061 GET_TD_SECONDS(self),
2062 GET_TD_MICROSECONDS(self));
2063}
2064
Tim Peters2a799bf2002-12-16 20:18:38 +00002065static PyObject *
Antoine Pitroube6859d2009-11-25 23:02:32 +00002066delta_total_seconds(PyObject *self)
2067{
2068 return PyFloat_FromDouble(GET_TD_MICROSECONDS(self) / 1000000.0 +
2069 GET_TD_SECONDS(self) +
2070 GET_TD_DAYS(self) * 24.0 * 3600.0);
2071}
2072
2073static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002074delta_reduce(PyDateTime_Delta* self)
2075{
Christian Heimes90aa7642007-12-19 02:45:37 +00002076 return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002077}
2078
2079#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2080
2081static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002082
Neal Norwitzdfb80862002-12-19 02:30:56 +00002083 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002084 PyDoc_STR("Number of days.")},
2085
Neal Norwitzdfb80862002-12-19 02:30:56 +00002086 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002087 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2088
Neal Norwitzdfb80862002-12-19 02:30:56 +00002089 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002090 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2091 {NULL}
2092};
2093
2094static PyMethodDef delta_methods[] = {
Antoine Pitroube6859d2009-11-25 23:02:32 +00002095 {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2096 PyDoc_STR("Total seconds in the duration.")},
2097
2098 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
Guido van Rossum177e41a2003-01-30 22:06:23 +00002099 PyDoc_STR("__reduce__() -> (cls, state)")},
2100
Tim Peters2a799bf2002-12-16 20:18:38 +00002101 {NULL, NULL},
2102};
2103
2104static char delta_doc[] =
2105PyDoc_STR("Difference between two datetime values.");
2106
2107static PyNumberMethods delta_as_number = {
2108 delta_add, /* nb_add */
2109 delta_subtract, /* nb_subtract */
2110 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002111 0, /* nb_remainder */
2112 0, /* nb_divmod */
2113 0, /* nb_power */
2114 (unaryfunc)delta_negative, /* nb_negative */
2115 (unaryfunc)delta_positive, /* nb_positive */
2116 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002117 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002118 0, /*nb_invert*/
2119 0, /*nb_lshift*/
2120 0, /*nb_rshift*/
2121 0, /*nb_and*/
2122 0, /*nb_xor*/
2123 0, /*nb_or*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002124 0, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00002125 0, /*nb_reserved*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002126 0, /*nb_float*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002127 0, /*nb_inplace_add*/
2128 0, /*nb_inplace_subtract*/
2129 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002130 0, /*nb_inplace_remainder*/
2131 0, /*nb_inplace_power*/
2132 0, /*nb_inplace_lshift*/
2133 0, /*nb_inplace_rshift*/
2134 0, /*nb_inplace_and*/
2135 0, /*nb_inplace_xor*/
2136 0, /*nb_inplace_or*/
2137 delta_divide, /* nb_floor_divide */
2138 0, /* nb_true_divide */
2139 0, /* nb_inplace_floor_divide */
2140 0, /* nb_inplace_true_divide */
2141};
2142
2143static PyTypeObject PyDateTime_DeltaType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002144 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002145 "datetime.timedelta", /* tp_name */
2146 sizeof(PyDateTime_Delta), /* tp_basicsize */
2147 0, /* tp_itemsize */
2148 0, /* tp_dealloc */
2149 0, /* tp_print */
2150 0, /* tp_getattr */
2151 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002152 0, /* tp_reserved */
Tim Peters2a799bf2002-12-16 20:18:38 +00002153 (reprfunc)delta_repr, /* tp_repr */
2154 &delta_as_number, /* tp_as_number */
2155 0, /* tp_as_sequence */
2156 0, /* tp_as_mapping */
2157 (hashfunc)delta_hash, /* tp_hash */
2158 0, /* tp_call */
2159 (reprfunc)delta_str, /* tp_str */
2160 PyObject_GenericGetAttr, /* tp_getattro */
2161 0, /* tp_setattro */
2162 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002163 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002164 delta_doc, /* tp_doc */
2165 0, /* tp_traverse */
2166 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002167 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002168 0, /* tp_weaklistoffset */
2169 0, /* tp_iter */
2170 0, /* tp_iternext */
2171 delta_methods, /* tp_methods */
2172 delta_members, /* tp_members */
2173 0, /* tp_getset */
2174 0, /* tp_base */
2175 0, /* tp_dict */
2176 0, /* tp_descr_get */
2177 0, /* tp_descr_set */
2178 0, /* tp_dictoffset */
2179 0, /* tp_init */
2180 0, /* tp_alloc */
2181 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002182 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002183};
2184
2185/*
2186 * PyDateTime_Date implementation.
2187 */
2188
2189/* Accessor properties. */
2190
2191static PyObject *
2192date_year(PyDateTime_Date *self, void *unused)
2193{
Christian Heimes217cfd12007-12-02 14:31:20 +00002194 return PyLong_FromLong(GET_YEAR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002195}
2196
2197static PyObject *
2198date_month(PyDateTime_Date *self, void *unused)
2199{
Christian Heimes217cfd12007-12-02 14:31:20 +00002200 return PyLong_FromLong(GET_MONTH(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002201}
2202
2203static PyObject *
2204date_day(PyDateTime_Date *self, void *unused)
2205{
Christian Heimes217cfd12007-12-02 14:31:20 +00002206 return PyLong_FromLong(GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002207}
2208
2209static PyGetSetDef date_getset[] = {
2210 {"year", (getter)date_year},
2211 {"month", (getter)date_month},
2212 {"day", (getter)date_day},
2213 {NULL}
2214};
2215
2216/* Constructors. */
2217
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002218static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002219
Tim Peters2a799bf2002-12-16 20:18:38 +00002220static PyObject *
2221date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2222{
2223 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002224 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002225 int year;
2226 int month;
2227 int day;
2228
Guido van Rossum177e41a2003-01-30 22:06:23 +00002229 /* Check for invocation from pickle with __getstate__ state */
2230 if (PyTuple_GET_SIZE(args) == 1 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00002231 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2232 PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2233 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002234 {
Tim Peters70533e22003-02-01 04:40:04 +00002235 PyDateTime_Date *me;
2236
Tim Peters604c0132004-06-07 23:04:33 +00002237 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002238 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00002239 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00002240 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2241 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002242 }
Tim Peters70533e22003-02-01 04:40:04 +00002243 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002244 }
2245
Tim Peters12bf3392002-12-24 05:41:27 +00002246 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002247 &year, &month, &day)) {
2248 if (check_date_args(year, month, day) < 0)
2249 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002250 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002251 }
2252 return self;
2253}
2254
2255/* Return new date from localtime(t). */
2256static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002257date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002258{
2259 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002260 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002261 PyObject *result = NULL;
2262
Tim Peters1b6f7a92004-06-20 02:50:16 +00002263 t = _PyTime_DoubleToTimet(ts);
2264 if (t == (time_t)-1 && PyErr_Occurred())
2265 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002266 tm = localtime(&t);
2267 if (tm)
2268 result = PyObject_CallFunction(cls, "iii",
2269 tm->tm_year + 1900,
2270 tm->tm_mon + 1,
2271 tm->tm_mday);
2272 else
2273 PyErr_SetString(PyExc_ValueError,
2274 "timestamp out of range for "
2275 "platform localtime() function");
2276 return result;
2277}
2278
2279/* Return new date from current time.
2280 * We say this is equivalent to fromtimestamp(time.time()), and the
2281 * only way to be sure of that is to *call* time.time(). That's not
2282 * generally the same as calling C's time.
2283 */
2284static PyObject *
2285date_today(PyObject *cls, PyObject *dummy)
2286{
2287 PyObject *time;
2288 PyObject *result;
2289
2290 time = time_time();
2291 if (time == NULL)
2292 return NULL;
2293
2294 /* Note well: today() is a class method, so this may not call
2295 * date.fromtimestamp. For example, it may call
2296 * datetime.fromtimestamp. That's why we need all the accuracy
2297 * time.time() delivers; if someone were gonzo about optimization,
2298 * date.today() could get away with plain C time().
2299 */
2300 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2301 Py_DECREF(time);
2302 return result;
2303}
2304
2305/* Return new date from given timestamp (Python timestamp -- a double). */
2306static PyObject *
2307date_fromtimestamp(PyObject *cls, PyObject *args)
2308{
2309 double timestamp;
2310 PyObject *result = NULL;
2311
2312 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002313 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002314 return result;
2315}
2316
2317/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2318 * the ordinal is out of range.
2319 */
2320static PyObject *
2321date_fromordinal(PyObject *cls, PyObject *args)
2322{
2323 PyObject *result = NULL;
2324 int ordinal;
2325
2326 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2327 int year;
2328 int month;
2329 int day;
2330
2331 if (ordinal < 1)
2332 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2333 ">= 1");
2334 else {
2335 ord_to_ymd(ordinal, &year, &month, &day);
2336 result = PyObject_CallFunction(cls, "iii",
2337 year, month, day);
2338 }
2339 }
2340 return result;
2341}
2342
2343/*
2344 * Date arithmetic.
2345 */
2346
2347/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2348 * instead.
2349 */
2350static PyObject *
2351add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2352{
2353 PyObject *result = NULL;
2354 int year = GET_YEAR(date);
2355 int month = GET_MONTH(date);
2356 int deltadays = GET_TD_DAYS(delta);
2357 /* C-level overflow is impossible because |deltadays| < 1e9. */
2358 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2359
2360 if (normalize_date(&year, &month, &day) >= 0)
2361 result = new_date(year, month, day);
2362 return result;
2363}
2364
2365static PyObject *
2366date_add(PyObject *left, PyObject *right)
2367{
2368 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2369 Py_INCREF(Py_NotImplemented);
2370 return Py_NotImplemented;
2371 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002372 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002373 /* date + ??? */
2374 if (PyDelta_Check(right))
2375 /* date + delta */
2376 return add_date_timedelta((PyDateTime_Date *) left,
2377 (PyDateTime_Delta *) right,
2378 0);
2379 }
2380 else {
2381 /* ??? + date
2382 * 'right' must be one of us, or we wouldn't have been called
2383 */
2384 if (PyDelta_Check(left))
2385 /* delta + date */
2386 return add_date_timedelta((PyDateTime_Date *) right,
2387 (PyDateTime_Delta *) left,
2388 0);
2389 }
2390 Py_INCREF(Py_NotImplemented);
2391 return Py_NotImplemented;
2392}
2393
2394static PyObject *
2395date_subtract(PyObject *left, PyObject *right)
2396{
2397 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2398 Py_INCREF(Py_NotImplemented);
2399 return Py_NotImplemented;
2400 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002401 if (PyDate_Check(left)) {
2402 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002403 /* date - date */
2404 int left_ord = ymd_to_ord(GET_YEAR(left),
2405 GET_MONTH(left),
2406 GET_DAY(left));
2407 int right_ord = ymd_to_ord(GET_YEAR(right),
2408 GET_MONTH(right),
2409 GET_DAY(right));
2410 return new_delta(left_ord - right_ord, 0, 0, 0);
2411 }
2412 if (PyDelta_Check(right)) {
2413 /* date - delta */
2414 return add_date_timedelta((PyDateTime_Date *) left,
2415 (PyDateTime_Delta *) right,
2416 1);
2417 }
2418 }
2419 Py_INCREF(Py_NotImplemented);
2420 return Py_NotImplemented;
2421}
2422
2423
2424/* Various ways to turn a date into a string. */
2425
2426static PyObject *
2427date_repr(PyDateTime_Date *self)
2428{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002429 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002430 Py_TYPE(self)->tp_name,
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002431 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002432}
2433
2434static PyObject *
2435date_isoformat(PyDateTime_Date *self)
2436{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002437 return PyUnicode_FromFormat("%04d-%02d-%02d",
2438 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002439}
2440
Tim Peterse2df5ff2003-05-02 18:39:55 +00002441/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002442static PyObject *
2443date_str(PyDateTime_Date *self)
2444{
2445 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2446}
2447
2448
2449static PyObject *
2450date_ctime(PyDateTime_Date *self)
2451{
2452 return format_ctime(self, 0, 0, 0);
2453}
2454
2455static PyObject *
2456date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2457{
2458 /* This method can be inherited, and needs to call the
2459 * timetuple() method appropriate to self's class.
2460 */
2461 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00002462 PyObject *tuple;
Georg Brandlf78e02b2008-06-10 17:40:04 +00002463 PyObject *format;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002464 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002465
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002466 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00002467 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002468 return NULL;
2469
2470 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2471 if (tuple == NULL)
2472 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002473 result = wrap_strftime((PyObject *)self, format, tuple,
2474 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002475 Py_DECREF(tuple);
2476 return result;
2477}
2478
Eric Smith1ba31142007-09-11 18:06:02 +00002479static PyObject *
2480date_format(PyDateTime_Date *self, PyObject *args)
2481{
2482 PyObject *format;
2483
2484 if (!PyArg_ParseTuple(args, "U:__format__", &format))
2485 return NULL;
2486
2487 /* if the format is zero length, return str(self) */
2488 if (PyUnicode_GetSize(format) == 0)
Thomas Heller519a0422007-11-15 20:48:54 +00002489 return PyObject_Str((PyObject *)self);
Eric Smith1ba31142007-09-11 18:06:02 +00002490
2491 return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
2492}
2493
Tim Peters2a799bf2002-12-16 20:18:38 +00002494/* ISO methods. */
2495
2496static PyObject *
2497date_isoweekday(PyDateTime_Date *self)
2498{
2499 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2500
Christian Heimes217cfd12007-12-02 14:31:20 +00002501 return PyLong_FromLong(dow + 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00002502}
2503
2504static PyObject *
2505date_isocalendar(PyDateTime_Date *self)
2506{
2507 int year = GET_YEAR(self);
2508 int week1_monday = iso_week1_monday(year);
2509 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2510 int week;
2511 int day;
2512
2513 week = divmod(today - week1_monday, 7, &day);
2514 if (week < 0) {
2515 --year;
2516 week1_monday = iso_week1_monday(year);
2517 week = divmod(today - week1_monday, 7, &day);
2518 }
2519 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2520 ++year;
2521 week = 0;
2522 }
2523 return Py_BuildValue("iii", year, week + 1, day + 1);
2524}
2525
2526/* Miscellaneous methods. */
2527
Tim Peters2a799bf2002-12-16 20:18:38 +00002528static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002529date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002530{
Guido van Rossum19960592006-08-24 17:29:38 +00002531 if (PyDate_Check(other)) {
2532 int diff = memcmp(((PyDateTime_Date *)self)->data,
2533 ((PyDateTime_Date *)other)->data,
2534 _PyDateTime_DATE_DATASIZE);
2535 return diff_to_bool(diff, op);
2536 }
2537 else {
Tim Peters07534a62003-02-07 22:50:28 +00002538 Py_INCREF(Py_NotImplemented);
2539 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002540 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002541}
2542
2543static PyObject *
2544date_timetuple(PyDateTime_Date *self)
2545{
2546 return build_struct_time(GET_YEAR(self),
2547 GET_MONTH(self),
2548 GET_DAY(self),
2549 0, 0, 0, -1);
2550}
2551
Tim Peters12bf3392002-12-24 05:41:27 +00002552static PyObject *
2553date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2554{
2555 PyObject *clone;
2556 PyObject *tuple;
2557 int year = GET_YEAR(self);
2558 int month = GET_MONTH(self);
2559 int day = GET_DAY(self);
2560
2561 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2562 &year, &month, &day))
2563 return NULL;
2564 tuple = Py_BuildValue("iii", year, month, day);
2565 if (tuple == NULL)
2566 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002567 clone = date_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00002568 Py_DECREF(tuple);
2569 return clone;
2570}
2571
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002572/*
2573 Borrowed from stringobject.c, originally it was string_hash()
2574*/
2575static long
2576generic_hash(unsigned char *data, int len)
2577{
2578 register unsigned char *p;
2579 register long x;
2580
2581 p = (unsigned char *) data;
2582 x = *p << 7;
2583 while (--len >= 0)
2584 x = (1000003*x) ^ *p++;
2585 x ^= len;
2586 if (x == -1)
2587 x = -2;
2588
2589 return x;
2590}
2591
2592
2593static PyObject *date_getstate(PyDateTime_Date *self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002594
2595static long
2596date_hash(PyDateTime_Date *self)
2597{
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002598 if (self->hashcode == -1)
2599 self->hashcode = generic_hash(
2600 (unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
Guido van Rossum254348e2007-11-21 19:29:53 +00002601
Tim Peters2a799bf2002-12-16 20:18:38 +00002602 return self->hashcode;
2603}
2604
2605static PyObject *
2606date_toordinal(PyDateTime_Date *self)
2607{
Christian Heimes217cfd12007-12-02 14:31:20 +00002608 return PyLong_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
Tim Peters2a799bf2002-12-16 20:18:38 +00002609 GET_DAY(self)));
2610}
2611
2612static PyObject *
2613date_weekday(PyDateTime_Date *self)
2614{
2615 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2616
Christian Heimes217cfd12007-12-02 14:31:20 +00002617 return PyLong_FromLong(dow);
Tim Peters2a799bf2002-12-16 20:18:38 +00002618}
2619
Tim Peters371935f2003-02-01 01:52:50 +00002620/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002621
Tim Petersb57f8f02003-02-01 02:54:15 +00002622/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002623static PyObject *
Guido van Rossumfd53fd62007-08-24 04:05:13 +00002624date_getstate(PyDateTime_Date *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00002625{
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002626 PyObject* field;
Christian Heimes72b710a2008-05-26 13:28:38 +00002627 field = PyBytes_FromStringAndSize((char*)self->data,
Guido van Rossum254348e2007-11-21 19:29:53 +00002628 _PyDateTime_DATE_DATASIZE);
Martin v. Löwis10a60b32007-07-18 02:28:27 +00002629 return Py_BuildValue("(N)", field);
Tim Peters2a799bf2002-12-16 20:18:38 +00002630}
2631
2632static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002633date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002634{
Christian Heimes90aa7642007-12-19 02:45:37 +00002635 return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002636}
2637
2638static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002639
Tim Peters2a799bf2002-12-16 20:18:38 +00002640 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002641
Tim Peters2a799bf2002-12-16 20:18:38 +00002642 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2643 METH_CLASS,
2644 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2645 "time.time()).")},
2646
2647 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2648 METH_CLASS,
2649 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2650 "ordinal.")},
2651
2652 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2653 PyDoc_STR("Current date or datetime: same as "
2654 "self.__class__.fromtimestamp(time.time()).")},
2655
2656 /* Instance methods: */
2657
2658 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2659 PyDoc_STR("Return ctime() style string.")},
2660
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002661 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002662 PyDoc_STR("format -> strftime() style string.")},
2663
Eric Smith1ba31142007-09-11 18:06:02 +00002664 {"__format__", (PyCFunction)date_format, METH_VARARGS,
2665 PyDoc_STR("Formats self with strftime.")},
2666
Tim Peters2a799bf2002-12-16 20:18:38 +00002667 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2668 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2669
2670 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2671 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2672 "weekday.")},
2673
2674 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2675 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2676
2677 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2678 PyDoc_STR("Return the day of the week represented by the date.\n"
2679 "Monday == 1 ... Sunday == 7")},
2680
2681 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2682 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2683 "1 is day 1.")},
2684
2685 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2686 PyDoc_STR("Return the day of the week represented by the date.\n"
2687 "Monday == 0 ... Sunday == 6")},
2688
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002689 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002690 PyDoc_STR("Return date with new specified fields.")},
2691
Guido van Rossum177e41a2003-01-30 22:06:23 +00002692 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2693 PyDoc_STR("__reduce__() -> (cls, state)")},
2694
Tim Peters2a799bf2002-12-16 20:18:38 +00002695 {NULL, NULL}
2696};
2697
2698static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002699PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002700
2701static PyNumberMethods date_as_number = {
2702 date_add, /* nb_add */
2703 date_subtract, /* nb_subtract */
2704 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002705 0, /* nb_remainder */
2706 0, /* nb_divmod */
2707 0, /* nb_power */
2708 0, /* nb_negative */
2709 0, /* nb_positive */
2710 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002711 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002712};
2713
2714static PyTypeObject PyDateTime_DateType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002715 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002716 "datetime.date", /* tp_name */
2717 sizeof(PyDateTime_Date), /* tp_basicsize */
2718 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002719 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002720 0, /* tp_print */
2721 0, /* tp_getattr */
2722 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002723 0, /* tp_reserved */
Tim Peters2a799bf2002-12-16 20:18:38 +00002724 (reprfunc)date_repr, /* tp_repr */
2725 &date_as_number, /* tp_as_number */
2726 0, /* tp_as_sequence */
2727 0, /* tp_as_mapping */
2728 (hashfunc)date_hash, /* tp_hash */
2729 0, /* tp_call */
2730 (reprfunc)date_str, /* tp_str */
2731 PyObject_GenericGetAttr, /* tp_getattro */
2732 0, /* tp_setattro */
2733 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002734 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002735 date_doc, /* tp_doc */
2736 0, /* tp_traverse */
2737 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002738 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002739 0, /* tp_weaklistoffset */
2740 0, /* tp_iter */
2741 0, /* tp_iternext */
2742 date_methods, /* tp_methods */
2743 0, /* tp_members */
2744 date_getset, /* tp_getset */
2745 0, /* tp_base */
2746 0, /* tp_dict */
2747 0, /* tp_descr_get */
2748 0, /* tp_descr_set */
2749 0, /* tp_dictoffset */
2750 0, /* tp_init */
2751 0, /* tp_alloc */
2752 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002753 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002754};
2755
2756/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002757 * PyDateTime_TZInfo implementation.
2758 */
2759
2760/* This is a pure abstract base class, so doesn't do anything beyond
2761 * raising NotImplemented exceptions. Real tzinfo classes need
2762 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002763 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002764 * be subclasses of this tzinfo class, which is easy and quick to check).
2765 *
2766 * Note: For reasons having to do with pickling of subclasses, we have
2767 * to allow tzinfo objects to be instantiated. This wasn't an issue
2768 * in the Python implementation (__init__() could raise NotImplementedError
2769 * there without ill effect), but doing so in the C implementation hit a
2770 * brick wall.
2771 */
2772
2773static PyObject *
2774tzinfo_nogo(const char* methodname)
2775{
2776 PyErr_Format(PyExc_NotImplementedError,
2777 "a tzinfo subclass must implement %s()",
2778 methodname);
2779 return NULL;
2780}
2781
2782/* Methods. A subclass must implement these. */
2783
Tim Peters52dcce22003-01-23 16:36:11 +00002784static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002785tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2786{
2787 return tzinfo_nogo("tzname");
2788}
2789
Tim Peters52dcce22003-01-23 16:36:11 +00002790static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002791tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2792{
2793 return tzinfo_nogo("utcoffset");
2794}
2795
Tim Peters52dcce22003-01-23 16:36:11 +00002796static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002797tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2798{
2799 return tzinfo_nogo("dst");
2800}
2801
Tim Peters52dcce22003-01-23 16:36:11 +00002802static PyObject *
2803tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2804{
2805 int y, m, d, hh, mm, ss, us;
2806
2807 PyObject *result;
2808 int off, dst;
2809 int none;
2810 int delta;
2811
2812 if (! PyDateTime_Check(dt)) {
2813 PyErr_SetString(PyExc_TypeError,
2814 "fromutc: argument must be a datetime");
2815 return NULL;
2816 }
2817 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2818 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2819 "is not self");
2820 return NULL;
2821 }
2822
2823 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2824 if (off == -1 && PyErr_Occurred())
2825 return NULL;
2826 if (none) {
2827 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2828 "utcoffset() result required");
2829 return NULL;
2830 }
2831
2832 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2833 if (dst == -1 && PyErr_Occurred())
2834 return NULL;
2835 if (none) {
2836 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2837 "dst() result required");
2838 return NULL;
2839 }
2840
2841 y = GET_YEAR(dt);
2842 m = GET_MONTH(dt);
2843 d = GET_DAY(dt);
2844 hh = DATE_GET_HOUR(dt);
2845 mm = DATE_GET_MINUTE(dt);
2846 ss = DATE_GET_SECOND(dt);
2847 us = DATE_GET_MICROSECOND(dt);
2848
2849 delta = off - dst;
2850 mm += delta;
2851 if ((mm < 0 || mm >= 60) &&
2852 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002853 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002854 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2855 if (result == NULL)
2856 return result;
2857
2858 dst = call_dst(dt->tzinfo, result, &none);
2859 if (dst == -1 && PyErr_Occurred())
2860 goto Fail;
2861 if (none)
2862 goto Inconsistent;
2863 if (dst == 0)
2864 return result;
2865
2866 mm += dst;
2867 if ((mm < 0 || mm >= 60) &&
2868 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2869 goto Fail;
2870 Py_DECREF(result);
2871 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2872 return result;
2873
2874Inconsistent:
2875 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2876 "inconsistent results; cannot convert");
2877
2878 /* fall thru to failure */
2879Fail:
2880 Py_DECREF(result);
2881 return NULL;
2882}
2883
Tim Peters2a799bf2002-12-16 20:18:38 +00002884/*
2885 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002886 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002887 */
2888
Guido van Rossum177e41a2003-01-30 22:06:23 +00002889static PyObject *
2890tzinfo_reduce(PyObject *self)
2891{
2892 PyObject *args, *state, *tmp;
2893 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002894
Guido van Rossum177e41a2003-01-30 22:06:23 +00002895 tmp = PyTuple_New(0);
2896 if (tmp == NULL)
2897 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002898
Guido van Rossum177e41a2003-01-30 22:06:23 +00002899 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2900 if (getinitargs != NULL) {
2901 args = PyObject_CallObject(getinitargs, tmp);
2902 Py_DECREF(getinitargs);
2903 if (args == NULL) {
2904 Py_DECREF(tmp);
2905 return NULL;
2906 }
2907 }
2908 else {
2909 PyErr_Clear();
2910 args = tmp;
2911 Py_INCREF(args);
2912 }
2913
2914 getstate = PyObject_GetAttrString(self, "__getstate__");
2915 if (getstate != NULL) {
2916 state = PyObject_CallObject(getstate, tmp);
2917 Py_DECREF(getstate);
2918 if (state == NULL) {
2919 Py_DECREF(args);
2920 Py_DECREF(tmp);
2921 return NULL;
2922 }
2923 }
2924 else {
2925 PyObject **dictptr;
2926 PyErr_Clear();
2927 state = Py_None;
2928 dictptr = _PyObject_GetDictPtr(self);
2929 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2930 state = *dictptr;
2931 Py_INCREF(state);
2932 }
2933
2934 Py_DECREF(tmp);
2935
2936 if (state == Py_None) {
2937 Py_DECREF(state);
Christian Heimes90aa7642007-12-19 02:45:37 +00002938 return Py_BuildValue("(ON)", Py_TYPE(self), args);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002939 }
2940 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002941 return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
Guido van Rossum177e41a2003-01-30 22:06:23 +00002942}
Tim Peters2a799bf2002-12-16 20:18:38 +00002943
2944static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002945
Tim Peters2a799bf2002-12-16 20:18:38 +00002946 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2947 PyDoc_STR("datetime -> string name of time zone.")},
2948
2949 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2950 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2951 "west of UTC).")},
2952
2953 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2954 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2955
Tim Peters52dcce22003-01-23 16:36:11 +00002956 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2957 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2958
Guido van Rossum177e41a2003-01-30 22:06:23 +00002959 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2960 PyDoc_STR("-> (cls, state)")},
2961
Tim Peters2a799bf2002-12-16 20:18:38 +00002962 {NULL, NULL}
2963};
2964
2965static char tzinfo_doc[] =
2966PyDoc_STR("Abstract base class for time zone info objects.");
2967
Neal Norwitz227b5332006-03-22 09:28:35 +00002968static PyTypeObject PyDateTime_TZInfoType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002969 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00002970 "datetime.tzinfo", /* tp_name */
2971 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2972 0, /* tp_itemsize */
2973 0, /* tp_dealloc */
2974 0, /* tp_print */
2975 0, /* tp_getattr */
2976 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002977 0, /* tp_reserved */
Tim Peters2a799bf2002-12-16 20:18:38 +00002978 0, /* tp_repr */
2979 0, /* tp_as_number */
2980 0, /* tp_as_sequence */
2981 0, /* tp_as_mapping */
2982 0, /* tp_hash */
2983 0, /* tp_call */
2984 0, /* tp_str */
2985 PyObject_GenericGetAttr, /* tp_getattro */
2986 0, /* tp_setattro */
2987 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002988 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002989 tzinfo_doc, /* tp_doc */
2990 0, /* tp_traverse */
2991 0, /* tp_clear */
2992 0, /* tp_richcompare */
2993 0, /* tp_weaklistoffset */
2994 0, /* tp_iter */
2995 0, /* tp_iternext */
2996 tzinfo_methods, /* tp_methods */
2997 0, /* tp_members */
2998 0, /* tp_getset */
2999 0, /* tp_base */
3000 0, /* tp_dict */
3001 0, /* tp_descr_get */
3002 0, /* tp_descr_set */
3003 0, /* tp_dictoffset */
3004 0, /* tp_init */
3005 0, /* tp_alloc */
3006 PyType_GenericNew, /* tp_new */
3007 0, /* tp_free */
3008};
3009
3010/*
Tim Peters37f39822003-01-10 03:49:02 +00003011 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003012 */
3013
Tim Peters37f39822003-01-10 03:49:02 +00003014/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00003015 */
3016
3017static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003018time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003019{
Christian Heimes217cfd12007-12-02 14:31:20 +00003020 return PyLong_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003021}
3022
Tim Peters37f39822003-01-10 03:49:02 +00003023static PyObject *
3024time_minute(PyDateTime_Time *self, void *unused)
3025{
Christian Heimes217cfd12007-12-02 14:31:20 +00003026 return PyLong_FromLong(TIME_GET_MINUTE(self));
Tim Peters37f39822003-01-10 03:49:02 +00003027}
3028
3029/* The name time_second conflicted with some platform header file. */
3030static PyObject *
3031py_time_second(PyDateTime_Time *self, void *unused)
3032{
Christian Heimes217cfd12007-12-02 14:31:20 +00003033 return PyLong_FromLong(TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003034}
3035
3036static PyObject *
3037time_microsecond(PyDateTime_Time *self, void *unused)
3038{
Christian Heimes217cfd12007-12-02 14:31:20 +00003039 return PyLong_FromLong(TIME_GET_MICROSECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003040}
3041
3042static PyObject *
3043time_tzinfo(PyDateTime_Time *self, void *unused)
3044{
Tim Petersa032d2e2003-01-11 00:15:54 +00003045 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003046 Py_INCREF(result);
3047 return result;
3048}
3049
3050static PyGetSetDef time_getset[] = {
3051 {"hour", (getter)time_hour},
3052 {"minute", (getter)time_minute},
3053 {"second", (getter)py_time_second},
3054 {"microsecond", (getter)time_microsecond},
3055 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003056 {NULL}
3057};
3058
3059/*
3060 * Constructors.
3061 */
3062
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003063static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003064 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003065
Tim Peters2a799bf2002-12-16 20:18:38 +00003066static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003067time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003068{
3069 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003070 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003071 int hour = 0;
3072 int minute = 0;
3073 int second = 0;
3074 int usecond = 0;
3075 PyObject *tzinfo = Py_None;
3076
Guido van Rossum177e41a2003-01-30 22:06:23 +00003077 /* Check for invocation from pickle with __getstate__ state */
3078 if (PyTuple_GET_SIZE(args) >= 1 &&
3079 PyTuple_GET_SIZE(args) <= 2 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00003080 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3081 PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3082 ((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003083 {
Tim Peters70533e22003-02-01 04:40:04 +00003084 PyDateTime_Time *me;
3085 char aware;
3086
3087 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003088 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003089 if (check_tzinfo_subclass(tzinfo) < 0) {
3090 PyErr_SetString(PyExc_TypeError, "bad "
3091 "tzinfo state arg");
3092 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003093 }
3094 }
Tim Peters70533e22003-02-01 04:40:04 +00003095 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003096 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003097 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003098 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003099
3100 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3101 me->hashcode = -1;
3102 me->hastzinfo = aware;
3103 if (aware) {
3104 Py_INCREF(tzinfo);
3105 me->tzinfo = tzinfo;
3106 }
3107 }
3108 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003109 }
3110
Tim Peters37f39822003-01-10 03:49:02 +00003111 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003112 &hour, &minute, &second, &usecond,
3113 &tzinfo)) {
3114 if (check_time_args(hour, minute, second, usecond) < 0)
3115 return NULL;
3116 if (check_tzinfo_subclass(tzinfo) < 0)
3117 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003118 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3119 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003120 }
3121 return self;
3122}
3123
3124/*
3125 * Destructor.
3126 */
3127
3128static void
Tim Peters37f39822003-01-10 03:49:02 +00003129time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003130{
Tim Petersa032d2e2003-01-11 00:15:54 +00003131 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003132 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003133 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003134 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003135}
3136
3137/*
Tim Peters855fe882002-12-22 03:43:39 +00003138 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003139 */
3140
Tim Peters2a799bf2002-12-16 20:18:38 +00003141/* These are all METH_NOARGS, so don't need to check the arglist. */
3142static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003143time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003144 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003145 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003146}
3147
3148static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003149time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003150 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003151 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003152}
3153
3154static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003155time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003156 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003157 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003158}
3159
3160/*
Tim Peters37f39822003-01-10 03:49:02 +00003161 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003162 */
3163
3164static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003165time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003166{
Christian Heimes90aa7642007-12-19 02:45:37 +00003167 const char *type_name = Py_TYPE(self)->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003168 int h = TIME_GET_HOUR(self);
3169 int m = TIME_GET_MINUTE(self);
3170 int s = TIME_GET_SECOND(self);
3171 int us = TIME_GET_MICROSECOND(self);
3172 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003173
Tim Peters37f39822003-01-10 03:49:02 +00003174 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003175 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3176 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003177 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003178 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3179 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003180 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003181 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003182 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003183 result = append_keyword_tzinfo(result, self->tzinfo);
3184 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003185}
3186
Tim Peters37f39822003-01-10 03:49:02 +00003187static PyObject *
3188time_str(PyDateTime_Time *self)
3189{
3190 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3191}
Tim Peters2a799bf2002-12-16 20:18:38 +00003192
3193static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003194time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003195{
3196 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003197 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003198 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003199
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003200 if (us)
3201 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3202 TIME_GET_HOUR(self),
3203 TIME_GET_MINUTE(self),
3204 TIME_GET_SECOND(self),
3205 us);
3206 else
3207 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3208 TIME_GET_HOUR(self),
3209 TIME_GET_MINUTE(self),
3210 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003211
Tim Petersa032d2e2003-01-11 00:15:54 +00003212 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003213 return result;
3214
3215 /* We need to append the UTC offset. */
3216 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003217 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003218 Py_DECREF(result);
3219 return NULL;
3220 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003221 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003222 return result;
3223}
3224
Tim Peters37f39822003-01-10 03:49:02 +00003225static PyObject *
3226time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3227{
3228 PyObject *result;
Tim Peters37f39822003-01-10 03:49:02 +00003229 PyObject *tuple;
Georg Brandlf78e02b2008-06-10 17:40:04 +00003230 PyObject *format;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003231 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003232
Guido van Rossum98297ee2007-11-06 21:34:58 +00003233 if (! PyArg_ParseTupleAndKeywords(args, kw, "U:strftime", keywords,
Guido van Rossumbce56a62007-05-10 18:04:33 +00003234 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003235 return NULL;
3236
3237 /* Python's strftime does insane things with the year part of the
3238 * timetuple. The year is forced to (the otherwise nonsensical)
3239 * 1900 to worm around that.
3240 */
3241 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003242 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003243 TIME_GET_HOUR(self),
3244 TIME_GET_MINUTE(self),
3245 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003246 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003247 if (tuple == NULL)
3248 return NULL;
3249 assert(PyTuple_Size(tuple) == 9);
Georg Brandlf78e02b2008-06-10 17:40:04 +00003250 result = wrap_strftime((PyObject *)self, format, tuple,
3251 Py_None);
Tim Peters37f39822003-01-10 03:49:02 +00003252 Py_DECREF(tuple);
3253 return result;
3254}
Tim Peters2a799bf2002-12-16 20:18:38 +00003255
3256/*
3257 * Miscellaneous methods.
3258 */
3259
Tim Peters37f39822003-01-10 03:49:02 +00003260static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003261time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003262{
3263 int diff;
3264 naivety n1, n2;
3265 int offset1, offset2;
3266
3267 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003268 Py_INCREF(Py_NotImplemented);
3269 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003270 }
Guido van Rossum19960592006-08-24 17:29:38 +00003271 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3272 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003273 return NULL;
3274 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3275 /* If they're both naive, or both aware and have the same offsets,
3276 * we get off cheap. Note that if they're both naive, offset1 ==
3277 * offset2 == 0 at this point.
3278 */
3279 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003280 diff = memcmp(((PyDateTime_Time *)self)->data,
3281 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003282 _PyDateTime_TIME_DATASIZE);
3283 return diff_to_bool(diff, op);
3284 }
3285
3286 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3287 assert(offset1 != offset2); /* else last "if" handled it */
3288 /* Convert everything except microseconds to seconds. These
3289 * can't overflow (no more than the # of seconds in 2 days).
3290 */
3291 offset1 = TIME_GET_HOUR(self) * 3600 +
3292 (TIME_GET_MINUTE(self) - offset1) * 60 +
3293 TIME_GET_SECOND(self);
3294 offset2 = TIME_GET_HOUR(other) * 3600 +
3295 (TIME_GET_MINUTE(other) - offset2) * 60 +
3296 TIME_GET_SECOND(other);
3297 diff = offset1 - offset2;
3298 if (diff == 0)
3299 diff = TIME_GET_MICROSECOND(self) -
3300 TIME_GET_MICROSECOND(other);
3301 return diff_to_bool(diff, op);
3302 }
3303
3304 assert(n1 != n2);
3305 PyErr_SetString(PyExc_TypeError,
3306 "can't compare offset-naive and "
3307 "offset-aware times");
3308 return NULL;
3309}
3310
3311static long
3312time_hash(PyDateTime_Time *self)
3313{
3314 if (self->hashcode == -1) {
3315 naivety n;
3316 int offset;
3317 PyObject *temp;
3318
3319 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3320 assert(n != OFFSET_UNKNOWN);
3321 if (n == OFFSET_ERROR)
3322 return -1;
3323
3324 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003325 if (offset == 0) {
3326 self->hashcode = generic_hash(
3327 (unsigned char *)self->data, _PyDateTime_TIME_DATASIZE);
3328 return self->hashcode;
3329 }
Tim Peters37f39822003-01-10 03:49:02 +00003330 else {
3331 int hour;
3332 int minute;
3333
3334 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003335 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003336 hour = divmod(TIME_GET_HOUR(self) * 60 +
3337 TIME_GET_MINUTE(self) - offset,
3338 60,
3339 &minute);
3340 if (0 <= hour && hour < 24)
3341 temp = new_time(hour, minute,
3342 TIME_GET_SECOND(self),
3343 TIME_GET_MICROSECOND(self),
3344 Py_None);
3345 else
3346 temp = Py_BuildValue("iiii",
3347 hour, minute,
3348 TIME_GET_SECOND(self),
3349 TIME_GET_MICROSECOND(self));
3350 }
3351 if (temp != NULL) {
3352 self->hashcode = PyObject_Hash(temp);
3353 Py_DECREF(temp);
3354 }
3355 }
3356 return self->hashcode;
3357}
Tim Peters2a799bf2002-12-16 20:18:38 +00003358
Tim Peters12bf3392002-12-24 05:41:27 +00003359static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003360time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003361{
3362 PyObject *clone;
3363 PyObject *tuple;
3364 int hh = TIME_GET_HOUR(self);
3365 int mm = TIME_GET_MINUTE(self);
3366 int ss = TIME_GET_SECOND(self);
3367 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003368 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003369
3370 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003371 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003372 &hh, &mm, &ss, &us, &tzinfo))
3373 return NULL;
3374 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3375 if (tuple == NULL)
3376 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003377 clone = time_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003378 Py_DECREF(tuple);
3379 return clone;
3380}
3381
Tim Peters2a799bf2002-12-16 20:18:38 +00003382static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003383time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003384{
3385 int offset;
3386 int none;
3387
3388 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3389 /* Since utcoffset is in whole minutes, nothing can
3390 * alter the conclusion that this is nonzero.
3391 */
3392 return 1;
3393 }
3394 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003395 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003396 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003397 if (offset == -1 && PyErr_Occurred())
3398 return -1;
3399 }
3400 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3401}
3402
Tim Peters371935f2003-02-01 01:52:50 +00003403/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003404
Tim Peters33e0f382003-01-10 02:05:14 +00003405/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003406 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3407 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003408 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003409 */
3410static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003411time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003412{
3413 PyObject *basestate;
3414 PyObject *result = NULL;
3415
Christian Heimes72b710a2008-05-26 13:28:38 +00003416 basestate = PyBytes_FromStringAndSize((char *)self->data,
Tim Peters33e0f382003-01-10 02:05:14 +00003417 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003418 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003419 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003420 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003421 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003422 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003423 Py_DECREF(basestate);
3424 }
3425 return result;
3426}
3427
3428static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003429time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003430{
Christian Heimes90aa7642007-12-19 02:45:37 +00003431 return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003432}
3433
Tim Peters37f39822003-01-10 03:49:02 +00003434static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003435
Thomas Wouterscf297e42007-02-23 15:07:44 +00003436 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003437 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3438 "[+HH:MM].")},
3439
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003440 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003441 PyDoc_STR("format -> strftime() style string.")},
3442
Eric Smith8fd3eba2008-02-17 19:48:00 +00003443 {"__format__", (PyCFunction)date_format, METH_VARARGS,
Eric Smith1ba31142007-09-11 18:06:02 +00003444 PyDoc_STR("Formats self with strftime.")},
3445
Tim Peters37f39822003-01-10 03:49:02 +00003446 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003447 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3448
Tim Peters37f39822003-01-10 03:49:02 +00003449 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003450 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3451
Tim Peters37f39822003-01-10 03:49:02 +00003452 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003453 PyDoc_STR("Return self.tzinfo.dst(self).")},
3454
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003455 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003456 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003457
Guido van Rossum177e41a2003-01-30 22:06:23 +00003458 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3459 PyDoc_STR("__reduce__() -> (cls, state)")},
3460
Tim Peters2a799bf2002-12-16 20:18:38 +00003461 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003462};
3463
Tim Peters37f39822003-01-10 03:49:02 +00003464static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003465PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3466\n\
3467All arguments are optional. tzinfo may be None, or an instance of\n\
3468a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003469
Tim Peters37f39822003-01-10 03:49:02 +00003470static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003471 0, /* nb_add */
3472 0, /* nb_subtract */
3473 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003474 0, /* nb_remainder */
3475 0, /* nb_divmod */
3476 0, /* nb_power */
3477 0, /* nb_negative */
3478 0, /* nb_positive */
3479 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003480 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003481};
3482
Neal Norwitz227b5332006-03-22 09:28:35 +00003483static PyTypeObject PyDateTime_TimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003484 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00003485 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003486 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003487 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003488 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003489 0, /* tp_print */
3490 0, /* tp_getattr */
3491 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003492 0, /* tp_reserved */
Tim Peters37f39822003-01-10 03:49:02 +00003493 (reprfunc)time_repr, /* tp_repr */
3494 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003495 0, /* tp_as_sequence */
3496 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003497 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003498 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003499 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003500 PyObject_GenericGetAttr, /* tp_getattro */
3501 0, /* tp_setattro */
3502 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003503 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003504 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003505 0, /* tp_traverse */
3506 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003507 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003508 0, /* tp_weaklistoffset */
3509 0, /* tp_iter */
3510 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003511 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003512 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003513 time_getset, /* tp_getset */
3514 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003515 0, /* tp_dict */
3516 0, /* tp_descr_get */
3517 0, /* tp_descr_set */
3518 0, /* tp_dictoffset */
3519 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003520 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003521 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003522 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003523};
3524
3525/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003526 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003527 */
3528
Tim Petersa9bc1682003-01-11 03:39:11 +00003529/* Accessor properties. Properties for day, month, and year are inherited
3530 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003531 */
3532
3533static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003534datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003535{
Christian Heimes217cfd12007-12-02 14:31:20 +00003536 return PyLong_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003537}
3538
Tim Petersa9bc1682003-01-11 03:39:11 +00003539static PyObject *
3540datetime_minute(PyDateTime_DateTime *self, void *unused)
3541{
Christian Heimes217cfd12007-12-02 14:31:20 +00003542 return PyLong_FromLong(DATE_GET_MINUTE(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003543}
3544
3545static PyObject *
3546datetime_second(PyDateTime_DateTime *self, void *unused)
3547{
Christian Heimes217cfd12007-12-02 14:31:20 +00003548 return PyLong_FromLong(DATE_GET_SECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003549}
3550
3551static PyObject *
3552datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3553{
Christian Heimes217cfd12007-12-02 14:31:20 +00003554 return PyLong_FromLong(DATE_GET_MICROSECOND(self));
Tim Petersa9bc1682003-01-11 03:39:11 +00003555}
3556
3557static PyObject *
3558datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3559{
3560 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3561 Py_INCREF(result);
3562 return result;
3563}
3564
3565static PyGetSetDef datetime_getset[] = {
3566 {"hour", (getter)datetime_hour},
3567 {"minute", (getter)datetime_minute},
3568 {"second", (getter)datetime_second},
3569 {"microsecond", (getter)datetime_microsecond},
3570 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003571 {NULL}
3572};
3573
3574/*
3575 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003576 */
3577
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003578static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003579 "year", "month", "day", "hour", "minute", "second",
3580 "microsecond", "tzinfo", NULL
3581};
3582
Tim Peters2a799bf2002-12-16 20:18:38 +00003583static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003584datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003585{
3586 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003587 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003588 int year;
3589 int month;
3590 int day;
3591 int hour = 0;
3592 int minute = 0;
3593 int second = 0;
3594 int usecond = 0;
3595 PyObject *tzinfo = Py_None;
3596
Guido van Rossum177e41a2003-01-30 22:06:23 +00003597 /* Check for invocation from pickle with __getstate__ state */
3598 if (PyTuple_GET_SIZE(args) >= 1 &&
3599 PyTuple_GET_SIZE(args) <= 2 &&
Christian Heimes72b710a2008-05-26 13:28:38 +00003600 PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3601 PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3602 MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003603 {
Tim Peters70533e22003-02-01 04:40:04 +00003604 PyDateTime_DateTime *me;
3605 char aware;
3606
3607 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003608 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003609 if (check_tzinfo_subclass(tzinfo) < 0) {
3610 PyErr_SetString(PyExc_TypeError, "bad "
3611 "tzinfo state arg");
3612 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003613 }
3614 }
Tim Peters70533e22003-02-01 04:40:04 +00003615 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003616 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003617 if (me != NULL) {
Christian Heimes72b710a2008-05-26 13:28:38 +00003618 char *pdata = PyBytes_AS_STRING(state);
Tim Peters70533e22003-02-01 04:40:04 +00003619
3620 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3621 me->hashcode = -1;
3622 me->hastzinfo = aware;
3623 if (aware) {
3624 Py_INCREF(tzinfo);
3625 me->tzinfo = tzinfo;
3626 }
3627 }
3628 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003629 }
3630
Tim Petersa9bc1682003-01-11 03:39:11 +00003631 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003632 &year, &month, &day, &hour, &minute,
3633 &second, &usecond, &tzinfo)) {
3634 if (check_date_args(year, month, day) < 0)
3635 return NULL;
3636 if (check_time_args(hour, minute, second, usecond) < 0)
3637 return NULL;
3638 if (check_tzinfo_subclass(tzinfo) < 0)
3639 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003640 self = new_datetime_ex(year, month, day,
3641 hour, minute, second, usecond,
3642 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003643 }
3644 return self;
3645}
3646
Tim Petersa9bc1682003-01-11 03:39:11 +00003647/* TM_FUNC is the shared type of localtime() and gmtime(). */
3648typedef struct tm *(*TM_FUNC)(const time_t *timer);
3649
3650/* Internal helper.
3651 * Build datetime from a time_t and a distinct count of microseconds.
3652 * Pass localtime or gmtime for f, to control the interpretation of timet.
3653 */
3654static PyObject *
3655datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3656 PyObject *tzinfo)
3657{
3658 struct tm *tm;
3659 PyObject *result = NULL;
3660
3661 tm = f(&timet);
3662 if (tm) {
3663 /* The platform localtime/gmtime may insert leap seconds,
3664 * indicated by tm->tm_sec > 59. We don't care about them,
3665 * except to the extent that passing them on to the datetime
3666 * constructor would raise ValueError for a reason that
3667 * made no sense to the user.
3668 */
3669 if (tm->tm_sec > 59)
3670 tm->tm_sec = 59;
3671 result = PyObject_CallFunction(cls, "iiiiiiiO",
3672 tm->tm_year + 1900,
3673 tm->tm_mon + 1,
3674 tm->tm_mday,
3675 tm->tm_hour,
3676 tm->tm_min,
3677 tm->tm_sec,
3678 us,
3679 tzinfo);
3680 }
3681 else
3682 PyErr_SetString(PyExc_ValueError,
3683 "timestamp out of range for "
3684 "platform localtime()/gmtime() function");
3685 return result;
3686}
3687
3688/* Internal helper.
3689 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3690 * to control the interpretation of the timestamp. Since a double doesn't
3691 * have enough bits to cover a datetime's full range of precision, it's
3692 * better to call datetime_from_timet_and_us provided you have a way
3693 * to get that much precision (e.g., C time() isn't good enough).
3694 */
3695static PyObject *
3696datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3697 PyObject *tzinfo)
3698{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003699 time_t timet;
3700 double fraction;
3701 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003702
Tim Peters1b6f7a92004-06-20 02:50:16 +00003703 timet = _PyTime_DoubleToTimet(timestamp);
3704 if (timet == (time_t)-1 && PyErr_Occurred())
3705 return NULL;
3706 fraction = timestamp - (double)timet;
3707 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003708 if (us < 0) {
3709 /* Truncation towards zero is not what we wanted
3710 for negative numbers (Python's mod semantics) */
3711 timet -= 1;
3712 us += 1000000;
3713 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003714 /* If timestamp is less than one microsecond smaller than a
3715 * full second, round up. Otherwise, ValueErrors are raised
3716 * for some floats. */
3717 if (us == 1000000) {
3718 timet += 1;
3719 us = 0;
3720 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003721 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3722}
3723
3724/* Internal helper.
3725 * Build most accurate possible datetime for current time. Pass localtime or
3726 * gmtime for f as appropriate.
3727 */
3728static PyObject *
3729datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3730{
3731#ifdef HAVE_GETTIMEOFDAY
3732 struct timeval t;
3733
3734#ifdef GETTIMEOFDAY_NO_TZ
3735 gettimeofday(&t);
3736#else
3737 gettimeofday(&t, (struct timezone *)NULL);
3738#endif
3739 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3740 tzinfo);
3741
3742#else /* ! HAVE_GETTIMEOFDAY */
3743 /* No flavor of gettimeofday exists on this platform. Python's
3744 * time.time() does a lot of other platform tricks to get the
3745 * best time it can on the platform, and we're not going to do
3746 * better than that (if we could, the better code would belong
3747 * in time.time()!) We're limited by the precision of a double,
3748 * though.
3749 */
3750 PyObject *time;
3751 double dtime;
3752
3753 time = time_time();
3754 if (time == NULL)
3755 return NULL;
3756 dtime = PyFloat_AsDouble(time);
3757 Py_DECREF(time);
3758 if (dtime == -1.0 && PyErr_Occurred())
3759 return NULL;
3760 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3761#endif /* ! HAVE_GETTIMEOFDAY */
3762}
3763
Tim Peters2a799bf2002-12-16 20:18:38 +00003764/* Return best possible local time -- this isn't constrained by the
3765 * precision of a timestamp.
3766 */
3767static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003768datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003769{
Tim Peters10cadce2003-01-23 19:58:02 +00003770 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003771 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003772 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003773
Tim Peters10cadce2003-01-23 19:58:02 +00003774 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3775 &tzinfo))
3776 return NULL;
3777 if (check_tzinfo_subclass(tzinfo) < 0)
3778 return NULL;
3779
3780 self = datetime_best_possible(cls,
3781 tzinfo == Py_None ? localtime : gmtime,
3782 tzinfo);
3783 if (self != NULL && tzinfo != Py_None) {
3784 /* Convert UTC to tzinfo's zone. */
3785 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003786 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003787 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003788 }
3789 return self;
3790}
3791
Tim Petersa9bc1682003-01-11 03:39:11 +00003792/* Return best possible UTC time -- this isn't constrained by the
3793 * precision of a timestamp.
3794 */
3795static PyObject *
3796datetime_utcnow(PyObject *cls, PyObject *dummy)
3797{
3798 return datetime_best_possible(cls, gmtime, Py_None);
3799}
3800
Tim Peters2a799bf2002-12-16 20:18:38 +00003801/* Return new local datetime from timestamp (Python timestamp -- a double). */
3802static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003803datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003804{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003805 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003806 double timestamp;
3807 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003808 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003809
Tim Peters2a44a8d2003-01-23 20:53:10 +00003810 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3811 keywords, &timestamp, &tzinfo))
3812 return NULL;
3813 if (check_tzinfo_subclass(tzinfo) < 0)
3814 return NULL;
3815
3816 self = datetime_from_timestamp(cls,
3817 tzinfo == Py_None ? localtime : gmtime,
3818 timestamp,
3819 tzinfo);
3820 if (self != NULL && tzinfo != Py_None) {
3821 /* Convert UTC to tzinfo's zone. */
3822 PyObject *temp = self;
3823 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3824 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003825 }
3826 return self;
3827}
3828
Tim Petersa9bc1682003-01-11 03:39:11 +00003829/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3830static PyObject *
3831datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3832{
3833 double timestamp;
3834 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003835
Tim Petersa9bc1682003-01-11 03:39:11 +00003836 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3837 result = datetime_from_timestamp(cls, gmtime, timestamp,
3838 Py_None);
3839 return result;
3840}
3841
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003842/* Return new datetime from time.strptime(). */
3843static PyObject *
3844datetime_strptime(PyObject *cls, PyObject *args)
3845{
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003846 static PyObject *module = NULL;
3847 PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
Guido van Rossume8a17aa2007-08-29 17:28:42 +00003848 const Py_UNICODE *string, *format;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003849
Guido van Rossumfd53fd62007-08-24 04:05:13 +00003850 if (!PyArg_ParseTuple(args, "uu:strptime", &string, &format))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003851 return NULL;
3852
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003853 if (module == NULL &&
3854 (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003855 return NULL;
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003856
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003857 /* _strptime._strptime returns a two-element tuple. The first
3858 element is a time.struct_time object. The second is the
3859 microseconds (which are not defined for time.struct_time). */
Mark Dickinsonfc689dd2008-03-16 03:45:34 +00003860 obj = PyObject_CallMethod(module, "_strptime", "uu", string, format);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003861 if (obj != NULL) {
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003862 int i, good_timetuple = 1;
3863 long int ia[7];
3864 if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
3865 st = PySequence_GetItem(obj, 0);
3866 frac = PySequence_GetItem(obj, 1);
3867 if (st == NULL || frac == NULL)
3868 good_timetuple = 0;
3869 /* copy y/m/d/h/m/s values out of the
3870 time.struct_time */
3871 if (good_timetuple &&
3872 PySequence_Check(st) &&
3873 PySequence_Size(st) >= 6) {
3874 for (i=0; i < 6; i++) {
3875 PyObject *p = PySequence_GetItem(st, i);
3876 if (p == NULL) {
3877 good_timetuple = 0;
3878 break;
3879 }
3880 if (PyLong_Check(p))
3881 ia[i] = PyLong_AsLong(p);
3882 else
3883 good_timetuple = 0;
3884 Py_DECREF(p);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003885 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003886/* if (PyLong_CheckExact(p)) {
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00003887 ia[i] = PyLong_AsLongAndOverflow(p, &overflow);
3888 if (overflow)
3889 good_timetuple = 0;
3890 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003891 else
3892 good_timetuple = 0;
3893 Py_DECREF(p);
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003894*/ }
3895 else
3896 good_timetuple = 0;
3897 /* follow that up with a little dose of microseconds */
3898 if (PyLong_Check(frac))
3899 ia[6] = PyLong_AsLong(frac);
3900 else
3901 good_timetuple = 0;
3902 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003903 else
3904 good_timetuple = 0;
3905 if (good_timetuple)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003906 result = PyObject_CallFunction(cls, "iiiiiii",
3907 ia[0], ia[1], ia[2],
3908 ia[3], ia[4], ia[5],
3909 ia[6]);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003910 else
3911 PyErr_SetString(PyExc_ValueError,
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003912 "unexpected value from _strptime._strptime");
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003913 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00003914 Py_XDECREF(obj);
3915 Py_XDECREF(st);
3916 Py_XDECREF(frac);
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003917 return result;
3918}
3919
Tim Petersa9bc1682003-01-11 03:39:11 +00003920/* Return new datetime from date/datetime and time arguments. */
3921static PyObject *
3922datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3923{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003924 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003925 PyObject *date;
3926 PyObject *time;
3927 PyObject *result = NULL;
3928
3929 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3930 &PyDateTime_DateType, &date,
3931 &PyDateTime_TimeType, &time)) {
3932 PyObject *tzinfo = Py_None;
3933
3934 if (HASTZINFO(time))
3935 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3936 result = PyObject_CallFunction(cls, "iiiiiiiO",
3937 GET_YEAR(date),
3938 GET_MONTH(date),
3939 GET_DAY(date),
3940 TIME_GET_HOUR(time),
3941 TIME_GET_MINUTE(time),
3942 TIME_GET_SECOND(time),
3943 TIME_GET_MICROSECOND(time),
3944 tzinfo);
3945 }
3946 return result;
3947}
Tim Peters2a799bf2002-12-16 20:18:38 +00003948
3949/*
3950 * Destructor.
3951 */
3952
3953static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003954datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003955{
Tim Petersa9bc1682003-01-11 03:39:11 +00003956 if (HASTZINFO(self)) {
3957 Py_XDECREF(self->tzinfo);
3958 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003959 Py_TYPE(self)->tp_free((PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003960}
3961
3962/*
3963 * Indirect access to tzinfo methods.
3964 */
3965
Tim Peters2a799bf2002-12-16 20:18:38 +00003966/* These are all METH_NOARGS, so don't need to check the arglist. */
3967static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003968datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3969 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3970 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003971}
3972
3973static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003974datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3975 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3976 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003977}
3978
3979static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003980datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3981 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3982 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003983}
3984
3985/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003986 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003987 */
3988
Tim Petersa9bc1682003-01-11 03:39:11 +00003989/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3990 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003991 */
3992static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003993add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3994 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003995{
Tim Petersa9bc1682003-01-11 03:39:11 +00003996 /* Note that the C-level additions can't overflow, because of
3997 * invariant bounds on the member values.
3998 */
3999 int year = GET_YEAR(date);
4000 int month = GET_MONTH(date);
4001 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4002 int hour = DATE_GET_HOUR(date);
4003 int minute = DATE_GET_MINUTE(date);
4004 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4005 int microsecond = DATE_GET_MICROSECOND(date) +
4006 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00004007
Tim Petersa9bc1682003-01-11 03:39:11 +00004008 assert(factor == 1 || factor == -1);
4009 if (normalize_datetime(&year, &month, &day,
4010 &hour, &minute, &second, &microsecond) < 0)
4011 return NULL;
4012 else
4013 return new_datetime(year, month, day,
4014 hour, minute, second, microsecond,
4015 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004016}
4017
4018static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004019datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004020{
Tim Petersa9bc1682003-01-11 03:39:11 +00004021 if (PyDateTime_Check(left)) {
4022 /* datetime + ??? */
4023 if (PyDelta_Check(right))
4024 /* datetime + delta */
4025 return add_datetime_timedelta(
4026 (PyDateTime_DateTime *)left,
4027 (PyDateTime_Delta *)right,
4028 1);
4029 }
4030 else if (PyDelta_Check(left)) {
4031 /* delta + datetime */
4032 return add_datetime_timedelta((PyDateTime_DateTime *) right,
4033 (PyDateTime_Delta *) left,
4034 1);
4035 }
4036 Py_INCREF(Py_NotImplemented);
4037 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00004038}
4039
4040static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004041datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00004042{
4043 PyObject *result = Py_NotImplemented;
4044
4045 if (PyDateTime_Check(left)) {
4046 /* datetime - ??? */
4047 if (PyDateTime_Check(right)) {
4048 /* datetime - datetime */
4049 naivety n1, n2;
4050 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004051 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004052
Tim Peterse39a80c2002-12-30 21:28:52 +00004053 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4054 right, &offset2, &n2,
4055 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00004056 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00004057 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00004058 if (n1 != n2) {
4059 PyErr_SetString(PyExc_TypeError,
4060 "can't subtract offset-naive and "
4061 "offset-aware datetimes");
4062 return NULL;
4063 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004064 delta_d = ymd_to_ord(GET_YEAR(left),
4065 GET_MONTH(left),
4066 GET_DAY(left)) -
4067 ymd_to_ord(GET_YEAR(right),
4068 GET_MONTH(right),
4069 GET_DAY(right));
4070 /* These can't overflow, since the values are
4071 * normalized. At most this gives the number of
4072 * seconds in one day.
4073 */
4074 delta_s = (DATE_GET_HOUR(left) -
4075 DATE_GET_HOUR(right)) * 3600 +
4076 (DATE_GET_MINUTE(left) -
4077 DATE_GET_MINUTE(right)) * 60 +
4078 (DATE_GET_SECOND(left) -
4079 DATE_GET_SECOND(right));
4080 delta_us = DATE_GET_MICROSECOND(left) -
4081 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004082 /* (left - offset1) - (right - offset2) =
4083 * (left - right) + (offset2 - offset1)
4084 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004085 delta_s += (offset2 - offset1) * 60;
4086 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004087 }
4088 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004089 /* datetime - delta */
4090 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004091 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004092 (PyDateTime_Delta *)right,
4093 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004094 }
4095 }
4096
4097 if (result == Py_NotImplemented)
4098 Py_INCREF(result);
4099 return result;
4100}
4101
4102/* Various ways to turn a datetime into a string. */
4103
4104static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004105datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004106{
Christian Heimes90aa7642007-12-19 02:45:37 +00004107 const char *type_name = Py_TYPE(self)->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004108 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004109
Tim Petersa9bc1682003-01-11 03:39:11 +00004110 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004111 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004112 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004113 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004114 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4115 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4116 DATE_GET_SECOND(self),
4117 DATE_GET_MICROSECOND(self));
4118 }
4119 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004120 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004121 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004122 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004123 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4124 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4125 DATE_GET_SECOND(self));
4126 }
4127 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004128 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004129 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004130 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004131 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4132 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4133 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004134 if (baserepr == NULL || ! HASTZINFO(self))
4135 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004136 return append_keyword_tzinfo(baserepr, self->tzinfo);
4137}
4138
Tim Petersa9bc1682003-01-11 03:39:11 +00004139static PyObject *
4140datetime_str(PyDateTime_DateTime *self)
4141{
4142 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4143}
Tim Peters2a799bf2002-12-16 20:18:38 +00004144
4145static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004146datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004147{
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00004148 int sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004149 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004150 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004151 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004152 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004153
Walter Dörwaldd0941302007-07-01 21:58:22 +00004154 if (!PyArg_ParseTupleAndKeywords(args, kw, "|C:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004155 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004156 if (us)
4157 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4158 GET_YEAR(self), GET_MONTH(self),
4159 GET_DAY(self), (int)sep,
4160 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4161 DATE_GET_SECOND(self), us);
4162 else
4163 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4164 GET_YEAR(self), GET_MONTH(self),
4165 GET_DAY(self), (int)sep,
4166 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4167 DATE_GET_SECOND(self));
4168
4169 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004170 return result;
4171
4172 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004173 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004174 (PyObject *)self) < 0) {
4175 Py_DECREF(result);
4176 return NULL;
4177 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004178 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004179 return result;
4180}
4181
Tim Petersa9bc1682003-01-11 03:39:11 +00004182static PyObject *
4183datetime_ctime(PyDateTime_DateTime *self)
4184{
4185 return format_ctime((PyDateTime_Date *)self,
4186 DATE_GET_HOUR(self),
4187 DATE_GET_MINUTE(self),
4188 DATE_GET_SECOND(self));
4189}
4190
Tim Peters2a799bf2002-12-16 20:18:38 +00004191/* Miscellaneous methods. */
4192
Tim Petersa9bc1682003-01-11 03:39:11 +00004193static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004194datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004195{
4196 int diff;
4197 naivety n1, n2;
4198 int offset1, offset2;
4199
4200 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004201 if (PyDate_Check(other)) {
4202 /* Prevent invocation of date_richcompare. We want to
4203 return NotImplemented here to give the other object
4204 a chance. But since DateTime is a subclass of
4205 Date, if the other object is a Date, it would
4206 compute an ordering based on the date part alone,
4207 and we don't want that. So force unequal or
4208 uncomparable here in that case. */
4209 if (op == Py_EQ)
4210 Py_RETURN_FALSE;
4211 if (op == Py_NE)
4212 Py_RETURN_TRUE;
4213 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004214 }
Guido van Rossum19960592006-08-24 17:29:38 +00004215 Py_INCREF(Py_NotImplemented);
4216 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004217 }
4218
Guido van Rossum19960592006-08-24 17:29:38 +00004219 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4220 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004221 return NULL;
4222 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4223 /* If they're both naive, or both aware and have the same offsets,
4224 * we get off cheap. Note that if they're both naive, offset1 ==
4225 * offset2 == 0 at this point.
4226 */
4227 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004228 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4229 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004230 _PyDateTime_DATETIME_DATASIZE);
4231 return diff_to_bool(diff, op);
4232 }
4233
4234 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4235 PyDateTime_Delta *delta;
4236
4237 assert(offset1 != offset2); /* else last "if" handled it */
4238 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4239 other);
4240 if (delta == NULL)
4241 return NULL;
4242 diff = GET_TD_DAYS(delta);
4243 if (diff == 0)
4244 diff = GET_TD_SECONDS(delta) |
4245 GET_TD_MICROSECONDS(delta);
4246 Py_DECREF(delta);
4247 return diff_to_bool(diff, op);
4248 }
4249
4250 assert(n1 != n2);
4251 PyErr_SetString(PyExc_TypeError,
4252 "can't compare offset-naive and "
4253 "offset-aware datetimes");
4254 return NULL;
4255}
4256
4257static long
4258datetime_hash(PyDateTime_DateTime *self)
4259{
4260 if (self->hashcode == -1) {
4261 naivety n;
4262 int offset;
4263 PyObject *temp;
4264
4265 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4266 &offset);
4267 assert(n != OFFSET_UNKNOWN);
4268 if (n == OFFSET_ERROR)
4269 return -1;
4270
4271 /* Reduce this to a hash of another object. */
Guido van Rossumfd53fd62007-08-24 04:05:13 +00004272 if (n == OFFSET_NAIVE) {
4273 self->hashcode = generic_hash(
4274 (unsigned char *)self->data, _PyDateTime_DATETIME_DATASIZE);
4275 return self->hashcode;
4276 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004277 else {
4278 int days;
4279 int seconds;
4280
4281 assert(n == OFFSET_AWARE);
4282 assert(HASTZINFO(self));
4283 days = ymd_to_ord(GET_YEAR(self),
4284 GET_MONTH(self),
4285 GET_DAY(self));
4286 seconds = DATE_GET_HOUR(self) * 3600 +
4287 (DATE_GET_MINUTE(self) - offset) * 60 +
4288 DATE_GET_SECOND(self);
4289 temp = new_delta(days,
4290 seconds,
4291 DATE_GET_MICROSECOND(self),
4292 1);
4293 }
4294 if (temp != NULL) {
4295 self->hashcode = PyObject_Hash(temp);
4296 Py_DECREF(temp);
4297 }
4298 }
4299 return self->hashcode;
4300}
Tim Peters2a799bf2002-12-16 20:18:38 +00004301
4302static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004303datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004304{
4305 PyObject *clone;
4306 PyObject *tuple;
4307 int y = GET_YEAR(self);
4308 int m = GET_MONTH(self);
4309 int d = GET_DAY(self);
4310 int hh = DATE_GET_HOUR(self);
4311 int mm = DATE_GET_MINUTE(self);
4312 int ss = DATE_GET_SECOND(self);
4313 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004314 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004315
4316 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004317 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004318 &y, &m, &d, &hh, &mm, &ss, &us,
4319 &tzinfo))
4320 return NULL;
4321 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4322 if (tuple == NULL)
4323 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00004324 clone = datetime_new(Py_TYPE(self), tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004325 Py_DECREF(tuple);
4326 return clone;
4327}
4328
4329static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004330datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004331{
Tim Peters52dcce22003-01-23 16:36:11 +00004332 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004333 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004334 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004335
Tim Peters80475bb2002-12-25 07:40:55 +00004336 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004337 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004338
Tim Peters52dcce22003-01-23 16:36:11 +00004339 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4340 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004341 return NULL;
4342
Tim Peters52dcce22003-01-23 16:36:11 +00004343 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4344 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004345
Tim Peters52dcce22003-01-23 16:36:11 +00004346 /* Conversion to self's own time zone is a NOP. */
4347 if (self->tzinfo == tzinfo) {
4348 Py_INCREF(self);
4349 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004350 }
Tim Peters521fc152002-12-31 17:36:56 +00004351
Tim Peters52dcce22003-01-23 16:36:11 +00004352 /* Convert self to UTC. */
4353 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4354 if (offset == -1 && PyErr_Occurred())
4355 return NULL;
4356 if (none)
4357 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004358
Tim Peters52dcce22003-01-23 16:36:11 +00004359 y = GET_YEAR(self);
4360 m = GET_MONTH(self);
4361 d = GET_DAY(self);
4362 hh = DATE_GET_HOUR(self);
4363 mm = DATE_GET_MINUTE(self);
4364 ss = DATE_GET_SECOND(self);
4365 us = DATE_GET_MICROSECOND(self);
4366
4367 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004368 if ((mm < 0 || mm >= 60) &&
4369 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004370 return NULL;
4371
4372 /* Attach new tzinfo and let fromutc() do the rest. */
4373 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4374 if (result != NULL) {
4375 PyObject *temp = result;
4376
4377 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4378 Py_DECREF(temp);
4379 }
Tim Petersadf64202003-01-04 06:03:15 +00004380 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004381
Tim Peters52dcce22003-01-23 16:36:11 +00004382NeedAware:
4383 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4384 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004385 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004386}
4387
4388static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004389datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004390{
4391 int dstflag = -1;
4392
Tim Petersa9bc1682003-01-11 03:39:11 +00004393 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004394 int none;
4395
4396 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4397 if (dstflag == -1 && PyErr_Occurred())
4398 return NULL;
4399
4400 if (none)
4401 dstflag = -1;
4402 else if (dstflag != 0)
4403 dstflag = 1;
4404
4405 }
4406 return build_struct_time(GET_YEAR(self),
4407 GET_MONTH(self),
4408 GET_DAY(self),
4409 DATE_GET_HOUR(self),
4410 DATE_GET_MINUTE(self),
4411 DATE_GET_SECOND(self),
4412 dstflag);
4413}
4414
4415static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004416datetime_getdate(PyDateTime_DateTime *self)
4417{
4418 return new_date(GET_YEAR(self),
4419 GET_MONTH(self),
4420 GET_DAY(self));
4421}
4422
4423static PyObject *
4424datetime_gettime(PyDateTime_DateTime *self)
4425{
4426 return new_time(DATE_GET_HOUR(self),
4427 DATE_GET_MINUTE(self),
4428 DATE_GET_SECOND(self),
4429 DATE_GET_MICROSECOND(self),
4430 Py_None);
4431}
4432
4433static PyObject *
4434datetime_gettimetz(PyDateTime_DateTime *self)
4435{
4436 return new_time(DATE_GET_HOUR(self),
4437 DATE_GET_MINUTE(self),
4438 DATE_GET_SECOND(self),
4439 DATE_GET_MICROSECOND(self),
4440 HASTZINFO(self) ? self->tzinfo : Py_None);
4441}
4442
4443static PyObject *
4444datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004445{
4446 int y = GET_YEAR(self);
4447 int m = GET_MONTH(self);
4448 int d = GET_DAY(self);
4449 int hh = DATE_GET_HOUR(self);
4450 int mm = DATE_GET_MINUTE(self);
4451 int ss = DATE_GET_SECOND(self);
4452 int us = 0; /* microseconds are ignored in a timetuple */
4453 int offset = 0;
4454
Tim Petersa9bc1682003-01-11 03:39:11 +00004455 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004456 int none;
4457
4458 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4459 if (offset == -1 && PyErr_Occurred())
4460 return NULL;
4461 }
4462 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4463 * 0 in a UTC timetuple regardless of what dst() says.
4464 */
4465 if (offset) {
4466 /* Subtract offset minutes & normalize. */
4467 int stat;
4468
4469 mm -= offset;
4470 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4471 if (stat < 0) {
4472 /* At the edges, it's possible we overflowed
4473 * beyond MINYEAR or MAXYEAR.
4474 */
4475 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4476 PyErr_Clear();
4477 else
4478 return NULL;
4479 }
4480 }
4481 return build_struct_time(y, m, d, hh, mm, ss, 0);
4482}
4483
Tim Peters371935f2003-02-01 01:52:50 +00004484/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004485
Tim Petersa9bc1682003-01-11 03:39:11 +00004486/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004487 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4488 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004489 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004490 */
4491static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004492datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004493{
4494 PyObject *basestate;
4495 PyObject *result = NULL;
4496
Christian Heimes72b710a2008-05-26 13:28:38 +00004497 basestate = PyBytes_FromStringAndSize((char *)self->data,
Guido van Rossum254348e2007-11-21 19:29:53 +00004498 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004499 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004500 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004501 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004502 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004503 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004504 Py_DECREF(basestate);
4505 }
4506 return result;
4507}
4508
4509static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004510datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004511{
Christian Heimes90aa7642007-12-19 02:45:37 +00004512 return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004513}
4514
Tim Petersa9bc1682003-01-11 03:39:11 +00004515static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004516
Tim Peters2a799bf2002-12-16 20:18:38 +00004517 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004518
Tim Petersa9bc1682003-01-11 03:39:11 +00004519 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004520 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004521 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004522
Tim Petersa9bc1682003-01-11 03:39:11 +00004523 {"utcnow", (PyCFunction)datetime_utcnow,
4524 METH_NOARGS | METH_CLASS,
4525 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4526
4527 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004528 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004529 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004530
Tim Petersa9bc1682003-01-11 03:39:11 +00004531 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4532 METH_VARARGS | METH_CLASS,
4533 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4534 "(like time.time()).")},
4535
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004536 {"strptime", (PyCFunction)datetime_strptime,
4537 METH_VARARGS | METH_CLASS,
4538 PyDoc_STR("string, format -> new datetime parsed from a string "
4539 "(like time.strptime()).")},
4540
Tim Petersa9bc1682003-01-11 03:39:11 +00004541 {"combine", (PyCFunction)datetime_combine,
4542 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4543 PyDoc_STR("date, time -> datetime with same date and time fields")},
4544
Tim Peters2a799bf2002-12-16 20:18:38 +00004545 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004546
Tim Petersa9bc1682003-01-11 03:39:11 +00004547 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4548 PyDoc_STR("Return date object with same year, month and day.")},
4549
4550 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4551 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4552
4553 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4554 PyDoc_STR("Return time object with same time and tzinfo.")},
4555
4556 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4557 PyDoc_STR("Return ctime() style string.")},
4558
4559 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004560 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4561
Tim Petersa9bc1682003-01-11 03:39:11 +00004562 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004563 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4564
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004565 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004566 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4567 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4568 "sep is used to separate the year from the time, and "
4569 "defaults to 'T'.")},
4570
Tim Petersa9bc1682003-01-11 03:39:11 +00004571 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004572 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4573
Tim Petersa9bc1682003-01-11 03:39:11 +00004574 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004575 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4576
Tim Petersa9bc1682003-01-11 03:39:11 +00004577 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004578 PyDoc_STR("Return self.tzinfo.dst(self).")},
4579
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004580 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004581 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004582
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004583 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004584 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4585
Guido van Rossum177e41a2003-01-30 22:06:23 +00004586 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4587 PyDoc_STR("__reduce__() -> (cls, state)")},
4588
Tim Peters2a799bf2002-12-16 20:18:38 +00004589 {NULL, NULL}
4590};
4591
Tim Petersa9bc1682003-01-11 03:39:11 +00004592static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004593PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4594\n\
4595The year, month and day arguments are required. tzinfo may be None, or an\n\
4596instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004597
Tim Petersa9bc1682003-01-11 03:39:11 +00004598static PyNumberMethods datetime_as_number = {
4599 datetime_add, /* nb_add */
4600 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004601 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004602 0, /* nb_remainder */
4603 0, /* nb_divmod */
4604 0, /* nb_power */
4605 0, /* nb_negative */
4606 0, /* nb_positive */
4607 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004608 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004609};
4610
Neal Norwitz227b5332006-03-22 09:28:35 +00004611static PyTypeObject PyDateTime_DateTimeType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004612 PyVarObject_HEAD_INIT(NULL, 0)
Tim Peters0bf60bd2003-01-08 20:40:01 +00004613 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004614 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004615 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004616 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004617 0, /* tp_print */
4618 0, /* tp_getattr */
4619 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00004620 0, /* tp_reserved */
Tim Petersa9bc1682003-01-11 03:39:11 +00004621 (reprfunc)datetime_repr, /* tp_repr */
4622 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004623 0, /* tp_as_sequence */
4624 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004625 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004626 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004627 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004628 PyObject_GenericGetAttr, /* tp_getattro */
4629 0, /* tp_setattro */
4630 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004631 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004632 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004633 0, /* tp_traverse */
4634 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004635 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004636 0, /* tp_weaklistoffset */
4637 0, /* tp_iter */
4638 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004639 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004640 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004641 datetime_getset, /* tp_getset */
4642 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004643 0, /* tp_dict */
4644 0, /* tp_descr_get */
4645 0, /* tp_descr_set */
4646 0, /* tp_dictoffset */
4647 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004648 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004649 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004650 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004651};
4652
4653/* ---------------------------------------------------------------------------
4654 * Module methods and initialization.
4655 */
4656
4657static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004658 {NULL, NULL}
4659};
4660
Tim Peters9ddf40b2004-06-20 22:41:32 +00004661/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4662 * datetime.h.
4663 */
4664static PyDateTime_CAPI CAPI = {
4665 &PyDateTime_DateType,
4666 &PyDateTime_DateTimeType,
4667 &PyDateTime_TimeType,
4668 &PyDateTime_DeltaType,
4669 &PyDateTime_TZInfoType,
4670 new_date_ex,
4671 new_datetime_ex,
4672 new_time_ex,
4673 new_delta_ex,
4674 datetime_fromtimestamp,
4675 date_fromtimestamp
4676};
4677
4678
Martin v. Löwis1a214512008-06-11 05:26:20 +00004679
4680static struct PyModuleDef datetimemodule = {
4681 PyModuleDef_HEAD_INIT,
4682 "datetime",
4683 "Fast implementation of the datetime type.",
4684 -1,
4685 module_methods,
4686 NULL,
4687 NULL,
4688 NULL,
4689 NULL
4690};
4691
Tim Peters2a799bf2002-12-16 20:18:38 +00004692PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004693PyInit_datetime(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00004694{
4695 PyObject *m; /* a module object */
4696 PyObject *d; /* its dict */
4697 PyObject *x;
4698
Martin v. Löwis1a214512008-06-11 05:26:20 +00004699 m = PyModule_Create(&datetimemodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004700 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004701 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004702
4703 if (PyType_Ready(&PyDateTime_DateType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004704 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004705 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004706 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004707 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004708 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004709 if (PyType_Ready(&PyDateTime_TimeType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004710 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004711 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004712 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004713
Tim Peters2a799bf2002-12-16 20:18:38 +00004714 /* timedelta values */
4715 d = PyDateTime_DeltaType.tp_dict;
4716
Tim Peters2a799bf2002-12-16 20:18:38 +00004717 x = new_delta(0, 0, 1, 0);
4718 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004719 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004720 Py_DECREF(x);
4721
4722 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4723 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004724 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004725 Py_DECREF(x);
4726
4727 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4728 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004729 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004730 Py_DECREF(x);
4731
4732 /* date values */
4733 d = PyDateTime_DateType.tp_dict;
4734
4735 x = new_date(1, 1, 1);
4736 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004737 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004738 Py_DECREF(x);
4739
4740 x = new_date(MAXYEAR, 12, 31);
4741 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004742 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004743 Py_DECREF(x);
4744
4745 x = new_delta(1, 0, 0, 0);
4746 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004747 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004748 Py_DECREF(x);
4749
Tim Peters37f39822003-01-10 03:49:02 +00004750 /* time values */
4751 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004752
Tim Peters37f39822003-01-10 03:49:02 +00004753 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004754 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004755 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004756 Py_DECREF(x);
4757
Tim Peters37f39822003-01-10 03:49:02 +00004758 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004759 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004760 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004761 Py_DECREF(x);
4762
4763 x = new_delta(0, 0, 1, 0);
4764 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004765 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004766 Py_DECREF(x);
4767
Tim Petersa9bc1682003-01-11 03:39:11 +00004768 /* datetime values */
4769 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004770
Tim Petersa9bc1682003-01-11 03:39:11 +00004771 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004772 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004773 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004774 Py_DECREF(x);
4775
Tim Petersa9bc1682003-01-11 03:39:11 +00004776 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004777 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004778 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004779 Py_DECREF(x);
4780
4781 x = new_delta(0, 0, 1, 0);
4782 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004783 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004784 Py_DECREF(x);
4785
Tim Peters2a799bf2002-12-16 20:18:38 +00004786 /* module initialization */
4787 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4788 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4789
4790 Py_INCREF(&PyDateTime_DateType);
4791 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4792
Tim Petersa9bc1682003-01-11 03:39:11 +00004793 Py_INCREF(&PyDateTime_DateTimeType);
4794 PyModule_AddObject(m, "datetime",
4795 (PyObject *)&PyDateTime_DateTimeType);
4796
4797 Py_INCREF(&PyDateTime_TimeType);
4798 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4799
Tim Peters2a799bf2002-12-16 20:18:38 +00004800 Py_INCREF(&PyDateTime_DeltaType);
4801 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4802
Tim Peters2a799bf2002-12-16 20:18:38 +00004803 Py_INCREF(&PyDateTime_TZInfoType);
4804 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4805
Benjamin Petersonb173f782009-05-05 22:31:58 +00004806 x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
4807 if (x == NULL)
4808 return NULL;
4809 PyModule_AddObject(m, "datetime_CAPI", x);
Tim Peters9ddf40b2004-06-20 22:41:32 +00004810
Tim Peters2a799bf2002-12-16 20:18:38 +00004811 /* A 4-year cycle has an extra leap day over what we'd get from
4812 * pasting together 4 single years.
4813 */
4814 assert(DI4Y == 4 * 365 + 1);
4815 assert(DI4Y == days_before_year(4+1));
4816
4817 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4818 * get from pasting together 4 100-year cycles.
4819 */
4820 assert(DI400Y == 4 * DI100Y + 1);
4821 assert(DI400Y == days_before_year(400+1));
4822
4823 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4824 * pasting together 25 4-year cycles.
4825 */
4826 assert(DI100Y == 25 * DI4Y - 1);
4827 assert(DI100Y == days_before_year(100+1));
4828
Christian Heimes217cfd12007-12-02 14:31:20 +00004829 us_per_us = PyLong_FromLong(1);
4830 us_per_ms = PyLong_FromLong(1000);
4831 us_per_second = PyLong_FromLong(1000000);
4832 us_per_minute = PyLong_FromLong(60000000);
4833 seconds_per_day = PyLong_FromLong(24 * 3600);
Tim Peters2a799bf2002-12-16 20:18:38 +00004834 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4835 us_per_minute == NULL || seconds_per_day == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004836 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00004837
4838 /* The rest are too big for 32-bit ints, but even
4839 * us_per_week fits in 40 bits, so doubles should be exact.
4840 */
4841 us_per_hour = PyLong_FromDouble(3600000000.0);
4842 us_per_day = PyLong_FromDouble(86400000000.0);
4843 us_per_week = PyLong_FromDouble(604800000000.0);
4844 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00004845 return NULL;
4846 return m;
Tim Peters2a799bf2002-12-16 20:18:38 +00004847}
Tim Petersf3615152003-01-01 21:51:37 +00004848
4849/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004850Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004851 x.n = x stripped of its timezone -- its naive time.
4852 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4853 return None
4854 x.d = x.dst(), and assuming that doesn't raise an exception or
4855 return None
4856 x.s = x's standard offset, x.o - x.d
4857
4858Now some derived rules, where k is a duration (timedelta).
4859
48601. x.o = x.s + x.d
4861 This follows from the definition of x.s.
4862
Tim Petersc5dc4da2003-01-02 17:55:03 +000048632. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004864 This is actually a requirement, an assumption we need to make about
4865 sane tzinfo classes.
4866
48673. The naive UTC time corresponding to x is x.n - x.o.
4868 This is again a requirement for a sane tzinfo class.
4869
48704. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004871 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004872
Tim Petersc5dc4da2003-01-02 17:55:03 +000048735. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004874 Again follows from how arithmetic is defined.
4875
Tim Peters8bb5ad22003-01-24 02:44:45 +00004876Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004877(meaning that the various tzinfo methods exist, and don't blow up or return
4878None when called).
4879
Tim Petersa9bc1682003-01-11 03:39:11 +00004880The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004881x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004882
4883By #3, we want
4884
Tim Peters8bb5ad22003-01-24 02:44:45 +00004885 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004886
4887The algorithm starts by attaching tz to x.n, and calling that y. So
4888x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4889becomes true; in effect, we want to solve [2] for k:
4890
Tim Peters8bb5ad22003-01-24 02:44:45 +00004891 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004892
4893By #1, this is the same as
4894
Tim Peters8bb5ad22003-01-24 02:44:45 +00004895 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004896
4897By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4898Substituting that into [3],
4899
Tim Peters8bb5ad22003-01-24 02:44:45 +00004900 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4901 k - (y+k).s - (y+k).d = 0; rearranging,
4902 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4903 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004904
Tim Peters8bb5ad22003-01-24 02:44:45 +00004905On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4906approximate k by ignoring the (y+k).d term at first. Note that k can't be
4907very large, since all offset-returning methods return a duration of magnitude
4908less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4909be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004910
4911In any case, the new value is
4912
Tim Peters8bb5ad22003-01-24 02:44:45 +00004913 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004914
Tim Peters8bb5ad22003-01-24 02:44:45 +00004915It's helpful to step back at look at [4] from a higher level: it's simply
4916mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004917
4918At this point, if
4919
Tim Peters8bb5ad22003-01-24 02:44:45 +00004920 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004921
4922we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004923at the start of daylight time. Picture US Eastern for concreteness. The wall
4924time 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 +00004925sense then. The docs ask that an Eastern tzinfo class consider such a time to
4926be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4927on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004928the only spelling that makes sense on the local wall clock.
4929
Tim Petersc5dc4da2003-01-02 17:55:03 +00004930In fact, if [5] holds at this point, we do have the standard-time spelling,
4931but that takes a bit of proof. We first prove a stronger result. What's the
4932difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004933
Tim Peters8bb5ad22003-01-24 02:44:45 +00004934 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004935
Tim Petersc5dc4da2003-01-02 17:55:03 +00004936Now
4937 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004938 (y + y.s).n = by #5
4939 y.n + y.s = since y.n = x.n
4940 x.n + y.s = since z and y are have the same tzinfo member,
4941 y.s = z.s by #2
4942 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004943
Tim Petersc5dc4da2003-01-02 17:55:03 +00004944Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004945
Tim Petersc5dc4da2003-01-02 17:55:03 +00004946 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004947 x.n - ((x.n + z.s) - z.o) = expanding
4948 x.n - x.n - z.s + z.o = cancelling
4949 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004950 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004951
Tim Petersc5dc4da2003-01-02 17:55:03 +00004952So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004953
Tim Petersc5dc4da2003-01-02 17:55:03 +00004954If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004955spelling we wanted in the endcase described above. We're done. Contrarily,
4956if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004957
Tim Petersc5dc4da2003-01-02 17:55:03 +00004958If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4959add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004960local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004961
Tim Petersc5dc4da2003-01-02 17:55:03 +00004962Let
Tim Petersf3615152003-01-01 21:51:37 +00004963
Tim Peters4fede1a2003-01-04 00:26:59 +00004964 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004965
Tim Peters4fede1a2003-01-04 00:26:59 +00004966and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004967
Tim Peters8bb5ad22003-01-24 02:44:45 +00004968 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004969
Tim Peters8bb5ad22003-01-24 02:44:45 +00004970If so, we're done. If not, the tzinfo class is insane, according to the
4971assumptions we've made. This also requires a bit of proof. As before, let's
4972compute the difference between the LHS and RHS of [8] (and skipping some of
4973the justifications for the kinds of substitutions we've done several times
4974already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004975
Tim Peters8bb5ad22003-01-24 02:44:45 +00004976 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4977 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4978 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4979 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4980 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004981 - z.o + z'.o = #1 twice
4982 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4983 z'.d - z.d
4984
4985So 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 +00004986we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4987return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004988
Tim Peters8bb5ad22003-01-24 02:44:45 +00004989How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4990a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4991would have to change the result dst() returns: we start in DST, and moving
4992a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004993
Tim Peters8bb5ad22003-01-24 02:44:45 +00004994There isn't a sane case where this can happen. The closest it gets is at
4995the end of DST, where there's an hour in UTC with no spelling in a hybrid
4996tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4997that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4998UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4999time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
5000clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5001standard time. Since that's what the local clock *does*, we want to map both
5002UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00005003in local time, but so it goes -- it's the way the local clock works.
5004
Tim Peters8bb5ad22003-01-24 02:44:45 +00005005When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5006so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5007z' = 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 +00005008(correctly) concludes that z' is not UTC-equivalent to x.
5009
5010Because we know z.d said z was in daylight time (else [5] would have held and
5011we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00005012and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00005013return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5014but the reasoning doesn't depend on the example -- it depends on there being
5015two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00005016z' must be in standard time, and is the spelling we want in this case.
5017
5018Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5019concerned (because it takes z' as being in standard time rather than the
5020daylight time we intend here), but returning it gives the real-life "local
5021clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5022tz.
5023
5024When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5025the 1:MM standard time spelling we want.
5026
5027So how can this break? One of the assumptions must be violated. Two
5028possibilities:
5029
50301) [2] effectively says that y.s is invariant across all y belong to a given
5031 time zone. This isn't true if, for political reasons or continental drift,
5032 a region decides to change its base offset from UTC.
5033
50342) There may be versions of "double daylight" time where the tail end of
5035 the analysis gives up a step too early. I haven't thought about that
5036 enough to say.
5037
5038In any case, it's clear that the default fromutc() is strong enough to handle
5039"almost all" time zones: so long as the standard offset is invariant, it
5040doesn't matter if daylight time transition points change from year to year, or
5041if daylight time is skipped in some years; it doesn't matter how large or
5042small dst() may get within its bounds; and it doesn't even matter if some
5043perverse time zone returns a negative dst()). So a breaking case must be
5044pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00005045--------------------------------------------------------------------------- */