blob: 9872685fdcac0040479215ca3e39014bedc557d8 [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 */
16#define Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000017#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000018#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000019
20/* We require that C int be at least 32 bits, and use int virtually
21 * everywhere. In just a few cases we use a temp long, where a Python
22 * API returns a C long. In such cases, we have to ensure that the
23 * final result fits in a C int (this can be an issue on 64-bit boxes).
24 */
25#if SIZEOF_INT < 4
26# error "datetime.c requires that C int have at least 32 bits"
27#endif
28
29#define MINYEAR 1
30#define MAXYEAR 9999
31
32/* Nine decimal digits is easy to communicate, and leaves enough room
33 * so that two delta days can be added w/o fear of overflowing a signed
34 * 32-bit int, and with plenty of room left over to absorb any possible
35 * carries from adding seconds.
36 */
37#define MAX_DELTA_DAYS 999999999
38
39/* Rename the long macros in datetime.h to more reasonable short names. */
40#define GET_YEAR PyDateTime_GET_YEAR
41#define GET_MONTH PyDateTime_GET_MONTH
42#define GET_DAY PyDateTime_GET_DAY
43#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
44#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
45#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
46#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
47
48/* Date accessors for date and datetime. */
49#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
50 ((o)->data[1] = ((v) & 0x00ff)))
51#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
52#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
53
54/* Date/Time accessors for datetime. */
55#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
56#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
57#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
58#define DATE_SET_MICROSECOND(o, v) \
59 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
60 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
61 ((o)->data[9] = ((v) & 0x0000ff)))
62
63/* Time accessors for time. */
64#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
65#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
66#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
67#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
68#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
69#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
70#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
71#define TIME_SET_MICROSECOND(o, v) \
72 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
73 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
74 ((o)->data[5] = ((v) & 0x0000ff)))
75
76/* Delta accessors for timedelta. */
77#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
78#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
79#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
80
81#define SET_TD_DAYS(o, v) ((o)->days = (v))
82#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
83#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
84
Tim Petersa032d2e2003-01-11 00:15:54 +000085/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
86 * p->hastzinfo.
87 */
88#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
89
Tim Peters3f606292004-03-21 23:38:41 +000090/* M is a char or int claiming to be a valid month. The macro is equivalent
91 * to the two-sided Python test
92 * 1 <= M <= 12
93 */
94#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
95
Tim Peters2a799bf2002-12-16 20:18:38 +000096/* Forward declarations. */
97static PyTypeObject PyDateTime_DateType;
98static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +000099static PyTypeObject PyDateTime_DeltaType;
100static PyTypeObject PyDateTime_TimeType;
101static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000102
103/* ---------------------------------------------------------------------------
104 * Math utilities.
105 */
106
107/* k = i+j overflows iff k differs in sign from both inputs,
108 * iff k^i has sign bit set and k^j has sign bit set,
109 * iff (k^i)&(k^j) has sign bit set.
110 */
111#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
112 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
113
114/* Compute Python divmod(x, y), returning the quotient and storing the
115 * remainder into *r. The quotient is the floor of x/y, and that's
116 * the real point of this. C will probably truncate instead (C99
117 * requires truncation; C89 left it implementation-defined).
118 * Simplification: we *require* that y > 0 here. That's appropriate
119 * for all the uses made of it. This simplifies the code and makes
120 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
121 * overflow case).
122 */
123static int
124divmod(int x, int y, int *r)
125{
126 int quo;
127
128 assert(y > 0);
129 quo = x / y;
130 *r = x - quo * y;
131 if (*r < 0) {
132 --quo;
133 *r += y;
134 }
135 assert(0 <= *r && *r < y);
136 return quo;
137}
138
Tim Peters5d644dd2003-01-02 16:32:54 +0000139/* Round a double to the nearest long. |x| must be small enough to fit
140 * in a C long; this is not checked.
141 */
142static long
143round_to_long(double x)
144{
145 if (x >= 0.0)
146 x = floor(x + 0.5);
147 else
148 x = ceil(x - 0.5);
149 return (long)x;
150}
151
Tim Peters2a799bf2002-12-16 20:18:38 +0000152/* ---------------------------------------------------------------------------
153 * General calendrical helper functions
154 */
155
156/* For each month ordinal in 1..12, the number of days in that month,
157 * and the number of days before that month in the same year. These
158 * are correct for non-leap years only.
159 */
160static int _days_in_month[] = {
161 0, /* unused; this vector uses 1-based indexing */
162 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
163};
164
165static int _days_before_month[] = {
166 0, /* unused; this vector uses 1-based indexing */
167 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
168};
169
170/* year -> 1 if leap year, else 0. */
171static int
172is_leap(int year)
173{
174 /* Cast year to unsigned. The result is the same either way, but
175 * C can generate faster code for unsigned mod than for signed
176 * mod (especially for % 4 -- a good compiler should just grab
177 * the last 2 bits when the LHS is unsigned).
178 */
179 const unsigned int ayear = (unsigned int)year;
180 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
181}
182
183/* year, month -> number of days in that month in that year */
184static int
185days_in_month(int year, int month)
186{
187 assert(month >= 1);
188 assert(month <= 12);
189 if (month == 2 && is_leap(year))
190 return 29;
191 else
192 return _days_in_month[month];
193}
194
195/* year, month -> number of days in year preceeding first day of month */
196static int
197days_before_month(int year, int month)
198{
199 int days;
200
201 assert(month >= 1);
202 assert(month <= 12);
203 days = _days_before_month[month];
204 if (month > 2 && is_leap(year))
205 ++days;
206 return days;
207}
208
209/* year -> number of days before January 1st of year. Remember that we
210 * start with year 1, so days_before_year(1) == 0.
211 */
212static int
213days_before_year(int year)
214{
215 int y = year - 1;
216 /* This is incorrect if year <= 0; we really want the floor
217 * here. But so long as MINYEAR is 1, the smallest year this
218 * can see is 0 (this can happen in some normalization endcases),
219 * so we'll just special-case that.
220 */
221 assert (year >= 0);
222 if (y >= 0)
223 return y*365 + y/4 - y/100 + y/400;
224 else {
225 assert(y == -1);
226 return -366;
227 }
228}
229
230/* Number of days in 4, 100, and 400 year cycles. That these have
231 * the correct values is asserted in the module init function.
232 */
233#define DI4Y 1461 /* days_before_year(5); days in 4 years */
234#define DI100Y 36524 /* days_before_year(101); days in 100 years */
235#define DI400Y 146097 /* days_before_year(401); days in 400 years */
236
237/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
238static void
239ord_to_ymd(int ordinal, int *year, int *month, int *day)
240{
241 int n, n1, n4, n100, n400, leapyear, preceding;
242
243 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
244 * leap years repeats exactly every 400 years. The basic strategy is
245 * to find the closest 400-year boundary at or before ordinal, then
246 * work with the offset from that boundary to ordinal. Life is much
247 * clearer if we subtract 1 from ordinal first -- then the values
248 * of ordinal at 400-year boundaries are exactly those divisible
249 * by DI400Y:
250 *
251 * D M Y n n-1
252 * -- --- ---- ---------- ----------------
253 * 31 Dec -400 -DI400Y -DI400Y -1
254 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
255 * ...
256 * 30 Dec 000 -1 -2
257 * 31 Dec 000 0 -1
258 * 1 Jan 001 1 0 400-year boundary
259 * 2 Jan 001 2 1
260 * 3 Jan 001 3 2
261 * ...
262 * 31 Dec 400 DI400Y DI400Y -1
263 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
264 */
265 assert(ordinal >= 1);
266 --ordinal;
267 n400 = ordinal / DI400Y;
268 n = ordinal % DI400Y;
269 *year = n400 * 400 + 1;
270
271 /* Now n is the (non-negative) offset, in days, from January 1 of
272 * year, to the desired date. Now compute how many 100-year cycles
273 * precede n.
274 * Note that it's possible for n100 to equal 4! In that case 4 full
275 * 100-year cycles precede the desired day, which implies the
276 * desired day is December 31 at the end of a 400-year cycle.
277 */
278 n100 = n / DI100Y;
279 n = n % DI100Y;
280
281 /* Now compute how many 4-year cycles precede it. */
282 n4 = n / DI4Y;
283 n = n % DI4Y;
284
285 /* And now how many single years. Again n1 can be 4, and again
286 * meaning that the desired day is December 31 at the end of the
287 * 4-year cycle.
288 */
289 n1 = n / 365;
290 n = n % 365;
291
292 *year += n100 * 100 + n4 * 4 + n1;
293 if (n1 == 4 || n100 == 4) {
294 assert(n == 0);
295 *year -= 1;
296 *month = 12;
297 *day = 31;
298 return;
299 }
300
301 /* Now the year is correct, and n is the offset from January 1. We
302 * find the month via an estimate that's either exact or one too
303 * large.
304 */
305 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
306 assert(leapyear == is_leap(*year));
307 *month = (n + 50) >> 5;
308 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
309 if (preceding > n) {
310 /* estimate is too large */
311 *month -= 1;
312 preceding -= days_in_month(*year, *month);
313 }
314 n -= preceding;
315 assert(0 <= n);
316 assert(n < days_in_month(*year, *month));
317
318 *day = n + 1;
319}
320
321/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
322static int
323ymd_to_ord(int year, int month, int day)
324{
325 return days_before_year(year) + days_before_month(year, month) + day;
326}
327
328/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
329static int
330weekday(int year, int month, int day)
331{
332 return (ymd_to_ord(year, month, day) + 6) % 7;
333}
334
335/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
336 * first calendar week containing a Thursday.
337 */
338static int
339iso_week1_monday(int year)
340{
341 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
342 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
343 int first_weekday = (first_day + 6) % 7;
344 /* ordinal of closest Monday at or before 1/1 */
345 int week1_monday = first_day - first_weekday;
346
347 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
348 week1_monday += 7;
349 return week1_monday;
350}
351
352/* ---------------------------------------------------------------------------
353 * Range checkers.
354 */
355
356/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
357 * If not, raise OverflowError and return -1.
358 */
359static int
360check_delta_day_range(int days)
361{
362 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
363 return 0;
364 PyErr_Format(PyExc_OverflowError,
365 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000366 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000367 return -1;
368}
369
370/* Check that date arguments are in range. Return 0 if they are. If they
371 * aren't, raise ValueError and return -1.
372 */
373static int
374check_date_args(int year, int month, int day)
375{
376
377 if (year < MINYEAR || year > MAXYEAR) {
378 PyErr_SetString(PyExc_ValueError,
379 "year is out of range");
380 return -1;
381 }
382 if (month < 1 || month > 12) {
383 PyErr_SetString(PyExc_ValueError,
384 "month must be in 1..12");
385 return -1;
386 }
387 if (day < 1 || day > days_in_month(year, month)) {
388 PyErr_SetString(PyExc_ValueError,
389 "day is out of range for month");
390 return -1;
391 }
392 return 0;
393}
394
395/* Check that time arguments are in range. Return 0 if they are. If they
396 * aren't, raise ValueError and return -1.
397 */
398static int
399check_time_args(int h, int m, int s, int us)
400{
401 if (h < 0 || h > 23) {
402 PyErr_SetString(PyExc_ValueError,
403 "hour must be in 0..23");
404 return -1;
405 }
406 if (m < 0 || m > 59) {
407 PyErr_SetString(PyExc_ValueError,
408 "minute must be in 0..59");
409 return -1;
410 }
411 if (s < 0 || s > 59) {
412 PyErr_SetString(PyExc_ValueError,
413 "second must be in 0..59");
414 return -1;
415 }
416 if (us < 0 || us > 999999) {
417 PyErr_SetString(PyExc_ValueError,
418 "microsecond must be in 0..999999");
419 return -1;
420 }
421 return 0;
422}
423
424/* ---------------------------------------------------------------------------
425 * Normalization utilities.
426 */
427
428/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
429 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
430 * at least factor, enough of *lo is converted into "hi" units so that
431 * 0 <= *lo < factor. The input values must be such that int overflow
432 * is impossible.
433 */
434static void
435normalize_pair(int *hi, int *lo, int factor)
436{
437 assert(factor > 0);
438 assert(lo != hi);
439 if (*lo < 0 || *lo >= factor) {
440 const int num_hi = divmod(*lo, factor, lo);
441 const int new_hi = *hi + num_hi;
442 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
443 *hi = new_hi;
444 }
445 assert(0 <= *lo && *lo < factor);
446}
447
448/* Fiddle days (d), seconds (s), and microseconds (us) so that
449 * 0 <= *s < 24*3600
450 * 0 <= *us < 1000000
451 * The input values must be such that the internals don't overflow.
452 * The way this routine is used, we don't get close.
453 */
454static void
455normalize_d_s_us(int *d, int *s, int *us)
456{
457 if (*us < 0 || *us >= 1000000) {
458 normalize_pair(s, us, 1000000);
459 /* |s| can't be bigger than about
460 * |original s| + |original us|/1000000 now.
461 */
462
463 }
464 if (*s < 0 || *s >= 24*3600) {
465 normalize_pair(d, s, 24*3600);
466 /* |d| can't be bigger than about
467 * |original d| +
468 * (|original s| + |original us|/1000000) / (24*3600) now.
469 */
470 }
471 assert(0 <= *s && *s < 24*3600);
472 assert(0 <= *us && *us < 1000000);
473}
474
475/* Fiddle years (y), months (m), and days (d) so that
476 * 1 <= *m <= 12
477 * 1 <= *d <= days_in_month(*y, *m)
478 * The input values must be such that the internals don't overflow.
479 * The way this routine is used, we don't get close.
480 */
481static void
482normalize_y_m_d(int *y, int *m, int *d)
483{
484 int dim; /* # of days in month */
485
486 /* This gets muddy: the proper range for day can't be determined
487 * without knowing the correct month and year, but if day is, e.g.,
488 * plus or minus a million, the current month and year values make
489 * no sense (and may also be out of bounds themselves).
490 * Saying 12 months == 1 year should be non-controversial.
491 */
492 if (*m < 1 || *m > 12) {
493 --*m;
494 normalize_pair(y, m, 12);
495 ++*m;
496 /* |y| can't be bigger than about
497 * |original y| + |original m|/12 now.
498 */
499 }
500 assert(1 <= *m && *m <= 12);
501
502 /* Now only day can be out of bounds (year may also be out of bounds
503 * for a datetime object, but we don't care about that here).
504 * If day is out of bounds, what to do is arguable, but at least the
505 * method here is principled and explainable.
506 */
507 dim = days_in_month(*y, *m);
508 if (*d < 1 || *d > dim) {
509 /* Move day-1 days from the first of the month. First try to
510 * get off cheap if we're only one day out of range
511 * (adjustments for timezone alone can't be worse than that).
512 */
513 if (*d == 0) {
514 --*m;
515 if (*m > 0)
516 *d = days_in_month(*y, *m);
517 else {
518 --*y;
519 *m = 12;
520 *d = 31;
521 }
522 }
523 else if (*d == dim + 1) {
524 /* move forward a day */
525 ++*m;
526 *d = 1;
527 if (*m > 12) {
528 *m = 1;
529 ++*y;
530 }
531 }
532 else {
533 int ordinal = ymd_to_ord(*y, *m, 1) +
534 *d - 1;
535 ord_to_ymd(ordinal, y, m, d);
536 }
537 }
538 assert(*m > 0);
539 assert(*d > 0);
540}
541
542/* Fiddle out-of-bounds months and days so that the result makes some kind
543 * of sense. The parameters are both inputs and outputs. Returns < 0 on
544 * failure, where failure means the adjusted year is out of bounds.
545 */
546static int
547normalize_date(int *year, int *month, int *day)
548{
549 int result;
550
551 normalize_y_m_d(year, month, day);
552 if (MINYEAR <= *year && *year <= MAXYEAR)
553 result = 0;
554 else {
555 PyErr_SetString(PyExc_OverflowError,
556 "date value out of range");
557 result = -1;
558 }
559 return result;
560}
561
562/* Force all the datetime fields into range. The parameters are both
563 * inputs and outputs. Returns < 0 on error.
564 */
565static int
566normalize_datetime(int *year, int *month, int *day,
567 int *hour, int *minute, int *second,
568 int *microsecond)
569{
570 normalize_pair(second, microsecond, 1000000);
571 normalize_pair(minute, second, 60);
572 normalize_pair(hour, minute, 60);
573 normalize_pair(day, hour, 24);
574 return normalize_date(year, month, day);
575}
576
577/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000578 * Basic object allocation: tp_alloc implementations. These allocate
579 * Python objects of the right size and type, and do the Python object-
580 * initialization bit. If there's not enough memory, they return NULL after
581 * setting MemoryError. All data members remain uninitialized trash.
582 *
583 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000584 * member is needed. This is ugly, imprecise, and possibly insecure.
585 * tp_basicsize for the time and datetime types is set to the size of the
586 * struct that has room for the tzinfo member, so subclasses in Python will
587 * allocate enough space for a tzinfo member whether or not one is actually
588 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
589 * part is that PyType_GenericAlloc() (which subclasses in Python end up
590 * using) just happens today to effectively ignore the nitems argument
591 * when tp_itemsize is 0, which it is for these type objects. If that
592 * changes, perhaps the callers of tp_alloc slots in this file should
593 * be changed to force a 0 nitems argument unless the type being allocated
594 * is a base type implemented in this file (so that tp_alloc is time_alloc
595 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000596 */
597
598static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000599time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000600{
601 PyObject *self;
602
603 self = (PyObject *)
604 PyObject_MALLOC(aware ?
605 sizeof(PyDateTime_Time) :
606 sizeof(_PyDateTime_BaseTime));
607 if (self == NULL)
608 return (PyObject *)PyErr_NoMemory();
609 PyObject_INIT(self, type);
610 return self;
611}
612
613static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000614datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000615{
616 PyObject *self;
617
618 self = (PyObject *)
619 PyObject_MALLOC(aware ?
620 sizeof(PyDateTime_DateTime) :
621 sizeof(_PyDateTime_BaseDateTime));
622 if (self == NULL)
623 return (PyObject *)PyErr_NoMemory();
624 PyObject_INIT(self, type);
625 return self;
626}
627
628/* ---------------------------------------------------------------------------
629 * Helpers for setting object fields. These work on pointers to the
630 * appropriate base class.
631 */
632
633/* For date and datetime. */
634static void
635set_date_fields(PyDateTime_Date *self, int y, int m, int d)
636{
637 self->hashcode = -1;
638 SET_YEAR(self, y);
639 SET_MONTH(self, m);
640 SET_DAY(self, d);
641}
642
643/* ---------------------------------------------------------------------------
644 * Create various objects, mostly without range checking.
645 */
646
647/* Create a date instance with no range checking. */
648static PyObject *
649new_date_ex(int year, int month, int day, PyTypeObject *type)
650{
651 PyDateTime_Date *self;
652
653 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
654 if (self != NULL)
655 set_date_fields(self, year, month, day);
656 return (PyObject *) self;
657}
658
659#define new_date(year, month, day) \
660 new_date_ex(year, month, day, &PyDateTime_DateType)
661
662/* Create a datetime instance with no range checking. */
663static PyObject *
664new_datetime_ex(int year, int month, int day, int hour, int minute,
665 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
666{
667 PyDateTime_DateTime *self;
668 char aware = tzinfo != Py_None;
669
670 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
671 if (self != NULL) {
672 self->hastzinfo = aware;
673 set_date_fields((PyDateTime_Date *)self, year, month, day);
674 DATE_SET_HOUR(self, hour);
675 DATE_SET_MINUTE(self, minute);
676 DATE_SET_SECOND(self, second);
677 DATE_SET_MICROSECOND(self, usecond);
678 if (aware) {
679 Py_INCREF(tzinfo);
680 self->tzinfo = tzinfo;
681 }
682 }
683 return (PyObject *)self;
684}
685
686#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
687 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
688 &PyDateTime_DateTimeType)
689
690/* Create a time instance with no range checking. */
691static PyObject *
692new_time_ex(int hour, int minute, int second, int usecond,
693 PyObject *tzinfo, PyTypeObject *type)
694{
695 PyDateTime_Time *self;
696 char aware = tzinfo != Py_None;
697
698 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
699 if (self != NULL) {
700 self->hastzinfo = aware;
701 self->hashcode = -1;
702 TIME_SET_HOUR(self, hour);
703 TIME_SET_MINUTE(self, minute);
704 TIME_SET_SECOND(self, second);
705 TIME_SET_MICROSECOND(self, usecond);
706 if (aware) {
707 Py_INCREF(tzinfo);
708 self->tzinfo = tzinfo;
709 }
710 }
711 return (PyObject *)self;
712}
713
714#define new_time(hh, mm, ss, us, tzinfo) \
715 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
716
717/* Create a timedelta instance. Normalize the members iff normalize is
718 * true. Passing false is a speed optimization, if you know for sure
719 * that seconds and microseconds are already in their proper ranges. In any
720 * case, raises OverflowError and returns NULL if the normalized days is out
721 * of range).
722 */
723static PyObject *
724new_delta_ex(int days, int seconds, int microseconds, int normalize,
725 PyTypeObject *type)
726{
727 PyDateTime_Delta *self;
728
729 if (normalize)
730 normalize_d_s_us(&days, &seconds, &microseconds);
731 assert(0 <= seconds && seconds < 24*3600);
732 assert(0 <= microseconds && microseconds < 1000000);
733
734 if (check_delta_day_range(days) < 0)
735 return NULL;
736
737 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
738 if (self != NULL) {
739 self->hashcode = -1;
740 SET_TD_DAYS(self, days);
741 SET_TD_SECONDS(self, seconds);
742 SET_TD_MICROSECONDS(self, microseconds);
743 }
744 return (PyObject *) self;
745}
746
747#define new_delta(d, s, us, normalize) \
748 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
749
750/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000751 * tzinfo helpers.
752 */
753
Tim Peters855fe882002-12-22 03:43:39 +0000754/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
755 * raise TypeError and return -1.
756 */
757static int
758check_tzinfo_subclass(PyObject *p)
759{
760 if (p == Py_None || PyTZInfo_Check(p))
761 return 0;
762 PyErr_Format(PyExc_TypeError,
763 "tzinfo argument must be None or of a tzinfo subclass, "
764 "not type '%s'",
765 p->ob_type->tp_name);
766 return -1;
767}
768
Tim Petersbad8ff02002-12-30 20:52:32 +0000769/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000770 * If tzinfo is None, returns None.
771 */
772static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000773call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000774{
775 PyObject *result;
776
Tim Petersbad8ff02002-12-30 20:52:32 +0000777 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000778 assert(check_tzinfo_subclass(tzinfo) >= 0);
779 if (tzinfo == Py_None) {
780 result = Py_None;
781 Py_INCREF(result);
782 }
783 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000784 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000785 return result;
786}
787
Tim Peters2a799bf2002-12-16 20:18:38 +0000788/* If self has a tzinfo member, return a BORROWED reference to it. Else
789 * return NULL, which is NOT AN ERROR. There are no error returns here,
790 * and the caller must not decref the result.
791 */
792static PyObject *
793get_tzinfo_member(PyObject *self)
794{
795 PyObject *tzinfo = NULL;
796
Tim Petersa9bc1682003-01-11 03:39:11 +0000797 if (PyDateTime_Check(self) && HASTZINFO(self))
798 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000799 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000800 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000801
802 return tzinfo;
803}
804
Tim Petersbad8ff02002-12-30 20:52:32 +0000805/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000806 * result. tzinfo must be an instance of the tzinfo class. If the method
807 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000808 * return None or timedelta, TypeError is raised and this returns -1. If it
809 * returnsa timedelta and the value is out of range or isn't a whole number
810 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000811 * Else *none is set to 0 and the integer method result is returned.
812 */
813static int
814call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
815 int *none)
816{
817 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000818 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000819
820 assert(tzinfo != NULL);
821 assert(PyTZInfo_Check(tzinfo));
822 assert(tzinfoarg != NULL);
823
824 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000825 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000826 if (u == NULL)
827 return -1;
828
Tim Peters27362852002-12-23 16:17:39 +0000829 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000830 result = 0;
831 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 }
Tim Peters855fe882002-12-22 03:43:39 +0000833 else if (PyDelta_Check(u)) {
834 const int days = GET_TD_DAYS(u);
835 if (days < -1 || days > 0)
836 result = 24*60; /* trigger ValueError below */
837 else {
838 /* next line can't overflow because we know days
839 * is -1 or 0 now
840 */
841 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
842 result = divmod(ss, 60, &ss);
843 if (ss || GET_TD_MICROSECONDS(u)) {
844 PyErr_Format(PyExc_ValueError,
845 "tzinfo.%s() must return a "
846 "whole number of minutes",
847 name);
848 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000849 }
850 }
851 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000852 else {
853 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000854 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000855 "timedelta, not '%s'",
856 name, u->ob_type->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000857 }
858
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 Py_DECREF(u);
860 if (result < -1439 || result > 1439) {
861 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000862 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000863 "-1439 .. 1439",
864 name, result);
865 result = -1;
866 }
Tim Peters397301e2003-01-02 21:28:08 +0000867 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000868}
869
870/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
871 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
872 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000873 * doesn't return None or timedelta, TypeError is raised and this returns -1.
874 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
875 * # of minutes), ValueError is raised and this returns -1. Else *none is
876 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000877 */
878static int
879call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
880{
881 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
882}
883
Tim Petersbad8ff02002-12-30 20:52:32 +0000884/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
885 */
Tim Peters855fe882002-12-22 03:43:39 +0000886static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000887offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000888 PyObject *result;
889
Tim Petersbad8ff02002-12-30 20:52:32 +0000890 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000891 if (tzinfo == Py_None) {
892 result = Py_None;
893 Py_INCREF(result);
894 }
895 else {
896 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000897 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
898 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000899 if (offset < 0 && PyErr_Occurred())
900 return NULL;
901 if (none) {
902 result = Py_None;
903 Py_INCREF(result);
904 }
905 else
906 result = new_delta(0, offset * 60, 0, 1);
907 }
908 return result;
909}
910
Tim Peters2a799bf2002-12-16 20:18:38 +0000911/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
912 * result. tzinfo must be an instance of the tzinfo class. If dst()
913 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000914 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000915 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000916 * ValueError is raised and this returns -1. Else *none is set to 0 and
917 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000918 */
919static int
920call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
921{
922 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
923}
924
Tim Petersbad8ff02002-12-30 20:52:32 +0000925/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000926 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000927 * tzname() doesn't return None or a string, TypeError is raised and this
Tim Peters855fe882002-12-22 03:43:39 +0000928 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000929 */
930static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000931call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000932{
933 PyObject *result;
934
935 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000936 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000937 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000938
Tim Peters855fe882002-12-22 03:43:39 +0000939 if (tzinfo == Py_None) {
940 result = Py_None;
941 Py_INCREF(result);
942 }
943 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000944 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000945
946 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
947 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
Tim Peters2a799bf2002-12-16 20:18:38 +0000948 "return None or a string, not '%s'",
949 result->ob_type->tp_name);
950 Py_DECREF(result);
951 result = NULL;
952 }
953 return result;
954}
955
956typedef enum {
957 /* an exception has been set; the caller should pass it on */
958 OFFSET_ERROR,
959
Tim Petersa9bc1682003-01-11 03:39:11 +0000960 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000961 OFFSET_UNKNOWN,
962
963 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000964 * datetime with !hastzinfo
965 * datetime with None tzinfo,
966 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000967 * time with !hastzinfo
968 * time with None tzinfo,
969 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000970 */
971 OFFSET_NAIVE,
972
Tim Petersa9bc1682003-01-11 03:39:11 +0000973 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000974 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000975} naivety;
976
Tim Peters14b69412002-12-22 18:10:22 +0000977/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000978 * the "naivety" typedef for details. If the type is aware, *offset is set
979 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000980 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000981 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000982 */
983static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000984classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000985{
986 int none;
987 PyObject *tzinfo;
988
Tim Peterse39a80c2002-12-30 21:28:52 +0000989 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000990 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +0000991 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 if (tzinfo == Py_None)
993 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +0000994 if (tzinfo == NULL) {
995 /* note that a datetime passes the PyDate_Check test */
996 return (PyTime_Check(op) || PyDate_Check(op)) ?
997 OFFSET_NAIVE : OFFSET_UNKNOWN;
998 }
Tim Peterse39a80c2002-12-30 21:28:52 +0000999 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001000 if (*offset == -1 && PyErr_Occurred())
1001 return OFFSET_ERROR;
1002 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1003}
1004
Tim Peters00237032002-12-27 02:21:51 +00001005/* Classify two objects as to whether they're naive or offset-aware.
1006 * This isn't quite the same as calling classify_utcoffset() twice: for
1007 * binary operations (comparison and subtraction), we generally want to
1008 * ignore the tzinfo members if they're identical. This is by design,
1009 * so that results match "naive" expectations when mixing objects from a
1010 * single timezone. So in that case, this sets both offsets to 0 and
1011 * both naiveties to OFFSET_NAIVE.
1012 * The function returns 0 if everything's OK, and -1 on error.
1013 */
1014static int
1015classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001016 PyObject *tzinfoarg1,
1017 PyObject *o2, int *offset2, naivety *n2,
1018 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001019{
1020 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1021 *offset1 = *offset2 = 0;
1022 *n1 = *n2 = OFFSET_NAIVE;
1023 }
1024 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001025 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001026 if (*n1 == OFFSET_ERROR)
1027 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001028 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001029 if (*n2 == OFFSET_ERROR)
1030 return -1;
1031 }
1032 return 0;
1033}
1034
Tim Peters2a799bf2002-12-16 20:18:38 +00001035/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1036 * stuff
1037 * ", tzinfo=" + repr(tzinfo)
1038 * before the closing ")".
1039 */
1040static PyObject *
1041append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1042{
1043 PyObject *temp;
1044
1045 assert(PyString_Check(repr));
1046 assert(tzinfo);
1047 if (tzinfo == Py_None)
1048 return repr;
1049 /* Get rid of the trailing ')'. */
1050 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1051 temp = PyString_FromStringAndSize(PyString_AsString(repr),
1052 PyString_Size(repr) - 1);
1053 Py_DECREF(repr);
1054 if (temp == NULL)
1055 return NULL;
1056 repr = temp;
1057
1058 /* Append ", tzinfo=". */
1059 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
1060
1061 /* Append repr(tzinfo). */
1062 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
1063
1064 /* Add a closing paren. */
1065 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1066 return repr;
1067}
1068
1069/* ---------------------------------------------------------------------------
1070 * String format helpers.
1071 */
1072
1073static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001074format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001075{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001076 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001077 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1078 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001079 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001080 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1081 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1082 };
1083
1084 char buffer[128];
1085 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1086
1087 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1088 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1089 GET_DAY(date), hours, minutes, seconds,
1090 GET_YEAR(date));
1091 return PyString_FromString(buffer);
1092}
1093
1094/* Add an hours & minutes UTC offset string to buf. buf has no more than
1095 * buflen bytes remaining. The UTC offset is gotten by calling
1096 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1097 * *buf, and that's all. Else the returned value is checked for sanity (an
1098 * integer in range), and if that's OK it's converted to an hours & minutes
1099 * string of the form
1100 * sign HH sep MM
1101 * Returns 0 if everything is OK. If the return value from utcoffset() is
1102 * bogus, an appropriate exception is set and -1 is returned.
1103 */
1104static int
Tim Peters328fff72002-12-20 01:31:27 +00001105format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001106 PyObject *tzinfo, PyObject *tzinfoarg)
1107{
1108 int offset;
1109 int hours;
1110 int minutes;
1111 char sign;
1112 int none;
1113
1114 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1115 if (offset == -1 && PyErr_Occurred())
1116 return -1;
1117 if (none) {
1118 *buf = '\0';
1119 return 0;
1120 }
1121 sign = '+';
1122 if (offset < 0) {
1123 sign = '-';
1124 offset = - offset;
1125 }
1126 hours = divmod(offset, 60, &minutes);
1127 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1128 return 0;
1129}
1130
1131/* I sure don't want to reproduce the strftime code from the time module,
1132 * so this imports the module and calls it. All the hair is due to
1133 * giving special meanings to the %z and %Z format codes via a preprocessing
1134 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001135 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1136 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001137 */
1138static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001139wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1140 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001141{
1142 PyObject *result = NULL; /* guilty until proved innocent */
1143
1144 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1145 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1146
Guido van Rossumbce56a62007-05-10 18:04:33 +00001147 const char *pin;/* pointer to next char in input format */
1148 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001149 char ch; /* next char in input format */
1150
1151 PyObject *newfmt = NULL; /* py string, the output format */
1152 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001153 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001154 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001155 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001156
Guido van Rossumbce56a62007-05-10 18:04:33 +00001157 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001158 int ntoappend; /* # of bytes to append to output buffer */
1159
Tim Peters2a799bf2002-12-16 20:18:38 +00001160 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001161 assert(PyString_Check(format) || PyUnicode_Check(format));
1162
1163 /* Convert the input format to a C string and size */
1164 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1165 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001166
Tim Petersd6844152002-12-22 20:58:42 +00001167 /* Give up if the year is before 1900.
1168 * Python strftime() plays games with the year, and different
1169 * games depending on whether envar PYTHON2K is set. This makes
1170 * years before 1900 a nightmare, even if the platform strftime
1171 * supports them (and not all do).
1172 * We could get a lot farther here by avoiding Python's strftime
1173 * wrapper and calling the C strftime() directly, but that isn't
1174 * an option in the Python implementation of this module.
1175 */
1176 {
1177 long year;
1178 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1179 if (pyyear == NULL) return NULL;
1180 assert(PyInt_Check(pyyear));
1181 year = PyInt_AsLong(pyyear);
1182 Py_DECREF(pyyear);
1183 if (year < 1900) {
1184 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1185 "1900; the datetime strftime() "
1186 "methods require year >= 1900",
1187 year);
1188 return NULL;
1189 }
1190 }
1191
Tim Peters2a799bf2002-12-16 20:18:38 +00001192 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001193 * a new format. Since computing the replacements for those codes
1194 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001195 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001196 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001197 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1198 if (newfmt == NULL) goto Done;
1199 pnew = PyString_AsString(newfmt);
1200 usednew = 0;
1201
Tim Peters2a799bf2002-12-16 20:18:38 +00001202 while ((ch = *pin++) != '\0') {
1203 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001204 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001205 ntoappend = 1;
1206 }
1207 else if ((ch = *pin++) == '\0') {
1208 /* There's a lone trailing %; doesn't make sense. */
1209 PyErr_SetString(PyExc_ValueError, "strftime format "
1210 "ends with raw %");
1211 goto Done;
1212 }
1213 /* A % has been seen and ch is the character after it. */
1214 else if (ch == 'z') {
1215 if (zreplacement == NULL) {
1216 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001217 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001218 PyObject *tzinfo = get_tzinfo_member(object);
1219 zreplacement = PyString_FromString("");
1220 if (zreplacement == NULL) goto Done;
1221 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001222 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001223 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001224 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001225 "",
1226 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001227 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001228 goto Done;
1229 Py_DECREF(zreplacement);
1230 zreplacement = PyString_FromString(buf);
1231 if (zreplacement == NULL) goto Done;
1232 }
1233 }
1234 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001235 ptoappend = PyString_AS_STRING(zreplacement);
1236 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001237 }
1238 else if (ch == 'Z') {
1239 /* format tzname */
1240 if (Zreplacement == NULL) {
1241 PyObject *tzinfo = get_tzinfo_member(object);
1242 Zreplacement = PyString_FromString("");
1243 if (Zreplacement == NULL) goto Done;
1244 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001245 PyObject *temp;
1246 assert(tzinfoarg != NULL);
1247 temp = call_tzname(tzinfo, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001248 if (temp == NULL) goto Done;
1249 if (temp != Py_None) {
1250 assert(PyString_Check(temp));
1251 /* Since the tzname is getting
1252 * stuffed into the format, we
1253 * have to double any % signs
1254 * so that strftime doesn't
1255 * treat them as format codes.
1256 */
1257 Py_DECREF(Zreplacement);
1258 Zreplacement = PyObject_CallMethod(
1259 temp, "replace",
1260 "ss", "%", "%%");
1261 Py_DECREF(temp);
1262 if (Zreplacement == NULL)
1263 goto Done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001264 if (!PyString_Check(Zreplacement)) {
1265 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1266 goto Done;
1267 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001268 }
1269 else
1270 Py_DECREF(temp);
1271 }
1272 }
1273 assert(Zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001274 ptoappend = PyString_AS_STRING(Zreplacement);
1275 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001276 }
1277 else {
Tim Peters328fff72002-12-20 01:31:27 +00001278 /* percent followed by neither z nor Z */
1279 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001280 ntoappend = 2;
1281 }
1282
1283 /* Append the ntoappend chars starting at ptoappend to
1284 * the new format.
1285 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001286 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001287 assert(ntoappend >= 0);
1288 if (ntoappend == 0)
1289 continue;
1290 while (usednew + ntoappend > totalnew) {
1291 int bigger = totalnew << 1;
1292 if ((bigger >> 1) != totalnew) { /* overflow */
1293 PyErr_NoMemory();
1294 goto Done;
1295 }
1296 if (_PyString_Resize(&newfmt, bigger) < 0)
1297 goto Done;
1298 totalnew = bigger;
1299 pnew = PyString_AsString(newfmt) + usednew;
1300 }
1301 memcpy(pnew, ptoappend, ntoappend);
1302 pnew += ntoappend;
1303 usednew += ntoappend;
1304 assert(usednew <= totalnew);
1305 } /* end while() */
1306
1307 if (_PyString_Resize(&newfmt, usednew) < 0)
1308 goto Done;
1309 {
1310 PyObject *time = PyImport_ImportModule("time");
1311 if (time == NULL)
1312 goto Done;
1313 result = PyObject_CallMethod(time, "strftime", "OO",
1314 newfmt, timetuple);
1315 Py_DECREF(time);
1316 }
1317 Done:
1318 Py_XDECREF(zreplacement);
1319 Py_XDECREF(Zreplacement);
1320 Py_XDECREF(newfmt);
1321 return result;
1322}
1323
1324static char *
1325isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1326{
1327 int x;
1328 x = PyOS_snprintf(buffer, bufflen,
1329 "%04d-%02d-%02d",
1330 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1331 return buffer + x;
1332}
1333
1334static void
1335isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1336{
1337 int us = DATE_GET_MICROSECOND(dt);
1338
1339 PyOS_snprintf(buffer, bufflen,
1340 "%02d:%02d:%02d", /* 8 characters */
1341 DATE_GET_HOUR(dt),
1342 DATE_GET_MINUTE(dt),
1343 DATE_GET_SECOND(dt));
1344 if (us)
1345 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1346}
1347
1348/* ---------------------------------------------------------------------------
1349 * Wrap functions from the time module. These aren't directly available
1350 * from C. Perhaps they should be.
1351 */
1352
1353/* Call time.time() and return its result (a Python float). */
1354static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001355time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001356{
1357 PyObject *result = NULL;
1358 PyObject *time = PyImport_ImportModule("time");
1359
1360 if (time != NULL) {
1361 result = PyObject_CallMethod(time, "time", "()");
1362 Py_DECREF(time);
1363 }
1364 return result;
1365}
1366
1367/* Build a time.struct_time. The weekday and day number are automatically
1368 * computed from the y,m,d args.
1369 */
1370static PyObject *
1371build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1372{
1373 PyObject *time;
1374 PyObject *result = NULL;
1375
1376 time = PyImport_ImportModule("time");
1377 if (time != NULL) {
1378 result = PyObject_CallMethod(time, "struct_time",
1379 "((iiiiiiiii))",
1380 y, m, d,
1381 hh, mm, ss,
1382 weekday(y, m, d),
1383 days_before_month(y, m) + d,
1384 dstflag);
1385 Py_DECREF(time);
1386 }
1387 return result;
1388}
1389
1390/* ---------------------------------------------------------------------------
1391 * Miscellaneous helpers.
1392 */
1393
Guido van Rossum19960592006-08-24 17:29:38 +00001394/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001395 * The comparisons here all most naturally compute a cmp()-like result.
1396 * This little helper turns that into a bool result for rich comparisons.
1397 */
1398static PyObject *
1399diff_to_bool(int diff, int op)
1400{
1401 PyObject *result;
1402 int istrue;
1403
1404 switch (op) {
1405 case Py_EQ: istrue = diff == 0; break;
1406 case Py_NE: istrue = diff != 0; break;
1407 case Py_LE: istrue = diff <= 0; break;
1408 case Py_GE: istrue = diff >= 0; break;
1409 case Py_LT: istrue = diff < 0; break;
1410 case Py_GT: istrue = diff > 0; break;
1411 default:
1412 assert(! "op unknown");
1413 istrue = 0; /* To shut up compiler */
1414 }
1415 result = istrue ? Py_True : Py_False;
1416 Py_INCREF(result);
1417 return result;
1418}
1419
Tim Peters07534a62003-02-07 22:50:28 +00001420/* Raises a "can't compare" TypeError and returns NULL. */
1421static PyObject *
1422cmperror(PyObject *a, PyObject *b)
1423{
1424 PyErr_Format(PyExc_TypeError,
1425 "can't compare %s to %s",
1426 a->ob_type->tp_name, b->ob_type->tp_name);
1427 return NULL;
1428}
1429
Tim Peters2a799bf2002-12-16 20:18:38 +00001430/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001431 * Cached Python objects; these are set by the module init function.
1432 */
1433
1434/* Conversion factors. */
1435static PyObject *us_per_us = NULL; /* 1 */
1436static PyObject *us_per_ms = NULL; /* 1000 */
1437static PyObject *us_per_second = NULL; /* 1000000 */
1438static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1439static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1440static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1441static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1442static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1443
Tim Peters2a799bf2002-12-16 20:18:38 +00001444/* ---------------------------------------------------------------------------
1445 * Class implementations.
1446 */
1447
1448/*
1449 * PyDateTime_Delta implementation.
1450 */
1451
1452/* Convert a timedelta to a number of us,
1453 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1454 * as a Python int or long.
1455 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1456 * due to ubiquitous overflow possibilities.
1457 */
1458static PyObject *
1459delta_to_microseconds(PyDateTime_Delta *self)
1460{
1461 PyObject *x1 = NULL;
1462 PyObject *x2 = NULL;
1463 PyObject *x3 = NULL;
1464 PyObject *result = NULL;
1465
1466 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1467 if (x1 == NULL)
1468 goto Done;
1469 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1470 if (x2 == NULL)
1471 goto Done;
1472 Py_DECREF(x1);
1473 x1 = NULL;
1474
1475 /* x2 has days in seconds */
1476 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1477 if (x1 == NULL)
1478 goto Done;
1479 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1480 if (x3 == NULL)
1481 goto Done;
1482 Py_DECREF(x1);
1483 Py_DECREF(x2);
1484 x1 = x2 = NULL;
1485
1486 /* x3 has days+seconds in seconds */
1487 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1488 if (x1 == NULL)
1489 goto Done;
1490 Py_DECREF(x3);
1491 x3 = NULL;
1492
1493 /* x1 has days+seconds in us */
1494 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1495 if (x2 == NULL)
1496 goto Done;
1497 result = PyNumber_Add(x1, x2);
1498
1499Done:
1500 Py_XDECREF(x1);
1501 Py_XDECREF(x2);
1502 Py_XDECREF(x3);
1503 return result;
1504}
1505
1506/* Convert a number of us (as a Python int or long) to a timedelta.
1507 */
1508static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001509microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001510{
1511 int us;
1512 int s;
1513 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001514 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001515
1516 PyObject *tuple = NULL;
1517 PyObject *num = NULL;
1518 PyObject *result = NULL;
1519
1520 tuple = PyNumber_Divmod(pyus, us_per_second);
1521 if (tuple == NULL)
1522 goto Done;
1523
1524 num = PyTuple_GetItem(tuple, 1); /* us */
1525 if (num == NULL)
1526 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001527 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001528 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001529 if (temp == -1 && PyErr_Occurred())
1530 goto Done;
1531 assert(0 <= temp && temp < 1000000);
1532 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001533 if (us < 0) {
1534 /* The divisor was positive, so this must be an error. */
1535 assert(PyErr_Occurred());
1536 goto Done;
1537 }
1538
1539 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1540 if (num == NULL)
1541 goto Done;
1542 Py_INCREF(num);
1543 Py_DECREF(tuple);
1544
1545 tuple = PyNumber_Divmod(num, seconds_per_day);
1546 if (tuple == NULL)
1547 goto Done;
1548 Py_DECREF(num);
1549
1550 num = PyTuple_GetItem(tuple, 1); /* seconds */
1551 if (num == NULL)
1552 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001553 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001554 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001555 if (temp == -1 && PyErr_Occurred())
1556 goto Done;
1557 assert(0 <= temp && temp < 24*3600);
1558 s = (int)temp;
1559
Tim Peters2a799bf2002-12-16 20:18:38 +00001560 if (s < 0) {
1561 /* The divisor was positive, so this must be an error. */
1562 assert(PyErr_Occurred());
1563 goto Done;
1564 }
1565
1566 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1567 if (num == NULL)
1568 goto Done;
1569 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001570 temp = PyLong_AsLong(num);
1571 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001572 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001573 d = (int)temp;
1574 if ((long)d != temp) {
1575 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1576 "large to fit in a C int");
1577 goto Done;
1578 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001579 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001580
1581Done:
1582 Py_XDECREF(tuple);
1583 Py_XDECREF(num);
1584 return result;
1585}
1586
Tim Petersb0c854d2003-05-17 15:57:00 +00001587#define microseconds_to_delta(pymicros) \
1588 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1589
Tim Peters2a799bf2002-12-16 20:18:38 +00001590static PyObject *
1591multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1592{
1593 PyObject *pyus_in;
1594 PyObject *pyus_out;
1595 PyObject *result;
1596
1597 pyus_in = delta_to_microseconds(delta);
1598 if (pyus_in == NULL)
1599 return NULL;
1600
1601 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1602 Py_DECREF(pyus_in);
1603 if (pyus_out == NULL)
1604 return NULL;
1605
1606 result = microseconds_to_delta(pyus_out);
1607 Py_DECREF(pyus_out);
1608 return result;
1609}
1610
1611static PyObject *
1612divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1613{
1614 PyObject *pyus_in;
1615 PyObject *pyus_out;
1616 PyObject *result;
1617
1618 pyus_in = delta_to_microseconds(delta);
1619 if (pyus_in == NULL)
1620 return NULL;
1621
1622 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1623 Py_DECREF(pyus_in);
1624 if (pyus_out == NULL)
1625 return NULL;
1626
1627 result = microseconds_to_delta(pyus_out);
1628 Py_DECREF(pyus_out);
1629 return result;
1630}
1631
1632static PyObject *
1633delta_add(PyObject *left, PyObject *right)
1634{
1635 PyObject *result = Py_NotImplemented;
1636
1637 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1638 /* delta + delta */
1639 /* The C-level additions can't overflow because of the
1640 * invariant bounds.
1641 */
1642 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1643 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1644 int microseconds = GET_TD_MICROSECONDS(left) +
1645 GET_TD_MICROSECONDS(right);
1646 result = new_delta(days, seconds, microseconds, 1);
1647 }
1648
1649 if (result == Py_NotImplemented)
1650 Py_INCREF(result);
1651 return result;
1652}
1653
1654static PyObject *
1655delta_negative(PyDateTime_Delta *self)
1656{
1657 return new_delta(-GET_TD_DAYS(self),
1658 -GET_TD_SECONDS(self),
1659 -GET_TD_MICROSECONDS(self),
1660 1);
1661}
1662
1663static PyObject *
1664delta_positive(PyDateTime_Delta *self)
1665{
1666 /* Could optimize this (by returning self) if this isn't a
1667 * subclass -- but who uses unary + ? Approximately nobody.
1668 */
1669 return new_delta(GET_TD_DAYS(self),
1670 GET_TD_SECONDS(self),
1671 GET_TD_MICROSECONDS(self),
1672 0);
1673}
1674
1675static PyObject *
1676delta_abs(PyDateTime_Delta *self)
1677{
1678 PyObject *result;
1679
1680 assert(GET_TD_MICROSECONDS(self) >= 0);
1681 assert(GET_TD_SECONDS(self) >= 0);
1682
1683 if (GET_TD_DAYS(self) < 0)
1684 result = delta_negative(self);
1685 else
1686 result = delta_positive(self);
1687
1688 return result;
1689}
1690
1691static PyObject *
1692delta_subtract(PyObject *left, PyObject *right)
1693{
1694 PyObject *result = Py_NotImplemented;
1695
1696 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1697 /* delta - delta */
1698 PyObject *minus_right = PyNumber_Negative(right);
1699 if (minus_right) {
1700 result = delta_add(left, minus_right);
1701 Py_DECREF(minus_right);
1702 }
1703 else
1704 result = NULL;
1705 }
1706
1707 if (result == Py_NotImplemented)
1708 Py_INCREF(result);
1709 return result;
1710}
1711
Tim Peters2a799bf2002-12-16 20:18:38 +00001712static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001713delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001714{
Tim Petersaa7d8492003-02-08 03:28:59 +00001715 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001716 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001717 if (diff == 0) {
1718 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1719 if (diff == 0)
1720 diff = GET_TD_MICROSECONDS(self) -
1721 GET_TD_MICROSECONDS(other);
1722 }
Guido van Rossum19960592006-08-24 17:29:38 +00001723 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001724 }
Guido van Rossum19960592006-08-24 17:29:38 +00001725 else {
1726 Py_INCREF(Py_NotImplemented);
1727 return Py_NotImplemented;
1728 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001729}
1730
1731static PyObject *delta_getstate(PyDateTime_Delta *self);
1732
1733static long
1734delta_hash(PyDateTime_Delta *self)
1735{
1736 if (self->hashcode == -1) {
1737 PyObject *temp = delta_getstate(self);
1738 if (temp != NULL) {
1739 self->hashcode = PyObject_Hash(temp);
1740 Py_DECREF(temp);
1741 }
1742 }
1743 return self->hashcode;
1744}
1745
1746static PyObject *
1747delta_multiply(PyObject *left, PyObject *right)
1748{
1749 PyObject *result = Py_NotImplemented;
1750
1751 if (PyDelta_Check(left)) {
1752 /* delta * ??? */
1753 if (PyInt_Check(right) || PyLong_Check(right))
1754 result = multiply_int_timedelta(right,
1755 (PyDateTime_Delta *) left);
1756 }
1757 else if (PyInt_Check(left) || PyLong_Check(left))
1758 result = multiply_int_timedelta(left,
1759 (PyDateTime_Delta *) right);
1760
1761 if (result == Py_NotImplemented)
1762 Py_INCREF(result);
1763 return result;
1764}
1765
1766static PyObject *
1767delta_divide(PyObject *left, PyObject *right)
1768{
1769 PyObject *result = Py_NotImplemented;
1770
1771 if (PyDelta_Check(left)) {
1772 /* delta * ??? */
1773 if (PyInt_Check(right) || PyLong_Check(right))
1774 result = divide_timedelta_int(
1775 (PyDateTime_Delta *)left,
1776 right);
1777 }
1778
1779 if (result == Py_NotImplemented)
1780 Py_INCREF(result);
1781 return result;
1782}
1783
1784/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1785 * timedelta constructor. sofar is the # of microseconds accounted for
1786 * so far, and there are factor microseconds per current unit, the number
1787 * of which is given by num. num * factor is added to sofar in a
1788 * numerically careful way, and that's the result. Any fractional
1789 * microseconds left over (this can happen if num is a float type) are
1790 * added into *leftover.
1791 * Note that there are many ways this can give an error (NULL) return.
1792 */
1793static PyObject *
1794accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1795 double *leftover)
1796{
1797 PyObject *prod;
1798 PyObject *sum;
1799
1800 assert(num != NULL);
1801
1802 if (PyInt_Check(num) || PyLong_Check(num)) {
1803 prod = PyNumber_Multiply(num, factor);
1804 if (prod == NULL)
1805 return NULL;
1806 sum = PyNumber_Add(sofar, prod);
1807 Py_DECREF(prod);
1808 return sum;
1809 }
1810
1811 if (PyFloat_Check(num)) {
1812 double dnum;
1813 double fracpart;
1814 double intpart;
1815 PyObject *x;
1816 PyObject *y;
1817
1818 /* The Plan: decompose num into an integer part and a
1819 * fractional part, num = intpart + fracpart.
1820 * Then num * factor ==
1821 * intpart * factor + fracpart * factor
1822 * and the LHS can be computed exactly in long arithmetic.
1823 * The RHS is again broken into an int part and frac part.
1824 * and the frac part is added into *leftover.
1825 */
1826 dnum = PyFloat_AsDouble(num);
1827 if (dnum == -1.0 && PyErr_Occurred())
1828 return NULL;
1829 fracpart = modf(dnum, &intpart);
1830 x = PyLong_FromDouble(intpart);
1831 if (x == NULL)
1832 return NULL;
1833
1834 prod = PyNumber_Multiply(x, factor);
1835 Py_DECREF(x);
1836 if (prod == NULL)
1837 return NULL;
1838
1839 sum = PyNumber_Add(sofar, prod);
1840 Py_DECREF(prod);
1841 if (sum == NULL)
1842 return NULL;
1843
1844 if (fracpart == 0.0)
1845 return sum;
1846 /* So far we've lost no information. Dealing with the
1847 * fractional part requires float arithmetic, and may
1848 * lose a little info.
1849 */
1850 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001851 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001852
1853 dnum *= fracpart;
1854 fracpart = modf(dnum, &intpart);
1855 x = PyLong_FromDouble(intpart);
1856 if (x == NULL) {
1857 Py_DECREF(sum);
1858 return NULL;
1859 }
1860
1861 y = PyNumber_Add(sum, x);
1862 Py_DECREF(sum);
1863 Py_DECREF(x);
1864 *leftover += fracpart;
1865 return y;
1866 }
1867
1868 PyErr_Format(PyExc_TypeError,
1869 "unsupported type for timedelta %s component: %s",
1870 tag, num->ob_type->tp_name);
1871 return NULL;
1872}
1873
1874static PyObject *
1875delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1876{
1877 PyObject *self = NULL;
1878
1879 /* Argument objects. */
1880 PyObject *day = NULL;
1881 PyObject *second = NULL;
1882 PyObject *us = NULL;
1883 PyObject *ms = NULL;
1884 PyObject *minute = NULL;
1885 PyObject *hour = NULL;
1886 PyObject *week = NULL;
1887
1888 PyObject *x = NULL; /* running sum of microseconds */
1889 PyObject *y = NULL; /* temp sum of microseconds */
1890 double leftover_us = 0.0;
1891
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001892 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001893 "days", "seconds", "microseconds", "milliseconds",
1894 "minutes", "hours", "weeks", NULL
1895 };
1896
1897 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1898 keywords,
1899 &day, &second, &us,
1900 &ms, &minute, &hour, &week) == 0)
1901 goto Done;
1902
1903 x = PyInt_FromLong(0);
1904 if (x == NULL)
1905 goto Done;
1906
1907#define CLEANUP \
1908 Py_DECREF(x); \
1909 x = y; \
1910 if (x == NULL) \
1911 goto Done
1912
1913 if (us) {
1914 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1915 CLEANUP;
1916 }
1917 if (ms) {
1918 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1919 CLEANUP;
1920 }
1921 if (second) {
1922 y = accum("seconds", x, second, us_per_second, &leftover_us);
1923 CLEANUP;
1924 }
1925 if (minute) {
1926 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1927 CLEANUP;
1928 }
1929 if (hour) {
1930 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1931 CLEANUP;
1932 }
1933 if (day) {
1934 y = accum("days", x, day, us_per_day, &leftover_us);
1935 CLEANUP;
1936 }
1937 if (week) {
1938 y = accum("weeks", x, week, us_per_week, &leftover_us);
1939 CLEANUP;
1940 }
1941 if (leftover_us) {
1942 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001943 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001944 if (temp == NULL) {
1945 Py_DECREF(x);
1946 goto Done;
1947 }
1948 y = PyNumber_Add(x, temp);
1949 Py_DECREF(temp);
1950 CLEANUP;
1951 }
1952
Tim Petersb0c854d2003-05-17 15:57:00 +00001953 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001954 Py_DECREF(x);
1955Done:
1956 return self;
1957
1958#undef CLEANUP
1959}
1960
1961static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001962delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001963{
1964 return (GET_TD_DAYS(self) != 0
1965 || GET_TD_SECONDS(self) != 0
1966 || GET_TD_MICROSECONDS(self) != 0);
1967}
1968
1969static PyObject *
1970delta_repr(PyDateTime_Delta *self)
1971{
1972 if (GET_TD_MICROSECONDS(self) != 0)
1973 return PyString_FromFormat("%s(%d, %d, %d)",
1974 self->ob_type->tp_name,
1975 GET_TD_DAYS(self),
1976 GET_TD_SECONDS(self),
1977 GET_TD_MICROSECONDS(self));
1978 if (GET_TD_SECONDS(self) != 0)
1979 return PyString_FromFormat("%s(%d, %d)",
1980 self->ob_type->tp_name,
1981 GET_TD_DAYS(self),
1982 GET_TD_SECONDS(self));
1983
1984 return PyString_FromFormat("%s(%d)",
1985 self->ob_type->tp_name,
1986 GET_TD_DAYS(self));
1987}
1988
1989static PyObject *
1990delta_str(PyDateTime_Delta *self)
1991{
1992 int days = GET_TD_DAYS(self);
1993 int seconds = GET_TD_SECONDS(self);
1994 int us = GET_TD_MICROSECONDS(self);
1995 int hours;
1996 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00001997 char buf[100];
1998 char *pbuf = buf;
1999 size_t buflen = sizeof(buf);
2000 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002001
2002 minutes = divmod(seconds, 60, &seconds);
2003 hours = divmod(minutes, 60, &minutes);
2004
2005 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002006 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2007 (days == 1 || days == -1) ? "" : "s");
2008 if (n < 0 || (size_t)n >= buflen)
2009 goto Fail;
2010 pbuf += n;
2011 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002012 }
2013
Tim Petersba873472002-12-18 20:19:21 +00002014 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2015 hours, minutes, seconds);
2016 if (n < 0 || (size_t)n >= buflen)
2017 goto Fail;
2018 pbuf += n;
2019 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002020
2021 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002022 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2023 if (n < 0 || (size_t)n >= buflen)
2024 goto Fail;
2025 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002026 }
2027
Tim Petersba873472002-12-18 20:19:21 +00002028 return PyString_FromStringAndSize(buf, pbuf - buf);
2029
2030 Fail:
2031 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2032 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002033}
2034
Tim Peters371935f2003-02-01 01:52:50 +00002035/* Pickle support, a simple use of __reduce__. */
2036
Tim Petersb57f8f02003-02-01 02:54:15 +00002037/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002038static PyObject *
2039delta_getstate(PyDateTime_Delta *self)
2040{
2041 return Py_BuildValue("iii", GET_TD_DAYS(self),
2042 GET_TD_SECONDS(self),
2043 GET_TD_MICROSECONDS(self));
2044}
2045
Tim Peters2a799bf2002-12-16 20:18:38 +00002046static PyObject *
2047delta_reduce(PyDateTime_Delta* self)
2048{
Tim Peters8a60c222003-02-01 01:47:29 +00002049 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002050}
2051
2052#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2053
2054static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002055
Neal Norwitzdfb80862002-12-19 02:30:56 +00002056 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002057 PyDoc_STR("Number of days.")},
2058
Neal Norwitzdfb80862002-12-19 02:30:56 +00002059 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002060 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2061
Neal Norwitzdfb80862002-12-19 02:30:56 +00002062 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002063 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2064 {NULL}
2065};
2066
2067static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002068 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2069 PyDoc_STR("__reduce__() -> (cls, state)")},
2070
Tim Peters2a799bf2002-12-16 20:18:38 +00002071 {NULL, NULL},
2072};
2073
2074static char delta_doc[] =
2075PyDoc_STR("Difference between two datetime values.");
2076
2077static PyNumberMethods delta_as_number = {
2078 delta_add, /* nb_add */
2079 delta_subtract, /* nb_subtract */
2080 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002081 0, /* nb_remainder */
2082 0, /* nb_divmod */
2083 0, /* nb_power */
2084 (unaryfunc)delta_negative, /* nb_negative */
2085 (unaryfunc)delta_positive, /* nb_positive */
2086 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002087 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002088 0, /*nb_invert*/
2089 0, /*nb_lshift*/
2090 0, /*nb_rshift*/
2091 0, /*nb_and*/
2092 0, /*nb_xor*/
2093 0, /*nb_or*/
2094 0, /*nb_coerce*/
2095 0, /*nb_int*/
2096 0, /*nb_long*/
2097 0, /*nb_float*/
2098 0, /*nb_oct*/
2099 0, /*nb_hex*/
2100 0, /*nb_inplace_add*/
2101 0, /*nb_inplace_subtract*/
2102 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002103 0, /*nb_inplace_remainder*/
2104 0, /*nb_inplace_power*/
2105 0, /*nb_inplace_lshift*/
2106 0, /*nb_inplace_rshift*/
2107 0, /*nb_inplace_and*/
2108 0, /*nb_inplace_xor*/
2109 0, /*nb_inplace_or*/
2110 delta_divide, /* nb_floor_divide */
2111 0, /* nb_true_divide */
2112 0, /* nb_inplace_floor_divide */
2113 0, /* nb_inplace_true_divide */
2114};
2115
2116static PyTypeObject PyDateTime_DeltaType = {
2117 PyObject_HEAD_INIT(NULL)
2118 0, /* ob_size */
2119 "datetime.timedelta", /* tp_name */
2120 sizeof(PyDateTime_Delta), /* tp_basicsize */
2121 0, /* tp_itemsize */
2122 0, /* tp_dealloc */
2123 0, /* tp_print */
2124 0, /* tp_getattr */
2125 0, /* tp_setattr */
2126 0, /* tp_compare */
2127 (reprfunc)delta_repr, /* tp_repr */
2128 &delta_as_number, /* tp_as_number */
2129 0, /* tp_as_sequence */
2130 0, /* tp_as_mapping */
2131 (hashfunc)delta_hash, /* tp_hash */
2132 0, /* tp_call */
2133 (reprfunc)delta_str, /* tp_str */
2134 PyObject_GenericGetAttr, /* tp_getattro */
2135 0, /* tp_setattro */
2136 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002137 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002138 delta_doc, /* tp_doc */
2139 0, /* tp_traverse */
2140 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002141 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002142 0, /* tp_weaklistoffset */
2143 0, /* tp_iter */
2144 0, /* tp_iternext */
2145 delta_methods, /* tp_methods */
2146 delta_members, /* tp_members */
2147 0, /* tp_getset */
2148 0, /* tp_base */
2149 0, /* tp_dict */
2150 0, /* tp_descr_get */
2151 0, /* tp_descr_set */
2152 0, /* tp_dictoffset */
2153 0, /* tp_init */
2154 0, /* tp_alloc */
2155 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002156 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002157};
2158
2159/*
2160 * PyDateTime_Date implementation.
2161 */
2162
2163/* Accessor properties. */
2164
2165static PyObject *
2166date_year(PyDateTime_Date *self, void *unused)
2167{
2168 return PyInt_FromLong(GET_YEAR(self));
2169}
2170
2171static PyObject *
2172date_month(PyDateTime_Date *self, void *unused)
2173{
2174 return PyInt_FromLong(GET_MONTH(self));
2175}
2176
2177static PyObject *
2178date_day(PyDateTime_Date *self, void *unused)
2179{
2180 return PyInt_FromLong(GET_DAY(self));
2181}
2182
2183static PyGetSetDef date_getset[] = {
2184 {"year", (getter)date_year},
2185 {"month", (getter)date_month},
2186 {"day", (getter)date_day},
2187 {NULL}
2188};
2189
2190/* Constructors. */
2191
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002192static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002193
Tim Peters2a799bf2002-12-16 20:18:38 +00002194static PyObject *
2195date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2196{
2197 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002198 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002199 int year;
2200 int month;
2201 int day;
2202
Guido van Rossum177e41a2003-01-30 22:06:23 +00002203 /* Check for invocation from pickle with __getstate__ state */
2204 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002205 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002206 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2207 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002208 {
Tim Peters70533e22003-02-01 04:40:04 +00002209 PyDateTime_Date *me;
2210
Tim Peters604c0132004-06-07 23:04:33 +00002211 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002212 if (me != NULL) {
2213 char *pdata = PyString_AS_STRING(state);
2214 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2215 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002216 }
Tim Peters70533e22003-02-01 04:40:04 +00002217 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002218 }
2219
Tim Peters12bf3392002-12-24 05:41:27 +00002220 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002221 &year, &month, &day)) {
2222 if (check_date_args(year, month, day) < 0)
2223 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002224 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002225 }
2226 return self;
2227}
2228
2229/* Return new date from localtime(t). */
2230static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002231date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002232{
2233 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002234 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002235 PyObject *result = NULL;
2236
Tim Peters1b6f7a92004-06-20 02:50:16 +00002237 t = _PyTime_DoubleToTimet(ts);
2238 if (t == (time_t)-1 && PyErr_Occurred())
2239 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002240 tm = localtime(&t);
2241 if (tm)
2242 result = PyObject_CallFunction(cls, "iii",
2243 tm->tm_year + 1900,
2244 tm->tm_mon + 1,
2245 tm->tm_mday);
2246 else
2247 PyErr_SetString(PyExc_ValueError,
2248 "timestamp out of range for "
2249 "platform localtime() function");
2250 return result;
2251}
2252
2253/* Return new date from current time.
2254 * We say this is equivalent to fromtimestamp(time.time()), and the
2255 * only way to be sure of that is to *call* time.time(). That's not
2256 * generally the same as calling C's time.
2257 */
2258static PyObject *
2259date_today(PyObject *cls, PyObject *dummy)
2260{
2261 PyObject *time;
2262 PyObject *result;
2263
2264 time = time_time();
2265 if (time == NULL)
2266 return NULL;
2267
2268 /* Note well: today() is a class method, so this may not call
2269 * date.fromtimestamp. For example, it may call
2270 * datetime.fromtimestamp. That's why we need all the accuracy
2271 * time.time() delivers; if someone were gonzo about optimization,
2272 * date.today() could get away with plain C time().
2273 */
2274 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2275 Py_DECREF(time);
2276 return result;
2277}
2278
2279/* Return new date from given timestamp (Python timestamp -- a double). */
2280static PyObject *
2281date_fromtimestamp(PyObject *cls, PyObject *args)
2282{
2283 double timestamp;
2284 PyObject *result = NULL;
2285
2286 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002287 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002288 return result;
2289}
2290
2291/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2292 * the ordinal is out of range.
2293 */
2294static PyObject *
2295date_fromordinal(PyObject *cls, PyObject *args)
2296{
2297 PyObject *result = NULL;
2298 int ordinal;
2299
2300 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2301 int year;
2302 int month;
2303 int day;
2304
2305 if (ordinal < 1)
2306 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2307 ">= 1");
2308 else {
2309 ord_to_ymd(ordinal, &year, &month, &day);
2310 result = PyObject_CallFunction(cls, "iii",
2311 year, month, day);
2312 }
2313 }
2314 return result;
2315}
2316
2317/*
2318 * Date arithmetic.
2319 */
2320
2321/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2322 * instead.
2323 */
2324static PyObject *
2325add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2326{
2327 PyObject *result = NULL;
2328 int year = GET_YEAR(date);
2329 int month = GET_MONTH(date);
2330 int deltadays = GET_TD_DAYS(delta);
2331 /* C-level overflow is impossible because |deltadays| < 1e9. */
2332 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2333
2334 if (normalize_date(&year, &month, &day) >= 0)
2335 result = new_date(year, month, day);
2336 return result;
2337}
2338
2339static PyObject *
2340date_add(PyObject *left, PyObject *right)
2341{
2342 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2343 Py_INCREF(Py_NotImplemented);
2344 return Py_NotImplemented;
2345 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002346 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002347 /* date + ??? */
2348 if (PyDelta_Check(right))
2349 /* date + delta */
2350 return add_date_timedelta((PyDateTime_Date *) left,
2351 (PyDateTime_Delta *) right,
2352 0);
2353 }
2354 else {
2355 /* ??? + date
2356 * 'right' must be one of us, or we wouldn't have been called
2357 */
2358 if (PyDelta_Check(left))
2359 /* delta + date */
2360 return add_date_timedelta((PyDateTime_Date *) right,
2361 (PyDateTime_Delta *) left,
2362 0);
2363 }
2364 Py_INCREF(Py_NotImplemented);
2365 return Py_NotImplemented;
2366}
2367
2368static PyObject *
2369date_subtract(PyObject *left, PyObject *right)
2370{
2371 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2372 Py_INCREF(Py_NotImplemented);
2373 return Py_NotImplemented;
2374 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002375 if (PyDate_Check(left)) {
2376 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002377 /* date - date */
2378 int left_ord = ymd_to_ord(GET_YEAR(left),
2379 GET_MONTH(left),
2380 GET_DAY(left));
2381 int right_ord = ymd_to_ord(GET_YEAR(right),
2382 GET_MONTH(right),
2383 GET_DAY(right));
2384 return new_delta(left_ord - right_ord, 0, 0, 0);
2385 }
2386 if (PyDelta_Check(right)) {
2387 /* date - delta */
2388 return add_date_timedelta((PyDateTime_Date *) left,
2389 (PyDateTime_Delta *) right,
2390 1);
2391 }
2392 }
2393 Py_INCREF(Py_NotImplemented);
2394 return Py_NotImplemented;
2395}
2396
2397
2398/* Various ways to turn a date into a string. */
2399
2400static PyObject *
2401date_repr(PyDateTime_Date *self)
2402{
2403 char buffer[1028];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002404 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002405
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002406 type_name = self->ob_type->tp_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002407 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002408 type_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002409 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2410
2411 return PyString_FromString(buffer);
2412}
2413
2414static PyObject *
2415date_isoformat(PyDateTime_Date *self)
2416{
2417 char buffer[128];
2418
2419 isoformat_date(self, buffer, sizeof(buffer));
2420 return PyString_FromString(buffer);
2421}
2422
Tim Peterse2df5ff2003-05-02 18:39:55 +00002423/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002424static PyObject *
2425date_str(PyDateTime_Date *self)
2426{
2427 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2428}
2429
2430
2431static PyObject *
2432date_ctime(PyDateTime_Date *self)
2433{
2434 return format_ctime(self, 0, 0, 0);
2435}
2436
2437static PyObject *
2438date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2439{
2440 /* This method can be inherited, and needs to call the
2441 * timetuple() method appropriate to self's class.
2442 */
2443 PyObject *result;
2444 PyObject *format;
2445 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002446 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002447
Guido van Rossumbce56a62007-05-10 18:04:33 +00002448 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2449 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002450 return NULL;
2451
2452 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2453 if (tuple == NULL)
2454 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002455 result = wrap_strftime((PyObject *)self, format, tuple,
2456 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002457 Py_DECREF(tuple);
2458 return result;
2459}
2460
2461/* ISO methods. */
2462
2463static PyObject *
2464date_isoweekday(PyDateTime_Date *self)
2465{
2466 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2467
2468 return PyInt_FromLong(dow + 1);
2469}
2470
2471static PyObject *
2472date_isocalendar(PyDateTime_Date *self)
2473{
2474 int year = GET_YEAR(self);
2475 int week1_monday = iso_week1_monday(year);
2476 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2477 int week;
2478 int day;
2479
2480 week = divmod(today - week1_monday, 7, &day);
2481 if (week < 0) {
2482 --year;
2483 week1_monday = iso_week1_monday(year);
2484 week = divmod(today - week1_monday, 7, &day);
2485 }
2486 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2487 ++year;
2488 week = 0;
2489 }
2490 return Py_BuildValue("iii", year, week + 1, day + 1);
2491}
2492
2493/* Miscellaneous methods. */
2494
Tim Peters2a799bf2002-12-16 20:18:38 +00002495static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002496date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002497{
Guido van Rossum19960592006-08-24 17:29:38 +00002498 if (PyDate_Check(other)) {
2499 int diff = memcmp(((PyDateTime_Date *)self)->data,
2500 ((PyDateTime_Date *)other)->data,
2501 _PyDateTime_DATE_DATASIZE);
2502 return diff_to_bool(diff, op);
2503 }
2504 else {
Tim Peters07534a62003-02-07 22:50:28 +00002505 Py_INCREF(Py_NotImplemented);
2506 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002507 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002508}
2509
2510static PyObject *
2511date_timetuple(PyDateTime_Date *self)
2512{
2513 return build_struct_time(GET_YEAR(self),
2514 GET_MONTH(self),
2515 GET_DAY(self),
2516 0, 0, 0, -1);
2517}
2518
Tim Peters12bf3392002-12-24 05:41:27 +00002519static PyObject *
2520date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2521{
2522 PyObject *clone;
2523 PyObject *tuple;
2524 int year = GET_YEAR(self);
2525 int month = GET_MONTH(self);
2526 int day = GET_DAY(self);
2527
2528 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2529 &year, &month, &day))
2530 return NULL;
2531 tuple = Py_BuildValue("iii", year, month, day);
2532 if (tuple == NULL)
2533 return NULL;
2534 clone = date_new(self->ob_type, tuple, NULL);
2535 Py_DECREF(tuple);
2536 return clone;
2537}
2538
Tim Peters2a799bf2002-12-16 20:18:38 +00002539static PyObject *date_getstate(PyDateTime_Date *self);
2540
2541static long
2542date_hash(PyDateTime_Date *self)
2543{
2544 if (self->hashcode == -1) {
2545 PyObject *temp = date_getstate(self);
2546 if (temp != NULL) {
2547 self->hashcode = PyObject_Hash(temp);
2548 Py_DECREF(temp);
2549 }
2550 }
2551 return self->hashcode;
2552}
2553
2554static PyObject *
2555date_toordinal(PyDateTime_Date *self)
2556{
2557 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2558 GET_DAY(self)));
2559}
2560
2561static PyObject *
2562date_weekday(PyDateTime_Date *self)
2563{
2564 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2565
2566 return PyInt_FromLong(dow);
2567}
2568
Tim Peters371935f2003-02-01 01:52:50 +00002569/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002570
Tim Petersb57f8f02003-02-01 02:54:15 +00002571/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002572static PyObject *
2573date_getstate(PyDateTime_Date *self)
2574{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002575 return Py_BuildValue(
2576 "(N)",
2577 PyString_FromStringAndSize((char *)self->data,
2578 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002579}
2580
2581static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002582date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002583{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002584 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002585}
2586
2587static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002588
Tim Peters2a799bf2002-12-16 20:18:38 +00002589 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002590
Tim Peters2a799bf2002-12-16 20:18:38 +00002591 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2592 METH_CLASS,
2593 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2594 "time.time()).")},
2595
2596 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2597 METH_CLASS,
2598 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2599 "ordinal.")},
2600
2601 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2602 PyDoc_STR("Current date or datetime: same as "
2603 "self.__class__.fromtimestamp(time.time()).")},
2604
2605 /* Instance methods: */
2606
2607 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2608 PyDoc_STR("Return ctime() style string.")},
2609
2610 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2611 PyDoc_STR("format -> strftime() style string.")},
2612
2613 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2614 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2615
2616 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2617 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2618 "weekday.")},
2619
2620 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2621 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2622
2623 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2624 PyDoc_STR("Return the day of the week represented by the date.\n"
2625 "Monday == 1 ... Sunday == 7")},
2626
2627 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2628 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2629 "1 is day 1.")},
2630
2631 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2632 PyDoc_STR("Return the day of the week represented by the date.\n"
2633 "Monday == 0 ... Sunday == 6")},
2634
Tim Peters12bf3392002-12-24 05:41:27 +00002635 {"replace", (PyCFunction)date_replace, METH_KEYWORDS,
2636 PyDoc_STR("Return date with new specified fields.")},
2637
Guido van Rossum177e41a2003-01-30 22:06:23 +00002638 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2639 PyDoc_STR("__reduce__() -> (cls, state)")},
2640
Tim Peters2a799bf2002-12-16 20:18:38 +00002641 {NULL, NULL}
2642};
2643
2644static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002645PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002646
2647static PyNumberMethods date_as_number = {
2648 date_add, /* nb_add */
2649 date_subtract, /* nb_subtract */
2650 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002651 0, /* nb_remainder */
2652 0, /* nb_divmod */
2653 0, /* nb_power */
2654 0, /* nb_negative */
2655 0, /* nb_positive */
2656 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002657 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002658};
2659
2660static PyTypeObject PyDateTime_DateType = {
2661 PyObject_HEAD_INIT(NULL)
2662 0, /* ob_size */
2663 "datetime.date", /* tp_name */
2664 sizeof(PyDateTime_Date), /* tp_basicsize */
2665 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002666 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002667 0, /* tp_print */
2668 0, /* tp_getattr */
2669 0, /* tp_setattr */
2670 0, /* tp_compare */
2671 (reprfunc)date_repr, /* tp_repr */
2672 &date_as_number, /* tp_as_number */
2673 0, /* tp_as_sequence */
2674 0, /* tp_as_mapping */
2675 (hashfunc)date_hash, /* tp_hash */
2676 0, /* tp_call */
2677 (reprfunc)date_str, /* tp_str */
2678 PyObject_GenericGetAttr, /* tp_getattro */
2679 0, /* tp_setattro */
2680 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002681 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002682 date_doc, /* tp_doc */
2683 0, /* tp_traverse */
2684 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002685 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002686 0, /* tp_weaklistoffset */
2687 0, /* tp_iter */
2688 0, /* tp_iternext */
2689 date_methods, /* tp_methods */
2690 0, /* tp_members */
2691 date_getset, /* tp_getset */
2692 0, /* tp_base */
2693 0, /* tp_dict */
2694 0, /* tp_descr_get */
2695 0, /* tp_descr_set */
2696 0, /* tp_dictoffset */
2697 0, /* tp_init */
2698 0, /* tp_alloc */
2699 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002700 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002701};
2702
2703/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002704 * PyDateTime_TZInfo implementation.
2705 */
2706
2707/* This is a pure abstract base class, so doesn't do anything beyond
2708 * raising NotImplemented exceptions. Real tzinfo classes need
2709 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002710 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002711 * be subclasses of this tzinfo class, which is easy and quick to check).
2712 *
2713 * Note: For reasons having to do with pickling of subclasses, we have
2714 * to allow tzinfo objects to be instantiated. This wasn't an issue
2715 * in the Python implementation (__init__() could raise NotImplementedError
2716 * there without ill effect), but doing so in the C implementation hit a
2717 * brick wall.
2718 */
2719
2720static PyObject *
2721tzinfo_nogo(const char* methodname)
2722{
2723 PyErr_Format(PyExc_NotImplementedError,
2724 "a tzinfo subclass must implement %s()",
2725 methodname);
2726 return NULL;
2727}
2728
2729/* Methods. A subclass must implement these. */
2730
Tim Peters52dcce22003-01-23 16:36:11 +00002731static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002732tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2733{
2734 return tzinfo_nogo("tzname");
2735}
2736
Tim Peters52dcce22003-01-23 16:36:11 +00002737static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002738tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2739{
2740 return tzinfo_nogo("utcoffset");
2741}
2742
Tim Peters52dcce22003-01-23 16:36:11 +00002743static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002744tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2745{
2746 return tzinfo_nogo("dst");
2747}
2748
Tim Peters52dcce22003-01-23 16:36:11 +00002749static PyObject *
2750tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2751{
2752 int y, m, d, hh, mm, ss, us;
2753
2754 PyObject *result;
2755 int off, dst;
2756 int none;
2757 int delta;
2758
2759 if (! PyDateTime_Check(dt)) {
2760 PyErr_SetString(PyExc_TypeError,
2761 "fromutc: argument must be a datetime");
2762 return NULL;
2763 }
2764 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2765 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2766 "is not self");
2767 return NULL;
2768 }
2769
2770 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2771 if (off == -1 && PyErr_Occurred())
2772 return NULL;
2773 if (none) {
2774 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2775 "utcoffset() result required");
2776 return NULL;
2777 }
2778
2779 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2780 if (dst == -1 && PyErr_Occurred())
2781 return NULL;
2782 if (none) {
2783 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2784 "dst() result required");
2785 return NULL;
2786 }
2787
2788 y = GET_YEAR(dt);
2789 m = GET_MONTH(dt);
2790 d = GET_DAY(dt);
2791 hh = DATE_GET_HOUR(dt);
2792 mm = DATE_GET_MINUTE(dt);
2793 ss = DATE_GET_SECOND(dt);
2794 us = DATE_GET_MICROSECOND(dt);
2795
2796 delta = off - dst;
2797 mm += delta;
2798 if ((mm < 0 || mm >= 60) &&
2799 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002800 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002801 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2802 if (result == NULL)
2803 return result;
2804
2805 dst = call_dst(dt->tzinfo, result, &none);
2806 if (dst == -1 && PyErr_Occurred())
2807 goto Fail;
2808 if (none)
2809 goto Inconsistent;
2810 if (dst == 0)
2811 return result;
2812
2813 mm += dst;
2814 if ((mm < 0 || mm >= 60) &&
2815 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2816 goto Fail;
2817 Py_DECREF(result);
2818 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2819 return result;
2820
2821Inconsistent:
2822 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2823 "inconsistent results; cannot convert");
2824
2825 /* fall thru to failure */
2826Fail:
2827 Py_DECREF(result);
2828 return NULL;
2829}
2830
Tim Peters2a799bf2002-12-16 20:18:38 +00002831/*
2832 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002833 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002834 */
2835
Guido van Rossum177e41a2003-01-30 22:06:23 +00002836static PyObject *
2837tzinfo_reduce(PyObject *self)
2838{
2839 PyObject *args, *state, *tmp;
2840 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002841
Guido van Rossum177e41a2003-01-30 22:06:23 +00002842 tmp = PyTuple_New(0);
2843 if (tmp == NULL)
2844 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002845
Guido van Rossum177e41a2003-01-30 22:06:23 +00002846 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2847 if (getinitargs != NULL) {
2848 args = PyObject_CallObject(getinitargs, tmp);
2849 Py_DECREF(getinitargs);
2850 if (args == NULL) {
2851 Py_DECREF(tmp);
2852 return NULL;
2853 }
2854 }
2855 else {
2856 PyErr_Clear();
2857 args = tmp;
2858 Py_INCREF(args);
2859 }
2860
2861 getstate = PyObject_GetAttrString(self, "__getstate__");
2862 if (getstate != NULL) {
2863 state = PyObject_CallObject(getstate, tmp);
2864 Py_DECREF(getstate);
2865 if (state == NULL) {
2866 Py_DECREF(args);
2867 Py_DECREF(tmp);
2868 return NULL;
2869 }
2870 }
2871 else {
2872 PyObject **dictptr;
2873 PyErr_Clear();
2874 state = Py_None;
2875 dictptr = _PyObject_GetDictPtr(self);
2876 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2877 state = *dictptr;
2878 Py_INCREF(state);
2879 }
2880
2881 Py_DECREF(tmp);
2882
2883 if (state == Py_None) {
2884 Py_DECREF(state);
2885 return Py_BuildValue("(ON)", self->ob_type, args);
2886 }
2887 else
2888 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2889}
Tim Peters2a799bf2002-12-16 20:18:38 +00002890
2891static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002892
Tim Peters2a799bf2002-12-16 20:18:38 +00002893 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2894 PyDoc_STR("datetime -> string name of time zone.")},
2895
2896 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2897 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2898 "west of UTC).")},
2899
2900 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2901 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2902
Tim Peters52dcce22003-01-23 16:36:11 +00002903 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2904 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2905
Guido van Rossum177e41a2003-01-30 22:06:23 +00002906 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2907 PyDoc_STR("-> (cls, state)")},
2908
Tim Peters2a799bf2002-12-16 20:18:38 +00002909 {NULL, NULL}
2910};
2911
2912static char tzinfo_doc[] =
2913PyDoc_STR("Abstract base class for time zone info objects.");
2914
Neal Norwitz227b5332006-03-22 09:28:35 +00002915static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002916 PyObject_HEAD_INIT(NULL)
2917 0, /* ob_size */
2918 "datetime.tzinfo", /* tp_name */
2919 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2920 0, /* tp_itemsize */
2921 0, /* tp_dealloc */
2922 0, /* tp_print */
2923 0, /* tp_getattr */
2924 0, /* tp_setattr */
2925 0, /* tp_compare */
2926 0, /* tp_repr */
2927 0, /* tp_as_number */
2928 0, /* tp_as_sequence */
2929 0, /* tp_as_mapping */
2930 0, /* tp_hash */
2931 0, /* tp_call */
2932 0, /* tp_str */
2933 PyObject_GenericGetAttr, /* tp_getattro */
2934 0, /* tp_setattro */
2935 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002936 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002937 tzinfo_doc, /* tp_doc */
2938 0, /* tp_traverse */
2939 0, /* tp_clear */
2940 0, /* tp_richcompare */
2941 0, /* tp_weaklistoffset */
2942 0, /* tp_iter */
2943 0, /* tp_iternext */
2944 tzinfo_methods, /* tp_methods */
2945 0, /* tp_members */
2946 0, /* tp_getset */
2947 0, /* tp_base */
2948 0, /* tp_dict */
2949 0, /* tp_descr_get */
2950 0, /* tp_descr_set */
2951 0, /* tp_dictoffset */
2952 0, /* tp_init */
2953 0, /* tp_alloc */
2954 PyType_GenericNew, /* tp_new */
2955 0, /* tp_free */
2956};
2957
2958/*
Tim Peters37f39822003-01-10 03:49:02 +00002959 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002960 */
2961
Tim Peters37f39822003-01-10 03:49:02 +00002962/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002963 */
2964
2965static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002966time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002967{
Tim Peters37f39822003-01-10 03:49:02 +00002968 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002969}
2970
Tim Peters37f39822003-01-10 03:49:02 +00002971static PyObject *
2972time_minute(PyDateTime_Time *self, void *unused)
2973{
2974 return PyInt_FromLong(TIME_GET_MINUTE(self));
2975}
2976
2977/* The name time_second conflicted with some platform header file. */
2978static PyObject *
2979py_time_second(PyDateTime_Time *self, void *unused)
2980{
2981 return PyInt_FromLong(TIME_GET_SECOND(self));
2982}
2983
2984static PyObject *
2985time_microsecond(PyDateTime_Time *self, void *unused)
2986{
2987 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2988}
2989
2990static PyObject *
2991time_tzinfo(PyDateTime_Time *self, void *unused)
2992{
Tim Petersa032d2e2003-01-11 00:15:54 +00002993 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002994 Py_INCREF(result);
2995 return result;
2996}
2997
2998static PyGetSetDef time_getset[] = {
2999 {"hour", (getter)time_hour},
3000 {"minute", (getter)time_minute},
3001 {"second", (getter)py_time_second},
3002 {"microsecond", (getter)time_microsecond},
3003 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003004 {NULL}
3005};
3006
3007/*
3008 * Constructors.
3009 */
3010
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003011static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003012 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003013
Tim Peters2a799bf2002-12-16 20:18:38 +00003014static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003015time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003016{
3017 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003018 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003019 int hour = 0;
3020 int minute = 0;
3021 int second = 0;
3022 int usecond = 0;
3023 PyObject *tzinfo = Py_None;
3024
Guido van Rossum177e41a2003-01-30 22:06:23 +00003025 /* Check for invocation from pickle with __getstate__ state */
3026 if (PyTuple_GET_SIZE(args) >= 1 &&
3027 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003028 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003029 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3030 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003031 {
Tim Peters70533e22003-02-01 04:40:04 +00003032 PyDateTime_Time *me;
3033 char aware;
3034
3035 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003036 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003037 if (check_tzinfo_subclass(tzinfo) < 0) {
3038 PyErr_SetString(PyExc_TypeError, "bad "
3039 "tzinfo state arg");
3040 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003041 }
3042 }
Tim Peters70533e22003-02-01 04:40:04 +00003043 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003044 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003045 if (me != NULL) {
3046 char *pdata = PyString_AS_STRING(state);
3047
3048 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3049 me->hashcode = -1;
3050 me->hastzinfo = aware;
3051 if (aware) {
3052 Py_INCREF(tzinfo);
3053 me->tzinfo = tzinfo;
3054 }
3055 }
3056 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003057 }
3058
Tim Peters37f39822003-01-10 03:49:02 +00003059 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003060 &hour, &minute, &second, &usecond,
3061 &tzinfo)) {
3062 if (check_time_args(hour, minute, second, usecond) < 0)
3063 return NULL;
3064 if (check_tzinfo_subclass(tzinfo) < 0)
3065 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003066 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3067 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003068 }
3069 return self;
3070}
3071
3072/*
3073 * Destructor.
3074 */
3075
3076static void
Tim Peters37f39822003-01-10 03:49:02 +00003077time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003078{
Tim Petersa032d2e2003-01-11 00:15:54 +00003079 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003080 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003081 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003082 self->ob_type->tp_free((PyObject *)self);
3083}
3084
3085/*
Tim Peters855fe882002-12-22 03:43:39 +00003086 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003087 */
3088
Tim Peters2a799bf2002-12-16 20:18:38 +00003089/* These are all METH_NOARGS, so don't need to check the arglist. */
3090static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003091time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003092 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003093 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003094}
3095
3096static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003097time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003098 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003099 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003100}
3101
3102static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003103time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003104 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003105 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003106}
3107
3108/*
Tim Peters37f39822003-01-10 03:49:02 +00003109 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003110 */
3111
3112static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003113time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003114{
Tim Peters37f39822003-01-10 03:49:02 +00003115 char buffer[100];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003116 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003117 int h = TIME_GET_HOUR(self);
3118 int m = TIME_GET_MINUTE(self);
3119 int s = TIME_GET_SECOND(self);
3120 int us = TIME_GET_MICROSECOND(self);
3121 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003122
Tim Peters37f39822003-01-10 03:49:02 +00003123 if (us)
3124 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003125 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003126 else if (s)
3127 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003128 "%s(%d, %d, %d)", type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003129 else
3130 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003131 "%s(%d, %d)", type_name, h, m);
Tim Peters37f39822003-01-10 03:49:02 +00003132 result = PyString_FromString(buffer);
Tim Petersa032d2e2003-01-11 00:15:54 +00003133 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003134 result = append_keyword_tzinfo(result, self->tzinfo);
3135 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003136}
3137
Tim Peters37f39822003-01-10 03:49:02 +00003138static PyObject *
3139time_str(PyDateTime_Time *self)
3140{
3141 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3142}
Tim Peters2a799bf2002-12-16 20:18:38 +00003143
3144static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003145time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003146{
3147 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003148 PyObject *result;
3149 /* Reuse the time format code from the datetime type. */
3150 PyDateTime_DateTime datetime;
3151 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003152
Tim Peters37f39822003-01-10 03:49:02 +00003153 /* Copy over just the time bytes. */
3154 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3155 self->data,
3156 _PyDateTime_TIME_DATASIZE);
3157
3158 isoformat_time(pdatetime, buf, sizeof(buf));
3159 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003160 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003161 return result;
3162
3163 /* We need to append the UTC offset. */
3164 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003165 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003166 Py_DECREF(result);
3167 return NULL;
3168 }
3169 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3170 return result;
3171}
3172
Tim Peters37f39822003-01-10 03:49:02 +00003173static PyObject *
3174time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3175{
3176 PyObject *result;
3177 PyObject *format;
3178 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003179 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003180
Guido van Rossumbce56a62007-05-10 18:04:33 +00003181 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3182 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003183 return NULL;
3184
3185 /* Python's strftime does insane things with the year part of the
3186 * timetuple. The year is forced to (the otherwise nonsensical)
3187 * 1900 to worm around that.
3188 */
3189 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003190 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003191 TIME_GET_HOUR(self),
3192 TIME_GET_MINUTE(self),
3193 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003194 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003195 if (tuple == NULL)
3196 return NULL;
3197 assert(PyTuple_Size(tuple) == 9);
3198 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3199 Py_DECREF(tuple);
3200 return result;
3201}
Tim Peters2a799bf2002-12-16 20:18:38 +00003202
3203/*
3204 * Miscellaneous methods.
3205 */
3206
Tim Peters37f39822003-01-10 03:49:02 +00003207static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003208time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003209{
3210 int diff;
3211 naivety n1, n2;
3212 int offset1, offset2;
3213
3214 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003215 Py_INCREF(Py_NotImplemented);
3216 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003217 }
Guido van Rossum19960592006-08-24 17:29:38 +00003218 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3219 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003220 return NULL;
3221 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3222 /* If they're both naive, or both aware and have the same offsets,
3223 * we get off cheap. Note that if they're both naive, offset1 ==
3224 * offset2 == 0 at this point.
3225 */
3226 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003227 diff = memcmp(((PyDateTime_Time *)self)->data,
3228 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003229 _PyDateTime_TIME_DATASIZE);
3230 return diff_to_bool(diff, op);
3231 }
3232
3233 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3234 assert(offset1 != offset2); /* else last "if" handled it */
3235 /* Convert everything except microseconds to seconds. These
3236 * can't overflow (no more than the # of seconds in 2 days).
3237 */
3238 offset1 = TIME_GET_HOUR(self) * 3600 +
3239 (TIME_GET_MINUTE(self) - offset1) * 60 +
3240 TIME_GET_SECOND(self);
3241 offset2 = TIME_GET_HOUR(other) * 3600 +
3242 (TIME_GET_MINUTE(other) - offset2) * 60 +
3243 TIME_GET_SECOND(other);
3244 diff = offset1 - offset2;
3245 if (diff == 0)
3246 diff = TIME_GET_MICROSECOND(self) -
3247 TIME_GET_MICROSECOND(other);
3248 return diff_to_bool(diff, op);
3249 }
3250
3251 assert(n1 != n2);
3252 PyErr_SetString(PyExc_TypeError,
3253 "can't compare offset-naive and "
3254 "offset-aware times");
3255 return NULL;
3256}
3257
3258static long
3259time_hash(PyDateTime_Time *self)
3260{
3261 if (self->hashcode == -1) {
3262 naivety n;
3263 int offset;
3264 PyObject *temp;
3265
3266 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3267 assert(n != OFFSET_UNKNOWN);
3268 if (n == OFFSET_ERROR)
3269 return -1;
3270
3271 /* Reduce this to a hash of another object. */
3272 if (offset == 0)
3273 temp = PyString_FromStringAndSize((char *)self->data,
3274 _PyDateTime_TIME_DATASIZE);
3275 else {
3276 int hour;
3277 int minute;
3278
3279 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003280 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003281 hour = divmod(TIME_GET_HOUR(self) * 60 +
3282 TIME_GET_MINUTE(self) - offset,
3283 60,
3284 &minute);
3285 if (0 <= hour && hour < 24)
3286 temp = new_time(hour, minute,
3287 TIME_GET_SECOND(self),
3288 TIME_GET_MICROSECOND(self),
3289 Py_None);
3290 else
3291 temp = Py_BuildValue("iiii",
3292 hour, minute,
3293 TIME_GET_SECOND(self),
3294 TIME_GET_MICROSECOND(self));
3295 }
3296 if (temp != NULL) {
3297 self->hashcode = PyObject_Hash(temp);
3298 Py_DECREF(temp);
3299 }
3300 }
3301 return self->hashcode;
3302}
Tim Peters2a799bf2002-12-16 20:18:38 +00003303
Tim Peters12bf3392002-12-24 05:41:27 +00003304static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003305time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003306{
3307 PyObject *clone;
3308 PyObject *tuple;
3309 int hh = TIME_GET_HOUR(self);
3310 int mm = TIME_GET_MINUTE(self);
3311 int ss = TIME_GET_SECOND(self);
3312 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003313 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003314
3315 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003316 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003317 &hh, &mm, &ss, &us, &tzinfo))
3318 return NULL;
3319 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3320 if (tuple == NULL)
3321 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003322 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003323 Py_DECREF(tuple);
3324 return clone;
3325}
3326
Tim Peters2a799bf2002-12-16 20:18:38 +00003327static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003328time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003329{
3330 int offset;
3331 int none;
3332
3333 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3334 /* Since utcoffset is in whole minutes, nothing can
3335 * alter the conclusion that this is nonzero.
3336 */
3337 return 1;
3338 }
3339 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003340 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003341 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003342 if (offset == -1 && PyErr_Occurred())
3343 return -1;
3344 }
3345 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3346}
3347
Tim Peters371935f2003-02-01 01:52:50 +00003348/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003349
Tim Peters33e0f382003-01-10 02:05:14 +00003350/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003351 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3352 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003353 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003354 */
3355static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003356time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003357{
3358 PyObject *basestate;
3359 PyObject *result = NULL;
3360
Tim Peters33e0f382003-01-10 02:05:14 +00003361 basestate = PyString_FromStringAndSize((char *)self->data,
3362 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003363 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003364 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003365 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003366 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003367 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003368 Py_DECREF(basestate);
3369 }
3370 return result;
3371}
3372
3373static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003374time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003375{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003376 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003377}
3378
Tim Peters37f39822003-01-10 03:49:02 +00003379static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003380
Thomas Wouterscf297e42007-02-23 15:07:44 +00003381 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003382 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3383 "[+HH:MM].")},
3384
Tim Peters37f39822003-01-10 03:49:02 +00003385 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3386 PyDoc_STR("format -> strftime() style string.")},
3387
3388 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003389 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3390
Tim Peters37f39822003-01-10 03:49:02 +00003391 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003392 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3393
Tim Peters37f39822003-01-10 03:49:02 +00003394 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003395 PyDoc_STR("Return self.tzinfo.dst(self).")},
3396
Tim Peters37f39822003-01-10 03:49:02 +00003397 {"replace", (PyCFunction)time_replace, METH_KEYWORDS,
3398 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003399
Guido van Rossum177e41a2003-01-30 22:06:23 +00003400 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3401 PyDoc_STR("__reduce__() -> (cls, state)")},
3402
Tim Peters2a799bf2002-12-16 20:18:38 +00003403 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003404};
3405
Tim Peters37f39822003-01-10 03:49:02 +00003406static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003407PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3408\n\
3409All arguments are optional. tzinfo may be None, or an instance of\n\
3410a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003411
Tim Peters37f39822003-01-10 03:49:02 +00003412static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003413 0, /* nb_add */
3414 0, /* nb_subtract */
3415 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003416 0, /* nb_remainder */
3417 0, /* nb_divmod */
3418 0, /* nb_power */
3419 0, /* nb_negative */
3420 0, /* nb_positive */
3421 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003422 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003423};
3424
Neal Norwitz227b5332006-03-22 09:28:35 +00003425static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003426 PyObject_HEAD_INIT(NULL)
3427 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003428 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003429 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003430 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003431 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003432 0, /* tp_print */
3433 0, /* tp_getattr */
3434 0, /* tp_setattr */
3435 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003436 (reprfunc)time_repr, /* tp_repr */
3437 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003438 0, /* tp_as_sequence */
3439 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003440 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003441 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003442 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003443 PyObject_GenericGetAttr, /* tp_getattro */
3444 0, /* tp_setattro */
3445 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003446 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003447 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003448 0, /* tp_traverse */
3449 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003450 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003451 0, /* tp_weaklistoffset */
3452 0, /* tp_iter */
3453 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003454 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003455 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003456 time_getset, /* tp_getset */
3457 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003458 0, /* tp_dict */
3459 0, /* tp_descr_get */
3460 0, /* tp_descr_set */
3461 0, /* tp_dictoffset */
3462 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003463 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003464 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003465 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003466};
3467
3468/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003469 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003470 */
3471
Tim Petersa9bc1682003-01-11 03:39:11 +00003472/* Accessor properties. Properties for day, month, and year are inherited
3473 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003474 */
3475
3476static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003477datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003478{
Tim Petersa9bc1682003-01-11 03:39:11 +00003479 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003480}
3481
Tim Petersa9bc1682003-01-11 03:39:11 +00003482static PyObject *
3483datetime_minute(PyDateTime_DateTime *self, void *unused)
3484{
3485 return PyInt_FromLong(DATE_GET_MINUTE(self));
3486}
3487
3488static PyObject *
3489datetime_second(PyDateTime_DateTime *self, void *unused)
3490{
3491 return PyInt_FromLong(DATE_GET_SECOND(self));
3492}
3493
3494static PyObject *
3495datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3496{
3497 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3498}
3499
3500static PyObject *
3501datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3502{
3503 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3504 Py_INCREF(result);
3505 return result;
3506}
3507
3508static PyGetSetDef datetime_getset[] = {
3509 {"hour", (getter)datetime_hour},
3510 {"minute", (getter)datetime_minute},
3511 {"second", (getter)datetime_second},
3512 {"microsecond", (getter)datetime_microsecond},
3513 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003514 {NULL}
3515};
3516
3517/*
3518 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003519 */
3520
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003521static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003522 "year", "month", "day", "hour", "minute", "second",
3523 "microsecond", "tzinfo", NULL
3524};
3525
Tim Peters2a799bf2002-12-16 20:18:38 +00003526static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003527datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003528{
3529 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003530 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003531 int year;
3532 int month;
3533 int day;
3534 int hour = 0;
3535 int minute = 0;
3536 int second = 0;
3537 int usecond = 0;
3538 PyObject *tzinfo = Py_None;
3539
Guido van Rossum177e41a2003-01-30 22:06:23 +00003540 /* Check for invocation from pickle with __getstate__ state */
3541 if (PyTuple_GET_SIZE(args) >= 1 &&
3542 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003543 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003544 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3545 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003546 {
Tim Peters70533e22003-02-01 04:40:04 +00003547 PyDateTime_DateTime *me;
3548 char aware;
3549
3550 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003551 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003552 if (check_tzinfo_subclass(tzinfo) < 0) {
3553 PyErr_SetString(PyExc_TypeError, "bad "
3554 "tzinfo state arg");
3555 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003556 }
3557 }
Tim Peters70533e22003-02-01 04:40:04 +00003558 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003559 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003560 if (me != NULL) {
3561 char *pdata = PyString_AS_STRING(state);
3562
3563 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3564 me->hashcode = -1;
3565 me->hastzinfo = aware;
3566 if (aware) {
3567 Py_INCREF(tzinfo);
3568 me->tzinfo = tzinfo;
3569 }
3570 }
3571 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003572 }
3573
Tim Petersa9bc1682003-01-11 03:39:11 +00003574 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003575 &year, &month, &day, &hour, &minute,
3576 &second, &usecond, &tzinfo)) {
3577 if (check_date_args(year, month, day) < 0)
3578 return NULL;
3579 if (check_time_args(hour, minute, second, usecond) < 0)
3580 return NULL;
3581 if (check_tzinfo_subclass(tzinfo) < 0)
3582 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003583 self = new_datetime_ex(year, month, day,
3584 hour, minute, second, usecond,
3585 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003586 }
3587 return self;
3588}
3589
Tim Petersa9bc1682003-01-11 03:39:11 +00003590/* TM_FUNC is the shared type of localtime() and gmtime(). */
3591typedef struct tm *(*TM_FUNC)(const time_t *timer);
3592
3593/* Internal helper.
3594 * Build datetime from a time_t and a distinct count of microseconds.
3595 * Pass localtime or gmtime for f, to control the interpretation of timet.
3596 */
3597static PyObject *
3598datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3599 PyObject *tzinfo)
3600{
3601 struct tm *tm;
3602 PyObject *result = NULL;
3603
3604 tm = f(&timet);
3605 if (tm) {
3606 /* The platform localtime/gmtime may insert leap seconds,
3607 * indicated by tm->tm_sec > 59. We don't care about them,
3608 * except to the extent that passing them on to the datetime
3609 * constructor would raise ValueError for a reason that
3610 * made no sense to the user.
3611 */
3612 if (tm->tm_sec > 59)
3613 tm->tm_sec = 59;
3614 result = PyObject_CallFunction(cls, "iiiiiiiO",
3615 tm->tm_year + 1900,
3616 tm->tm_mon + 1,
3617 tm->tm_mday,
3618 tm->tm_hour,
3619 tm->tm_min,
3620 tm->tm_sec,
3621 us,
3622 tzinfo);
3623 }
3624 else
3625 PyErr_SetString(PyExc_ValueError,
3626 "timestamp out of range for "
3627 "platform localtime()/gmtime() function");
3628 return result;
3629}
3630
3631/* Internal helper.
3632 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3633 * to control the interpretation of the timestamp. Since a double doesn't
3634 * have enough bits to cover a datetime's full range of precision, it's
3635 * better to call datetime_from_timet_and_us provided you have a way
3636 * to get that much precision (e.g., C time() isn't good enough).
3637 */
3638static PyObject *
3639datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3640 PyObject *tzinfo)
3641{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003642 time_t timet;
3643 double fraction;
3644 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003645
Tim Peters1b6f7a92004-06-20 02:50:16 +00003646 timet = _PyTime_DoubleToTimet(timestamp);
3647 if (timet == (time_t)-1 && PyErr_Occurred())
3648 return NULL;
3649 fraction = timestamp - (double)timet;
3650 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003651 if (us < 0) {
3652 /* Truncation towards zero is not what we wanted
3653 for negative numbers (Python's mod semantics) */
3654 timet -= 1;
3655 us += 1000000;
3656 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003657 /* If timestamp is less than one microsecond smaller than a
3658 * full second, round up. Otherwise, ValueErrors are raised
3659 * for some floats. */
3660 if (us == 1000000) {
3661 timet += 1;
3662 us = 0;
3663 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003664 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3665}
3666
3667/* Internal helper.
3668 * Build most accurate possible datetime for current time. Pass localtime or
3669 * gmtime for f as appropriate.
3670 */
3671static PyObject *
3672datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3673{
3674#ifdef HAVE_GETTIMEOFDAY
3675 struct timeval t;
3676
3677#ifdef GETTIMEOFDAY_NO_TZ
3678 gettimeofday(&t);
3679#else
3680 gettimeofday(&t, (struct timezone *)NULL);
3681#endif
3682 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3683 tzinfo);
3684
3685#else /* ! HAVE_GETTIMEOFDAY */
3686 /* No flavor of gettimeofday exists on this platform. Python's
3687 * time.time() does a lot of other platform tricks to get the
3688 * best time it can on the platform, and we're not going to do
3689 * better than that (if we could, the better code would belong
3690 * in time.time()!) We're limited by the precision of a double,
3691 * though.
3692 */
3693 PyObject *time;
3694 double dtime;
3695
3696 time = time_time();
3697 if (time == NULL)
3698 return NULL;
3699 dtime = PyFloat_AsDouble(time);
3700 Py_DECREF(time);
3701 if (dtime == -1.0 && PyErr_Occurred())
3702 return NULL;
3703 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3704#endif /* ! HAVE_GETTIMEOFDAY */
3705}
3706
Tim Peters2a799bf2002-12-16 20:18:38 +00003707/* Return best possible local time -- this isn't constrained by the
3708 * precision of a timestamp.
3709 */
3710static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003711datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003712{
Tim Peters10cadce2003-01-23 19:58:02 +00003713 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003714 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003715 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003716
Tim Peters10cadce2003-01-23 19:58:02 +00003717 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3718 &tzinfo))
3719 return NULL;
3720 if (check_tzinfo_subclass(tzinfo) < 0)
3721 return NULL;
3722
3723 self = datetime_best_possible(cls,
3724 tzinfo == Py_None ? localtime : gmtime,
3725 tzinfo);
3726 if (self != NULL && tzinfo != Py_None) {
3727 /* Convert UTC to tzinfo's zone. */
3728 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003729 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003730 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003731 }
3732 return self;
3733}
3734
Tim Petersa9bc1682003-01-11 03:39:11 +00003735/* Return best possible UTC time -- this isn't constrained by the
3736 * precision of a timestamp.
3737 */
3738static PyObject *
3739datetime_utcnow(PyObject *cls, PyObject *dummy)
3740{
3741 return datetime_best_possible(cls, gmtime, Py_None);
3742}
3743
Tim Peters2a799bf2002-12-16 20:18:38 +00003744/* Return new local datetime from timestamp (Python timestamp -- a double). */
3745static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003746datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003747{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003748 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003749 double timestamp;
3750 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003751 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003752
Tim Peters2a44a8d2003-01-23 20:53:10 +00003753 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3754 keywords, &timestamp, &tzinfo))
3755 return NULL;
3756 if (check_tzinfo_subclass(tzinfo) < 0)
3757 return NULL;
3758
3759 self = datetime_from_timestamp(cls,
3760 tzinfo == Py_None ? localtime : gmtime,
3761 timestamp,
3762 tzinfo);
3763 if (self != NULL && tzinfo != Py_None) {
3764 /* Convert UTC to tzinfo's zone. */
3765 PyObject *temp = self;
3766 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3767 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003768 }
3769 return self;
3770}
3771
Tim Petersa9bc1682003-01-11 03:39:11 +00003772/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3773static PyObject *
3774datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3775{
3776 double timestamp;
3777 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003778
Tim Petersa9bc1682003-01-11 03:39:11 +00003779 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3780 result = datetime_from_timestamp(cls, gmtime, timestamp,
3781 Py_None);
3782 return result;
3783}
3784
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003785/* Return new datetime from time.strptime(). */
3786static PyObject *
3787datetime_strptime(PyObject *cls, PyObject *args)
3788{
3789 PyObject *result = NULL, *obj, *module;
3790 const char *string, *format;
3791
3792 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3793 return NULL;
3794
3795 if ((module = PyImport_ImportModule("time")) == NULL)
3796 return NULL;
3797 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3798 Py_DECREF(module);
3799
3800 if (obj != NULL) {
3801 int i, good_timetuple = 1;
3802 long int ia[6];
3803 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3804 for (i=0; i < 6; i++) {
3805 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003806 if (p == NULL) {
3807 Py_DECREF(obj);
3808 return NULL;
3809 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003810 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003811 ia[i] = PyInt_AsLong(p);
3812 else
3813 good_timetuple = 0;
3814 Py_DECREF(p);
3815 }
3816 else
3817 good_timetuple = 0;
3818 if (good_timetuple)
3819 result = PyObject_CallFunction(cls, "iiiiii",
3820 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3821 else
3822 PyErr_SetString(PyExc_ValueError,
3823 "unexpected value from time.strptime");
3824 Py_DECREF(obj);
3825 }
3826 return result;
3827}
3828
Tim Petersa9bc1682003-01-11 03:39:11 +00003829/* Return new datetime from date/datetime and time arguments. */
3830static PyObject *
3831datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3832{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003833 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003834 PyObject *date;
3835 PyObject *time;
3836 PyObject *result = NULL;
3837
3838 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3839 &PyDateTime_DateType, &date,
3840 &PyDateTime_TimeType, &time)) {
3841 PyObject *tzinfo = Py_None;
3842
3843 if (HASTZINFO(time))
3844 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3845 result = PyObject_CallFunction(cls, "iiiiiiiO",
3846 GET_YEAR(date),
3847 GET_MONTH(date),
3848 GET_DAY(date),
3849 TIME_GET_HOUR(time),
3850 TIME_GET_MINUTE(time),
3851 TIME_GET_SECOND(time),
3852 TIME_GET_MICROSECOND(time),
3853 tzinfo);
3854 }
3855 return result;
3856}
Tim Peters2a799bf2002-12-16 20:18:38 +00003857
3858/*
3859 * Destructor.
3860 */
3861
3862static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003863datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003864{
Tim Petersa9bc1682003-01-11 03:39:11 +00003865 if (HASTZINFO(self)) {
3866 Py_XDECREF(self->tzinfo);
3867 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003868 self->ob_type->tp_free((PyObject *)self);
3869}
3870
3871/*
3872 * Indirect access to tzinfo methods.
3873 */
3874
Tim Peters2a799bf2002-12-16 20:18:38 +00003875/* These are all METH_NOARGS, so don't need to check the arglist. */
3876static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003877datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3878 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3879 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003880}
3881
3882static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003883datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3884 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3885 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003886}
3887
3888static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003889datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3890 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3891 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003892}
3893
3894/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003895 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003896 */
3897
Tim Petersa9bc1682003-01-11 03:39:11 +00003898/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3899 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003900 */
3901static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003902add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3903 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003904{
Tim Petersa9bc1682003-01-11 03:39:11 +00003905 /* Note that the C-level additions can't overflow, because of
3906 * invariant bounds on the member values.
3907 */
3908 int year = GET_YEAR(date);
3909 int month = GET_MONTH(date);
3910 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3911 int hour = DATE_GET_HOUR(date);
3912 int minute = DATE_GET_MINUTE(date);
3913 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3914 int microsecond = DATE_GET_MICROSECOND(date) +
3915 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003916
Tim Petersa9bc1682003-01-11 03:39:11 +00003917 assert(factor == 1 || factor == -1);
3918 if (normalize_datetime(&year, &month, &day,
3919 &hour, &minute, &second, &microsecond) < 0)
3920 return NULL;
3921 else
3922 return new_datetime(year, month, day,
3923 hour, minute, second, microsecond,
3924 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003925}
3926
3927static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003928datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003929{
Tim Petersa9bc1682003-01-11 03:39:11 +00003930 if (PyDateTime_Check(left)) {
3931 /* datetime + ??? */
3932 if (PyDelta_Check(right))
3933 /* datetime + delta */
3934 return add_datetime_timedelta(
3935 (PyDateTime_DateTime *)left,
3936 (PyDateTime_Delta *)right,
3937 1);
3938 }
3939 else if (PyDelta_Check(left)) {
3940 /* delta + datetime */
3941 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3942 (PyDateTime_Delta *) left,
3943 1);
3944 }
3945 Py_INCREF(Py_NotImplemented);
3946 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003947}
3948
3949static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003950datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003951{
3952 PyObject *result = Py_NotImplemented;
3953
3954 if (PyDateTime_Check(left)) {
3955 /* datetime - ??? */
3956 if (PyDateTime_Check(right)) {
3957 /* datetime - datetime */
3958 naivety n1, n2;
3959 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003960 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003961
Tim Peterse39a80c2002-12-30 21:28:52 +00003962 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3963 right, &offset2, &n2,
3964 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003965 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003966 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003967 if (n1 != n2) {
3968 PyErr_SetString(PyExc_TypeError,
3969 "can't subtract offset-naive and "
3970 "offset-aware datetimes");
3971 return NULL;
3972 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003973 delta_d = ymd_to_ord(GET_YEAR(left),
3974 GET_MONTH(left),
3975 GET_DAY(left)) -
3976 ymd_to_ord(GET_YEAR(right),
3977 GET_MONTH(right),
3978 GET_DAY(right));
3979 /* These can't overflow, since the values are
3980 * normalized. At most this gives the number of
3981 * seconds in one day.
3982 */
3983 delta_s = (DATE_GET_HOUR(left) -
3984 DATE_GET_HOUR(right)) * 3600 +
3985 (DATE_GET_MINUTE(left) -
3986 DATE_GET_MINUTE(right)) * 60 +
3987 (DATE_GET_SECOND(left) -
3988 DATE_GET_SECOND(right));
3989 delta_us = DATE_GET_MICROSECOND(left) -
3990 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003991 /* (left - offset1) - (right - offset2) =
3992 * (left - right) + (offset2 - offset1)
3993 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003994 delta_s += (offset2 - offset1) * 60;
3995 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003996 }
3997 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003998 /* datetime - delta */
3999 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004000 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004001 (PyDateTime_Delta *)right,
4002 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004003 }
4004 }
4005
4006 if (result == Py_NotImplemented)
4007 Py_INCREF(result);
4008 return result;
4009}
4010
4011/* Various ways to turn a datetime into a string. */
4012
4013static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004014datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004015{
Tim Petersa9bc1682003-01-11 03:39:11 +00004016 char buffer[1000];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004017 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004018 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004019
Tim Petersa9bc1682003-01-11 03:39:11 +00004020 if (DATE_GET_MICROSECOND(self)) {
4021 PyOS_snprintf(buffer, sizeof(buffer),
4022 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004023 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004024 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4025 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4026 DATE_GET_SECOND(self),
4027 DATE_GET_MICROSECOND(self));
4028 }
4029 else if (DATE_GET_SECOND(self)) {
4030 PyOS_snprintf(buffer, sizeof(buffer),
4031 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004032 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004033 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4034 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4035 DATE_GET_SECOND(self));
4036 }
4037 else {
4038 PyOS_snprintf(buffer, sizeof(buffer),
4039 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004040 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004041 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4042 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4043 }
4044 baserepr = PyString_FromString(buffer);
4045 if (baserepr == NULL || ! HASTZINFO(self))
4046 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004047 return append_keyword_tzinfo(baserepr, self->tzinfo);
4048}
4049
Tim Petersa9bc1682003-01-11 03:39:11 +00004050static PyObject *
4051datetime_str(PyDateTime_DateTime *self)
4052{
4053 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4054}
Tim Peters2a799bf2002-12-16 20:18:38 +00004055
4056static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004057datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004058{
Tim Petersa9bc1682003-01-11 03:39:11 +00004059 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004060 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004061 char buffer[100];
4062 char *cp;
4063 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004064
Tim Petersa9bc1682003-01-11 03:39:11 +00004065 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4066 &sep))
4067 return NULL;
4068 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4069 assert(cp != NULL);
4070 *cp++ = sep;
4071 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4072 result = PyString_FromString(buffer);
4073 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004074 return result;
4075
4076 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004077 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004078 (PyObject *)self) < 0) {
4079 Py_DECREF(result);
4080 return NULL;
4081 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004082 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004083 return result;
4084}
4085
Tim Petersa9bc1682003-01-11 03:39:11 +00004086static PyObject *
4087datetime_ctime(PyDateTime_DateTime *self)
4088{
4089 return format_ctime((PyDateTime_Date *)self,
4090 DATE_GET_HOUR(self),
4091 DATE_GET_MINUTE(self),
4092 DATE_GET_SECOND(self));
4093}
4094
Tim Peters2a799bf2002-12-16 20:18:38 +00004095/* Miscellaneous methods. */
4096
Tim Petersa9bc1682003-01-11 03:39:11 +00004097static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004098datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004099{
4100 int diff;
4101 naivety n1, n2;
4102 int offset1, offset2;
4103
4104 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004105 if (PyDate_Check(other)) {
4106 /* Prevent invocation of date_richcompare. We want to
4107 return NotImplemented here to give the other object
4108 a chance. But since DateTime is a subclass of
4109 Date, if the other object is a Date, it would
4110 compute an ordering based on the date part alone,
4111 and we don't want that. So force unequal or
4112 uncomparable here in that case. */
4113 if (op == Py_EQ)
4114 Py_RETURN_FALSE;
4115 if (op == Py_NE)
4116 Py_RETURN_TRUE;
4117 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004118 }
Guido van Rossum19960592006-08-24 17:29:38 +00004119 Py_INCREF(Py_NotImplemented);
4120 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004121 }
4122
Guido van Rossum19960592006-08-24 17:29:38 +00004123 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4124 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004125 return NULL;
4126 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4127 /* If they're both naive, or both aware and have the same offsets,
4128 * we get off cheap. Note that if they're both naive, offset1 ==
4129 * offset2 == 0 at this point.
4130 */
4131 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004132 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4133 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004134 _PyDateTime_DATETIME_DATASIZE);
4135 return diff_to_bool(diff, op);
4136 }
4137
4138 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4139 PyDateTime_Delta *delta;
4140
4141 assert(offset1 != offset2); /* else last "if" handled it */
4142 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4143 other);
4144 if (delta == NULL)
4145 return NULL;
4146 diff = GET_TD_DAYS(delta);
4147 if (diff == 0)
4148 diff = GET_TD_SECONDS(delta) |
4149 GET_TD_MICROSECONDS(delta);
4150 Py_DECREF(delta);
4151 return diff_to_bool(diff, op);
4152 }
4153
4154 assert(n1 != n2);
4155 PyErr_SetString(PyExc_TypeError,
4156 "can't compare offset-naive and "
4157 "offset-aware datetimes");
4158 return NULL;
4159}
4160
4161static long
4162datetime_hash(PyDateTime_DateTime *self)
4163{
4164 if (self->hashcode == -1) {
4165 naivety n;
4166 int offset;
4167 PyObject *temp;
4168
4169 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4170 &offset);
4171 assert(n != OFFSET_UNKNOWN);
4172 if (n == OFFSET_ERROR)
4173 return -1;
4174
4175 /* Reduce this to a hash of another object. */
4176 if (n == OFFSET_NAIVE)
4177 temp = PyString_FromStringAndSize(
4178 (char *)self->data,
4179 _PyDateTime_DATETIME_DATASIZE);
4180 else {
4181 int days;
4182 int seconds;
4183
4184 assert(n == OFFSET_AWARE);
4185 assert(HASTZINFO(self));
4186 days = ymd_to_ord(GET_YEAR(self),
4187 GET_MONTH(self),
4188 GET_DAY(self));
4189 seconds = DATE_GET_HOUR(self) * 3600 +
4190 (DATE_GET_MINUTE(self) - offset) * 60 +
4191 DATE_GET_SECOND(self);
4192 temp = new_delta(days,
4193 seconds,
4194 DATE_GET_MICROSECOND(self),
4195 1);
4196 }
4197 if (temp != NULL) {
4198 self->hashcode = PyObject_Hash(temp);
4199 Py_DECREF(temp);
4200 }
4201 }
4202 return self->hashcode;
4203}
Tim Peters2a799bf2002-12-16 20:18:38 +00004204
4205static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004206datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004207{
4208 PyObject *clone;
4209 PyObject *tuple;
4210 int y = GET_YEAR(self);
4211 int m = GET_MONTH(self);
4212 int d = GET_DAY(self);
4213 int hh = DATE_GET_HOUR(self);
4214 int mm = DATE_GET_MINUTE(self);
4215 int ss = DATE_GET_SECOND(self);
4216 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004217 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004218
4219 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004220 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004221 &y, &m, &d, &hh, &mm, &ss, &us,
4222 &tzinfo))
4223 return NULL;
4224 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4225 if (tuple == NULL)
4226 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004227 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004228 Py_DECREF(tuple);
4229 return clone;
4230}
4231
4232static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004233datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004234{
Tim Peters52dcce22003-01-23 16:36:11 +00004235 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004236 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004237 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004238
Tim Peters80475bb2002-12-25 07:40:55 +00004239 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004240 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004241
Tim Peters52dcce22003-01-23 16:36:11 +00004242 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4243 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004244 return NULL;
4245
Tim Peters52dcce22003-01-23 16:36:11 +00004246 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4247 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004248
Tim Peters52dcce22003-01-23 16:36:11 +00004249 /* Conversion to self's own time zone is a NOP. */
4250 if (self->tzinfo == tzinfo) {
4251 Py_INCREF(self);
4252 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004253 }
Tim Peters521fc152002-12-31 17:36:56 +00004254
Tim Peters52dcce22003-01-23 16:36:11 +00004255 /* Convert self to UTC. */
4256 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4257 if (offset == -1 && PyErr_Occurred())
4258 return NULL;
4259 if (none)
4260 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004261
Tim Peters52dcce22003-01-23 16:36:11 +00004262 y = GET_YEAR(self);
4263 m = GET_MONTH(self);
4264 d = GET_DAY(self);
4265 hh = DATE_GET_HOUR(self);
4266 mm = DATE_GET_MINUTE(self);
4267 ss = DATE_GET_SECOND(self);
4268 us = DATE_GET_MICROSECOND(self);
4269
4270 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004271 if ((mm < 0 || mm >= 60) &&
4272 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004273 return NULL;
4274
4275 /* Attach new tzinfo and let fromutc() do the rest. */
4276 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4277 if (result != NULL) {
4278 PyObject *temp = result;
4279
4280 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4281 Py_DECREF(temp);
4282 }
Tim Petersadf64202003-01-04 06:03:15 +00004283 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004284
Tim Peters52dcce22003-01-23 16:36:11 +00004285NeedAware:
4286 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4287 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004288 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004289}
4290
4291static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004292datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004293{
4294 int dstflag = -1;
4295
Tim Petersa9bc1682003-01-11 03:39:11 +00004296 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004297 int none;
4298
4299 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4300 if (dstflag == -1 && PyErr_Occurred())
4301 return NULL;
4302
4303 if (none)
4304 dstflag = -1;
4305 else if (dstflag != 0)
4306 dstflag = 1;
4307
4308 }
4309 return build_struct_time(GET_YEAR(self),
4310 GET_MONTH(self),
4311 GET_DAY(self),
4312 DATE_GET_HOUR(self),
4313 DATE_GET_MINUTE(self),
4314 DATE_GET_SECOND(self),
4315 dstflag);
4316}
4317
4318static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004319datetime_getdate(PyDateTime_DateTime *self)
4320{
4321 return new_date(GET_YEAR(self),
4322 GET_MONTH(self),
4323 GET_DAY(self));
4324}
4325
4326static PyObject *
4327datetime_gettime(PyDateTime_DateTime *self)
4328{
4329 return new_time(DATE_GET_HOUR(self),
4330 DATE_GET_MINUTE(self),
4331 DATE_GET_SECOND(self),
4332 DATE_GET_MICROSECOND(self),
4333 Py_None);
4334}
4335
4336static PyObject *
4337datetime_gettimetz(PyDateTime_DateTime *self)
4338{
4339 return new_time(DATE_GET_HOUR(self),
4340 DATE_GET_MINUTE(self),
4341 DATE_GET_SECOND(self),
4342 DATE_GET_MICROSECOND(self),
4343 HASTZINFO(self) ? self->tzinfo : Py_None);
4344}
4345
4346static PyObject *
4347datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004348{
4349 int y = GET_YEAR(self);
4350 int m = GET_MONTH(self);
4351 int d = GET_DAY(self);
4352 int hh = DATE_GET_HOUR(self);
4353 int mm = DATE_GET_MINUTE(self);
4354 int ss = DATE_GET_SECOND(self);
4355 int us = 0; /* microseconds are ignored in a timetuple */
4356 int offset = 0;
4357
Tim Petersa9bc1682003-01-11 03:39:11 +00004358 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004359 int none;
4360
4361 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4362 if (offset == -1 && PyErr_Occurred())
4363 return NULL;
4364 }
4365 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4366 * 0 in a UTC timetuple regardless of what dst() says.
4367 */
4368 if (offset) {
4369 /* Subtract offset minutes & normalize. */
4370 int stat;
4371
4372 mm -= offset;
4373 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4374 if (stat < 0) {
4375 /* At the edges, it's possible we overflowed
4376 * beyond MINYEAR or MAXYEAR.
4377 */
4378 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4379 PyErr_Clear();
4380 else
4381 return NULL;
4382 }
4383 }
4384 return build_struct_time(y, m, d, hh, mm, ss, 0);
4385}
4386
Tim Peters371935f2003-02-01 01:52:50 +00004387/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004388
Tim Petersa9bc1682003-01-11 03:39:11 +00004389/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004390 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4391 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004392 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004393 */
4394static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004395datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004396{
4397 PyObject *basestate;
4398 PyObject *result = NULL;
4399
Tim Peters33e0f382003-01-10 02:05:14 +00004400 basestate = PyString_FromStringAndSize((char *)self->data,
4401 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004402 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004403 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004404 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004405 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004406 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004407 Py_DECREF(basestate);
4408 }
4409 return result;
4410}
4411
4412static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004413datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004414{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004415 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004416}
4417
Tim Petersa9bc1682003-01-11 03:39:11 +00004418static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004419
Tim Peters2a799bf2002-12-16 20:18:38 +00004420 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004421
Tim Petersa9bc1682003-01-11 03:39:11 +00004422 {"now", (PyCFunction)datetime_now,
Tim Peters2a799bf2002-12-16 20:18:38 +00004423 METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004424 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004425
Tim Petersa9bc1682003-01-11 03:39:11 +00004426 {"utcnow", (PyCFunction)datetime_utcnow,
4427 METH_NOARGS | METH_CLASS,
4428 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4429
4430 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Tim Peters2a799bf2002-12-16 20:18:38 +00004431 METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004432 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004433
Tim Petersa9bc1682003-01-11 03:39:11 +00004434 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4435 METH_VARARGS | METH_CLASS,
4436 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4437 "(like time.time()).")},
4438
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004439 {"strptime", (PyCFunction)datetime_strptime,
4440 METH_VARARGS | METH_CLASS,
4441 PyDoc_STR("string, format -> new datetime parsed from a string "
4442 "(like time.strptime()).")},
4443
Tim Petersa9bc1682003-01-11 03:39:11 +00004444 {"combine", (PyCFunction)datetime_combine,
4445 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4446 PyDoc_STR("date, time -> datetime with same date and time fields")},
4447
Tim Peters2a799bf2002-12-16 20:18:38 +00004448 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004449
Tim Petersa9bc1682003-01-11 03:39:11 +00004450 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4451 PyDoc_STR("Return date object with same year, month and day.")},
4452
4453 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4454 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4455
4456 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4457 PyDoc_STR("Return time object with same time and tzinfo.")},
4458
4459 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4460 PyDoc_STR("Return ctime() style string.")},
4461
4462 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004463 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4464
Tim Petersa9bc1682003-01-11 03:39:11 +00004465 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004466 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4467
Tim Petersa9bc1682003-01-11 03:39:11 +00004468 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004469 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4470 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4471 "sep is used to separate the year from the time, and "
4472 "defaults to 'T'.")},
4473
Tim Petersa9bc1682003-01-11 03:39:11 +00004474 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004475 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4476
Tim Petersa9bc1682003-01-11 03:39:11 +00004477 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004478 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4479
Tim Petersa9bc1682003-01-11 03:39:11 +00004480 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004481 PyDoc_STR("Return self.tzinfo.dst(self).")},
4482
Tim Petersa9bc1682003-01-11 03:39:11 +00004483 {"replace", (PyCFunction)datetime_replace, METH_KEYWORDS,
4484 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004485
Tim Petersa9bc1682003-01-11 03:39:11 +00004486 {"astimezone", (PyCFunction)datetime_astimezone, METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004487 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4488
Guido van Rossum177e41a2003-01-30 22:06:23 +00004489 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4490 PyDoc_STR("__reduce__() -> (cls, state)")},
4491
Tim Peters2a799bf2002-12-16 20:18:38 +00004492 {NULL, NULL}
4493};
4494
Tim Petersa9bc1682003-01-11 03:39:11 +00004495static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004496PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4497\n\
4498The year, month and day arguments are required. tzinfo may be None, or an\n\
4499instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004500
Tim Petersa9bc1682003-01-11 03:39:11 +00004501static PyNumberMethods datetime_as_number = {
4502 datetime_add, /* nb_add */
4503 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004504 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004505 0, /* nb_remainder */
4506 0, /* nb_divmod */
4507 0, /* nb_power */
4508 0, /* nb_negative */
4509 0, /* nb_positive */
4510 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004511 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004512};
4513
Neal Norwitz227b5332006-03-22 09:28:35 +00004514static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004515 PyObject_HEAD_INIT(NULL)
4516 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004517 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004518 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004519 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004520 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004521 0, /* tp_print */
4522 0, /* tp_getattr */
4523 0, /* tp_setattr */
4524 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004525 (reprfunc)datetime_repr, /* tp_repr */
4526 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 0, /* tp_as_sequence */
4528 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004529 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004530 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004531 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004532 PyObject_GenericGetAttr, /* tp_getattro */
4533 0, /* tp_setattro */
4534 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004535 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004536 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004537 0, /* tp_traverse */
4538 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004539 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004540 0, /* tp_weaklistoffset */
4541 0, /* tp_iter */
4542 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004543 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004544 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004545 datetime_getset, /* tp_getset */
4546 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004547 0, /* tp_dict */
4548 0, /* tp_descr_get */
4549 0, /* tp_descr_set */
4550 0, /* tp_dictoffset */
4551 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004552 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004553 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004554 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004555};
4556
4557/* ---------------------------------------------------------------------------
4558 * Module methods and initialization.
4559 */
4560
4561static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004562 {NULL, NULL}
4563};
4564
Tim Peters9ddf40b2004-06-20 22:41:32 +00004565/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4566 * datetime.h.
4567 */
4568static PyDateTime_CAPI CAPI = {
4569 &PyDateTime_DateType,
4570 &PyDateTime_DateTimeType,
4571 &PyDateTime_TimeType,
4572 &PyDateTime_DeltaType,
4573 &PyDateTime_TZInfoType,
4574 new_date_ex,
4575 new_datetime_ex,
4576 new_time_ex,
4577 new_delta_ex,
4578 datetime_fromtimestamp,
4579 date_fromtimestamp
4580};
4581
4582
Tim Peters2a799bf2002-12-16 20:18:38 +00004583PyMODINIT_FUNC
4584initdatetime(void)
4585{
4586 PyObject *m; /* a module object */
4587 PyObject *d; /* its dict */
4588 PyObject *x;
4589
Tim Peters2a799bf2002-12-16 20:18:38 +00004590 m = Py_InitModule3("datetime", module_methods,
4591 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004592 if (m == NULL)
4593 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004594
4595 if (PyType_Ready(&PyDateTime_DateType) < 0)
4596 return;
4597 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4598 return;
4599 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4600 return;
4601 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4602 return;
4603 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4604 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004605
Tim Peters2a799bf2002-12-16 20:18:38 +00004606 /* timedelta values */
4607 d = PyDateTime_DeltaType.tp_dict;
4608
Tim Peters2a799bf2002-12-16 20:18:38 +00004609 x = new_delta(0, 0, 1, 0);
4610 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4611 return;
4612 Py_DECREF(x);
4613
4614 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4615 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4616 return;
4617 Py_DECREF(x);
4618
4619 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4620 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4621 return;
4622 Py_DECREF(x);
4623
4624 /* date values */
4625 d = PyDateTime_DateType.tp_dict;
4626
4627 x = new_date(1, 1, 1);
4628 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4629 return;
4630 Py_DECREF(x);
4631
4632 x = new_date(MAXYEAR, 12, 31);
4633 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4634 return;
4635 Py_DECREF(x);
4636
4637 x = new_delta(1, 0, 0, 0);
4638 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4639 return;
4640 Py_DECREF(x);
4641
Tim Peters37f39822003-01-10 03:49:02 +00004642 /* time values */
4643 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004644
Tim Peters37f39822003-01-10 03:49:02 +00004645 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004646 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4647 return;
4648 Py_DECREF(x);
4649
Tim Peters37f39822003-01-10 03:49:02 +00004650 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004651 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4652 return;
4653 Py_DECREF(x);
4654
4655 x = new_delta(0, 0, 1, 0);
4656 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4657 return;
4658 Py_DECREF(x);
4659
Tim Petersa9bc1682003-01-11 03:39:11 +00004660 /* datetime values */
4661 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004662
Tim Petersa9bc1682003-01-11 03:39:11 +00004663 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004664 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4665 return;
4666 Py_DECREF(x);
4667
Tim Petersa9bc1682003-01-11 03:39:11 +00004668 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004669 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4670 return;
4671 Py_DECREF(x);
4672
4673 x = new_delta(0, 0, 1, 0);
4674 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4675 return;
4676 Py_DECREF(x);
4677
Tim Peters2a799bf2002-12-16 20:18:38 +00004678 /* module initialization */
4679 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4680 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4681
4682 Py_INCREF(&PyDateTime_DateType);
4683 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4684
Tim Petersa9bc1682003-01-11 03:39:11 +00004685 Py_INCREF(&PyDateTime_DateTimeType);
4686 PyModule_AddObject(m, "datetime",
4687 (PyObject *)&PyDateTime_DateTimeType);
4688
4689 Py_INCREF(&PyDateTime_TimeType);
4690 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4691
Tim Peters2a799bf2002-12-16 20:18:38 +00004692 Py_INCREF(&PyDateTime_DeltaType);
4693 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4694
Tim Peters2a799bf2002-12-16 20:18:38 +00004695 Py_INCREF(&PyDateTime_TZInfoType);
4696 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4697
Tim Peters9ddf40b2004-06-20 22:41:32 +00004698 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4699 NULL);
4700 if (x == NULL)
4701 return;
4702 PyModule_AddObject(m, "datetime_CAPI", x);
4703
Tim Peters2a799bf2002-12-16 20:18:38 +00004704 /* A 4-year cycle has an extra leap day over what we'd get from
4705 * pasting together 4 single years.
4706 */
4707 assert(DI4Y == 4 * 365 + 1);
4708 assert(DI4Y == days_before_year(4+1));
4709
4710 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4711 * get from pasting together 4 100-year cycles.
4712 */
4713 assert(DI400Y == 4 * DI100Y + 1);
4714 assert(DI400Y == days_before_year(400+1));
4715
4716 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4717 * pasting together 25 4-year cycles.
4718 */
4719 assert(DI100Y == 25 * DI4Y - 1);
4720 assert(DI100Y == days_before_year(100+1));
4721
4722 us_per_us = PyInt_FromLong(1);
4723 us_per_ms = PyInt_FromLong(1000);
4724 us_per_second = PyInt_FromLong(1000000);
4725 us_per_minute = PyInt_FromLong(60000000);
4726 seconds_per_day = PyInt_FromLong(24 * 3600);
4727 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4728 us_per_minute == NULL || seconds_per_day == NULL)
4729 return;
4730
4731 /* The rest are too big for 32-bit ints, but even
4732 * us_per_week fits in 40 bits, so doubles should be exact.
4733 */
4734 us_per_hour = PyLong_FromDouble(3600000000.0);
4735 us_per_day = PyLong_FromDouble(86400000000.0);
4736 us_per_week = PyLong_FromDouble(604800000000.0);
4737 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4738 return;
4739}
Tim Petersf3615152003-01-01 21:51:37 +00004740
4741/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004742Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004743 x.n = x stripped of its timezone -- its naive time.
4744 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4745 return None
4746 x.d = x.dst(), and assuming that doesn't raise an exception or
4747 return None
4748 x.s = x's standard offset, x.o - x.d
4749
4750Now some derived rules, where k is a duration (timedelta).
4751
47521. x.o = x.s + x.d
4753 This follows from the definition of x.s.
4754
Tim Petersc5dc4da2003-01-02 17:55:03 +000047552. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004756 This is actually a requirement, an assumption we need to make about
4757 sane tzinfo classes.
4758
47593. The naive UTC time corresponding to x is x.n - x.o.
4760 This is again a requirement for a sane tzinfo class.
4761
47624. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004763 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004764
Tim Petersc5dc4da2003-01-02 17:55:03 +000047655. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004766 Again follows from how arithmetic is defined.
4767
Tim Peters8bb5ad22003-01-24 02:44:45 +00004768Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004769(meaning that the various tzinfo methods exist, and don't blow up or return
4770None when called).
4771
Tim Petersa9bc1682003-01-11 03:39:11 +00004772The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004773x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004774
4775By #3, we want
4776
Tim Peters8bb5ad22003-01-24 02:44:45 +00004777 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004778
4779The algorithm starts by attaching tz to x.n, and calling that y. So
4780x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4781becomes true; in effect, we want to solve [2] for k:
4782
Tim Peters8bb5ad22003-01-24 02:44:45 +00004783 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004784
4785By #1, this is the same as
4786
Tim Peters8bb5ad22003-01-24 02:44:45 +00004787 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004788
4789By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4790Substituting that into [3],
4791
Tim Peters8bb5ad22003-01-24 02:44:45 +00004792 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4793 k - (y+k).s - (y+k).d = 0; rearranging,
4794 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4795 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004796
Tim Peters8bb5ad22003-01-24 02:44:45 +00004797On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4798approximate k by ignoring the (y+k).d term at first. Note that k can't be
4799very large, since all offset-returning methods return a duration of magnitude
4800less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4801be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004802
4803In any case, the new value is
4804
Tim Peters8bb5ad22003-01-24 02:44:45 +00004805 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004806
Tim Peters8bb5ad22003-01-24 02:44:45 +00004807It's helpful to step back at look at [4] from a higher level: it's simply
4808mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004809
4810At this point, if
4811
Tim Peters8bb5ad22003-01-24 02:44:45 +00004812 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004813
4814we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004815at the start of daylight time. Picture US Eastern for concreteness. The wall
4816time 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 +00004817sense then. The docs ask that an Eastern tzinfo class consider such a time to
4818be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4819on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004820the only spelling that makes sense on the local wall clock.
4821
Tim Petersc5dc4da2003-01-02 17:55:03 +00004822In fact, if [5] holds at this point, we do have the standard-time spelling,
4823but that takes a bit of proof. We first prove a stronger result. What's the
4824difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004825
Tim Peters8bb5ad22003-01-24 02:44:45 +00004826 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004827
Tim Petersc5dc4da2003-01-02 17:55:03 +00004828Now
4829 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004830 (y + y.s).n = by #5
4831 y.n + y.s = since y.n = x.n
4832 x.n + y.s = since z and y are have the same tzinfo member,
4833 y.s = z.s by #2
4834 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004835
Tim Petersc5dc4da2003-01-02 17:55:03 +00004836Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004837
Tim Petersc5dc4da2003-01-02 17:55:03 +00004838 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004839 x.n - ((x.n + z.s) - z.o) = expanding
4840 x.n - x.n - z.s + z.o = cancelling
4841 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004842 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004843
Tim Petersc5dc4da2003-01-02 17:55:03 +00004844So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004845
Tim Petersc5dc4da2003-01-02 17:55:03 +00004846If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004847spelling we wanted in the endcase described above. We're done. Contrarily,
4848if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004849
Tim Petersc5dc4da2003-01-02 17:55:03 +00004850If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4851add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004852local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004853
Tim Petersc5dc4da2003-01-02 17:55:03 +00004854Let
Tim Petersf3615152003-01-01 21:51:37 +00004855
Tim Peters4fede1a2003-01-04 00:26:59 +00004856 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004857
Tim Peters4fede1a2003-01-04 00:26:59 +00004858and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004859
Tim Peters8bb5ad22003-01-24 02:44:45 +00004860 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004861
Tim Peters8bb5ad22003-01-24 02:44:45 +00004862If so, we're done. If not, the tzinfo class is insane, according to the
4863assumptions we've made. This also requires a bit of proof. As before, let's
4864compute the difference between the LHS and RHS of [8] (and skipping some of
4865the justifications for the kinds of substitutions we've done several times
4866already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004867
Tim Peters8bb5ad22003-01-24 02:44:45 +00004868 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4869 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4870 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4871 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4872 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004873 - z.o + z'.o = #1 twice
4874 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4875 z'.d - z.d
4876
4877So 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 +00004878we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4879return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004880
Tim Peters8bb5ad22003-01-24 02:44:45 +00004881How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4882a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4883would have to change the result dst() returns: we start in DST, and moving
4884a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004885
Tim Peters8bb5ad22003-01-24 02:44:45 +00004886There isn't a sane case where this can happen. The closest it gets is at
4887the end of DST, where there's an hour in UTC with no spelling in a hybrid
4888tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4889that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4890UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4891time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4892clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4893standard time. Since that's what the local clock *does*, we want to map both
4894UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004895in local time, but so it goes -- it's the way the local clock works.
4896
Tim Peters8bb5ad22003-01-24 02:44:45 +00004897When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4898so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4899z' = 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 +00004900(correctly) concludes that z' is not UTC-equivalent to x.
4901
4902Because we know z.d said z was in daylight time (else [5] would have held and
4903we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004904and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004905return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4906but the reasoning doesn't depend on the example -- it depends on there being
4907two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004908z' must be in standard time, and is the spelling we want in this case.
4909
4910Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4911concerned (because it takes z' as being in standard time rather than the
4912daylight time we intend here), but returning it gives the real-life "local
4913clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4914tz.
4915
4916When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4917the 1:MM standard time spelling we want.
4918
4919So how can this break? One of the assumptions must be violated. Two
4920possibilities:
4921
49221) [2] effectively says that y.s is invariant across all y belong to a given
4923 time zone. This isn't true if, for political reasons or continental drift,
4924 a region decides to change its base offset from UTC.
4925
49262) There may be versions of "double daylight" time where the tail end of
4927 the analysis gives up a step too early. I haven't thought about that
4928 enough to say.
4929
4930In any case, it's clear that the default fromutc() is strong enough to handle
4931"almost all" time zones: so long as the standard offset is invariant, it
4932doesn't matter if daylight time transition points change from year to year, or
4933if daylight time is skipped in some years; it doesn't matter how large or
4934small dst() may get within its bounds; and it doesn't even matter if some
4935perverse time zone returns a negative dst()). So a breaking case must be
4936pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004937--------------------------------------------------------------------------- */