blob: c31d8e645830df8a61480d9419fe6723fa3368b1 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
28# error "datetime.c requires that C int have at least 32 bits"
29#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
33
34/* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
38 */
39#define MAX_DELTA_DAYS 999999999
40
41/* Rename the long macros in datetime.h to more reasonable short names. */
42#define GET_YEAR PyDateTime_GET_YEAR
43#define GET_MONTH PyDateTime_GET_MONTH
44#define GET_DAY PyDateTime_GET_DAY
45#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
49
50/* Date accessors for date and datetime. */
51#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
55
56/* Date/Time accessors for datetime. */
57#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60#define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
64
65/* Time accessors for time. */
66#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73#define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
77
78/* Delta accessors for timedelta. */
79#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
82
83#define SET_TD_DAYS(o, v) ((o)->days = (v))
84#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
85#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
86
Tim Petersa032d2e2003-01-11 00:15:54 +000087/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
89 */
90#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
91
Tim Peters3f606292004-03-21 23:38:41 +000092/* M is a char or int claiming to be a valid month. The macro is equivalent
93 * to the two-sided Python test
94 * 1 <= M <= 12
95 */
96#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
97
Tim Peters2a799bf2002-12-16 20:18:38 +000098/* Forward declarations. */
99static PyTypeObject PyDateTime_DateType;
100static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000101static PyTypeObject PyDateTime_DeltaType;
102static PyTypeObject PyDateTime_TimeType;
103static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000104
105/* ---------------------------------------------------------------------------
106 * Math utilities.
107 */
108
109/* k = i+j overflows iff k differs in sign from both inputs,
110 * iff k^i has sign bit set and k^j has sign bit set,
111 * iff (k^i)&(k^j) has sign bit set.
112 */
113#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
114 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
115
116/* Compute Python divmod(x, y), returning the quotient and storing the
117 * remainder into *r. The quotient is the floor of x/y, and that's
118 * the real point of this. C will probably truncate instead (C99
119 * requires truncation; C89 left it implementation-defined).
120 * Simplification: we *require* that y > 0 here. That's appropriate
121 * for all the uses made of it. This simplifies the code and makes
122 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
123 * overflow case).
124 */
125static int
126divmod(int x, int y, int *r)
127{
128 int quo;
129
130 assert(y > 0);
131 quo = x / y;
132 *r = x - quo * y;
133 if (*r < 0) {
134 --quo;
135 *r += y;
136 }
137 assert(0 <= *r && *r < y);
138 return quo;
139}
140
Tim Peters5d644dd2003-01-02 16:32:54 +0000141/* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
143 */
144static long
145round_to_long(double x)
146{
147 if (x >= 0.0)
148 x = floor(x + 0.5);
149 else
150 x = ceil(x - 0.5);
151 return (long)x;
152}
153
Tim Peters2a799bf2002-12-16 20:18:38 +0000154/* ---------------------------------------------------------------------------
155 * General calendrical helper functions
156 */
157
158/* For each month ordinal in 1..12, the number of days in that month,
159 * and the number of days before that month in the same year. These
160 * are correct for non-leap years only.
161 */
162static int _days_in_month[] = {
163 0, /* unused; this vector uses 1-based indexing */
164 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
165};
166
167static int _days_before_month[] = {
168 0, /* unused; this vector uses 1-based indexing */
169 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
170};
171
172/* year -> 1 if leap year, else 0. */
173static int
174is_leap(int year)
175{
176 /* Cast year to unsigned. The result is the same either way, but
177 * C can generate faster code for unsigned mod than for signed
178 * mod (especially for % 4 -- a good compiler should just grab
179 * the last 2 bits when the LHS is unsigned).
180 */
181 const unsigned int ayear = (unsigned int)year;
182 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
183}
184
185/* year, month -> number of days in that month in that year */
186static int
187days_in_month(int year, int month)
188{
189 assert(month >= 1);
190 assert(month <= 12);
191 if (month == 2 && is_leap(year))
192 return 29;
193 else
194 return _days_in_month[month];
195}
196
197/* year, month -> number of days in year preceeding first day of month */
198static int
199days_before_month(int year, int month)
200{
201 int days;
202
203 assert(month >= 1);
204 assert(month <= 12);
205 days = _days_before_month[month];
206 if (month > 2 && is_leap(year))
207 ++days;
208 return days;
209}
210
211/* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
213 */
214static int
215days_before_year(int year)
216{
217 int y = year - 1;
218 /* This is incorrect if year <= 0; we really want the floor
219 * here. But so long as MINYEAR is 1, the smallest year this
220 * can see is 0 (this can happen in some normalization endcases),
221 * so we'll just special-case that.
222 */
223 assert (year >= 0);
224 if (y >= 0)
225 return y*365 + y/4 - y/100 + y/400;
226 else {
227 assert(y == -1);
228 return -366;
229 }
230}
231
232/* Number of days in 4, 100, and 400 year cycles. That these have
233 * the correct values is asserted in the module init function.
234 */
235#define DI4Y 1461 /* days_before_year(5); days in 4 years */
236#define DI100Y 36524 /* days_before_year(101); days in 100 years */
237#define DI400Y 146097 /* days_before_year(401); days in 400 years */
238
239/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
240static void
241ord_to_ymd(int ordinal, int *year, int *month, int *day)
242{
243 int n, n1, n4, n100, n400, leapyear, preceding;
244
245 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
246 * leap years repeats exactly every 400 years. The basic strategy is
247 * to find the closest 400-year boundary at or before ordinal, then
248 * work with the offset from that boundary to ordinal. Life is much
249 * clearer if we subtract 1 from ordinal first -- then the values
250 * of ordinal at 400-year boundaries are exactly those divisible
251 * by DI400Y:
252 *
253 * D M Y n n-1
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
257 * ...
258 * 30 Dec 000 -1 -2
259 * 31 Dec 000 0 -1
260 * 1 Jan 001 1 0 400-year boundary
261 * 2 Jan 001 2 1
262 * 3 Jan 001 3 2
263 * ...
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
266 */
267 assert(ordinal >= 1);
268 --ordinal;
269 n400 = ordinal / DI400Y;
270 n = ordinal % DI400Y;
271 *year = n400 * 400 + 1;
272
273 /* Now n is the (non-negative) offset, in days, from January 1 of
274 * year, to the desired date. Now compute how many 100-year cycles
275 * precede n.
276 * Note that it's possible for n100 to equal 4! In that case 4 full
277 * 100-year cycles precede the desired day, which implies the
278 * desired day is December 31 at the end of a 400-year cycle.
279 */
280 n100 = n / DI100Y;
281 n = n % DI100Y;
282
283 /* Now compute how many 4-year cycles precede it. */
284 n4 = n / DI4Y;
285 n = n % DI4Y;
286
287 /* And now how many single years. Again n1 can be 4, and again
288 * meaning that the desired day is December 31 at the end of the
289 * 4-year cycle.
290 */
291 n1 = n / 365;
292 n = n % 365;
293
294 *year += n100 * 100 + n4 * 4 + n1;
295 if (n1 == 4 || n100 == 4) {
296 assert(n == 0);
297 *year -= 1;
298 *month = 12;
299 *day = 31;
300 return;
301 }
302
303 /* Now the year is correct, and n is the offset from January 1. We
304 * find the month via an estimate that's either exact or one too
305 * large.
306 */
307 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
308 assert(leapyear == is_leap(*year));
309 *month = (n + 50) >> 5;
310 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
311 if (preceding > n) {
312 /* estimate is too large */
313 *month -= 1;
314 preceding -= days_in_month(*year, *month);
315 }
316 n -= preceding;
317 assert(0 <= n);
318 assert(n < days_in_month(*year, *month));
319
320 *day = n + 1;
321}
322
323/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
324static int
325ymd_to_ord(int year, int month, int day)
326{
327 return days_before_year(year) + days_before_month(year, month) + day;
328}
329
330/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
331static int
332weekday(int year, int month, int day)
333{
334 return (ymd_to_ord(year, month, day) + 6) % 7;
335}
336
337/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
338 * first calendar week containing a Thursday.
339 */
340static int
341iso_week1_monday(int year)
342{
343 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
344 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
345 int first_weekday = (first_day + 6) % 7;
346 /* ordinal of closest Monday at or before 1/1 */
347 int week1_monday = first_day - first_weekday;
348
349 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
350 week1_monday += 7;
351 return week1_monday;
352}
353
354/* ---------------------------------------------------------------------------
355 * Range checkers.
356 */
357
358/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
360 */
361static int
362check_delta_day_range(int days)
363{
364 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
365 return 0;
366 PyErr_Format(PyExc_OverflowError,
367 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000368 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000369 return -1;
370}
371
372/* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
374 */
375static int
376check_date_args(int year, int month, int day)
377{
378
379 if (year < MINYEAR || year > MAXYEAR) {
380 PyErr_SetString(PyExc_ValueError,
381 "year is out of range");
382 return -1;
383 }
384 if (month < 1 || month > 12) {
385 PyErr_SetString(PyExc_ValueError,
386 "month must be in 1..12");
387 return -1;
388 }
389 if (day < 1 || day > days_in_month(year, month)) {
390 PyErr_SetString(PyExc_ValueError,
391 "day is out of range for month");
392 return -1;
393 }
394 return 0;
395}
396
397/* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_time_args(int h, int m, int s, int us)
402{
403 if (h < 0 || h > 23) {
404 PyErr_SetString(PyExc_ValueError,
405 "hour must be in 0..23");
406 return -1;
407 }
408 if (m < 0 || m > 59) {
409 PyErr_SetString(PyExc_ValueError,
410 "minute must be in 0..59");
411 return -1;
412 }
413 if (s < 0 || s > 59) {
414 PyErr_SetString(PyExc_ValueError,
415 "second must be in 0..59");
416 return -1;
417 }
418 if (us < 0 || us > 999999) {
419 PyErr_SetString(PyExc_ValueError,
420 "microsecond must be in 0..999999");
421 return -1;
422 }
423 return 0;
424}
425
426/* ---------------------------------------------------------------------------
427 * Normalization utilities.
428 */
429
430/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
431 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
432 * at least factor, enough of *lo is converted into "hi" units so that
433 * 0 <= *lo < factor. The input values must be such that int overflow
434 * is impossible.
435 */
436static void
437normalize_pair(int *hi, int *lo, int factor)
438{
439 assert(factor > 0);
440 assert(lo != hi);
441 if (*lo < 0 || *lo >= factor) {
442 const int num_hi = divmod(*lo, factor, lo);
443 const int new_hi = *hi + num_hi;
444 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
445 *hi = new_hi;
446 }
447 assert(0 <= *lo && *lo < factor);
448}
449
450/* Fiddle days (d), seconds (s), and microseconds (us) so that
451 * 0 <= *s < 24*3600
452 * 0 <= *us < 1000000
453 * The input values must be such that the internals don't overflow.
454 * The way this routine is used, we don't get close.
455 */
456static void
457normalize_d_s_us(int *d, int *s, int *us)
458{
459 if (*us < 0 || *us >= 1000000) {
460 normalize_pair(s, us, 1000000);
461 /* |s| can't be bigger than about
462 * |original s| + |original us|/1000000 now.
463 */
464
465 }
466 if (*s < 0 || *s >= 24*3600) {
467 normalize_pair(d, s, 24*3600);
468 /* |d| can't be bigger than about
469 * |original d| +
470 * (|original s| + |original us|/1000000) / (24*3600) now.
471 */
472 }
473 assert(0 <= *s && *s < 24*3600);
474 assert(0 <= *us && *us < 1000000);
475}
476
477/* Fiddle years (y), months (m), and days (d) so that
478 * 1 <= *m <= 12
479 * 1 <= *d <= days_in_month(*y, *m)
480 * The input values must be such that the internals don't overflow.
481 * The way this routine is used, we don't get close.
482 */
483static void
484normalize_y_m_d(int *y, int *m, int *d)
485{
486 int dim; /* # of days in month */
487
488 /* This gets muddy: the proper range for day can't be determined
489 * without knowing the correct month and year, but if day is, e.g.,
490 * plus or minus a million, the current month and year values make
491 * no sense (and may also be out of bounds themselves).
492 * Saying 12 months == 1 year should be non-controversial.
493 */
494 if (*m < 1 || *m > 12) {
495 --*m;
496 normalize_pair(y, m, 12);
497 ++*m;
498 /* |y| can't be bigger than about
499 * |original y| + |original m|/12 now.
500 */
501 }
502 assert(1 <= *m && *m <= 12);
503
504 /* Now only day can be out of bounds (year may also be out of bounds
505 * for a datetime object, but we don't care about that here).
506 * If day is out of bounds, what to do is arguable, but at least the
507 * method here is principled and explainable.
508 */
509 dim = days_in_month(*y, *m);
510 if (*d < 1 || *d > dim) {
511 /* Move day-1 days from the first of the month. First try to
512 * get off cheap if we're only one day out of range
513 * (adjustments for timezone alone can't be worse than that).
514 */
515 if (*d == 0) {
516 --*m;
517 if (*m > 0)
518 *d = days_in_month(*y, *m);
519 else {
520 --*y;
521 *m = 12;
522 *d = 31;
523 }
524 }
525 else if (*d == dim + 1) {
526 /* move forward a day */
527 ++*m;
528 *d = 1;
529 if (*m > 12) {
530 *m = 1;
531 ++*y;
532 }
533 }
534 else {
535 int ordinal = ymd_to_ord(*y, *m, 1) +
536 *d - 1;
537 ord_to_ymd(ordinal, y, m, d);
538 }
539 }
540 assert(*m > 0);
541 assert(*d > 0);
542}
543
544/* Fiddle out-of-bounds months and days so that the result makes some kind
545 * of sense. The parameters are both inputs and outputs. Returns < 0 on
546 * failure, where failure means the adjusted year is out of bounds.
547 */
548static int
549normalize_date(int *year, int *month, int *day)
550{
551 int result;
552
553 normalize_y_m_d(year, month, day);
554 if (MINYEAR <= *year && *year <= MAXYEAR)
555 result = 0;
556 else {
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 result = -1;
560 }
561 return result;
562}
563
564/* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
566 */
567static int
568normalize_datetime(int *year, int *month, int *day,
569 int *hour, int *minute, int *second,
570 int *microsecond)
571{
572 normalize_pair(second, microsecond, 1000000);
573 normalize_pair(minute, second, 60);
574 normalize_pair(hour, minute, 60);
575 normalize_pair(day, hour, 24);
576 return normalize_date(year, month, day);
577}
578
579/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000580 * Basic object allocation: tp_alloc implementations. These allocate
581 * Python objects of the right size and type, and do the Python object-
582 * initialization bit. If there's not enough memory, they return NULL after
583 * setting MemoryError. All data members remain uninitialized trash.
584 *
585 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000586 * member is needed. This is ugly, imprecise, and possibly insecure.
587 * tp_basicsize for the time and datetime types is set to the size of the
588 * struct that has room for the tzinfo member, so subclasses in Python will
589 * allocate enough space for a tzinfo member whether or not one is actually
590 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
591 * part is that PyType_GenericAlloc() (which subclasses in Python end up
592 * using) just happens today to effectively ignore the nitems argument
593 * when tp_itemsize is 0, which it is for these type objects. If that
594 * changes, perhaps the callers of tp_alloc slots in this file should
595 * be changed to force a 0 nitems argument unless the type being allocated
596 * is a base type implemented in this file (so that tp_alloc is time_alloc
597 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000598 */
599
600static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000601time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000602{
603 PyObject *self;
604
605 self = (PyObject *)
606 PyObject_MALLOC(aware ?
607 sizeof(PyDateTime_Time) :
608 sizeof(_PyDateTime_BaseTime));
609 if (self == NULL)
610 return (PyObject *)PyErr_NoMemory();
611 PyObject_INIT(self, type);
612 return self;
613}
614
615static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000616datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000617{
618 PyObject *self;
619
620 self = (PyObject *)
621 PyObject_MALLOC(aware ?
622 sizeof(PyDateTime_DateTime) :
623 sizeof(_PyDateTime_BaseDateTime));
624 if (self == NULL)
625 return (PyObject *)PyErr_NoMemory();
626 PyObject_INIT(self, type);
627 return self;
628}
629
630/* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
633 */
634
635/* For date and datetime. */
636static void
637set_date_fields(PyDateTime_Date *self, int y, int m, int d)
638{
639 self->hashcode = -1;
640 SET_YEAR(self, y);
641 SET_MONTH(self, m);
642 SET_DAY(self, d);
643}
644
645/* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
647 */
648
649/* Create a date instance with no range checking. */
650static PyObject *
651new_date_ex(int year, int month, int day, PyTypeObject *type)
652{
653 PyDateTime_Date *self;
654
655 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
656 if (self != NULL)
657 set_date_fields(self, year, month, day);
658 return (PyObject *) self;
659}
660
661#define new_date(year, month, day) \
662 new_date_ex(year, month, day, &PyDateTime_DateType)
663
664/* Create a datetime instance with no range checking. */
665static PyObject *
666new_datetime_ex(int year, int month, int day, int hour, int minute,
667 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
668{
669 PyDateTime_DateTime *self;
670 char aware = tzinfo != Py_None;
671
672 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
673 if (self != NULL) {
674 self->hastzinfo = aware;
675 set_date_fields((PyDateTime_Date *)self, year, month, day);
676 DATE_SET_HOUR(self, hour);
677 DATE_SET_MINUTE(self, minute);
678 DATE_SET_SECOND(self, second);
679 DATE_SET_MICROSECOND(self, usecond);
680 if (aware) {
681 Py_INCREF(tzinfo);
682 self->tzinfo = tzinfo;
683 }
684 }
685 return (PyObject *)self;
686}
687
688#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
689 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
690 &PyDateTime_DateTimeType)
691
692/* Create a time instance with no range checking. */
693static PyObject *
694new_time_ex(int hour, int minute, int second, int usecond,
695 PyObject *tzinfo, PyTypeObject *type)
696{
697 PyDateTime_Time *self;
698 char aware = tzinfo != Py_None;
699
700 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
701 if (self != NULL) {
702 self->hastzinfo = aware;
703 self->hashcode = -1;
704 TIME_SET_HOUR(self, hour);
705 TIME_SET_MINUTE(self, minute);
706 TIME_SET_SECOND(self, second);
707 TIME_SET_MICROSECOND(self, usecond);
708 if (aware) {
709 Py_INCREF(tzinfo);
710 self->tzinfo = tzinfo;
711 }
712 }
713 return (PyObject *)self;
714}
715
716#define new_time(hh, mm, ss, us, tzinfo) \
717 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
718
719/* Create a timedelta instance. Normalize the members iff normalize is
720 * true. Passing false is a speed optimization, if you know for sure
721 * that seconds and microseconds are already in their proper ranges. In any
722 * case, raises OverflowError and returns NULL if the normalized days is out
723 * of range).
724 */
725static PyObject *
726new_delta_ex(int days, int seconds, int microseconds, int normalize,
727 PyTypeObject *type)
728{
729 PyDateTime_Delta *self;
730
731 if (normalize)
732 normalize_d_s_us(&days, &seconds, &microseconds);
733 assert(0 <= seconds && seconds < 24*3600);
734 assert(0 <= microseconds && microseconds < 1000000);
735
736 if (check_delta_day_range(days) < 0)
737 return NULL;
738
739 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
740 if (self != NULL) {
741 self->hashcode = -1;
742 SET_TD_DAYS(self, days);
743 SET_TD_SECONDS(self, seconds);
744 SET_TD_MICROSECONDS(self, microseconds);
745 }
746 return (PyObject *) self;
747}
748
749#define new_delta(d, s, us, normalize) \
750 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
751
752/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000753 * tzinfo helpers.
754 */
755
Tim Peters855fe882002-12-22 03:43:39 +0000756/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
758 */
759static int
760check_tzinfo_subclass(PyObject *p)
761{
762 if (p == Py_None || PyTZInfo_Check(p))
763 return 0;
764 PyErr_Format(PyExc_TypeError,
765 "tzinfo argument must be None or of a tzinfo subclass, "
766 "not type '%s'",
767 p->ob_type->tp_name);
768 return -1;
769}
770
Tim Petersbad8ff02002-12-30 20:52:32 +0000771/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000772 * If tzinfo is None, returns None.
773 */
774static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000775call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000776{
777 PyObject *result;
778
Tim Petersbad8ff02002-12-30 20:52:32 +0000779 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
784 }
785 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000787 return result;
788}
789
Tim Peters2a799bf2002-12-16 20:18:38 +0000790/* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
793 */
794static PyObject *
795get_tzinfo_member(PyObject *self)
796{
797 PyObject *tzinfo = NULL;
798
Tim Petersa9bc1682003-01-11 03:39:11 +0000799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000801 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
804 return tzinfo;
805}
806
Tim Petersbad8ff02002-12-30 20:52:32 +0000807/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * Else *none is set to 0 and the integer method result is returned.
814 */
815static int
816call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
818{
819 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000820 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000821
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
825
826 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 if (u == NULL)
829 return -1;
830
Tim Peters27362852002-12-23 16:17:39 +0000831 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 result = 0;
833 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000834 }
Tim Peters855fe882002-12-22 03:43:39 +0000835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
842 */
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000851 }
852 }
853 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000854 else {
855 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000856 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000857 "timedelta, not '%s'",
858 name, u->ob_type->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 }
860
Tim Peters2a799bf2002-12-16 20:18:38 +0000861 Py_DECREF(u);
862 if (result < -1439 || result > 1439) {
863 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000864 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000865 "-1439 .. 1439",
866 name, result);
867 result = -1;
868 }
Tim Peters397301e2003-01-02 21:28:08 +0000869 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000870}
871
872/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
873 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
874 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000875 * doesn't return None or timedelta, TypeError is raised and this returns -1.
876 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
877 * # of minutes), ValueError is raised and this returns -1. Else *none is
878 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000879 */
880static int
881call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
882{
883 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
884}
885
Tim Petersbad8ff02002-12-30 20:52:32 +0000886/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
887 */
Tim Peters855fe882002-12-22 03:43:39 +0000888static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000889offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000890 PyObject *result;
891
Tim Petersbad8ff02002-12-30 20:52:32 +0000892 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000893 if (tzinfo == Py_None) {
894 result = Py_None;
895 Py_INCREF(result);
896 }
897 else {
898 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000899 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
900 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000901 if (offset < 0 && PyErr_Occurred())
902 return NULL;
903 if (none) {
904 result = Py_None;
905 Py_INCREF(result);
906 }
907 else
908 result = new_delta(0, offset * 60, 0, 1);
909 }
910 return result;
911}
912
Tim Peters2a799bf2002-12-16 20:18:38 +0000913/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If dst()
915 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000916 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000917 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000918 * ValueError is raised and this returns -1. Else *none is set to 0 and
919 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000920 */
921static int
922call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
923{
924 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
925}
926
Tim Petersbad8ff02002-12-30 20:52:32 +0000927/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000928 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000929 * tzname() doesn't return None or a string, TypeError is raised and this
Tim Peters855fe882002-12-22 03:43:39 +0000930 * returns NULL.
Tim Peters2a799bf2002-12-16 20:18:38 +0000931 */
932static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000933call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000934{
935 PyObject *result;
936
937 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000938 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000939 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000940
Tim Peters855fe882002-12-22 03:43:39 +0000941 if (tzinfo == Py_None) {
942 result = Py_None;
943 Py_INCREF(result);
944 }
945 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000946 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000947
948 if (result != NULL && result != Py_None && ! PyString_Check(result)) {
949 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
Tim Peters2a799bf2002-12-16 20:18:38 +0000950 "return None or a string, not '%s'",
951 result->ob_type->tp_name);
952 Py_DECREF(result);
953 result = NULL;
954 }
955 return result;
956}
957
958typedef enum {
959 /* an exception has been set; the caller should pass it on */
960 OFFSET_ERROR,
961
Tim Petersa9bc1682003-01-11 03:39:11 +0000962 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000963 OFFSET_UNKNOWN,
964
965 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000966 * datetime with !hastzinfo
967 * datetime with None tzinfo,
968 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000969 * time with !hastzinfo
970 * time with None tzinfo,
971 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000972 */
973 OFFSET_NAIVE,
974
Tim Petersa9bc1682003-01-11 03:39:11 +0000975 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000976 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000977} naivety;
978
Tim Peters14b69412002-12-22 18:10:22 +0000979/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 * the "naivety" typedef for details. If the type is aware, *offset is set
981 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000982 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000983 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000984 */
985static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000986classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000987{
988 int none;
989 PyObject *tzinfo;
990
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +0000993 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +0000994 if (tzinfo == Py_None)
995 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +0000996 if (tzinfo == NULL) {
997 /* note that a datetime passes the PyDate_Check test */
998 return (PyTime_Check(op) || PyDate_Check(op)) ?
999 OFFSET_NAIVE : OFFSET_UNKNOWN;
1000 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001001 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (*offset == -1 && PyErr_Occurred())
1003 return OFFSET_ERROR;
1004 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1005}
1006
Tim Peters00237032002-12-27 02:21:51 +00001007/* Classify two objects as to whether they're naive or offset-aware.
1008 * This isn't quite the same as calling classify_utcoffset() twice: for
1009 * binary operations (comparison and subtraction), we generally want to
1010 * ignore the tzinfo members if they're identical. This is by design,
1011 * so that results match "naive" expectations when mixing objects from a
1012 * single timezone. So in that case, this sets both offsets to 0 and
1013 * both naiveties to OFFSET_NAIVE.
1014 * The function returns 0 if everything's OK, and -1 on error.
1015 */
1016static int
1017classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001018 PyObject *tzinfoarg1,
1019 PyObject *o2, int *offset2, naivety *n2,
1020 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001021{
1022 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1023 *offset1 = *offset2 = 0;
1024 *n1 = *n2 = OFFSET_NAIVE;
1025 }
1026 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001027 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001028 if (*n1 == OFFSET_ERROR)
1029 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001030 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001031 if (*n2 == OFFSET_ERROR)
1032 return -1;
1033 }
1034 return 0;
1035}
1036
Tim Peters2a799bf2002-12-16 20:18:38 +00001037/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1038 * stuff
1039 * ", tzinfo=" + repr(tzinfo)
1040 * before the closing ")".
1041 */
1042static PyObject *
1043append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1044{
1045 PyObject *temp;
1046
1047 assert(PyString_Check(repr));
1048 assert(tzinfo);
1049 if (tzinfo == Py_None)
1050 return repr;
1051 /* Get rid of the trailing ')'. */
1052 assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1053 temp = PyString_FromStringAndSize(PyString_AsString(repr),
1054 PyString_Size(repr) - 1);
1055 Py_DECREF(repr);
1056 if (temp == NULL)
1057 return NULL;
1058 repr = temp;
1059
1060 /* Append ", tzinfo=". */
1061 PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
1062
1063 /* Append repr(tzinfo). */
1064 PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
1065
1066 /* Add a closing paren. */
1067 PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1068 return repr;
1069}
1070
1071/* ---------------------------------------------------------------------------
1072 * String format helpers.
1073 */
1074
1075static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001076format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001077{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001078 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001079 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1080 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001081 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001082 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1083 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1084 };
1085
1086 char buffer[128];
1087 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1088
1089 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1090 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1091 GET_DAY(date), hours, minutes, seconds,
1092 GET_YEAR(date));
1093 return PyString_FromString(buffer);
1094}
1095
1096/* Add an hours & minutes UTC offset string to buf. buf has no more than
1097 * buflen bytes remaining. The UTC offset is gotten by calling
1098 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1099 * *buf, and that's all. Else the returned value is checked for sanity (an
1100 * integer in range), and if that's OK it's converted to an hours & minutes
1101 * string of the form
1102 * sign HH sep MM
1103 * Returns 0 if everything is OK. If the return value from utcoffset() is
1104 * bogus, an appropriate exception is set and -1 is returned.
1105 */
1106static int
Tim Peters328fff72002-12-20 01:31:27 +00001107format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001108 PyObject *tzinfo, PyObject *tzinfoarg)
1109{
1110 int offset;
1111 int hours;
1112 int minutes;
1113 char sign;
1114 int none;
1115
1116 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1117 if (offset == -1 && PyErr_Occurred())
1118 return -1;
1119 if (none) {
1120 *buf = '\0';
1121 return 0;
1122 }
1123 sign = '+';
1124 if (offset < 0) {
1125 sign = '-';
1126 offset = - offset;
1127 }
1128 hours = divmod(offset, 60, &minutes);
1129 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1130 return 0;
1131}
1132
1133/* I sure don't want to reproduce the strftime code from the time module,
1134 * so this imports the module and calls it. All the hair is due to
1135 * giving special meanings to the %z and %Z format codes via a preprocessing
1136 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001137 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1138 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001139 */
1140static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001141wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1142 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001143{
1144 PyObject *result = NULL; /* guilty until proved innocent */
1145
1146 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1147 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1148
Guido van Rossumbce56a62007-05-10 18:04:33 +00001149 const char *pin;/* pointer to next char in input format */
1150 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001151 char ch; /* next char in input format */
1152
1153 PyObject *newfmt = NULL; /* py string, the output format */
1154 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001155 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001156 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001157 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001158
Guido van Rossumbce56a62007-05-10 18:04:33 +00001159 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001160 int ntoappend; /* # of bytes to append to output buffer */
1161
Tim Peters2a799bf2002-12-16 20:18:38 +00001162 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001163 assert(PyString_Check(format) || PyUnicode_Check(format));
1164
1165 /* Convert the input format to a C string and size */
1166 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1167 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001168
Tim Petersd6844152002-12-22 20:58:42 +00001169 /* Give up if the year is before 1900.
1170 * Python strftime() plays games with the year, and different
1171 * games depending on whether envar PYTHON2K is set. This makes
1172 * years before 1900 a nightmare, even if the platform strftime
1173 * supports them (and not all do).
1174 * We could get a lot farther here by avoiding Python's strftime
1175 * wrapper and calling the C strftime() directly, but that isn't
1176 * an option in the Python implementation of this module.
1177 */
1178 {
1179 long year;
1180 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1181 if (pyyear == NULL) return NULL;
1182 assert(PyInt_Check(pyyear));
1183 year = PyInt_AsLong(pyyear);
1184 Py_DECREF(pyyear);
1185 if (year < 1900) {
1186 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1187 "1900; the datetime strftime() "
1188 "methods require year >= 1900",
1189 year);
1190 return NULL;
1191 }
1192 }
1193
Tim Peters2a799bf2002-12-16 20:18:38 +00001194 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001195 * a new format. Since computing the replacements for those codes
1196 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001197 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001198 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001199 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1200 if (newfmt == NULL) goto Done;
1201 pnew = PyString_AsString(newfmt);
1202 usednew = 0;
1203
Tim Peters2a799bf2002-12-16 20:18:38 +00001204 while ((ch = *pin++) != '\0') {
1205 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001206 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001207 ntoappend = 1;
1208 }
1209 else if ((ch = *pin++) == '\0') {
1210 /* There's a lone trailing %; doesn't make sense. */
1211 PyErr_SetString(PyExc_ValueError, "strftime format "
1212 "ends with raw %");
1213 goto Done;
1214 }
1215 /* A % has been seen and ch is the character after it. */
1216 else if (ch == 'z') {
1217 if (zreplacement == NULL) {
1218 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001219 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001220 PyObject *tzinfo = get_tzinfo_member(object);
1221 zreplacement = PyString_FromString("");
1222 if (zreplacement == NULL) goto Done;
1223 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001224 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001225 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001226 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001227 "",
1228 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001229 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001230 goto Done;
1231 Py_DECREF(zreplacement);
1232 zreplacement = PyString_FromString(buf);
1233 if (zreplacement == NULL) goto Done;
1234 }
1235 }
1236 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001237 ptoappend = PyString_AS_STRING(zreplacement);
1238 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001239 }
1240 else if (ch == 'Z') {
1241 /* format tzname */
1242 if (Zreplacement == NULL) {
1243 PyObject *tzinfo = get_tzinfo_member(object);
1244 Zreplacement = PyString_FromString("");
1245 if (Zreplacement == NULL) goto Done;
1246 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001247 PyObject *temp;
1248 assert(tzinfoarg != NULL);
1249 temp = call_tzname(tzinfo, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001250 if (temp == NULL) goto Done;
1251 if (temp != Py_None) {
1252 assert(PyString_Check(temp));
1253 /* Since the tzname is getting
1254 * stuffed into the format, we
1255 * have to double any % signs
1256 * so that strftime doesn't
1257 * treat them as format codes.
1258 */
1259 Py_DECREF(Zreplacement);
1260 Zreplacement = PyObject_CallMethod(
1261 temp, "replace",
1262 "ss", "%", "%%");
1263 Py_DECREF(temp);
1264 if (Zreplacement == NULL)
1265 goto Done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001266 if (!PyString_Check(Zreplacement)) {
1267 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1268 goto Done;
1269 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001270 }
1271 else
1272 Py_DECREF(temp);
1273 }
1274 }
1275 assert(Zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001276 ptoappend = PyString_AS_STRING(Zreplacement);
1277 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001278 }
1279 else {
Tim Peters328fff72002-12-20 01:31:27 +00001280 /* percent followed by neither z nor Z */
1281 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001282 ntoappend = 2;
1283 }
1284
1285 /* Append the ntoappend chars starting at ptoappend to
1286 * the new format.
1287 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001289 assert(ntoappend >= 0);
1290 if (ntoappend == 0)
1291 continue;
1292 while (usednew + ntoappend > totalnew) {
1293 int bigger = totalnew << 1;
1294 if ((bigger >> 1) != totalnew) { /* overflow */
1295 PyErr_NoMemory();
1296 goto Done;
1297 }
1298 if (_PyString_Resize(&newfmt, bigger) < 0)
1299 goto Done;
1300 totalnew = bigger;
1301 pnew = PyString_AsString(newfmt) + usednew;
1302 }
1303 memcpy(pnew, ptoappend, ntoappend);
1304 pnew += ntoappend;
1305 usednew += ntoappend;
1306 assert(usednew <= totalnew);
1307 } /* end while() */
1308
1309 if (_PyString_Resize(&newfmt, usednew) < 0)
1310 goto Done;
1311 {
1312 PyObject *time = PyImport_ImportModule("time");
1313 if (time == NULL)
1314 goto Done;
1315 result = PyObject_CallMethod(time, "strftime", "OO",
1316 newfmt, timetuple);
1317 Py_DECREF(time);
1318 }
1319 Done:
1320 Py_XDECREF(zreplacement);
1321 Py_XDECREF(Zreplacement);
1322 Py_XDECREF(newfmt);
1323 return result;
1324}
1325
1326static char *
1327isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1328{
1329 int x;
1330 x = PyOS_snprintf(buffer, bufflen,
1331 "%04d-%02d-%02d",
1332 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1333 return buffer + x;
1334}
1335
1336static void
1337isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1338{
1339 int us = DATE_GET_MICROSECOND(dt);
1340
1341 PyOS_snprintf(buffer, bufflen,
1342 "%02d:%02d:%02d", /* 8 characters */
1343 DATE_GET_HOUR(dt),
1344 DATE_GET_MINUTE(dt),
1345 DATE_GET_SECOND(dt));
1346 if (us)
1347 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1348}
1349
1350/* ---------------------------------------------------------------------------
1351 * Wrap functions from the time module. These aren't directly available
1352 * from C. Perhaps they should be.
1353 */
1354
1355/* Call time.time() and return its result (a Python float). */
1356static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001357time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001358{
1359 PyObject *result = NULL;
1360 PyObject *time = PyImport_ImportModule("time");
1361
1362 if (time != NULL) {
1363 result = PyObject_CallMethod(time, "time", "()");
1364 Py_DECREF(time);
1365 }
1366 return result;
1367}
1368
1369/* Build a time.struct_time. The weekday and day number are automatically
1370 * computed from the y,m,d args.
1371 */
1372static PyObject *
1373build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1374{
1375 PyObject *time;
1376 PyObject *result = NULL;
1377
1378 time = PyImport_ImportModule("time");
1379 if (time != NULL) {
1380 result = PyObject_CallMethod(time, "struct_time",
1381 "((iiiiiiiii))",
1382 y, m, d,
1383 hh, mm, ss,
1384 weekday(y, m, d),
1385 days_before_month(y, m) + d,
1386 dstflag);
1387 Py_DECREF(time);
1388 }
1389 return result;
1390}
1391
1392/* ---------------------------------------------------------------------------
1393 * Miscellaneous helpers.
1394 */
1395
Guido van Rossum19960592006-08-24 17:29:38 +00001396/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001397 * The comparisons here all most naturally compute a cmp()-like result.
1398 * This little helper turns that into a bool result for rich comparisons.
1399 */
1400static PyObject *
1401diff_to_bool(int diff, int op)
1402{
1403 PyObject *result;
1404 int istrue;
1405
1406 switch (op) {
1407 case Py_EQ: istrue = diff == 0; break;
1408 case Py_NE: istrue = diff != 0; break;
1409 case Py_LE: istrue = diff <= 0; break;
1410 case Py_GE: istrue = diff >= 0; break;
1411 case Py_LT: istrue = diff < 0; break;
1412 case Py_GT: istrue = diff > 0; break;
1413 default:
1414 assert(! "op unknown");
1415 istrue = 0; /* To shut up compiler */
1416 }
1417 result = istrue ? Py_True : Py_False;
1418 Py_INCREF(result);
1419 return result;
1420}
1421
Tim Peters07534a62003-02-07 22:50:28 +00001422/* Raises a "can't compare" TypeError and returns NULL. */
1423static PyObject *
1424cmperror(PyObject *a, PyObject *b)
1425{
1426 PyErr_Format(PyExc_TypeError,
1427 "can't compare %s to %s",
1428 a->ob_type->tp_name, b->ob_type->tp_name);
1429 return NULL;
1430}
1431
Tim Peters2a799bf2002-12-16 20:18:38 +00001432/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001433 * Cached Python objects; these are set by the module init function.
1434 */
1435
1436/* Conversion factors. */
1437static PyObject *us_per_us = NULL; /* 1 */
1438static PyObject *us_per_ms = NULL; /* 1000 */
1439static PyObject *us_per_second = NULL; /* 1000000 */
1440static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1441static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1442static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1443static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1444static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1445
Tim Peters2a799bf2002-12-16 20:18:38 +00001446/* ---------------------------------------------------------------------------
1447 * Class implementations.
1448 */
1449
1450/*
1451 * PyDateTime_Delta implementation.
1452 */
1453
1454/* Convert a timedelta to a number of us,
1455 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1456 * as a Python int or long.
1457 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1458 * due to ubiquitous overflow possibilities.
1459 */
1460static PyObject *
1461delta_to_microseconds(PyDateTime_Delta *self)
1462{
1463 PyObject *x1 = NULL;
1464 PyObject *x2 = NULL;
1465 PyObject *x3 = NULL;
1466 PyObject *result = NULL;
1467
1468 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1469 if (x1 == NULL)
1470 goto Done;
1471 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1472 if (x2 == NULL)
1473 goto Done;
1474 Py_DECREF(x1);
1475 x1 = NULL;
1476
1477 /* x2 has days in seconds */
1478 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1479 if (x1 == NULL)
1480 goto Done;
1481 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1482 if (x3 == NULL)
1483 goto Done;
1484 Py_DECREF(x1);
1485 Py_DECREF(x2);
1486 x1 = x2 = NULL;
1487
1488 /* x3 has days+seconds in seconds */
1489 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1490 if (x1 == NULL)
1491 goto Done;
1492 Py_DECREF(x3);
1493 x3 = NULL;
1494
1495 /* x1 has days+seconds in us */
1496 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1497 if (x2 == NULL)
1498 goto Done;
1499 result = PyNumber_Add(x1, x2);
1500
1501Done:
1502 Py_XDECREF(x1);
1503 Py_XDECREF(x2);
1504 Py_XDECREF(x3);
1505 return result;
1506}
1507
1508/* Convert a number of us (as a Python int or long) to a timedelta.
1509 */
1510static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001511microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001512{
1513 int us;
1514 int s;
1515 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001516 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001517
1518 PyObject *tuple = NULL;
1519 PyObject *num = NULL;
1520 PyObject *result = NULL;
1521
1522 tuple = PyNumber_Divmod(pyus, us_per_second);
1523 if (tuple == NULL)
1524 goto Done;
1525
1526 num = PyTuple_GetItem(tuple, 1); /* us */
1527 if (num == NULL)
1528 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001529 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001530 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001531 if (temp == -1 && PyErr_Occurred())
1532 goto Done;
1533 assert(0 <= temp && temp < 1000000);
1534 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001535 if (us < 0) {
1536 /* The divisor was positive, so this must be an error. */
1537 assert(PyErr_Occurred());
1538 goto Done;
1539 }
1540
1541 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1542 if (num == NULL)
1543 goto Done;
1544 Py_INCREF(num);
1545 Py_DECREF(tuple);
1546
1547 tuple = PyNumber_Divmod(num, seconds_per_day);
1548 if (tuple == NULL)
1549 goto Done;
1550 Py_DECREF(num);
1551
1552 num = PyTuple_GetItem(tuple, 1); /* seconds */
1553 if (num == NULL)
1554 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001555 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001556 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001557 if (temp == -1 && PyErr_Occurred())
1558 goto Done;
1559 assert(0 <= temp && temp < 24*3600);
1560 s = (int)temp;
1561
Tim Peters2a799bf2002-12-16 20:18:38 +00001562 if (s < 0) {
1563 /* The divisor was positive, so this must be an error. */
1564 assert(PyErr_Occurred());
1565 goto Done;
1566 }
1567
1568 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1569 if (num == NULL)
1570 goto Done;
1571 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001572 temp = PyLong_AsLong(num);
1573 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001574 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001575 d = (int)temp;
1576 if ((long)d != temp) {
1577 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1578 "large to fit in a C int");
1579 goto Done;
1580 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001581 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001582
1583Done:
1584 Py_XDECREF(tuple);
1585 Py_XDECREF(num);
1586 return result;
1587}
1588
Tim Petersb0c854d2003-05-17 15:57:00 +00001589#define microseconds_to_delta(pymicros) \
1590 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1591
Tim Peters2a799bf2002-12-16 20:18:38 +00001592static PyObject *
1593multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1594{
1595 PyObject *pyus_in;
1596 PyObject *pyus_out;
1597 PyObject *result;
1598
1599 pyus_in = delta_to_microseconds(delta);
1600 if (pyus_in == NULL)
1601 return NULL;
1602
1603 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1604 Py_DECREF(pyus_in);
1605 if (pyus_out == NULL)
1606 return NULL;
1607
1608 result = microseconds_to_delta(pyus_out);
1609 Py_DECREF(pyus_out);
1610 return result;
1611}
1612
1613static PyObject *
1614divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1615{
1616 PyObject *pyus_in;
1617 PyObject *pyus_out;
1618 PyObject *result;
1619
1620 pyus_in = delta_to_microseconds(delta);
1621 if (pyus_in == NULL)
1622 return NULL;
1623
1624 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1625 Py_DECREF(pyus_in);
1626 if (pyus_out == NULL)
1627 return NULL;
1628
1629 result = microseconds_to_delta(pyus_out);
1630 Py_DECREF(pyus_out);
1631 return result;
1632}
1633
1634static PyObject *
1635delta_add(PyObject *left, PyObject *right)
1636{
1637 PyObject *result = Py_NotImplemented;
1638
1639 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1640 /* delta + delta */
1641 /* The C-level additions can't overflow because of the
1642 * invariant bounds.
1643 */
1644 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1645 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1646 int microseconds = GET_TD_MICROSECONDS(left) +
1647 GET_TD_MICROSECONDS(right);
1648 result = new_delta(days, seconds, microseconds, 1);
1649 }
1650
1651 if (result == Py_NotImplemented)
1652 Py_INCREF(result);
1653 return result;
1654}
1655
1656static PyObject *
1657delta_negative(PyDateTime_Delta *self)
1658{
1659 return new_delta(-GET_TD_DAYS(self),
1660 -GET_TD_SECONDS(self),
1661 -GET_TD_MICROSECONDS(self),
1662 1);
1663}
1664
1665static PyObject *
1666delta_positive(PyDateTime_Delta *self)
1667{
1668 /* Could optimize this (by returning self) if this isn't a
1669 * subclass -- but who uses unary + ? Approximately nobody.
1670 */
1671 return new_delta(GET_TD_DAYS(self),
1672 GET_TD_SECONDS(self),
1673 GET_TD_MICROSECONDS(self),
1674 0);
1675}
1676
1677static PyObject *
1678delta_abs(PyDateTime_Delta *self)
1679{
1680 PyObject *result;
1681
1682 assert(GET_TD_MICROSECONDS(self) >= 0);
1683 assert(GET_TD_SECONDS(self) >= 0);
1684
1685 if (GET_TD_DAYS(self) < 0)
1686 result = delta_negative(self);
1687 else
1688 result = delta_positive(self);
1689
1690 return result;
1691}
1692
1693static PyObject *
1694delta_subtract(PyObject *left, PyObject *right)
1695{
1696 PyObject *result = Py_NotImplemented;
1697
1698 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1699 /* delta - delta */
1700 PyObject *minus_right = PyNumber_Negative(right);
1701 if (minus_right) {
1702 result = delta_add(left, minus_right);
1703 Py_DECREF(minus_right);
1704 }
1705 else
1706 result = NULL;
1707 }
1708
1709 if (result == Py_NotImplemented)
1710 Py_INCREF(result);
1711 return result;
1712}
1713
Tim Peters2a799bf2002-12-16 20:18:38 +00001714static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001715delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001716{
Tim Petersaa7d8492003-02-08 03:28:59 +00001717 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001718 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001719 if (diff == 0) {
1720 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1721 if (diff == 0)
1722 diff = GET_TD_MICROSECONDS(self) -
1723 GET_TD_MICROSECONDS(other);
1724 }
Guido van Rossum19960592006-08-24 17:29:38 +00001725 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001726 }
Guido van Rossum19960592006-08-24 17:29:38 +00001727 else {
1728 Py_INCREF(Py_NotImplemented);
1729 return Py_NotImplemented;
1730 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001731}
1732
1733static PyObject *delta_getstate(PyDateTime_Delta *self);
1734
1735static long
1736delta_hash(PyDateTime_Delta *self)
1737{
1738 if (self->hashcode == -1) {
1739 PyObject *temp = delta_getstate(self);
1740 if (temp != NULL) {
1741 self->hashcode = PyObject_Hash(temp);
1742 Py_DECREF(temp);
1743 }
1744 }
1745 return self->hashcode;
1746}
1747
1748static PyObject *
1749delta_multiply(PyObject *left, PyObject *right)
1750{
1751 PyObject *result = Py_NotImplemented;
1752
1753 if (PyDelta_Check(left)) {
1754 /* delta * ??? */
1755 if (PyInt_Check(right) || PyLong_Check(right))
1756 result = multiply_int_timedelta(right,
1757 (PyDateTime_Delta *) left);
1758 }
1759 else if (PyInt_Check(left) || PyLong_Check(left))
1760 result = multiply_int_timedelta(left,
1761 (PyDateTime_Delta *) right);
1762
1763 if (result == Py_NotImplemented)
1764 Py_INCREF(result);
1765 return result;
1766}
1767
1768static PyObject *
1769delta_divide(PyObject *left, PyObject *right)
1770{
1771 PyObject *result = Py_NotImplemented;
1772
1773 if (PyDelta_Check(left)) {
1774 /* delta * ??? */
1775 if (PyInt_Check(right) || PyLong_Check(right))
1776 result = divide_timedelta_int(
1777 (PyDateTime_Delta *)left,
1778 right);
1779 }
1780
1781 if (result == Py_NotImplemented)
1782 Py_INCREF(result);
1783 return result;
1784}
1785
1786/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1787 * timedelta constructor. sofar is the # of microseconds accounted for
1788 * so far, and there are factor microseconds per current unit, the number
1789 * of which is given by num. num * factor is added to sofar in a
1790 * numerically careful way, and that's the result. Any fractional
1791 * microseconds left over (this can happen if num is a float type) are
1792 * added into *leftover.
1793 * Note that there are many ways this can give an error (NULL) return.
1794 */
1795static PyObject *
1796accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1797 double *leftover)
1798{
1799 PyObject *prod;
1800 PyObject *sum;
1801
1802 assert(num != NULL);
1803
1804 if (PyInt_Check(num) || PyLong_Check(num)) {
1805 prod = PyNumber_Multiply(num, factor);
1806 if (prod == NULL)
1807 return NULL;
1808 sum = PyNumber_Add(sofar, prod);
1809 Py_DECREF(prod);
1810 return sum;
1811 }
1812
1813 if (PyFloat_Check(num)) {
1814 double dnum;
1815 double fracpart;
1816 double intpart;
1817 PyObject *x;
1818 PyObject *y;
1819
1820 /* The Plan: decompose num into an integer part and a
1821 * fractional part, num = intpart + fracpart.
1822 * Then num * factor ==
1823 * intpart * factor + fracpart * factor
1824 * and the LHS can be computed exactly in long arithmetic.
1825 * The RHS is again broken into an int part and frac part.
1826 * and the frac part is added into *leftover.
1827 */
1828 dnum = PyFloat_AsDouble(num);
1829 if (dnum == -1.0 && PyErr_Occurred())
1830 return NULL;
1831 fracpart = modf(dnum, &intpart);
1832 x = PyLong_FromDouble(intpart);
1833 if (x == NULL)
1834 return NULL;
1835
1836 prod = PyNumber_Multiply(x, factor);
1837 Py_DECREF(x);
1838 if (prod == NULL)
1839 return NULL;
1840
1841 sum = PyNumber_Add(sofar, prod);
1842 Py_DECREF(prod);
1843 if (sum == NULL)
1844 return NULL;
1845
1846 if (fracpart == 0.0)
1847 return sum;
1848 /* So far we've lost no information. Dealing with the
1849 * fractional part requires float arithmetic, and may
1850 * lose a little info.
1851 */
1852 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001853 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001854
1855 dnum *= fracpart;
1856 fracpart = modf(dnum, &intpart);
1857 x = PyLong_FromDouble(intpart);
1858 if (x == NULL) {
1859 Py_DECREF(sum);
1860 return NULL;
1861 }
1862
1863 y = PyNumber_Add(sum, x);
1864 Py_DECREF(sum);
1865 Py_DECREF(x);
1866 *leftover += fracpart;
1867 return y;
1868 }
1869
1870 PyErr_Format(PyExc_TypeError,
1871 "unsupported type for timedelta %s component: %s",
1872 tag, num->ob_type->tp_name);
1873 return NULL;
1874}
1875
1876static PyObject *
1877delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1878{
1879 PyObject *self = NULL;
1880
1881 /* Argument objects. */
1882 PyObject *day = NULL;
1883 PyObject *second = NULL;
1884 PyObject *us = NULL;
1885 PyObject *ms = NULL;
1886 PyObject *minute = NULL;
1887 PyObject *hour = NULL;
1888 PyObject *week = NULL;
1889
1890 PyObject *x = NULL; /* running sum of microseconds */
1891 PyObject *y = NULL; /* temp sum of microseconds */
1892 double leftover_us = 0.0;
1893
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001894 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001895 "days", "seconds", "microseconds", "milliseconds",
1896 "minutes", "hours", "weeks", NULL
1897 };
1898
1899 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1900 keywords,
1901 &day, &second, &us,
1902 &ms, &minute, &hour, &week) == 0)
1903 goto Done;
1904
1905 x = PyInt_FromLong(0);
1906 if (x == NULL)
1907 goto Done;
1908
1909#define CLEANUP \
1910 Py_DECREF(x); \
1911 x = y; \
1912 if (x == NULL) \
1913 goto Done
1914
1915 if (us) {
1916 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1917 CLEANUP;
1918 }
1919 if (ms) {
1920 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1921 CLEANUP;
1922 }
1923 if (second) {
1924 y = accum("seconds", x, second, us_per_second, &leftover_us);
1925 CLEANUP;
1926 }
1927 if (minute) {
1928 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1929 CLEANUP;
1930 }
1931 if (hour) {
1932 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1933 CLEANUP;
1934 }
1935 if (day) {
1936 y = accum("days", x, day, us_per_day, &leftover_us);
1937 CLEANUP;
1938 }
1939 if (week) {
1940 y = accum("weeks", x, week, us_per_week, &leftover_us);
1941 CLEANUP;
1942 }
1943 if (leftover_us) {
1944 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001945 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001946 if (temp == NULL) {
1947 Py_DECREF(x);
1948 goto Done;
1949 }
1950 y = PyNumber_Add(x, temp);
1951 Py_DECREF(temp);
1952 CLEANUP;
1953 }
1954
Tim Petersb0c854d2003-05-17 15:57:00 +00001955 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001956 Py_DECREF(x);
1957Done:
1958 return self;
1959
1960#undef CLEANUP
1961}
1962
1963static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001964delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001965{
1966 return (GET_TD_DAYS(self) != 0
1967 || GET_TD_SECONDS(self) != 0
1968 || GET_TD_MICROSECONDS(self) != 0);
1969}
1970
1971static PyObject *
1972delta_repr(PyDateTime_Delta *self)
1973{
1974 if (GET_TD_MICROSECONDS(self) != 0)
1975 return PyString_FromFormat("%s(%d, %d, %d)",
1976 self->ob_type->tp_name,
1977 GET_TD_DAYS(self),
1978 GET_TD_SECONDS(self),
1979 GET_TD_MICROSECONDS(self));
1980 if (GET_TD_SECONDS(self) != 0)
1981 return PyString_FromFormat("%s(%d, %d)",
1982 self->ob_type->tp_name,
1983 GET_TD_DAYS(self),
1984 GET_TD_SECONDS(self));
1985
1986 return PyString_FromFormat("%s(%d)",
1987 self->ob_type->tp_name,
1988 GET_TD_DAYS(self));
1989}
1990
1991static PyObject *
1992delta_str(PyDateTime_Delta *self)
1993{
1994 int days = GET_TD_DAYS(self);
1995 int seconds = GET_TD_SECONDS(self);
1996 int us = GET_TD_MICROSECONDS(self);
1997 int hours;
1998 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00001999 char buf[100];
2000 char *pbuf = buf;
2001 size_t buflen = sizeof(buf);
2002 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002003
2004 minutes = divmod(seconds, 60, &seconds);
2005 hours = divmod(minutes, 60, &minutes);
2006
2007 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002008 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2009 (days == 1 || days == -1) ? "" : "s");
2010 if (n < 0 || (size_t)n >= buflen)
2011 goto Fail;
2012 pbuf += n;
2013 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002014 }
2015
Tim Petersba873472002-12-18 20:19:21 +00002016 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2017 hours, minutes, seconds);
2018 if (n < 0 || (size_t)n >= buflen)
2019 goto Fail;
2020 pbuf += n;
2021 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002022
2023 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002024 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2025 if (n < 0 || (size_t)n >= buflen)
2026 goto Fail;
2027 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002028 }
2029
Tim Petersba873472002-12-18 20:19:21 +00002030 return PyString_FromStringAndSize(buf, pbuf - buf);
2031
2032 Fail:
2033 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2034 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002035}
2036
Tim Peters371935f2003-02-01 01:52:50 +00002037/* Pickle support, a simple use of __reduce__. */
2038
Tim Petersb57f8f02003-02-01 02:54:15 +00002039/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002040static PyObject *
2041delta_getstate(PyDateTime_Delta *self)
2042{
2043 return Py_BuildValue("iii", GET_TD_DAYS(self),
2044 GET_TD_SECONDS(self),
2045 GET_TD_MICROSECONDS(self));
2046}
2047
Tim Peters2a799bf2002-12-16 20:18:38 +00002048static PyObject *
2049delta_reduce(PyDateTime_Delta* self)
2050{
Tim Peters8a60c222003-02-01 01:47:29 +00002051 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002052}
2053
2054#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2055
2056static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002057
Neal Norwitzdfb80862002-12-19 02:30:56 +00002058 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002059 PyDoc_STR("Number of days.")},
2060
Neal Norwitzdfb80862002-12-19 02:30:56 +00002061 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002062 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2063
Neal Norwitzdfb80862002-12-19 02:30:56 +00002064 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002065 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2066 {NULL}
2067};
2068
2069static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002070 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2071 PyDoc_STR("__reduce__() -> (cls, state)")},
2072
Tim Peters2a799bf2002-12-16 20:18:38 +00002073 {NULL, NULL},
2074};
2075
2076static char delta_doc[] =
2077PyDoc_STR("Difference between two datetime values.");
2078
2079static PyNumberMethods delta_as_number = {
2080 delta_add, /* nb_add */
2081 delta_subtract, /* nb_subtract */
2082 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002083 0, /* nb_remainder */
2084 0, /* nb_divmod */
2085 0, /* nb_power */
2086 (unaryfunc)delta_negative, /* nb_negative */
2087 (unaryfunc)delta_positive, /* nb_positive */
2088 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002089 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002090 0, /*nb_invert*/
2091 0, /*nb_lshift*/
2092 0, /*nb_rshift*/
2093 0, /*nb_and*/
2094 0, /*nb_xor*/
2095 0, /*nb_or*/
2096 0, /*nb_coerce*/
2097 0, /*nb_int*/
2098 0, /*nb_long*/
2099 0, /*nb_float*/
2100 0, /*nb_oct*/
2101 0, /*nb_hex*/
2102 0, /*nb_inplace_add*/
2103 0, /*nb_inplace_subtract*/
2104 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002105 0, /*nb_inplace_remainder*/
2106 0, /*nb_inplace_power*/
2107 0, /*nb_inplace_lshift*/
2108 0, /*nb_inplace_rshift*/
2109 0, /*nb_inplace_and*/
2110 0, /*nb_inplace_xor*/
2111 0, /*nb_inplace_or*/
2112 delta_divide, /* nb_floor_divide */
2113 0, /* nb_true_divide */
2114 0, /* nb_inplace_floor_divide */
2115 0, /* nb_inplace_true_divide */
2116};
2117
2118static PyTypeObject PyDateTime_DeltaType = {
2119 PyObject_HEAD_INIT(NULL)
2120 0, /* ob_size */
2121 "datetime.timedelta", /* tp_name */
2122 sizeof(PyDateTime_Delta), /* tp_basicsize */
2123 0, /* tp_itemsize */
2124 0, /* tp_dealloc */
2125 0, /* tp_print */
2126 0, /* tp_getattr */
2127 0, /* tp_setattr */
2128 0, /* tp_compare */
2129 (reprfunc)delta_repr, /* tp_repr */
2130 &delta_as_number, /* tp_as_number */
2131 0, /* tp_as_sequence */
2132 0, /* tp_as_mapping */
2133 (hashfunc)delta_hash, /* tp_hash */
2134 0, /* tp_call */
2135 (reprfunc)delta_str, /* tp_str */
2136 PyObject_GenericGetAttr, /* tp_getattro */
2137 0, /* tp_setattro */
2138 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002139 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002140 delta_doc, /* tp_doc */
2141 0, /* tp_traverse */
2142 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002143 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002144 0, /* tp_weaklistoffset */
2145 0, /* tp_iter */
2146 0, /* tp_iternext */
2147 delta_methods, /* tp_methods */
2148 delta_members, /* tp_members */
2149 0, /* tp_getset */
2150 0, /* tp_base */
2151 0, /* tp_dict */
2152 0, /* tp_descr_get */
2153 0, /* tp_descr_set */
2154 0, /* tp_dictoffset */
2155 0, /* tp_init */
2156 0, /* tp_alloc */
2157 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002158 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002159};
2160
2161/*
2162 * PyDateTime_Date implementation.
2163 */
2164
2165/* Accessor properties. */
2166
2167static PyObject *
2168date_year(PyDateTime_Date *self, void *unused)
2169{
2170 return PyInt_FromLong(GET_YEAR(self));
2171}
2172
2173static PyObject *
2174date_month(PyDateTime_Date *self, void *unused)
2175{
2176 return PyInt_FromLong(GET_MONTH(self));
2177}
2178
2179static PyObject *
2180date_day(PyDateTime_Date *self, void *unused)
2181{
2182 return PyInt_FromLong(GET_DAY(self));
2183}
2184
2185static PyGetSetDef date_getset[] = {
2186 {"year", (getter)date_year},
2187 {"month", (getter)date_month},
2188 {"day", (getter)date_day},
2189 {NULL}
2190};
2191
2192/* Constructors. */
2193
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002194static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002195
Tim Peters2a799bf2002-12-16 20:18:38 +00002196static PyObject *
2197date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2198{
2199 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002200 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002201 int year;
2202 int month;
2203 int day;
2204
Guido van Rossum177e41a2003-01-30 22:06:23 +00002205 /* Check for invocation from pickle with __getstate__ state */
2206 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002207 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002208 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2209 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002210 {
Tim Peters70533e22003-02-01 04:40:04 +00002211 PyDateTime_Date *me;
2212
Tim Peters604c0132004-06-07 23:04:33 +00002213 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002214 if (me != NULL) {
2215 char *pdata = PyString_AS_STRING(state);
2216 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2217 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002218 }
Tim Peters70533e22003-02-01 04:40:04 +00002219 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002220 }
2221
Tim Peters12bf3392002-12-24 05:41:27 +00002222 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002223 &year, &month, &day)) {
2224 if (check_date_args(year, month, day) < 0)
2225 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002226 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002227 }
2228 return self;
2229}
2230
2231/* Return new date from localtime(t). */
2232static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002233date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002234{
2235 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002236 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002237 PyObject *result = NULL;
2238
Tim Peters1b6f7a92004-06-20 02:50:16 +00002239 t = _PyTime_DoubleToTimet(ts);
2240 if (t == (time_t)-1 && PyErr_Occurred())
2241 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002242 tm = localtime(&t);
2243 if (tm)
2244 result = PyObject_CallFunction(cls, "iii",
2245 tm->tm_year + 1900,
2246 tm->tm_mon + 1,
2247 tm->tm_mday);
2248 else
2249 PyErr_SetString(PyExc_ValueError,
2250 "timestamp out of range for "
2251 "platform localtime() function");
2252 return result;
2253}
2254
2255/* Return new date from current time.
2256 * We say this is equivalent to fromtimestamp(time.time()), and the
2257 * only way to be sure of that is to *call* time.time(). That's not
2258 * generally the same as calling C's time.
2259 */
2260static PyObject *
2261date_today(PyObject *cls, PyObject *dummy)
2262{
2263 PyObject *time;
2264 PyObject *result;
2265
2266 time = time_time();
2267 if (time == NULL)
2268 return NULL;
2269
2270 /* Note well: today() is a class method, so this may not call
2271 * date.fromtimestamp. For example, it may call
2272 * datetime.fromtimestamp. That's why we need all the accuracy
2273 * time.time() delivers; if someone were gonzo about optimization,
2274 * date.today() could get away with plain C time().
2275 */
2276 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2277 Py_DECREF(time);
2278 return result;
2279}
2280
2281/* Return new date from given timestamp (Python timestamp -- a double). */
2282static PyObject *
2283date_fromtimestamp(PyObject *cls, PyObject *args)
2284{
2285 double timestamp;
2286 PyObject *result = NULL;
2287
2288 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002289 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002290 return result;
2291}
2292
2293/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2294 * the ordinal is out of range.
2295 */
2296static PyObject *
2297date_fromordinal(PyObject *cls, PyObject *args)
2298{
2299 PyObject *result = NULL;
2300 int ordinal;
2301
2302 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2303 int year;
2304 int month;
2305 int day;
2306
2307 if (ordinal < 1)
2308 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2309 ">= 1");
2310 else {
2311 ord_to_ymd(ordinal, &year, &month, &day);
2312 result = PyObject_CallFunction(cls, "iii",
2313 year, month, day);
2314 }
2315 }
2316 return result;
2317}
2318
2319/*
2320 * Date arithmetic.
2321 */
2322
2323/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2324 * instead.
2325 */
2326static PyObject *
2327add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2328{
2329 PyObject *result = NULL;
2330 int year = GET_YEAR(date);
2331 int month = GET_MONTH(date);
2332 int deltadays = GET_TD_DAYS(delta);
2333 /* C-level overflow is impossible because |deltadays| < 1e9. */
2334 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2335
2336 if (normalize_date(&year, &month, &day) >= 0)
2337 result = new_date(year, month, day);
2338 return result;
2339}
2340
2341static PyObject *
2342date_add(PyObject *left, PyObject *right)
2343{
2344 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2345 Py_INCREF(Py_NotImplemented);
2346 return Py_NotImplemented;
2347 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002348 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002349 /* date + ??? */
2350 if (PyDelta_Check(right))
2351 /* date + delta */
2352 return add_date_timedelta((PyDateTime_Date *) left,
2353 (PyDateTime_Delta *) right,
2354 0);
2355 }
2356 else {
2357 /* ??? + date
2358 * 'right' must be one of us, or we wouldn't have been called
2359 */
2360 if (PyDelta_Check(left))
2361 /* delta + date */
2362 return add_date_timedelta((PyDateTime_Date *) right,
2363 (PyDateTime_Delta *) left,
2364 0);
2365 }
2366 Py_INCREF(Py_NotImplemented);
2367 return Py_NotImplemented;
2368}
2369
2370static PyObject *
2371date_subtract(PyObject *left, PyObject *right)
2372{
2373 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2374 Py_INCREF(Py_NotImplemented);
2375 return Py_NotImplemented;
2376 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002377 if (PyDate_Check(left)) {
2378 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002379 /* date - date */
2380 int left_ord = ymd_to_ord(GET_YEAR(left),
2381 GET_MONTH(left),
2382 GET_DAY(left));
2383 int right_ord = ymd_to_ord(GET_YEAR(right),
2384 GET_MONTH(right),
2385 GET_DAY(right));
2386 return new_delta(left_ord - right_ord, 0, 0, 0);
2387 }
2388 if (PyDelta_Check(right)) {
2389 /* date - delta */
2390 return add_date_timedelta((PyDateTime_Date *) left,
2391 (PyDateTime_Delta *) right,
2392 1);
2393 }
2394 }
2395 Py_INCREF(Py_NotImplemented);
2396 return Py_NotImplemented;
2397}
2398
2399
2400/* Various ways to turn a date into a string. */
2401
2402static PyObject *
2403date_repr(PyDateTime_Date *self)
2404{
2405 char buffer[1028];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002406 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002407
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002408 type_name = self->ob_type->tp_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002409 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002410 type_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002411 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2412
2413 return PyString_FromString(buffer);
2414}
2415
2416static PyObject *
2417date_isoformat(PyDateTime_Date *self)
2418{
2419 char buffer[128];
2420
2421 isoformat_date(self, buffer, sizeof(buffer));
2422 return PyString_FromString(buffer);
2423}
2424
Tim Peterse2df5ff2003-05-02 18:39:55 +00002425/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002426static PyObject *
2427date_str(PyDateTime_Date *self)
2428{
2429 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2430}
2431
2432
2433static PyObject *
2434date_ctime(PyDateTime_Date *self)
2435{
2436 return format_ctime(self, 0, 0, 0);
2437}
2438
2439static PyObject *
2440date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2441{
2442 /* This method can be inherited, and needs to call the
2443 * timetuple() method appropriate to self's class.
2444 */
2445 PyObject *result;
2446 PyObject *format;
2447 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002448 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002449
Guido van Rossumbce56a62007-05-10 18:04:33 +00002450 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2451 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002452 return NULL;
2453
2454 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2455 if (tuple == NULL)
2456 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002457 result = wrap_strftime((PyObject *)self, format, tuple,
2458 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002459 Py_DECREF(tuple);
2460 return result;
2461}
2462
2463/* ISO methods. */
2464
2465static PyObject *
2466date_isoweekday(PyDateTime_Date *self)
2467{
2468 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2469
2470 return PyInt_FromLong(dow + 1);
2471}
2472
2473static PyObject *
2474date_isocalendar(PyDateTime_Date *self)
2475{
2476 int year = GET_YEAR(self);
2477 int week1_monday = iso_week1_monday(year);
2478 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2479 int week;
2480 int day;
2481
2482 week = divmod(today - week1_monday, 7, &day);
2483 if (week < 0) {
2484 --year;
2485 week1_monday = iso_week1_monday(year);
2486 week = divmod(today - week1_monday, 7, &day);
2487 }
2488 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2489 ++year;
2490 week = 0;
2491 }
2492 return Py_BuildValue("iii", year, week + 1, day + 1);
2493}
2494
2495/* Miscellaneous methods. */
2496
Tim Peters2a799bf2002-12-16 20:18:38 +00002497static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002498date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002499{
Guido van Rossum19960592006-08-24 17:29:38 +00002500 if (PyDate_Check(other)) {
2501 int diff = memcmp(((PyDateTime_Date *)self)->data,
2502 ((PyDateTime_Date *)other)->data,
2503 _PyDateTime_DATE_DATASIZE);
2504 return diff_to_bool(diff, op);
2505 }
2506 else {
Tim Peters07534a62003-02-07 22:50:28 +00002507 Py_INCREF(Py_NotImplemented);
2508 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002509 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002510}
2511
2512static PyObject *
2513date_timetuple(PyDateTime_Date *self)
2514{
2515 return build_struct_time(GET_YEAR(self),
2516 GET_MONTH(self),
2517 GET_DAY(self),
2518 0, 0, 0, -1);
2519}
2520
Tim Peters12bf3392002-12-24 05:41:27 +00002521static PyObject *
2522date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2523{
2524 PyObject *clone;
2525 PyObject *tuple;
2526 int year = GET_YEAR(self);
2527 int month = GET_MONTH(self);
2528 int day = GET_DAY(self);
2529
2530 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2531 &year, &month, &day))
2532 return NULL;
2533 tuple = Py_BuildValue("iii", year, month, day);
2534 if (tuple == NULL)
2535 return NULL;
2536 clone = date_new(self->ob_type, tuple, NULL);
2537 Py_DECREF(tuple);
2538 return clone;
2539}
2540
Tim Peters2a799bf2002-12-16 20:18:38 +00002541static PyObject *date_getstate(PyDateTime_Date *self);
2542
2543static long
2544date_hash(PyDateTime_Date *self)
2545{
2546 if (self->hashcode == -1) {
2547 PyObject *temp = date_getstate(self);
2548 if (temp != NULL) {
2549 self->hashcode = PyObject_Hash(temp);
2550 Py_DECREF(temp);
2551 }
2552 }
2553 return self->hashcode;
2554}
2555
2556static PyObject *
2557date_toordinal(PyDateTime_Date *self)
2558{
2559 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2560 GET_DAY(self)));
2561}
2562
2563static PyObject *
2564date_weekday(PyDateTime_Date *self)
2565{
2566 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2567
2568 return PyInt_FromLong(dow);
2569}
2570
Tim Peters371935f2003-02-01 01:52:50 +00002571/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002572
Tim Petersb57f8f02003-02-01 02:54:15 +00002573/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002574static PyObject *
2575date_getstate(PyDateTime_Date *self)
2576{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002577 return Py_BuildValue(
2578 "(N)",
2579 PyString_FromStringAndSize((char *)self->data,
2580 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002581}
2582
2583static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002584date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002585{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002586 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002587}
2588
2589static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002590
Tim Peters2a799bf2002-12-16 20:18:38 +00002591 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002592
Tim Peters2a799bf2002-12-16 20:18:38 +00002593 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2594 METH_CLASS,
2595 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2596 "time.time()).")},
2597
2598 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2599 METH_CLASS,
2600 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2601 "ordinal.")},
2602
2603 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2604 PyDoc_STR("Current date or datetime: same as "
2605 "self.__class__.fromtimestamp(time.time()).")},
2606
2607 /* Instance methods: */
2608
2609 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2610 PyDoc_STR("Return ctime() style string.")},
2611
2612 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2613 PyDoc_STR("format -> strftime() style string.")},
2614
2615 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2616 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2617
2618 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2619 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2620 "weekday.")},
2621
2622 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2623 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2624
2625 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2626 PyDoc_STR("Return the day of the week represented by the date.\n"
2627 "Monday == 1 ... Sunday == 7")},
2628
2629 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2630 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2631 "1 is day 1.")},
2632
2633 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2634 PyDoc_STR("Return the day of the week represented by the date.\n"
2635 "Monday == 0 ... Sunday == 6")},
2636
Tim Peters12bf3392002-12-24 05:41:27 +00002637 {"replace", (PyCFunction)date_replace, METH_KEYWORDS,
2638 PyDoc_STR("Return date with new specified fields.")},
2639
Guido van Rossum177e41a2003-01-30 22:06:23 +00002640 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2641 PyDoc_STR("__reduce__() -> (cls, state)")},
2642
Tim Peters2a799bf2002-12-16 20:18:38 +00002643 {NULL, NULL}
2644};
2645
2646static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002647PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002648
2649static PyNumberMethods date_as_number = {
2650 date_add, /* nb_add */
2651 date_subtract, /* nb_subtract */
2652 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002653 0, /* nb_remainder */
2654 0, /* nb_divmod */
2655 0, /* nb_power */
2656 0, /* nb_negative */
2657 0, /* nb_positive */
2658 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002659 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002660};
2661
2662static PyTypeObject PyDateTime_DateType = {
2663 PyObject_HEAD_INIT(NULL)
2664 0, /* ob_size */
2665 "datetime.date", /* tp_name */
2666 sizeof(PyDateTime_Date), /* tp_basicsize */
2667 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002668 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002669 0, /* tp_print */
2670 0, /* tp_getattr */
2671 0, /* tp_setattr */
2672 0, /* tp_compare */
2673 (reprfunc)date_repr, /* tp_repr */
2674 &date_as_number, /* tp_as_number */
2675 0, /* tp_as_sequence */
2676 0, /* tp_as_mapping */
2677 (hashfunc)date_hash, /* tp_hash */
2678 0, /* tp_call */
2679 (reprfunc)date_str, /* tp_str */
2680 PyObject_GenericGetAttr, /* tp_getattro */
2681 0, /* tp_setattro */
2682 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002683 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002684 date_doc, /* tp_doc */
2685 0, /* tp_traverse */
2686 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002687 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002688 0, /* tp_weaklistoffset */
2689 0, /* tp_iter */
2690 0, /* tp_iternext */
2691 date_methods, /* tp_methods */
2692 0, /* tp_members */
2693 date_getset, /* tp_getset */
2694 0, /* tp_base */
2695 0, /* tp_dict */
2696 0, /* tp_descr_get */
2697 0, /* tp_descr_set */
2698 0, /* tp_dictoffset */
2699 0, /* tp_init */
2700 0, /* tp_alloc */
2701 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002702 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002703};
2704
2705/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002706 * PyDateTime_TZInfo implementation.
2707 */
2708
2709/* This is a pure abstract base class, so doesn't do anything beyond
2710 * raising NotImplemented exceptions. Real tzinfo classes need
2711 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002712 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002713 * be subclasses of this tzinfo class, which is easy and quick to check).
2714 *
2715 * Note: For reasons having to do with pickling of subclasses, we have
2716 * to allow tzinfo objects to be instantiated. This wasn't an issue
2717 * in the Python implementation (__init__() could raise NotImplementedError
2718 * there without ill effect), but doing so in the C implementation hit a
2719 * brick wall.
2720 */
2721
2722static PyObject *
2723tzinfo_nogo(const char* methodname)
2724{
2725 PyErr_Format(PyExc_NotImplementedError,
2726 "a tzinfo subclass must implement %s()",
2727 methodname);
2728 return NULL;
2729}
2730
2731/* Methods. A subclass must implement these. */
2732
Tim Peters52dcce22003-01-23 16:36:11 +00002733static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002734tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2735{
2736 return tzinfo_nogo("tzname");
2737}
2738
Tim Peters52dcce22003-01-23 16:36:11 +00002739static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002740tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2741{
2742 return tzinfo_nogo("utcoffset");
2743}
2744
Tim Peters52dcce22003-01-23 16:36:11 +00002745static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002746tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2747{
2748 return tzinfo_nogo("dst");
2749}
2750
Tim Peters52dcce22003-01-23 16:36:11 +00002751static PyObject *
2752tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2753{
2754 int y, m, d, hh, mm, ss, us;
2755
2756 PyObject *result;
2757 int off, dst;
2758 int none;
2759 int delta;
2760
2761 if (! PyDateTime_Check(dt)) {
2762 PyErr_SetString(PyExc_TypeError,
2763 "fromutc: argument must be a datetime");
2764 return NULL;
2765 }
2766 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2767 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2768 "is not self");
2769 return NULL;
2770 }
2771
2772 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2773 if (off == -1 && PyErr_Occurred())
2774 return NULL;
2775 if (none) {
2776 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2777 "utcoffset() result required");
2778 return NULL;
2779 }
2780
2781 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2782 if (dst == -1 && PyErr_Occurred())
2783 return NULL;
2784 if (none) {
2785 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2786 "dst() result required");
2787 return NULL;
2788 }
2789
2790 y = GET_YEAR(dt);
2791 m = GET_MONTH(dt);
2792 d = GET_DAY(dt);
2793 hh = DATE_GET_HOUR(dt);
2794 mm = DATE_GET_MINUTE(dt);
2795 ss = DATE_GET_SECOND(dt);
2796 us = DATE_GET_MICROSECOND(dt);
2797
2798 delta = off - dst;
2799 mm += delta;
2800 if ((mm < 0 || mm >= 60) &&
2801 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002802 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002803 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2804 if (result == NULL)
2805 return result;
2806
2807 dst = call_dst(dt->tzinfo, result, &none);
2808 if (dst == -1 && PyErr_Occurred())
2809 goto Fail;
2810 if (none)
2811 goto Inconsistent;
2812 if (dst == 0)
2813 return result;
2814
2815 mm += dst;
2816 if ((mm < 0 || mm >= 60) &&
2817 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2818 goto Fail;
2819 Py_DECREF(result);
2820 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2821 return result;
2822
2823Inconsistent:
2824 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2825 "inconsistent results; cannot convert");
2826
2827 /* fall thru to failure */
2828Fail:
2829 Py_DECREF(result);
2830 return NULL;
2831}
2832
Tim Peters2a799bf2002-12-16 20:18:38 +00002833/*
2834 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002835 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002836 */
2837
Guido van Rossum177e41a2003-01-30 22:06:23 +00002838static PyObject *
2839tzinfo_reduce(PyObject *self)
2840{
2841 PyObject *args, *state, *tmp;
2842 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002843
Guido van Rossum177e41a2003-01-30 22:06:23 +00002844 tmp = PyTuple_New(0);
2845 if (tmp == NULL)
2846 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002847
Guido van Rossum177e41a2003-01-30 22:06:23 +00002848 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2849 if (getinitargs != NULL) {
2850 args = PyObject_CallObject(getinitargs, tmp);
2851 Py_DECREF(getinitargs);
2852 if (args == NULL) {
2853 Py_DECREF(tmp);
2854 return NULL;
2855 }
2856 }
2857 else {
2858 PyErr_Clear();
2859 args = tmp;
2860 Py_INCREF(args);
2861 }
2862
2863 getstate = PyObject_GetAttrString(self, "__getstate__");
2864 if (getstate != NULL) {
2865 state = PyObject_CallObject(getstate, tmp);
2866 Py_DECREF(getstate);
2867 if (state == NULL) {
2868 Py_DECREF(args);
2869 Py_DECREF(tmp);
2870 return NULL;
2871 }
2872 }
2873 else {
2874 PyObject **dictptr;
2875 PyErr_Clear();
2876 state = Py_None;
2877 dictptr = _PyObject_GetDictPtr(self);
2878 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2879 state = *dictptr;
2880 Py_INCREF(state);
2881 }
2882
2883 Py_DECREF(tmp);
2884
2885 if (state == Py_None) {
2886 Py_DECREF(state);
2887 return Py_BuildValue("(ON)", self->ob_type, args);
2888 }
2889 else
2890 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2891}
Tim Peters2a799bf2002-12-16 20:18:38 +00002892
2893static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002894
Tim Peters2a799bf2002-12-16 20:18:38 +00002895 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2896 PyDoc_STR("datetime -> string name of time zone.")},
2897
2898 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2899 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2900 "west of UTC).")},
2901
2902 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2903 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2904
Tim Peters52dcce22003-01-23 16:36:11 +00002905 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2906 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2907
Guido van Rossum177e41a2003-01-30 22:06:23 +00002908 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2909 PyDoc_STR("-> (cls, state)")},
2910
Tim Peters2a799bf2002-12-16 20:18:38 +00002911 {NULL, NULL}
2912};
2913
2914static char tzinfo_doc[] =
2915PyDoc_STR("Abstract base class for time zone info objects.");
2916
Neal Norwitz227b5332006-03-22 09:28:35 +00002917static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002918 PyObject_HEAD_INIT(NULL)
2919 0, /* ob_size */
2920 "datetime.tzinfo", /* tp_name */
2921 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2922 0, /* tp_itemsize */
2923 0, /* tp_dealloc */
2924 0, /* tp_print */
2925 0, /* tp_getattr */
2926 0, /* tp_setattr */
2927 0, /* tp_compare */
2928 0, /* tp_repr */
2929 0, /* tp_as_number */
2930 0, /* tp_as_sequence */
2931 0, /* tp_as_mapping */
2932 0, /* tp_hash */
2933 0, /* tp_call */
2934 0, /* tp_str */
2935 PyObject_GenericGetAttr, /* tp_getattro */
2936 0, /* tp_setattro */
2937 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002938 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002939 tzinfo_doc, /* tp_doc */
2940 0, /* tp_traverse */
2941 0, /* tp_clear */
2942 0, /* tp_richcompare */
2943 0, /* tp_weaklistoffset */
2944 0, /* tp_iter */
2945 0, /* tp_iternext */
2946 tzinfo_methods, /* tp_methods */
2947 0, /* tp_members */
2948 0, /* tp_getset */
2949 0, /* tp_base */
2950 0, /* tp_dict */
2951 0, /* tp_descr_get */
2952 0, /* tp_descr_set */
2953 0, /* tp_dictoffset */
2954 0, /* tp_init */
2955 0, /* tp_alloc */
2956 PyType_GenericNew, /* tp_new */
2957 0, /* tp_free */
2958};
2959
2960/*
Tim Peters37f39822003-01-10 03:49:02 +00002961 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002962 */
2963
Tim Peters37f39822003-01-10 03:49:02 +00002964/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002965 */
2966
2967static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002968time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002969{
Tim Peters37f39822003-01-10 03:49:02 +00002970 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002971}
2972
Tim Peters37f39822003-01-10 03:49:02 +00002973static PyObject *
2974time_minute(PyDateTime_Time *self, void *unused)
2975{
2976 return PyInt_FromLong(TIME_GET_MINUTE(self));
2977}
2978
2979/* The name time_second conflicted with some platform header file. */
2980static PyObject *
2981py_time_second(PyDateTime_Time *self, void *unused)
2982{
2983 return PyInt_FromLong(TIME_GET_SECOND(self));
2984}
2985
2986static PyObject *
2987time_microsecond(PyDateTime_Time *self, void *unused)
2988{
2989 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2990}
2991
2992static PyObject *
2993time_tzinfo(PyDateTime_Time *self, void *unused)
2994{
Tim Petersa032d2e2003-01-11 00:15:54 +00002995 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002996 Py_INCREF(result);
2997 return result;
2998}
2999
3000static PyGetSetDef time_getset[] = {
3001 {"hour", (getter)time_hour},
3002 {"minute", (getter)time_minute},
3003 {"second", (getter)py_time_second},
3004 {"microsecond", (getter)time_microsecond},
3005 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003006 {NULL}
3007};
3008
3009/*
3010 * Constructors.
3011 */
3012
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003013static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003014 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003015
Tim Peters2a799bf2002-12-16 20:18:38 +00003016static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003017time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003018{
3019 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003020 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003021 int hour = 0;
3022 int minute = 0;
3023 int second = 0;
3024 int usecond = 0;
3025 PyObject *tzinfo = Py_None;
3026
Guido van Rossum177e41a2003-01-30 22:06:23 +00003027 /* Check for invocation from pickle with __getstate__ state */
3028 if (PyTuple_GET_SIZE(args) >= 1 &&
3029 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003030 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003031 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3032 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003033 {
Tim Peters70533e22003-02-01 04:40:04 +00003034 PyDateTime_Time *me;
3035 char aware;
3036
3037 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003038 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003039 if (check_tzinfo_subclass(tzinfo) < 0) {
3040 PyErr_SetString(PyExc_TypeError, "bad "
3041 "tzinfo state arg");
3042 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003043 }
3044 }
Tim Peters70533e22003-02-01 04:40:04 +00003045 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003046 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003047 if (me != NULL) {
3048 char *pdata = PyString_AS_STRING(state);
3049
3050 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3051 me->hashcode = -1;
3052 me->hastzinfo = aware;
3053 if (aware) {
3054 Py_INCREF(tzinfo);
3055 me->tzinfo = tzinfo;
3056 }
3057 }
3058 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003059 }
3060
Tim Peters37f39822003-01-10 03:49:02 +00003061 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003062 &hour, &minute, &second, &usecond,
3063 &tzinfo)) {
3064 if (check_time_args(hour, minute, second, usecond) < 0)
3065 return NULL;
3066 if (check_tzinfo_subclass(tzinfo) < 0)
3067 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003068 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3069 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003070 }
3071 return self;
3072}
3073
3074/*
3075 * Destructor.
3076 */
3077
3078static void
Tim Peters37f39822003-01-10 03:49:02 +00003079time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003080{
Tim Petersa032d2e2003-01-11 00:15:54 +00003081 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003082 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003083 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003084 self->ob_type->tp_free((PyObject *)self);
3085}
3086
3087/*
Tim Peters855fe882002-12-22 03:43:39 +00003088 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003089 */
3090
Tim Peters2a799bf2002-12-16 20:18:38 +00003091/* These are all METH_NOARGS, so don't need to check the arglist. */
3092static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003093time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003094 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003095 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003096}
3097
3098static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003099time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003100 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003101 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003102}
3103
3104static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003105time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003106 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003107 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003108}
3109
3110/*
Tim Peters37f39822003-01-10 03:49:02 +00003111 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003112 */
3113
3114static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003115time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003116{
Tim Peters37f39822003-01-10 03:49:02 +00003117 char buffer[100];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003118 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003119 int h = TIME_GET_HOUR(self);
3120 int m = TIME_GET_MINUTE(self);
3121 int s = TIME_GET_SECOND(self);
3122 int us = TIME_GET_MICROSECOND(self);
3123 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003124
Tim Peters37f39822003-01-10 03:49:02 +00003125 if (us)
3126 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003127 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003128 else if (s)
3129 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003130 "%s(%d, %d, %d)", type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003131 else
3132 PyOS_snprintf(buffer, sizeof(buffer),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003133 "%s(%d, %d)", type_name, h, m);
Tim Peters37f39822003-01-10 03:49:02 +00003134 result = PyString_FromString(buffer);
Tim Petersa032d2e2003-01-11 00:15:54 +00003135 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003136 result = append_keyword_tzinfo(result, self->tzinfo);
3137 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003138}
3139
Tim Peters37f39822003-01-10 03:49:02 +00003140static PyObject *
3141time_str(PyDateTime_Time *self)
3142{
3143 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3144}
Tim Peters2a799bf2002-12-16 20:18:38 +00003145
3146static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003147time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003148{
3149 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003150 PyObject *result;
3151 /* Reuse the time format code from the datetime type. */
3152 PyDateTime_DateTime datetime;
3153 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003154
Tim Peters37f39822003-01-10 03:49:02 +00003155 /* Copy over just the time bytes. */
3156 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3157 self->data,
3158 _PyDateTime_TIME_DATASIZE);
3159
3160 isoformat_time(pdatetime, buf, sizeof(buf));
3161 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003162 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003163 return result;
3164
3165 /* We need to append the UTC offset. */
3166 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003167 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003168 Py_DECREF(result);
3169 return NULL;
3170 }
3171 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3172 return result;
3173}
3174
Tim Peters37f39822003-01-10 03:49:02 +00003175static PyObject *
3176time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3177{
3178 PyObject *result;
3179 PyObject *format;
3180 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003181 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003182
Guido van Rossumbce56a62007-05-10 18:04:33 +00003183 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3184 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003185 return NULL;
3186
3187 /* Python's strftime does insane things with the year part of the
3188 * timetuple. The year is forced to (the otherwise nonsensical)
3189 * 1900 to worm around that.
3190 */
3191 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003192 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003193 TIME_GET_HOUR(self),
3194 TIME_GET_MINUTE(self),
3195 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003196 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003197 if (tuple == NULL)
3198 return NULL;
3199 assert(PyTuple_Size(tuple) == 9);
3200 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3201 Py_DECREF(tuple);
3202 return result;
3203}
Tim Peters2a799bf2002-12-16 20:18:38 +00003204
3205/*
3206 * Miscellaneous methods.
3207 */
3208
Tim Peters37f39822003-01-10 03:49:02 +00003209static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003210time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003211{
3212 int diff;
3213 naivety n1, n2;
3214 int offset1, offset2;
3215
3216 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003217 Py_INCREF(Py_NotImplemented);
3218 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003219 }
Guido van Rossum19960592006-08-24 17:29:38 +00003220 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3221 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003222 return NULL;
3223 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3224 /* If they're both naive, or both aware and have the same offsets,
3225 * we get off cheap. Note that if they're both naive, offset1 ==
3226 * offset2 == 0 at this point.
3227 */
3228 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003229 diff = memcmp(((PyDateTime_Time *)self)->data,
3230 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003231 _PyDateTime_TIME_DATASIZE);
3232 return diff_to_bool(diff, op);
3233 }
3234
3235 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3236 assert(offset1 != offset2); /* else last "if" handled it */
3237 /* Convert everything except microseconds to seconds. These
3238 * can't overflow (no more than the # of seconds in 2 days).
3239 */
3240 offset1 = TIME_GET_HOUR(self) * 3600 +
3241 (TIME_GET_MINUTE(self) - offset1) * 60 +
3242 TIME_GET_SECOND(self);
3243 offset2 = TIME_GET_HOUR(other) * 3600 +
3244 (TIME_GET_MINUTE(other) - offset2) * 60 +
3245 TIME_GET_SECOND(other);
3246 diff = offset1 - offset2;
3247 if (diff == 0)
3248 diff = TIME_GET_MICROSECOND(self) -
3249 TIME_GET_MICROSECOND(other);
3250 return diff_to_bool(diff, op);
3251 }
3252
3253 assert(n1 != n2);
3254 PyErr_SetString(PyExc_TypeError,
3255 "can't compare offset-naive and "
3256 "offset-aware times");
3257 return NULL;
3258}
3259
3260static long
3261time_hash(PyDateTime_Time *self)
3262{
3263 if (self->hashcode == -1) {
3264 naivety n;
3265 int offset;
3266 PyObject *temp;
3267
3268 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3269 assert(n != OFFSET_UNKNOWN);
3270 if (n == OFFSET_ERROR)
3271 return -1;
3272
3273 /* Reduce this to a hash of another object. */
3274 if (offset == 0)
3275 temp = PyString_FromStringAndSize((char *)self->data,
3276 _PyDateTime_TIME_DATASIZE);
3277 else {
3278 int hour;
3279 int minute;
3280
3281 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003282 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003283 hour = divmod(TIME_GET_HOUR(self) * 60 +
3284 TIME_GET_MINUTE(self) - offset,
3285 60,
3286 &minute);
3287 if (0 <= hour && hour < 24)
3288 temp = new_time(hour, minute,
3289 TIME_GET_SECOND(self),
3290 TIME_GET_MICROSECOND(self),
3291 Py_None);
3292 else
3293 temp = Py_BuildValue("iiii",
3294 hour, minute,
3295 TIME_GET_SECOND(self),
3296 TIME_GET_MICROSECOND(self));
3297 }
3298 if (temp != NULL) {
3299 self->hashcode = PyObject_Hash(temp);
3300 Py_DECREF(temp);
3301 }
3302 }
3303 return self->hashcode;
3304}
Tim Peters2a799bf2002-12-16 20:18:38 +00003305
Tim Peters12bf3392002-12-24 05:41:27 +00003306static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003307time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003308{
3309 PyObject *clone;
3310 PyObject *tuple;
3311 int hh = TIME_GET_HOUR(self);
3312 int mm = TIME_GET_MINUTE(self);
3313 int ss = TIME_GET_SECOND(self);
3314 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003315 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003316
3317 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003318 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003319 &hh, &mm, &ss, &us, &tzinfo))
3320 return NULL;
3321 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3322 if (tuple == NULL)
3323 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003324 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003325 Py_DECREF(tuple);
3326 return clone;
3327}
3328
Tim Peters2a799bf2002-12-16 20:18:38 +00003329static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003330time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003331{
3332 int offset;
3333 int none;
3334
3335 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3336 /* Since utcoffset is in whole minutes, nothing can
3337 * alter the conclusion that this is nonzero.
3338 */
3339 return 1;
3340 }
3341 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003342 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003343 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003344 if (offset == -1 && PyErr_Occurred())
3345 return -1;
3346 }
3347 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3348}
3349
Tim Peters371935f2003-02-01 01:52:50 +00003350/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003351
Tim Peters33e0f382003-01-10 02:05:14 +00003352/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003353 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3354 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003355 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003356 */
3357static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003358time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003359{
3360 PyObject *basestate;
3361 PyObject *result = NULL;
3362
Tim Peters33e0f382003-01-10 02:05:14 +00003363 basestate = PyString_FromStringAndSize((char *)self->data,
3364 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003365 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003366 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003367 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003368 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003369 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003370 Py_DECREF(basestate);
3371 }
3372 return result;
3373}
3374
3375static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003376time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003377{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003378 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003379}
3380
Tim Peters37f39822003-01-10 03:49:02 +00003381static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003382
Thomas Wouterscf297e42007-02-23 15:07:44 +00003383 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003384 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3385 "[+HH:MM].")},
3386
Tim Peters37f39822003-01-10 03:49:02 +00003387 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3388 PyDoc_STR("format -> strftime() style string.")},
3389
3390 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003391 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3392
Tim Peters37f39822003-01-10 03:49:02 +00003393 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003394 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3395
Tim Peters37f39822003-01-10 03:49:02 +00003396 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003397 PyDoc_STR("Return self.tzinfo.dst(self).")},
3398
Tim Peters37f39822003-01-10 03:49:02 +00003399 {"replace", (PyCFunction)time_replace, METH_KEYWORDS,
3400 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003401
Guido van Rossum177e41a2003-01-30 22:06:23 +00003402 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3403 PyDoc_STR("__reduce__() -> (cls, state)")},
3404
Tim Peters2a799bf2002-12-16 20:18:38 +00003405 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003406};
3407
Tim Peters37f39822003-01-10 03:49:02 +00003408static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003409PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3410\n\
3411All arguments are optional. tzinfo may be None, or an instance of\n\
3412a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003413
Tim Peters37f39822003-01-10 03:49:02 +00003414static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003415 0, /* nb_add */
3416 0, /* nb_subtract */
3417 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003418 0, /* nb_remainder */
3419 0, /* nb_divmod */
3420 0, /* nb_power */
3421 0, /* nb_negative */
3422 0, /* nb_positive */
3423 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003424 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003425};
3426
Neal Norwitz227b5332006-03-22 09:28:35 +00003427static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 PyObject_HEAD_INIT(NULL)
3429 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003430 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003431 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003432 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003433 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003434 0, /* tp_print */
3435 0, /* tp_getattr */
3436 0, /* tp_setattr */
3437 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003438 (reprfunc)time_repr, /* tp_repr */
3439 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003440 0, /* tp_as_sequence */
3441 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003442 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003443 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003444 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003445 PyObject_GenericGetAttr, /* tp_getattro */
3446 0, /* tp_setattro */
3447 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003448 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003449 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003450 0, /* tp_traverse */
3451 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003452 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003453 0, /* tp_weaklistoffset */
3454 0, /* tp_iter */
3455 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003456 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003457 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003458 time_getset, /* tp_getset */
3459 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003460 0, /* tp_dict */
3461 0, /* tp_descr_get */
3462 0, /* tp_descr_set */
3463 0, /* tp_dictoffset */
3464 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003465 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003466 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003467 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003468};
3469
3470/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003471 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003472 */
3473
Tim Petersa9bc1682003-01-11 03:39:11 +00003474/* Accessor properties. Properties for day, month, and year are inherited
3475 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003476 */
3477
3478static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003479datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003480{
Tim Petersa9bc1682003-01-11 03:39:11 +00003481 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003482}
3483
Tim Petersa9bc1682003-01-11 03:39:11 +00003484static PyObject *
3485datetime_minute(PyDateTime_DateTime *self, void *unused)
3486{
3487 return PyInt_FromLong(DATE_GET_MINUTE(self));
3488}
3489
3490static PyObject *
3491datetime_second(PyDateTime_DateTime *self, void *unused)
3492{
3493 return PyInt_FromLong(DATE_GET_SECOND(self));
3494}
3495
3496static PyObject *
3497datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3498{
3499 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3500}
3501
3502static PyObject *
3503datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3504{
3505 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3506 Py_INCREF(result);
3507 return result;
3508}
3509
3510static PyGetSetDef datetime_getset[] = {
3511 {"hour", (getter)datetime_hour},
3512 {"minute", (getter)datetime_minute},
3513 {"second", (getter)datetime_second},
3514 {"microsecond", (getter)datetime_microsecond},
3515 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003516 {NULL}
3517};
3518
3519/*
3520 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003521 */
3522
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003523static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003524 "year", "month", "day", "hour", "minute", "second",
3525 "microsecond", "tzinfo", NULL
3526};
3527
Tim Peters2a799bf2002-12-16 20:18:38 +00003528static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003529datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003530{
3531 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003532 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003533 int year;
3534 int month;
3535 int day;
3536 int hour = 0;
3537 int minute = 0;
3538 int second = 0;
3539 int usecond = 0;
3540 PyObject *tzinfo = Py_None;
3541
Guido van Rossum177e41a2003-01-30 22:06:23 +00003542 /* Check for invocation from pickle with __getstate__ state */
3543 if (PyTuple_GET_SIZE(args) >= 1 &&
3544 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003545 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003546 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3547 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003548 {
Tim Peters70533e22003-02-01 04:40:04 +00003549 PyDateTime_DateTime *me;
3550 char aware;
3551
3552 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003553 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003554 if (check_tzinfo_subclass(tzinfo) < 0) {
3555 PyErr_SetString(PyExc_TypeError, "bad "
3556 "tzinfo state arg");
3557 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003558 }
3559 }
Tim Peters70533e22003-02-01 04:40:04 +00003560 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003561 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003562 if (me != NULL) {
3563 char *pdata = PyString_AS_STRING(state);
3564
3565 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3566 me->hashcode = -1;
3567 me->hastzinfo = aware;
3568 if (aware) {
3569 Py_INCREF(tzinfo);
3570 me->tzinfo = tzinfo;
3571 }
3572 }
3573 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003574 }
3575
Tim Petersa9bc1682003-01-11 03:39:11 +00003576 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003577 &year, &month, &day, &hour, &minute,
3578 &second, &usecond, &tzinfo)) {
3579 if (check_date_args(year, month, day) < 0)
3580 return NULL;
3581 if (check_time_args(hour, minute, second, usecond) < 0)
3582 return NULL;
3583 if (check_tzinfo_subclass(tzinfo) < 0)
3584 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003585 self = new_datetime_ex(year, month, day,
3586 hour, minute, second, usecond,
3587 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003588 }
3589 return self;
3590}
3591
Tim Petersa9bc1682003-01-11 03:39:11 +00003592/* TM_FUNC is the shared type of localtime() and gmtime(). */
3593typedef struct tm *(*TM_FUNC)(const time_t *timer);
3594
3595/* Internal helper.
3596 * Build datetime from a time_t and a distinct count of microseconds.
3597 * Pass localtime or gmtime for f, to control the interpretation of timet.
3598 */
3599static PyObject *
3600datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3601 PyObject *tzinfo)
3602{
3603 struct tm *tm;
3604 PyObject *result = NULL;
3605
3606 tm = f(&timet);
3607 if (tm) {
3608 /* The platform localtime/gmtime may insert leap seconds,
3609 * indicated by tm->tm_sec > 59. We don't care about them,
3610 * except to the extent that passing them on to the datetime
3611 * constructor would raise ValueError for a reason that
3612 * made no sense to the user.
3613 */
3614 if (tm->tm_sec > 59)
3615 tm->tm_sec = 59;
3616 result = PyObject_CallFunction(cls, "iiiiiiiO",
3617 tm->tm_year + 1900,
3618 tm->tm_mon + 1,
3619 tm->tm_mday,
3620 tm->tm_hour,
3621 tm->tm_min,
3622 tm->tm_sec,
3623 us,
3624 tzinfo);
3625 }
3626 else
3627 PyErr_SetString(PyExc_ValueError,
3628 "timestamp out of range for "
3629 "platform localtime()/gmtime() function");
3630 return result;
3631}
3632
3633/* Internal helper.
3634 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3635 * to control the interpretation of the timestamp. Since a double doesn't
3636 * have enough bits to cover a datetime's full range of precision, it's
3637 * better to call datetime_from_timet_and_us provided you have a way
3638 * to get that much precision (e.g., C time() isn't good enough).
3639 */
3640static PyObject *
3641datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3642 PyObject *tzinfo)
3643{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003644 time_t timet;
3645 double fraction;
3646 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003647
Tim Peters1b6f7a92004-06-20 02:50:16 +00003648 timet = _PyTime_DoubleToTimet(timestamp);
3649 if (timet == (time_t)-1 && PyErr_Occurred())
3650 return NULL;
3651 fraction = timestamp - (double)timet;
3652 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003653 if (us < 0) {
3654 /* Truncation towards zero is not what we wanted
3655 for negative numbers (Python's mod semantics) */
3656 timet -= 1;
3657 us += 1000000;
3658 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003659 /* If timestamp is less than one microsecond smaller than a
3660 * full second, round up. Otherwise, ValueErrors are raised
3661 * for some floats. */
3662 if (us == 1000000) {
3663 timet += 1;
3664 us = 0;
3665 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003666 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3667}
3668
3669/* Internal helper.
3670 * Build most accurate possible datetime for current time. Pass localtime or
3671 * gmtime for f as appropriate.
3672 */
3673static PyObject *
3674datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3675{
3676#ifdef HAVE_GETTIMEOFDAY
3677 struct timeval t;
3678
3679#ifdef GETTIMEOFDAY_NO_TZ
3680 gettimeofday(&t);
3681#else
3682 gettimeofday(&t, (struct timezone *)NULL);
3683#endif
3684 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3685 tzinfo);
3686
3687#else /* ! HAVE_GETTIMEOFDAY */
3688 /* No flavor of gettimeofday exists on this platform. Python's
3689 * time.time() does a lot of other platform tricks to get the
3690 * best time it can on the platform, and we're not going to do
3691 * better than that (if we could, the better code would belong
3692 * in time.time()!) We're limited by the precision of a double,
3693 * though.
3694 */
3695 PyObject *time;
3696 double dtime;
3697
3698 time = time_time();
3699 if (time == NULL)
3700 return NULL;
3701 dtime = PyFloat_AsDouble(time);
3702 Py_DECREF(time);
3703 if (dtime == -1.0 && PyErr_Occurred())
3704 return NULL;
3705 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3706#endif /* ! HAVE_GETTIMEOFDAY */
3707}
3708
Tim Peters2a799bf2002-12-16 20:18:38 +00003709/* Return best possible local time -- this isn't constrained by the
3710 * precision of a timestamp.
3711 */
3712static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003713datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003714{
Tim Peters10cadce2003-01-23 19:58:02 +00003715 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003716 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003717 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003718
Tim Peters10cadce2003-01-23 19:58:02 +00003719 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3720 &tzinfo))
3721 return NULL;
3722 if (check_tzinfo_subclass(tzinfo) < 0)
3723 return NULL;
3724
3725 self = datetime_best_possible(cls,
3726 tzinfo == Py_None ? localtime : gmtime,
3727 tzinfo);
3728 if (self != NULL && tzinfo != Py_None) {
3729 /* Convert UTC to tzinfo's zone. */
3730 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003731 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003732 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003733 }
3734 return self;
3735}
3736
Tim Petersa9bc1682003-01-11 03:39:11 +00003737/* Return best possible UTC time -- this isn't constrained by the
3738 * precision of a timestamp.
3739 */
3740static PyObject *
3741datetime_utcnow(PyObject *cls, PyObject *dummy)
3742{
3743 return datetime_best_possible(cls, gmtime, Py_None);
3744}
3745
Tim Peters2a799bf2002-12-16 20:18:38 +00003746/* Return new local datetime from timestamp (Python timestamp -- a double). */
3747static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003748datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003749{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003750 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003751 double timestamp;
3752 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003753 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003754
Tim Peters2a44a8d2003-01-23 20:53:10 +00003755 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3756 keywords, &timestamp, &tzinfo))
3757 return NULL;
3758 if (check_tzinfo_subclass(tzinfo) < 0)
3759 return NULL;
3760
3761 self = datetime_from_timestamp(cls,
3762 tzinfo == Py_None ? localtime : gmtime,
3763 timestamp,
3764 tzinfo);
3765 if (self != NULL && tzinfo != Py_None) {
3766 /* Convert UTC to tzinfo's zone. */
3767 PyObject *temp = self;
3768 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3769 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003770 }
3771 return self;
3772}
3773
Tim Petersa9bc1682003-01-11 03:39:11 +00003774/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3775static PyObject *
3776datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3777{
3778 double timestamp;
3779 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003780
Tim Petersa9bc1682003-01-11 03:39:11 +00003781 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3782 result = datetime_from_timestamp(cls, gmtime, timestamp,
3783 Py_None);
3784 return result;
3785}
3786
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003787/* Return new datetime from time.strptime(). */
3788static PyObject *
3789datetime_strptime(PyObject *cls, PyObject *args)
3790{
3791 PyObject *result = NULL, *obj, *module;
3792 const char *string, *format;
3793
3794 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3795 return NULL;
3796
3797 if ((module = PyImport_ImportModule("time")) == NULL)
3798 return NULL;
3799 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3800 Py_DECREF(module);
3801
3802 if (obj != NULL) {
3803 int i, good_timetuple = 1;
3804 long int ia[6];
3805 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3806 for (i=0; i < 6; i++) {
3807 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003808 if (p == NULL) {
3809 Py_DECREF(obj);
3810 return NULL;
3811 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003812 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003813 ia[i] = PyInt_AsLong(p);
3814 else
3815 good_timetuple = 0;
3816 Py_DECREF(p);
3817 }
3818 else
3819 good_timetuple = 0;
3820 if (good_timetuple)
3821 result = PyObject_CallFunction(cls, "iiiiii",
3822 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3823 else
3824 PyErr_SetString(PyExc_ValueError,
3825 "unexpected value from time.strptime");
3826 Py_DECREF(obj);
3827 }
3828 return result;
3829}
3830
Tim Petersa9bc1682003-01-11 03:39:11 +00003831/* Return new datetime from date/datetime and time arguments. */
3832static PyObject *
3833datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3834{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003835 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003836 PyObject *date;
3837 PyObject *time;
3838 PyObject *result = NULL;
3839
3840 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3841 &PyDateTime_DateType, &date,
3842 &PyDateTime_TimeType, &time)) {
3843 PyObject *tzinfo = Py_None;
3844
3845 if (HASTZINFO(time))
3846 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3847 result = PyObject_CallFunction(cls, "iiiiiiiO",
3848 GET_YEAR(date),
3849 GET_MONTH(date),
3850 GET_DAY(date),
3851 TIME_GET_HOUR(time),
3852 TIME_GET_MINUTE(time),
3853 TIME_GET_SECOND(time),
3854 TIME_GET_MICROSECOND(time),
3855 tzinfo);
3856 }
3857 return result;
3858}
Tim Peters2a799bf2002-12-16 20:18:38 +00003859
3860/*
3861 * Destructor.
3862 */
3863
3864static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003865datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003866{
Tim Petersa9bc1682003-01-11 03:39:11 +00003867 if (HASTZINFO(self)) {
3868 Py_XDECREF(self->tzinfo);
3869 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003870 self->ob_type->tp_free((PyObject *)self);
3871}
3872
3873/*
3874 * Indirect access to tzinfo methods.
3875 */
3876
Tim Peters2a799bf2002-12-16 20:18:38 +00003877/* These are all METH_NOARGS, so don't need to check the arglist. */
3878static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003879datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3880 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3881 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003882}
3883
3884static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003885datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3886 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3887 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003888}
3889
3890static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003891datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3892 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3893 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003894}
3895
3896/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003897 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003898 */
3899
Tim Petersa9bc1682003-01-11 03:39:11 +00003900/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3901 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003902 */
3903static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003904add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3905 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003906{
Tim Petersa9bc1682003-01-11 03:39:11 +00003907 /* Note that the C-level additions can't overflow, because of
3908 * invariant bounds on the member values.
3909 */
3910 int year = GET_YEAR(date);
3911 int month = GET_MONTH(date);
3912 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3913 int hour = DATE_GET_HOUR(date);
3914 int minute = DATE_GET_MINUTE(date);
3915 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3916 int microsecond = DATE_GET_MICROSECOND(date) +
3917 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003918
Tim Petersa9bc1682003-01-11 03:39:11 +00003919 assert(factor == 1 || factor == -1);
3920 if (normalize_datetime(&year, &month, &day,
3921 &hour, &minute, &second, &microsecond) < 0)
3922 return NULL;
3923 else
3924 return new_datetime(year, month, day,
3925 hour, minute, second, microsecond,
3926 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003927}
3928
3929static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003930datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003931{
Tim Petersa9bc1682003-01-11 03:39:11 +00003932 if (PyDateTime_Check(left)) {
3933 /* datetime + ??? */
3934 if (PyDelta_Check(right))
3935 /* datetime + delta */
3936 return add_datetime_timedelta(
3937 (PyDateTime_DateTime *)left,
3938 (PyDateTime_Delta *)right,
3939 1);
3940 }
3941 else if (PyDelta_Check(left)) {
3942 /* delta + datetime */
3943 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3944 (PyDateTime_Delta *) left,
3945 1);
3946 }
3947 Py_INCREF(Py_NotImplemented);
3948 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003949}
3950
3951static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003952datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003953{
3954 PyObject *result = Py_NotImplemented;
3955
3956 if (PyDateTime_Check(left)) {
3957 /* datetime - ??? */
3958 if (PyDateTime_Check(right)) {
3959 /* datetime - datetime */
3960 naivety n1, n2;
3961 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003962 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003963
Tim Peterse39a80c2002-12-30 21:28:52 +00003964 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3965 right, &offset2, &n2,
3966 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003967 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003968 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003969 if (n1 != n2) {
3970 PyErr_SetString(PyExc_TypeError,
3971 "can't subtract offset-naive and "
3972 "offset-aware datetimes");
3973 return NULL;
3974 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003975 delta_d = ymd_to_ord(GET_YEAR(left),
3976 GET_MONTH(left),
3977 GET_DAY(left)) -
3978 ymd_to_ord(GET_YEAR(right),
3979 GET_MONTH(right),
3980 GET_DAY(right));
3981 /* These can't overflow, since the values are
3982 * normalized. At most this gives the number of
3983 * seconds in one day.
3984 */
3985 delta_s = (DATE_GET_HOUR(left) -
3986 DATE_GET_HOUR(right)) * 3600 +
3987 (DATE_GET_MINUTE(left) -
3988 DATE_GET_MINUTE(right)) * 60 +
3989 (DATE_GET_SECOND(left) -
3990 DATE_GET_SECOND(right));
3991 delta_us = DATE_GET_MICROSECOND(left) -
3992 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003993 /* (left - offset1) - (right - offset2) =
3994 * (left - right) + (offset2 - offset1)
3995 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003996 delta_s += (offset2 - offset1) * 60;
3997 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003998 }
3999 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004000 /* datetime - delta */
4001 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004002 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004003 (PyDateTime_Delta *)right,
4004 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004005 }
4006 }
4007
4008 if (result == Py_NotImplemented)
4009 Py_INCREF(result);
4010 return result;
4011}
4012
4013/* Various ways to turn a datetime into a string. */
4014
4015static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004016datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004017{
Tim Petersa9bc1682003-01-11 03:39:11 +00004018 char buffer[1000];
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004019 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004020 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004021
Tim Petersa9bc1682003-01-11 03:39:11 +00004022 if (DATE_GET_MICROSECOND(self)) {
4023 PyOS_snprintf(buffer, sizeof(buffer),
4024 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004025 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004026 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4027 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4028 DATE_GET_SECOND(self),
4029 DATE_GET_MICROSECOND(self));
4030 }
4031 else if (DATE_GET_SECOND(self)) {
4032 PyOS_snprintf(buffer, sizeof(buffer),
4033 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004034 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004035 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4036 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4037 DATE_GET_SECOND(self));
4038 }
4039 else {
4040 PyOS_snprintf(buffer, sizeof(buffer),
4041 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004042 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004043 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4044 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4045 }
4046 baserepr = PyString_FromString(buffer);
4047 if (baserepr == NULL || ! HASTZINFO(self))
4048 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004049 return append_keyword_tzinfo(baserepr, self->tzinfo);
4050}
4051
Tim Petersa9bc1682003-01-11 03:39:11 +00004052static PyObject *
4053datetime_str(PyDateTime_DateTime *self)
4054{
4055 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4056}
Tim Peters2a799bf2002-12-16 20:18:38 +00004057
4058static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004059datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004060{
Tim Petersa9bc1682003-01-11 03:39:11 +00004061 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004062 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004063 char buffer[100];
4064 char *cp;
4065 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004066
Tim Petersa9bc1682003-01-11 03:39:11 +00004067 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4068 &sep))
4069 return NULL;
4070 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4071 assert(cp != NULL);
4072 *cp++ = sep;
4073 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4074 result = PyString_FromString(buffer);
4075 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004076 return result;
4077
4078 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004079 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004080 (PyObject *)self) < 0) {
4081 Py_DECREF(result);
4082 return NULL;
4083 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004084 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004085 return result;
4086}
4087
Tim Petersa9bc1682003-01-11 03:39:11 +00004088static PyObject *
4089datetime_ctime(PyDateTime_DateTime *self)
4090{
4091 return format_ctime((PyDateTime_Date *)self,
4092 DATE_GET_HOUR(self),
4093 DATE_GET_MINUTE(self),
4094 DATE_GET_SECOND(self));
4095}
4096
Tim Peters2a799bf2002-12-16 20:18:38 +00004097/* Miscellaneous methods. */
4098
Tim Petersa9bc1682003-01-11 03:39:11 +00004099static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004100datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004101{
4102 int diff;
4103 naivety n1, n2;
4104 int offset1, offset2;
4105
4106 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004107 if (PyDate_Check(other)) {
4108 /* Prevent invocation of date_richcompare. We want to
4109 return NotImplemented here to give the other object
4110 a chance. But since DateTime is a subclass of
4111 Date, if the other object is a Date, it would
4112 compute an ordering based on the date part alone,
4113 and we don't want that. So force unequal or
4114 uncomparable here in that case. */
4115 if (op == Py_EQ)
4116 Py_RETURN_FALSE;
4117 if (op == Py_NE)
4118 Py_RETURN_TRUE;
4119 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004120 }
Guido van Rossum19960592006-08-24 17:29:38 +00004121 Py_INCREF(Py_NotImplemented);
4122 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004123 }
4124
Guido van Rossum19960592006-08-24 17:29:38 +00004125 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4126 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004127 return NULL;
4128 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4129 /* If they're both naive, or both aware and have the same offsets,
4130 * we get off cheap. Note that if they're both naive, offset1 ==
4131 * offset2 == 0 at this point.
4132 */
4133 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004134 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4135 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004136 _PyDateTime_DATETIME_DATASIZE);
4137 return diff_to_bool(diff, op);
4138 }
4139
4140 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4141 PyDateTime_Delta *delta;
4142
4143 assert(offset1 != offset2); /* else last "if" handled it */
4144 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4145 other);
4146 if (delta == NULL)
4147 return NULL;
4148 diff = GET_TD_DAYS(delta);
4149 if (diff == 0)
4150 diff = GET_TD_SECONDS(delta) |
4151 GET_TD_MICROSECONDS(delta);
4152 Py_DECREF(delta);
4153 return diff_to_bool(diff, op);
4154 }
4155
4156 assert(n1 != n2);
4157 PyErr_SetString(PyExc_TypeError,
4158 "can't compare offset-naive and "
4159 "offset-aware datetimes");
4160 return NULL;
4161}
4162
4163static long
4164datetime_hash(PyDateTime_DateTime *self)
4165{
4166 if (self->hashcode == -1) {
4167 naivety n;
4168 int offset;
4169 PyObject *temp;
4170
4171 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4172 &offset);
4173 assert(n != OFFSET_UNKNOWN);
4174 if (n == OFFSET_ERROR)
4175 return -1;
4176
4177 /* Reduce this to a hash of another object. */
4178 if (n == OFFSET_NAIVE)
4179 temp = PyString_FromStringAndSize(
4180 (char *)self->data,
4181 _PyDateTime_DATETIME_DATASIZE);
4182 else {
4183 int days;
4184 int seconds;
4185
4186 assert(n == OFFSET_AWARE);
4187 assert(HASTZINFO(self));
4188 days = ymd_to_ord(GET_YEAR(self),
4189 GET_MONTH(self),
4190 GET_DAY(self));
4191 seconds = DATE_GET_HOUR(self) * 3600 +
4192 (DATE_GET_MINUTE(self) - offset) * 60 +
4193 DATE_GET_SECOND(self);
4194 temp = new_delta(days,
4195 seconds,
4196 DATE_GET_MICROSECOND(self),
4197 1);
4198 }
4199 if (temp != NULL) {
4200 self->hashcode = PyObject_Hash(temp);
4201 Py_DECREF(temp);
4202 }
4203 }
4204 return self->hashcode;
4205}
Tim Peters2a799bf2002-12-16 20:18:38 +00004206
4207static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004208datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004209{
4210 PyObject *clone;
4211 PyObject *tuple;
4212 int y = GET_YEAR(self);
4213 int m = GET_MONTH(self);
4214 int d = GET_DAY(self);
4215 int hh = DATE_GET_HOUR(self);
4216 int mm = DATE_GET_MINUTE(self);
4217 int ss = DATE_GET_SECOND(self);
4218 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004219 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004220
4221 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004222 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004223 &y, &m, &d, &hh, &mm, &ss, &us,
4224 &tzinfo))
4225 return NULL;
4226 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4227 if (tuple == NULL)
4228 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004229 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004230 Py_DECREF(tuple);
4231 return clone;
4232}
4233
4234static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004235datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004236{
Tim Peters52dcce22003-01-23 16:36:11 +00004237 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004238 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004239 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004240
Tim Peters80475bb2002-12-25 07:40:55 +00004241 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004242 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004243
Tim Peters52dcce22003-01-23 16:36:11 +00004244 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4245 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004246 return NULL;
4247
Tim Peters52dcce22003-01-23 16:36:11 +00004248 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4249 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004250
Tim Peters52dcce22003-01-23 16:36:11 +00004251 /* Conversion to self's own time zone is a NOP. */
4252 if (self->tzinfo == tzinfo) {
4253 Py_INCREF(self);
4254 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004255 }
Tim Peters521fc152002-12-31 17:36:56 +00004256
Tim Peters52dcce22003-01-23 16:36:11 +00004257 /* Convert self to UTC. */
4258 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4259 if (offset == -1 && PyErr_Occurred())
4260 return NULL;
4261 if (none)
4262 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004263
Tim Peters52dcce22003-01-23 16:36:11 +00004264 y = GET_YEAR(self);
4265 m = GET_MONTH(self);
4266 d = GET_DAY(self);
4267 hh = DATE_GET_HOUR(self);
4268 mm = DATE_GET_MINUTE(self);
4269 ss = DATE_GET_SECOND(self);
4270 us = DATE_GET_MICROSECOND(self);
4271
4272 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004273 if ((mm < 0 || mm >= 60) &&
4274 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004275 return NULL;
4276
4277 /* Attach new tzinfo and let fromutc() do the rest. */
4278 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4279 if (result != NULL) {
4280 PyObject *temp = result;
4281
4282 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4283 Py_DECREF(temp);
4284 }
Tim Petersadf64202003-01-04 06:03:15 +00004285 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004286
Tim Peters52dcce22003-01-23 16:36:11 +00004287NeedAware:
4288 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4289 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004290 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004291}
4292
4293static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004294datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004295{
4296 int dstflag = -1;
4297
Tim Petersa9bc1682003-01-11 03:39:11 +00004298 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004299 int none;
4300
4301 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4302 if (dstflag == -1 && PyErr_Occurred())
4303 return NULL;
4304
4305 if (none)
4306 dstflag = -1;
4307 else if (dstflag != 0)
4308 dstflag = 1;
4309
4310 }
4311 return build_struct_time(GET_YEAR(self),
4312 GET_MONTH(self),
4313 GET_DAY(self),
4314 DATE_GET_HOUR(self),
4315 DATE_GET_MINUTE(self),
4316 DATE_GET_SECOND(self),
4317 dstflag);
4318}
4319
4320static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004321datetime_getdate(PyDateTime_DateTime *self)
4322{
4323 return new_date(GET_YEAR(self),
4324 GET_MONTH(self),
4325 GET_DAY(self));
4326}
4327
4328static PyObject *
4329datetime_gettime(PyDateTime_DateTime *self)
4330{
4331 return new_time(DATE_GET_HOUR(self),
4332 DATE_GET_MINUTE(self),
4333 DATE_GET_SECOND(self),
4334 DATE_GET_MICROSECOND(self),
4335 Py_None);
4336}
4337
4338static PyObject *
4339datetime_gettimetz(PyDateTime_DateTime *self)
4340{
4341 return new_time(DATE_GET_HOUR(self),
4342 DATE_GET_MINUTE(self),
4343 DATE_GET_SECOND(self),
4344 DATE_GET_MICROSECOND(self),
4345 HASTZINFO(self) ? self->tzinfo : Py_None);
4346}
4347
4348static PyObject *
4349datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004350{
4351 int y = GET_YEAR(self);
4352 int m = GET_MONTH(self);
4353 int d = GET_DAY(self);
4354 int hh = DATE_GET_HOUR(self);
4355 int mm = DATE_GET_MINUTE(self);
4356 int ss = DATE_GET_SECOND(self);
4357 int us = 0; /* microseconds are ignored in a timetuple */
4358 int offset = 0;
4359
Tim Petersa9bc1682003-01-11 03:39:11 +00004360 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004361 int none;
4362
4363 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4364 if (offset == -1 && PyErr_Occurred())
4365 return NULL;
4366 }
4367 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4368 * 0 in a UTC timetuple regardless of what dst() says.
4369 */
4370 if (offset) {
4371 /* Subtract offset minutes & normalize. */
4372 int stat;
4373
4374 mm -= offset;
4375 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4376 if (stat < 0) {
4377 /* At the edges, it's possible we overflowed
4378 * beyond MINYEAR or MAXYEAR.
4379 */
4380 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4381 PyErr_Clear();
4382 else
4383 return NULL;
4384 }
4385 }
4386 return build_struct_time(y, m, d, hh, mm, ss, 0);
4387}
4388
Tim Peters371935f2003-02-01 01:52:50 +00004389/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004390
Tim Petersa9bc1682003-01-11 03:39:11 +00004391/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004392 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4393 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004394 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004395 */
4396static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004397datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004398{
4399 PyObject *basestate;
4400 PyObject *result = NULL;
4401
Tim Peters33e0f382003-01-10 02:05:14 +00004402 basestate = PyString_FromStringAndSize((char *)self->data,
4403 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004404 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004405 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004406 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004407 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004408 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004409 Py_DECREF(basestate);
4410 }
4411 return result;
4412}
4413
4414static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004415datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004416{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004417 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004418}
4419
Tim Petersa9bc1682003-01-11 03:39:11 +00004420static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004421
Tim Peters2a799bf2002-12-16 20:18:38 +00004422 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004423
Tim Petersa9bc1682003-01-11 03:39:11 +00004424 {"now", (PyCFunction)datetime_now,
Tim Peters2a799bf2002-12-16 20:18:38 +00004425 METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004426 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004427
Tim Petersa9bc1682003-01-11 03:39:11 +00004428 {"utcnow", (PyCFunction)datetime_utcnow,
4429 METH_NOARGS | METH_CLASS,
4430 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4431
4432 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Tim Peters2a799bf2002-12-16 20:18:38 +00004433 METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004434 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004435
Tim Petersa9bc1682003-01-11 03:39:11 +00004436 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4437 METH_VARARGS | METH_CLASS,
4438 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4439 "(like time.time()).")},
4440
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004441 {"strptime", (PyCFunction)datetime_strptime,
4442 METH_VARARGS | METH_CLASS,
4443 PyDoc_STR("string, format -> new datetime parsed from a string "
4444 "(like time.strptime()).")},
4445
Tim Petersa9bc1682003-01-11 03:39:11 +00004446 {"combine", (PyCFunction)datetime_combine,
4447 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4448 PyDoc_STR("date, time -> datetime with same date and time fields")},
4449
Tim Peters2a799bf2002-12-16 20:18:38 +00004450 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004451
Tim Petersa9bc1682003-01-11 03:39:11 +00004452 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4453 PyDoc_STR("Return date object with same year, month and day.")},
4454
4455 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4456 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4457
4458 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4459 PyDoc_STR("Return time object with same time and tzinfo.")},
4460
4461 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4462 PyDoc_STR("Return ctime() style string.")},
4463
4464 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004465 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4466
Tim Petersa9bc1682003-01-11 03:39:11 +00004467 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004468 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4469
Tim Petersa9bc1682003-01-11 03:39:11 +00004470 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004471 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4472 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4473 "sep is used to separate the year from the time, and "
4474 "defaults to 'T'.")},
4475
Tim Petersa9bc1682003-01-11 03:39:11 +00004476 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004477 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4478
Tim Petersa9bc1682003-01-11 03:39:11 +00004479 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004480 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4481
Tim Petersa9bc1682003-01-11 03:39:11 +00004482 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004483 PyDoc_STR("Return self.tzinfo.dst(self).")},
4484
Tim Petersa9bc1682003-01-11 03:39:11 +00004485 {"replace", (PyCFunction)datetime_replace, METH_KEYWORDS,
4486 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004487
Tim Petersa9bc1682003-01-11 03:39:11 +00004488 {"astimezone", (PyCFunction)datetime_astimezone, METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004489 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4490
Guido van Rossum177e41a2003-01-30 22:06:23 +00004491 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4492 PyDoc_STR("__reduce__() -> (cls, state)")},
4493
Tim Peters2a799bf2002-12-16 20:18:38 +00004494 {NULL, NULL}
4495};
4496
Tim Petersa9bc1682003-01-11 03:39:11 +00004497static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004498PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4499\n\
4500The year, month and day arguments are required. tzinfo may be None, or an\n\
4501instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004502
Tim Petersa9bc1682003-01-11 03:39:11 +00004503static PyNumberMethods datetime_as_number = {
4504 datetime_add, /* nb_add */
4505 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004506 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004507 0, /* nb_remainder */
4508 0, /* nb_divmod */
4509 0, /* nb_power */
4510 0, /* nb_negative */
4511 0, /* nb_positive */
4512 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004513 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004514};
4515
Neal Norwitz227b5332006-03-22 09:28:35 +00004516static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004517 PyObject_HEAD_INIT(NULL)
4518 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004519 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004520 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004521 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004522 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004523 0, /* tp_print */
4524 0, /* tp_getattr */
4525 0, /* tp_setattr */
4526 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004527 (reprfunc)datetime_repr, /* tp_repr */
4528 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004529 0, /* tp_as_sequence */
4530 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004531 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004532 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004533 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004534 PyObject_GenericGetAttr, /* tp_getattro */
4535 0, /* tp_setattro */
4536 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004537 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004538 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004539 0, /* tp_traverse */
4540 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004541 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004542 0, /* tp_weaklistoffset */
4543 0, /* tp_iter */
4544 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004545 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004546 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004547 datetime_getset, /* tp_getset */
4548 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004549 0, /* tp_dict */
4550 0, /* tp_descr_get */
4551 0, /* tp_descr_set */
4552 0, /* tp_dictoffset */
4553 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004554 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004555 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004556 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004557};
4558
4559/* ---------------------------------------------------------------------------
4560 * Module methods and initialization.
4561 */
4562
4563static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004564 {NULL, NULL}
4565};
4566
Tim Peters9ddf40b2004-06-20 22:41:32 +00004567/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4568 * datetime.h.
4569 */
4570static PyDateTime_CAPI CAPI = {
4571 &PyDateTime_DateType,
4572 &PyDateTime_DateTimeType,
4573 &PyDateTime_TimeType,
4574 &PyDateTime_DeltaType,
4575 &PyDateTime_TZInfoType,
4576 new_date_ex,
4577 new_datetime_ex,
4578 new_time_ex,
4579 new_delta_ex,
4580 datetime_fromtimestamp,
4581 date_fromtimestamp
4582};
4583
4584
Tim Peters2a799bf2002-12-16 20:18:38 +00004585PyMODINIT_FUNC
4586initdatetime(void)
4587{
4588 PyObject *m; /* a module object */
4589 PyObject *d; /* its dict */
4590 PyObject *x;
4591
Tim Peters2a799bf2002-12-16 20:18:38 +00004592 m = Py_InitModule3("datetime", module_methods,
4593 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004594 if (m == NULL)
4595 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004596
4597 if (PyType_Ready(&PyDateTime_DateType) < 0)
4598 return;
4599 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4600 return;
4601 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4602 return;
4603 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4604 return;
4605 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4606 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004607
Tim Peters2a799bf2002-12-16 20:18:38 +00004608 /* timedelta values */
4609 d = PyDateTime_DeltaType.tp_dict;
4610
Tim Peters2a799bf2002-12-16 20:18:38 +00004611 x = new_delta(0, 0, 1, 0);
4612 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4613 return;
4614 Py_DECREF(x);
4615
4616 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4617 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4618 return;
4619 Py_DECREF(x);
4620
4621 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4622 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4623 return;
4624 Py_DECREF(x);
4625
4626 /* date values */
4627 d = PyDateTime_DateType.tp_dict;
4628
4629 x = new_date(1, 1, 1);
4630 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4631 return;
4632 Py_DECREF(x);
4633
4634 x = new_date(MAXYEAR, 12, 31);
4635 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4636 return;
4637 Py_DECREF(x);
4638
4639 x = new_delta(1, 0, 0, 0);
4640 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4641 return;
4642 Py_DECREF(x);
4643
Tim Peters37f39822003-01-10 03:49:02 +00004644 /* time values */
4645 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004646
Tim Peters37f39822003-01-10 03:49:02 +00004647 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004648 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4649 return;
4650 Py_DECREF(x);
4651
Tim Peters37f39822003-01-10 03:49:02 +00004652 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004653 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4654 return;
4655 Py_DECREF(x);
4656
4657 x = new_delta(0, 0, 1, 0);
4658 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4659 return;
4660 Py_DECREF(x);
4661
Tim Petersa9bc1682003-01-11 03:39:11 +00004662 /* datetime values */
4663 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004664
Tim Petersa9bc1682003-01-11 03:39:11 +00004665 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004666 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4667 return;
4668 Py_DECREF(x);
4669
Tim Petersa9bc1682003-01-11 03:39:11 +00004670 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004671 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4672 return;
4673 Py_DECREF(x);
4674
4675 x = new_delta(0, 0, 1, 0);
4676 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4677 return;
4678 Py_DECREF(x);
4679
Tim Peters2a799bf2002-12-16 20:18:38 +00004680 /* module initialization */
4681 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4682 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4683
4684 Py_INCREF(&PyDateTime_DateType);
4685 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4686
Tim Petersa9bc1682003-01-11 03:39:11 +00004687 Py_INCREF(&PyDateTime_DateTimeType);
4688 PyModule_AddObject(m, "datetime",
4689 (PyObject *)&PyDateTime_DateTimeType);
4690
4691 Py_INCREF(&PyDateTime_TimeType);
4692 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4693
Tim Peters2a799bf2002-12-16 20:18:38 +00004694 Py_INCREF(&PyDateTime_DeltaType);
4695 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4696
Tim Peters2a799bf2002-12-16 20:18:38 +00004697 Py_INCREF(&PyDateTime_TZInfoType);
4698 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4699
Tim Peters9ddf40b2004-06-20 22:41:32 +00004700 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4701 NULL);
4702 if (x == NULL)
4703 return;
4704 PyModule_AddObject(m, "datetime_CAPI", x);
4705
Tim Peters2a799bf2002-12-16 20:18:38 +00004706 /* A 4-year cycle has an extra leap day over what we'd get from
4707 * pasting together 4 single years.
4708 */
4709 assert(DI4Y == 4 * 365 + 1);
4710 assert(DI4Y == days_before_year(4+1));
4711
4712 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4713 * get from pasting together 4 100-year cycles.
4714 */
4715 assert(DI400Y == 4 * DI100Y + 1);
4716 assert(DI400Y == days_before_year(400+1));
4717
4718 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4719 * pasting together 25 4-year cycles.
4720 */
4721 assert(DI100Y == 25 * DI4Y - 1);
4722 assert(DI100Y == days_before_year(100+1));
4723
4724 us_per_us = PyInt_FromLong(1);
4725 us_per_ms = PyInt_FromLong(1000);
4726 us_per_second = PyInt_FromLong(1000000);
4727 us_per_minute = PyInt_FromLong(60000000);
4728 seconds_per_day = PyInt_FromLong(24 * 3600);
4729 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4730 us_per_minute == NULL || seconds_per_day == NULL)
4731 return;
4732
4733 /* The rest are too big for 32-bit ints, but even
4734 * us_per_week fits in 40 bits, so doubles should be exact.
4735 */
4736 us_per_hour = PyLong_FromDouble(3600000000.0);
4737 us_per_day = PyLong_FromDouble(86400000000.0);
4738 us_per_week = PyLong_FromDouble(604800000000.0);
4739 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4740 return;
4741}
Tim Petersf3615152003-01-01 21:51:37 +00004742
4743/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004744Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004745 x.n = x stripped of its timezone -- its naive time.
4746 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4747 return None
4748 x.d = x.dst(), and assuming that doesn't raise an exception or
4749 return None
4750 x.s = x's standard offset, x.o - x.d
4751
4752Now some derived rules, where k is a duration (timedelta).
4753
47541. x.o = x.s + x.d
4755 This follows from the definition of x.s.
4756
Tim Petersc5dc4da2003-01-02 17:55:03 +000047572. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004758 This is actually a requirement, an assumption we need to make about
4759 sane tzinfo classes.
4760
47613. The naive UTC time corresponding to x is x.n - x.o.
4762 This is again a requirement for a sane tzinfo class.
4763
47644. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004765 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004766
Tim Petersc5dc4da2003-01-02 17:55:03 +000047675. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004768 Again follows from how arithmetic is defined.
4769
Tim Peters8bb5ad22003-01-24 02:44:45 +00004770Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004771(meaning that the various tzinfo methods exist, and don't blow up or return
4772None when called).
4773
Tim Petersa9bc1682003-01-11 03:39:11 +00004774The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004775x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004776
4777By #3, we want
4778
Tim Peters8bb5ad22003-01-24 02:44:45 +00004779 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004780
4781The algorithm starts by attaching tz to x.n, and calling that y. So
4782x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4783becomes true; in effect, we want to solve [2] for k:
4784
Tim Peters8bb5ad22003-01-24 02:44:45 +00004785 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004786
4787By #1, this is the same as
4788
Tim Peters8bb5ad22003-01-24 02:44:45 +00004789 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004790
4791By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4792Substituting that into [3],
4793
Tim Peters8bb5ad22003-01-24 02:44:45 +00004794 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4795 k - (y+k).s - (y+k).d = 0; rearranging,
4796 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4797 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004798
Tim Peters8bb5ad22003-01-24 02:44:45 +00004799On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4800approximate k by ignoring the (y+k).d term at first. Note that k can't be
4801very large, since all offset-returning methods return a duration of magnitude
4802less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4803be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004804
4805In any case, the new value is
4806
Tim Peters8bb5ad22003-01-24 02:44:45 +00004807 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004808
Tim Peters8bb5ad22003-01-24 02:44:45 +00004809It's helpful to step back at look at [4] from a higher level: it's simply
4810mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004811
4812At this point, if
4813
Tim Peters8bb5ad22003-01-24 02:44:45 +00004814 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004815
4816we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004817at the start of daylight time. Picture US Eastern for concreteness. The wall
4818time 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 +00004819sense then. The docs ask that an Eastern tzinfo class consider such a time to
4820be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4821on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004822the only spelling that makes sense on the local wall clock.
4823
Tim Petersc5dc4da2003-01-02 17:55:03 +00004824In fact, if [5] holds at this point, we do have the standard-time spelling,
4825but that takes a bit of proof. We first prove a stronger result. What's the
4826difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004827
Tim Peters8bb5ad22003-01-24 02:44:45 +00004828 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004829
Tim Petersc5dc4da2003-01-02 17:55:03 +00004830Now
4831 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004832 (y + y.s).n = by #5
4833 y.n + y.s = since y.n = x.n
4834 x.n + y.s = since z and y are have the same tzinfo member,
4835 y.s = z.s by #2
4836 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004837
Tim Petersc5dc4da2003-01-02 17:55:03 +00004838Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004839
Tim Petersc5dc4da2003-01-02 17:55:03 +00004840 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004841 x.n - ((x.n + z.s) - z.o) = expanding
4842 x.n - x.n - z.s + z.o = cancelling
4843 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004844 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004845
Tim Petersc5dc4da2003-01-02 17:55:03 +00004846So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004847
Tim Petersc5dc4da2003-01-02 17:55:03 +00004848If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004849spelling we wanted in the endcase described above. We're done. Contrarily,
4850if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004851
Tim Petersc5dc4da2003-01-02 17:55:03 +00004852If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4853add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004854local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004855
Tim Petersc5dc4da2003-01-02 17:55:03 +00004856Let
Tim Petersf3615152003-01-01 21:51:37 +00004857
Tim Peters4fede1a2003-01-04 00:26:59 +00004858 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004859
Tim Peters4fede1a2003-01-04 00:26:59 +00004860and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004861
Tim Peters8bb5ad22003-01-24 02:44:45 +00004862 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004863
Tim Peters8bb5ad22003-01-24 02:44:45 +00004864If so, we're done. If not, the tzinfo class is insane, according to the
4865assumptions we've made. This also requires a bit of proof. As before, let's
4866compute the difference between the LHS and RHS of [8] (and skipping some of
4867the justifications for the kinds of substitutions we've done several times
4868already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004869
Tim Peters8bb5ad22003-01-24 02:44:45 +00004870 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4871 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4872 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4873 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4874 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004875 - z.o + z'.o = #1 twice
4876 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4877 z'.d - z.d
4878
4879So 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 +00004880we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4881return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004882
Tim Peters8bb5ad22003-01-24 02:44:45 +00004883How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4884a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4885would have to change the result dst() returns: we start in DST, and moving
4886a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004887
Tim Peters8bb5ad22003-01-24 02:44:45 +00004888There isn't a sane case where this can happen. The closest it gets is at
4889the end of DST, where there's an hour in UTC with no spelling in a hybrid
4890tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4891that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4892UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4893time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4894clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4895standard time. Since that's what the local clock *does*, we want to map both
4896UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004897in local time, but so it goes -- it's the way the local clock works.
4898
Tim Peters8bb5ad22003-01-24 02:44:45 +00004899When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4900so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4901z' = 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 +00004902(correctly) concludes that z' is not UTC-equivalent to x.
4903
4904Because we know z.d said z was in daylight time (else [5] would have held and
4905we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004906and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004907return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4908but the reasoning doesn't depend on the example -- it depends on there being
4909two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004910z' must be in standard time, and is the spelling we want in this case.
4911
4912Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4913concerned (because it takes z' as being in standard time rather than the
4914daylight time we intend here), but returning it gives the real-life "local
4915clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4916tz.
4917
4918When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4919the 1:MM standard time spelling we want.
4920
4921So how can this break? One of the assumptions must be violated. Two
4922possibilities:
4923
49241) [2] effectively says that y.s is invariant across all y belong to a given
4925 time zone. This isn't true if, for political reasons or continental drift,
4926 a region decides to change its base offset from UTC.
4927
49282) There may be versions of "double daylight" time where the tail end of
4929 the analysis gives up a step too early. I haven't thought about that
4930 enough to say.
4931
4932In any case, it's clear that the default fromutc() is strong enough to handle
4933"almost all" time zones: so long as the standard offset is invariant, it
4934doesn't matter if daylight time transition points change from year to year, or
4935if daylight time is skipped in some years; it doesn't matter how large or
4936small dst() may get within its bounds; and it doesn't even matter if some
4937perverse time zone returns a negative dst()). So a breaking case must be
4938pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004939--------------------------------------------------------------------------- */