blob: 34112c01d41a654591e9a48786fe1cf08c14fe48 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
Kristján Valur Jónsson55d53f02007-05-02 15:55:14 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Kristján Valur Jónsson55d53f02007-05-02 15:55:14 +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
Martin v. Löwis73c01d42008-02-14 11:26:18 +00001116 assert(buflen >= 1);
1117
Tim Peters2a799bf2002-12-16 20:18:38 +00001118 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1119 if (offset == -1 && PyErr_Occurred())
1120 return -1;
1121 if (none) {
1122 *buf = '\0';
1123 return 0;
1124 }
1125 sign = '+';
1126 if (offset < 0) {
1127 sign = '-';
1128 offset = - offset;
1129 }
1130 hours = divmod(offset, 60, &minutes);
1131 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1132 return 0;
1133}
1134
1135/* I sure don't want to reproduce the strftime code from the time module,
1136 * so this imports the module and calls it. All the hair is due to
1137 * giving special meanings to the %z and %Z format codes via a preprocessing
1138 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001139 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1140 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001141 */
1142static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001143wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1144 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001145{
1146 PyObject *result = NULL; /* guilty until proved innocent */
1147
1148 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1149 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1150
1151 char *pin; /* pointer to next char in input format */
1152 char ch; /* next char in input format */
1153
1154 PyObject *newfmt = NULL; /* py string, the output format */
1155 char *pnew; /* pointer to available byte in output format */
Georg Brandl6d7c3632006-09-30 11:17:43 +00001156 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001157 exclusive of trailing \0 */
Georg Brandl6d7c3632006-09-30 11:17:43 +00001158 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001159
1160 char *ptoappend; /* pointer to string to append to output buffer */
1161 int ntoappend; /* # of bytes to append to output buffer */
1162
Tim Peters2a799bf2002-12-16 20:18:38 +00001163 assert(object && format && timetuple);
1164 assert(PyString_Check(format));
1165
Tim Petersd6844152002-12-22 20:58:42 +00001166 /* Give up if the year is before 1900.
1167 * Python strftime() plays games with the year, and different
1168 * games depending on whether envar PYTHON2K is set. This makes
1169 * years before 1900 a nightmare, even if the platform strftime
1170 * supports them (and not all do).
1171 * We could get a lot farther here by avoiding Python's strftime
1172 * wrapper and calling the C strftime() directly, but that isn't
1173 * an option in the Python implementation of this module.
1174 */
1175 {
1176 long year;
1177 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1178 if (pyyear == NULL) return NULL;
1179 assert(PyInt_Check(pyyear));
1180 year = PyInt_AsLong(pyyear);
1181 Py_DECREF(pyyear);
1182 if (year < 1900) {
1183 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1184 "1900; the datetime strftime() "
1185 "methods require year >= 1900",
1186 year);
1187 return NULL;
1188 }
1189 }
1190
Tim Peters2a799bf2002-12-16 20:18:38 +00001191 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001192 * a new format. Since computing the replacements for those codes
1193 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001194 */
Martin v. Löwis73c01d42008-02-14 11:26:18 +00001195 if (PyString_Size(format) > INT_MAX - 1) {
1196 PyErr_NoMemory();
1197 goto Done;
1198 }
1199
Raymond Hettingerf69d9f62003-06-27 08:14:17 +00001200 totalnew = PyString_Size(format) + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001201 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1202 if (newfmt == NULL) goto Done;
1203 pnew = PyString_AsString(newfmt);
1204 usednew = 0;
1205
1206 pin = PyString_AsString(format);
1207 while ((ch = *pin++) != '\0') {
1208 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001209 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001210 ntoappend = 1;
1211 }
1212 else if ((ch = *pin++) == '\0') {
1213 /* There's a lone trailing %; doesn't make sense. */
1214 PyErr_SetString(PyExc_ValueError, "strftime format "
1215 "ends with raw %");
1216 goto Done;
1217 }
1218 /* A % has been seen and ch is the character after it. */
1219 else if (ch == 'z') {
1220 if (zreplacement == NULL) {
1221 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001222 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001223 PyObject *tzinfo = get_tzinfo_member(object);
1224 zreplacement = PyString_FromString("");
1225 if (zreplacement == NULL) goto Done;
1226 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001227 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001228 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001229 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001230 "",
1231 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001232 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001233 goto Done;
1234 Py_DECREF(zreplacement);
1235 zreplacement = PyString_FromString(buf);
1236 if (zreplacement == NULL) goto Done;
1237 }
1238 }
1239 assert(zreplacement != NULL);
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001240 ptoappend = PyString_AS_STRING(zreplacement);
1241 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001242 }
1243 else if (ch == 'Z') {
1244 /* format tzname */
1245 if (Zreplacement == NULL) {
1246 PyObject *tzinfo = get_tzinfo_member(object);
1247 Zreplacement = PyString_FromString("");
1248 if (Zreplacement == NULL) goto Done;
1249 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001250 PyObject *temp;
1251 assert(tzinfoarg != NULL);
1252 temp = call_tzname(tzinfo, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001253 if (temp == NULL) goto Done;
1254 if (temp != Py_None) {
1255 assert(PyString_Check(temp));
1256 /* Since the tzname is getting
1257 * stuffed into the format, we
1258 * have to double any % signs
1259 * so that strftime doesn't
1260 * treat them as format codes.
1261 */
1262 Py_DECREF(Zreplacement);
1263 Zreplacement = PyObject_CallMethod(
1264 temp, "replace",
1265 "ss", "%", "%%");
1266 Py_DECREF(temp);
1267 if (Zreplacement == NULL)
1268 goto Done;
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001269 if (!PyString_Check(Zreplacement)) {
1270 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1271 goto Done;
1272 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001273 }
1274 else
1275 Py_DECREF(temp);
1276 }
1277 }
1278 assert(Zreplacement != NULL);
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001279 ptoappend = PyString_AS_STRING(Zreplacement);
1280 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001281 }
1282 else {
Tim Peters328fff72002-12-20 01:31:27 +00001283 /* percent followed by neither z nor Z */
1284 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001285 ntoappend = 2;
1286 }
1287
1288 /* Append the ntoappend chars starting at ptoappend to
1289 * the new format.
1290 */
Neal Norwitzd5b0c9b2006-03-20 01:58:39 +00001291 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001292 assert(ntoappend >= 0);
1293 if (ntoappend == 0)
1294 continue;
1295 while (usednew + ntoappend > totalnew) {
1296 int bigger = totalnew << 1;
1297 if ((bigger >> 1) != totalnew) { /* overflow */
1298 PyErr_NoMemory();
1299 goto Done;
1300 }
1301 if (_PyString_Resize(&newfmt, bigger) < 0)
1302 goto Done;
1303 totalnew = bigger;
1304 pnew = PyString_AsString(newfmt) + usednew;
1305 }
1306 memcpy(pnew, ptoappend, ntoappend);
1307 pnew += ntoappend;
1308 usednew += ntoappend;
1309 assert(usednew <= totalnew);
1310 } /* end while() */
1311
1312 if (_PyString_Resize(&newfmt, usednew) < 0)
1313 goto Done;
1314 {
1315 PyObject *time = PyImport_ImportModule("time");
1316 if (time == NULL)
1317 goto Done;
1318 result = PyObject_CallMethod(time, "strftime", "OO",
1319 newfmt, timetuple);
1320 Py_DECREF(time);
1321 }
1322 Done:
1323 Py_XDECREF(zreplacement);
1324 Py_XDECREF(Zreplacement);
1325 Py_XDECREF(newfmt);
1326 return result;
1327}
1328
1329static char *
1330isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1331{
1332 int x;
1333 x = PyOS_snprintf(buffer, bufflen,
1334 "%04d-%02d-%02d",
1335 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1336 return buffer + x;
1337}
1338
1339static void
1340isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1341{
1342 int us = DATE_GET_MICROSECOND(dt);
1343
1344 PyOS_snprintf(buffer, bufflen,
1345 "%02d:%02d:%02d", /* 8 characters */
1346 DATE_GET_HOUR(dt),
1347 DATE_GET_MINUTE(dt),
1348 DATE_GET_SECOND(dt));
1349 if (us)
1350 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1351}
1352
1353/* ---------------------------------------------------------------------------
1354 * Wrap functions from the time module. These aren't directly available
1355 * from C. Perhaps they should be.
1356 */
1357
1358/* Call time.time() and return its result (a Python float). */
1359static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001360time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001361{
1362 PyObject *result = NULL;
1363 PyObject *time = PyImport_ImportModule("time");
1364
1365 if (time != NULL) {
1366 result = PyObject_CallMethod(time, "time", "()");
1367 Py_DECREF(time);
1368 }
1369 return result;
1370}
1371
1372/* Build a time.struct_time. The weekday and day number are automatically
1373 * computed from the y,m,d args.
1374 */
1375static PyObject *
1376build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1377{
1378 PyObject *time;
1379 PyObject *result = NULL;
1380
1381 time = PyImport_ImportModule("time");
1382 if (time != NULL) {
1383 result = PyObject_CallMethod(time, "struct_time",
1384 "((iiiiiiiii))",
1385 y, m, d,
1386 hh, mm, ss,
1387 weekday(y, m, d),
1388 days_before_month(y, m) + d,
1389 dstflag);
1390 Py_DECREF(time);
1391 }
1392 return result;
1393}
1394
1395/* ---------------------------------------------------------------------------
1396 * Miscellaneous helpers.
1397 */
1398
1399/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1400 * The comparisons here all most naturally compute a cmp()-like result.
1401 * This little helper turns that into a bool result for rich comparisons.
1402 */
1403static PyObject *
1404diff_to_bool(int diff, int op)
1405{
1406 PyObject *result;
1407 int istrue;
1408
1409 switch (op) {
1410 case Py_EQ: istrue = diff == 0; break;
1411 case Py_NE: istrue = diff != 0; break;
1412 case Py_LE: istrue = diff <= 0; break;
1413 case Py_GE: istrue = diff >= 0; break;
1414 case Py_LT: istrue = diff < 0; break;
1415 case Py_GT: istrue = diff > 0; break;
1416 default:
1417 assert(! "op unknown");
1418 istrue = 0; /* To shut up compiler */
1419 }
1420 result = istrue ? Py_True : Py_False;
1421 Py_INCREF(result);
1422 return result;
1423}
1424
Tim Peters07534a62003-02-07 22:50:28 +00001425/* Raises a "can't compare" TypeError and returns NULL. */
1426static PyObject *
1427cmperror(PyObject *a, PyObject *b)
1428{
1429 PyErr_Format(PyExc_TypeError,
1430 "can't compare %s to %s",
1431 a->ob_type->tp_name, b->ob_type->tp_name);
1432 return NULL;
1433}
1434
Tim Peters2a799bf2002-12-16 20:18:38 +00001435/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001436 * Cached Python objects; these are set by the module init function.
1437 */
1438
1439/* Conversion factors. */
1440static PyObject *us_per_us = NULL; /* 1 */
1441static PyObject *us_per_ms = NULL; /* 1000 */
1442static PyObject *us_per_second = NULL; /* 1000000 */
1443static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1444static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1445static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1446static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1447static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1448
Tim Peters2a799bf2002-12-16 20:18:38 +00001449/* ---------------------------------------------------------------------------
1450 * Class implementations.
1451 */
1452
1453/*
1454 * PyDateTime_Delta implementation.
1455 */
1456
1457/* Convert a timedelta to a number of us,
1458 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1459 * as a Python int or long.
1460 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1461 * due to ubiquitous overflow possibilities.
1462 */
1463static PyObject *
1464delta_to_microseconds(PyDateTime_Delta *self)
1465{
1466 PyObject *x1 = NULL;
1467 PyObject *x2 = NULL;
1468 PyObject *x3 = NULL;
1469 PyObject *result = NULL;
1470
1471 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1472 if (x1 == NULL)
1473 goto Done;
1474 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1475 if (x2 == NULL)
1476 goto Done;
1477 Py_DECREF(x1);
1478 x1 = NULL;
1479
1480 /* x2 has days in seconds */
1481 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1482 if (x1 == NULL)
1483 goto Done;
1484 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1485 if (x3 == NULL)
1486 goto Done;
1487 Py_DECREF(x1);
1488 Py_DECREF(x2);
1489 x1 = x2 = NULL;
1490
1491 /* x3 has days+seconds in seconds */
1492 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1493 if (x1 == NULL)
1494 goto Done;
1495 Py_DECREF(x3);
1496 x3 = NULL;
1497
1498 /* x1 has days+seconds in us */
1499 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1500 if (x2 == NULL)
1501 goto Done;
1502 result = PyNumber_Add(x1, x2);
1503
1504Done:
1505 Py_XDECREF(x1);
1506 Py_XDECREF(x2);
1507 Py_XDECREF(x3);
1508 return result;
1509}
1510
1511/* Convert a number of us (as a Python int or long) to a timedelta.
1512 */
1513static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001514microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001515{
1516 int us;
1517 int s;
1518 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001519 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001520
1521 PyObject *tuple = NULL;
1522 PyObject *num = NULL;
1523 PyObject *result = NULL;
1524
1525 tuple = PyNumber_Divmod(pyus, us_per_second);
1526 if (tuple == NULL)
1527 goto Done;
1528
1529 num = PyTuple_GetItem(tuple, 1); /* us */
1530 if (num == NULL)
1531 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001532 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001533 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001534 if (temp == -1 && PyErr_Occurred())
1535 goto Done;
1536 assert(0 <= temp && temp < 1000000);
1537 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001538 if (us < 0) {
1539 /* The divisor was positive, so this must be an error. */
1540 assert(PyErr_Occurred());
1541 goto Done;
1542 }
1543
1544 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1545 if (num == NULL)
1546 goto Done;
1547 Py_INCREF(num);
1548 Py_DECREF(tuple);
1549
1550 tuple = PyNumber_Divmod(num, seconds_per_day);
1551 if (tuple == NULL)
1552 goto Done;
1553 Py_DECREF(num);
1554
1555 num = PyTuple_GetItem(tuple, 1); /* seconds */
1556 if (num == NULL)
1557 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001558 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001559 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001560 if (temp == -1 && PyErr_Occurred())
1561 goto Done;
1562 assert(0 <= temp && temp < 24*3600);
1563 s = (int)temp;
1564
Tim Peters2a799bf2002-12-16 20:18:38 +00001565 if (s < 0) {
1566 /* The divisor was positive, so this must be an error. */
1567 assert(PyErr_Occurred());
1568 goto Done;
1569 }
1570
1571 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1572 if (num == NULL)
1573 goto Done;
1574 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001575 temp = PyLong_AsLong(num);
1576 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001577 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001578 d = (int)temp;
1579 if ((long)d != temp) {
1580 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1581 "large to fit in a C int");
1582 goto Done;
1583 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001584 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001585
1586Done:
1587 Py_XDECREF(tuple);
1588 Py_XDECREF(num);
1589 return result;
1590}
1591
Tim Petersb0c854d2003-05-17 15:57:00 +00001592#define microseconds_to_delta(pymicros) \
1593 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1594
Tim Peters2a799bf2002-12-16 20:18:38 +00001595static PyObject *
1596multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1597{
1598 PyObject *pyus_in;
1599 PyObject *pyus_out;
1600 PyObject *result;
1601
1602 pyus_in = delta_to_microseconds(delta);
1603 if (pyus_in == NULL)
1604 return NULL;
1605
1606 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1607 Py_DECREF(pyus_in);
1608 if (pyus_out == NULL)
1609 return NULL;
1610
1611 result = microseconds_to_delta(pyus_out);
1612 Py_DECREF(pyus_out);
1613 return result;
1614}
1615
1616static PyObject *
1617divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1618{
1619 PyObject *pyus_in;
1620 PyObject *pyus_out;
1621 PyObject *result;
1622
1623 pyus_in = delta_to_microseconds(delta);
1624 if (pyus_in == NULL)
1625 return NULL;
1626
1627 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1628 Py_DECREF(pyus_in);
1629 if (pyus_out == NULL)
1630 return NULL;
1631
1632 result = microseconds_to_delta(pyus_out);
1633 Py_DECREF(pyus_out);
1634 return result;
1635}
1636
1637static PyObject *
1638delta_add(PyObject *left, PyObject *right)
1639{
1640 PyObject *result = Py_NotImplemented;
1641
1642 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1643 /* delta + delta */
1644 /* The C-level additions can't overflow because of the
1645 * invariant bounds.
1646 */
1647 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1648 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1649 int microseconds = GET_TD_MICROSECONDS(left) +
1650 GET_TD_MICROSECONDS(right);
1651 result = new_delta(days, seconds, microseconds, 1);
1652 }
1653
1654 if (result == Py_NotImplemented)
1655 Py_INCREF(result);
1656 return result;
1657}
1658
1659static PyObject *
1660delta_negative(PyDateTime_Delta *self)
1661{
1662 return new_delta(-GET_TD_DAYS(self),
1663 -GET_TD_SECONDS(self),
1664 -GET_TD_MICROSECONDS(self),
1665 1);
1666}
1667
1668static PyObject *
1669delta_positive(PyDateTime_Delta *self)
1670{
1671 /* Could optimize this (by returning self) if this isn't a
1672 * subclass -- but who uses unary + ? Approximately nobody.
1673 */
1674 return new_delta(GET_TD_DAYS(self),
1675 GET_TD_SECONDS(self),
1676 GET_TD_MICROSECONDS(self),
1677 0);
1678}
1679
1680static PyObject *
1681delta_abs(PyDateTime_Delta *self)
1682{
1683 PyObject *result;
1684
1685 assert(GET_TD_MICROSECONDS(self) >= 0);
1686 assert(GET_TD_SECONDS(self) >= 0);
1687
1688 if (GET_TD_DAYS(self) < 0)
1689 result = delta_negative(self);
1690 else
1691 result = delta_positive(self);
1692
1693 return result;
1694}
1695
1696static PyObject *
1697delta_subtract(PyObject *left, PyObject *right)
1698{
1699 PyObject *result = Py_NotImplemented;
1700
1701 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1702 /* delta - delta */
1703 PyObject *minus_right = PyNumber_Negative(right);
1704 if (minus_right) {
1705 result = delta_add(left, minus_right);
1706 Py_DECREF(minus_right);
1707 }
1708 else
1709 result = NULL;
1710 }
1711
1712 if (result == Py_NotImplemented)
1713 Py_INCREF(result);
1714 return result;
1715}
1716
1717/* This is more natural as a tp_compare, but doesn't work then: for whatever
1718 * reason, Python's try_3way_compare ignores tp_compare unless
1719 * PyInstance_Check returns true, but these aren't old-style classes.
1720 */
1721static PyObject *
1722delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1723{
Tim Peters07534a62003-02-07 22:50:28 +00001724 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00001725
Tim Petersaa7d8492003-02-08 03:28:59 +00001726 if (PyDelta_Check(other)) {
Tim Peters07534a62003-02-07 22:50:28 +00001727 diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1728 if (diff == 0) {
1729 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1730 if (diff == 0)
1731 diff = GET_TD_MICROSECONDS(self) -
1732 GET_TD_MICROSECONDS(other);
1733 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001734 }
Tim Peters07534a62003-02-07 22:50:28 +00001735 else if (op == Py_EQ || op == Py_NE)
1736 diff = 1; /* any non-zero value will do */
1737
1738 else /* stop this from falling back to address comparison */
1739 return cmperror((PyObject *)self, other);
1740
Tim Peters2a799bf2002-12-16 20:18:38 +00001741 return diff_to_bool(diff, op);
1742}
1743
1744static PyObject *delta_getstate(PyDateTime_Delta *self);
1745
1746static long
1747delta_hash(PyDateTime_Delta *self)
1748{
1749 if (self->hashcode == -1) {
1750 PyObject *temp = delta_getstate(self);
1751 if (temp != NULL) {
1752 self->hashcode = PyObject_Hash(temp);
1753 Py_DECREF(temp);
1754 }
1755 }
1756 return self->hashcode;
1757}
1758
1759static PyObject *
1760delta_multiply(PyObject *left, PyObject *right)
1761{
1762 PyObject *result = Py_NotImplemented;
1763
1764 if (PyDelta_Check(left)) {
1765 /* delta * ??? */
1766 if (PyInt_Check(right) || PyLong_Check(right))
1767 result = multiply_int_timedelta(right,
1768 (PyDateTime_Delta *) left);
1769 }
1770 else if (PyInt_Check(left) || PyLong_Check(left))
1771 result = multiply_int_timedelta(left,
1772 (PyDateTime_Delta *) right);
1773
1774 if (result == Py_NotImplemented)
1775 Py_INCREF(result);
1776 return result;
1777}
1778
1779static PyObject *
1780delta_divide(PyObject *left, PyObject *right)
1781{
1782 PyObject *result = Py_NotImplemented;
1783
1784 if (PyDelta_Check(left)) {
1785 /* delta * ??? */
1786 if (PyInt_Check(right) || PyLong_Check(right))
1787 result = divide_timedelta_int(
1788 (PyDateTime_Delta *)left,
1789 right);
1790 }
1791
1792 if (result == Py_NotImplemented)
1793 Py_INCREF(result);
1794 return result;
1795}
1796
1797/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1798 * timedelta constructor. sofar is the # of microseconds accounted for
1799 * so far, and there are factor microseconds per current unit, the number
1800 * of which is given by num. num * factor is added to sofar in a
1801 * numerically careful way, and that's the result. Any fractional
1802 * microseconds left over (this can happen if num is a float type) are
1803 * added into *leftover.
1804 * Note that there are many ways this can give an error (NULL) return.
1805 */
1806static PyObject *
1807accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1808 double *leftover)
1809{
1810 PyObject *prod;
1811 PyObject *sum;
1812
1813 assert(num != NULL);
1814
1815 if (PyInt_Check(num) || PyLong_Check(num)) {
1816 prod = PyNumber_Multiply(num, factor);
1817 if (prod == NULL)
1818 return NULL;
1819 sum = PyNumber_Add(sofar, prod);
1820 Py_DECREF(prod);
1821 return sum;
1822 }
1823
1824 if (PyFloat_Check(num)) {
1825 double dnum;
1826 double fracpart;
1827 double intpart;
1828 PyObject *x;
1829 PyObject *y;
1830
1831 /* The Plan: decompose num into an integer part and a
1832 * fractional part, num = intpart + fracpart.
1833 * Then num * factor ==
1834 * intpart * factor + fracpart * factor
1835 * and the LHS can be computed exactly in long arithmetic.
1836 * The RHS is again broken into an int part and frac part.
1837 * and the frac part is added into *leftover.
1838 */
1839 dnum = PyFloat_AsDouble(num);
1840 if (dnum == -1.0 && PyErr_Occurred())
1841 return NULL;
1842 fracpart = modf(dnum, &intpart);
1843 x = PyLong_FromDouble(intpart);
1844 if (x == NULL)
1845 return NULL;
1846
1847 prod = PyNumber_Multiply(x, factor);
1848 Py_DECREF(x);
1849 if (prod == NULL)
1850 return NULL;
1851
1852 sum = PyNumber_Add(sofar, prod);
1853 Py_DECREF(prod);
1854 if (sum == NULL)
1855 return NULL;
1856
1857 if (fracpart == 0.0)
1858 return sum;
1859 /* So far we've lost no information. Dealing with the
1860 * fractional part requires float arithmetic, and may
1861 * lose a little info.
1862 */
1863 assert(PyInt_Check(factor) || PyLong_Check(factor));
1864 if (PyInt_Check(factor))
1865 dnum = (double)PyInt_AsLong(factor);
1866 else
1867 dnum = PyLong_AsDouble(factor);
1868
1869 dnum *= fracpart;
1870 fracpart = modf(dnum, &intpart);
1871 x = PyLong_FromDouble(intpart);
1872 if (x == NULL) {
1873 Py_DECREF(sum);
1874 return NULL;
1875 }
1876
1877 y = PyNumber_Add(sum, x);
1878 Py_DECREF(sum);
1879 Py_DECREF(x);
1880 *leftover += fracpart;
1881 return y;
1882 }
1883
1884 PyErr_Format(PyExc_TypeError,
1885 "unsupported type for timedelta %s component: %s",
1886 tag, num->ob_type->tp_name);
1887 return NULL;
1888}
1889
1890static PyObject *
1891delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1892{
1893 PyObject *self = NULL;
1894
1895 /* Argument objects. */
1896 PyObject *day = NULL;
1897 PyObject *second = NULL;
1898 PyObject *us = NULL;
1899 PyObject *ms = NULL;
1900 PyObject *minute = NULL;
1901 PyObject *hour = NULL;
1902 PyObject *week = NULL;
1903
1904 PyObject *x = NULL; /* running sum of microseconds */
1905 PyObject *y = NULL; /* temp sum of microseconds */
1906 double leftover_us = 0.0;
1907
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001908 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001909 "days", "seconds", "microseconds", "milliseconds",
1910 "minutes", "hours", "weeks", NULL
1911 };
1912
1913 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1914 keywords,
1915 &day, &second, &us,
1916 &ms, &minute, &hour, &week) == 0)
1917 goto Done;
1918
1919 x = PyInt_FromLong(0);
1920 if (x == NULL)
1921 goto Done;
1922
1923#define CLEANUP \
1924 Py_DECREF(x); \
1925 x = y; \
1926 if (x == NULL) \
1927 goto Done
1928
1929 if (us) {
1930 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1931 CLEANUP;
1932 }
1933 if (ms) {
1934 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1935 CLEANUP;
1936 }
1937 if (second) {
1938 y = accum("seconds", x, second, us_per_second, &leftover_us);
1939 CLEANUP;
1940 }
1941 if (minute) {
1942 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1943 CLEANUP;
1944 }
1945 if (hour) {
1946 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1947 CLEANUP;
1948 }
1949 if (day) {
1950 y = accum("days", x, day, us_per_day, &leftover_us);
1951 CLEANUP;
1952 }
1953 if (week) {
1954 y = accum("weeks", x, week, us_per_week, &leftover_us);
1955 CLEANUP;
1956 }
1957 if (leftover_us) {
1958 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001959 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001960 if (temp == NULL) {
1961 Py_DECREF(x);
1962 goto Done;
1963 }
1964 y = PyNumber_Add(x, temp);
1965 Py_DECREF(temp);
1966 CLEANUP;
1967 }
1968
Tim Petersb0c854d2003-05-17 15:57:00 +00001969 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001970 Py_DECREF(x);
1971Done:
1972 return self;
1973
1974#undef CLEANUP
1975}
1976
1977static int
1978delta_nonzero(PyDateTime_Delta *self)
1979{
1980 return (GET_TD_DAYS(self) != 0
1981 || GET_TD_SECONDS(self) != 0
1982 || GET_TD_MICROSECONDS(self) != 0);
1983}
1984
1985static PyObject *
1986delta_repr(PyDateTime_Delta *self)
1987{
1988 if (GET_TD_MICROSECONDS(self) != 0)
1989 return PyString_FromFormat("%s(%d, %d, %d)",
1990 self->ob_type->tp_name,
1991 GET_TD_DAYS(self),
1992 GET_TD_SECONDS(self),
1993 GET_TD_MICROSECONDS(self));
1994 if (GET_TD_SECONDS(self) != 0)
1995 return PyString_FromFormat("%s(%d, %d)",
1996 self->ob_type->tp_name,
1997 GET_TD_DAYS(self),
1998 GET_TD_SECONDS(self));
1999
2000 return PyString_FromFormat("%s(%d)",
2001 self->ob_type->tp_name,
2002 GET_TD_DAYS(self));
2003}
2004
2005static PyObject *
2006delta_str(PyDateTime_Delta *self)
2007{
2008 int days = GET_TD_DAYS(self);
2009 int seconds = GET_TD_SECONDS(self);
2010 int us = GET_TD_MICROSECONDS(self);
2011 int hours;
2012 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00002013 char buf[100];
2014 char *pbuf = buf;
2015 size_t buflen = sizeof(buf);
2016 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002017
2018 minutes = divmod(seconds, 60, &seconds);
2019 hours = divmod(minutes, 60, &minutes);
2020
2021 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002022 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2023 (days == 1 || days == -1) ? "" : "s");
2024 if (n < 0 || (size_t)n >= buflen)
2025 goto Fail;
2026 pbuf += n;
2027 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002028 }
2029
Tim Petersba873472002-12-18 20:19:21 +00002030 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2031 hours, minutes, seconds);
2032 if (n < 0 || (size_t)n >= buflen)
2033 goto Fail;
2034 pbuf += n;
2035 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002036
2037 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002038 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2039 if (n < 0 || (size_t)n >= buflen)
2040 goto Fail;
2041 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002042 }
2043
Tim Petersba873472002-12-18 20:19:21 +00002044 return PyString_FromStringAndSize(buf, pbuf - buf);
2045
2046 Fail:
2047 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2048 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002049}
2050
Tim Peters371935f2003-02-01 01:52:50 +00002051/* Pickle support, a simple use of __reduce__. */
2052
Tim Petersb57f8f02003-02-01 02:54:15 +00002053/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002054static PyObject *
2055delta_getstate(PyDateTime_Delta *self)
2056{
2057 return Py_BuildValue("iii", GET_TD_DAYS(self),
2058 GET_TD_SECONDS(self),
2059 GET_TD_MICROSECONDS(self));
2060}
2061
Tim Peters2a799bf2002-12-16 20:18:38 +00002062static PyObject *
2063delta_reduce(PyDateTime_Delta* self)
2064{
Tim Peters8a60c222003-02-01 01:47:29 +00002065 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002066}
2067
2068#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2069
2070static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002071
Neal Norwitzdfb80862002-12-19 02:30:56 +00002072 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002073 PyDoc_STR("Number of days.")},
2074
Neal Norwitzdfb80862002-12-19 02:30:56 +00002075 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002076 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2077
Neal Norwitzdfb80862002-12-19 02:30:56 +00002078 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002079 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2080 {NULL}
2081};
2082
2083static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002084 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2085 PyDoc_STR("__reduce__() -> (cls, state)")},
2086
Tim Peters2a799bf2002-12-16 20:18:38 +00002087 {NULL, NULL},
2088};
2089
2090static char delta_doc[] =
2091PyDoc_STR("Difference between two datetime values.");
2092
2093static PyNumberMethods delta_as_number = {
2094 delta_add, /* nb_add */
2095 delta_subtract, /* nb_subtract */
2096 delta_multiply, /* nb_multiply */
2097 delta_divide, /* nb_divide */
2098 0, /* nb_remainder */
2099 0, /* nb_divmod */
2100 0, /* nb_power */
2101 (unaryfunc)delta_negative, /* nb_negative */
2102 (unaryfunc)delta_positive, /* nb_positive */
2103 (unaryfunc)delta_abs, /* nb_absolute */
2104 (inquiry)delta_nonzero, /* nb_nonzero */
2105 0, /*nb_invert*/
2106 0, /*nb_lshift*/
2107 0, /*nb_rshift*/
2108 0, /*nb_and*/
2109 0, /*nb_xor*/
2110 0, /*nb_or*/
2111 0, /*nb_coerce*/
2112 0, /*nb_int*/
2113 0, /*nb_long*/
2114 0, /*nb_float*/
2115 0, /*nb_oct*/
2116 0, /*nb_hex*/
2117 0, /*nb_inplace_add*/
2118 0, /*nb_inplace_subtract*/
2119 0, /*nb_inplace_multiply*/
2120 0, /*nb_inplace_divide*/
2121 0, /*nb_inplace_remainder*/
2122 0, /*nb_inplace_power*/
2123 0, /*nb_inplace_lshift*/
2124 0, /*nb_inplace_rshift*/
2125 0, /*nb_inplace_and*/
2126 0, /*nb_inplace_xor*/
2127 0, /*nb_inplace_or*/
2128 delta_divide, /* nb_floor_divide */
2129 0, /* nb_true_divide */
2130 0, /* nb_inplace_floor_divide */
2131 0, /* nb_inplace_true_divide */
2132};
2133
2134static PyTypeObject PyDateTime_DeltaType = {
2135 PyObject_HEAD_INIT(NULL)
2136 0, /* ob_size */
2137 "datetime.timedelta", /* tp_name */
2138 sizeof(PyDateTime_Delta), /* tp_basicsize */
2139 0, /* tp_itemsize */
2140 0, /* tp_dealloc */
2141 0, /* tp_print */
2142 0, /* tp_getattr */
2143 0, /* tp_setattr */
2144 0, /* tp_compare */
2145 (reprfunc)delta_repr, /* tp_repr */
2146 &delta_as_number, /* tp_as_number */
2147 0, /* tp_as_sequence */
2148 0, /* tp_as_mapping */
2149 (hashfunc)delta_hash, /* tp_hash */
2150 0, /* tp_call */
2151 (reprfunc)delta_str, /* tp_str */
2152 PyObject_GenericGetAttr, /* tp_getattro */
2153 0, /* tp_setattro */
2154 0, /* tp_as_buffer */
Tim Petersb0c854d2003-05-17 15:57:00 +00002155 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2156 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002157 delta_doc, /* tp_doc */
2158 0, /* tp_traverse */
2159 0, /* tp_clear */
2160 (richcmpfunc)delta_richcompare, /* tp_richcompare */
2161 0, /* tp_weaklistoffset */
2162 0, /* tp_iter */
2163 0, /* tp_iternext */
2164 delta_methods, /* tp_methods */
2165 delta_members, /* tp_members */
2166 0, /* tp_getset */
2167 0, /* tp_base */
2168 0, /* tp_dict */
2169 0, /* tp_descr_get */
2170 0, /* tp_descr_set */
2171 0, /* tp_dictoffset */
2172 0, /* tp_init */
2173 0, /* tp_alloc */
2174 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002175 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002176};
2177
2178/*
2179 * PyDateTime_Date implementation.
2180 */
2181
2182/* Accessor properties. */
2183
2184static PyObject *
2185date_year(PyDateTime_Date *self, void *unused)
2186{
2187 return PyInt_FromLong(GET_YEAR(self));
2188}
2189
2190static PyObject *
2191date_month(PyDateTime_Date *self, void *unused)
2192{
2193 return PyInt_FromLong(GET_MONTH(self));
2194}
2195
2196static PyObject *
2197date_day(PyDateTime_Date *self, void *unused)
2198{
2199 return PyInt_FromLong(GET_DAY(self));
2200}
2201
2202static PyGetSetDef date_getset[] = {
2203 {"year", (getter)date_year},
2204 {"month", (getter)date_month},
2205 {"day", (getter)date_day},
2206 {NULL}
2207};
2208
2209/* Constructors. */
2210
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002211static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002212
Tim Peters2a799bf2002-12-16 20:18:38 +00002213static PyObject *
2214date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2215{
2216 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002217 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002218 int year;
2219 int month;
2220 int day;
2221
Guido van Rossum177e41a2003-01-30 22:06:23 +00002222 /* Check for invocation from pickle with __getstate__ state */
2223 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002224 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002225 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2226 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002227 {
Tim Peters70533e22003-02-01 04:40:04 +00002228 PyDateTime_Date *me;
2229
Tim Peters604c0132004-06-07 23:04:33 +00002230 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002231 if (me != NULL) {
2232 char *pdata = PyString_AS_STRING(state);
2233 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2234 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002235 }
Tim Peters70533e22003-02-01 04:40:04 +00002236 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002237 }
2238
Tim Peters12bf3392002-12-24 05:41:27 +00002239 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002240 &year, &month, &day)) {
2241 if (check_date_args(year, month, day) < 0)
2242 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002243 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002244 }
2245 return self;
2246}
2247
2248/* Return new date from localtime(t). */
2249static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002250date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002251{
2252 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002253 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002254 PyObject *result = NULL;
2255
Tim Peters1b6f7a92004-06-20 02:50:16 +00002256 t = _PyTime_DoubleToTimet(ts);
2257 if (t == (time_t)-1 && PyErr_Occurred())
2258 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002259 tm = localtime(&t);
2260 if (tm)
2261 result = PyObject_CallFunction(cls, "iii",
2262 tm->tm_year + 1900,
2263 tm->tm_mon + 1,
2264 tm->tm_mday);
2265 else
2266 PyErr_SetString(PyExc_ValueError,
2267 "timestamp out of range for "
2268 "platform localtime() function");
2269 return result;
2270}
2271
2272/* Return new date from current time.
2273 * We say this is equivalent to fromtimestamp(time.time()), and the
2274 * only way to be sure of that is to *call* time.time(). That's not
2275 * generally the same as calling C's time.
2276 */
2277static PyObject *
2278date_today(PyObject *cls, PyObject *dummy)
2279{
2280 PyObject *time;
2281 PyObject *result;
2282
2283 time = time_time();
2284 if (time == NULL)
2285 return NULL;
2286
2287 /* Note well: today() is a class method, so this may not call
2288 * date.fromtimestamp. For example, it may call
2289 * datetime.fromtimestamp. That's why we need all the accuracy
2290 * time.time() delivers; if someone were gonzo about optimization,
2291 * date.today() could get away with plain C time().
2292 */
2293 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2294 Py_DECREF(time);
2295 return result;
2296}
2297
2298/* Return new date from given timestamp (Python timestamp -- a double). */
2299static PyObject *
2300date_fromtimestamp(PyObject *cls, PyObject *args)
2301{
2302 double timestamp;
2303 PyObject *result = NULL;
2304
2305 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002306 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002307 return result;
2308}
2309
2310/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2311 * the ordinal is out of range.
2312 */
2313static PyObject *
2314date_fromordinal(PyObject *cls, PyObject *args)
2315{
2316 PyObject *result = NULL;
2317 int ordinal;
2318
2319 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2320 int year;
2321 int month;
2322 int day;
2323
2324 if (ordinal < 1)
2325 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2326 ">= 1");
2327 else {
2328 ord_to_ymd(ordinal, &year, &month, &day);
2329 result = PyObject_CallFunction(cls, "iii",
2330 year, month, day);
2331 }
2332 }
2333 return result;
2334}
2335
2336/*
2337 * Date arithmetic.
2338 */
2339
2340/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2341 * instead.
2342 */
2343static PyObject *
2344add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2345{
2346 PyObject *result = NULL;
2347 int year = GET_YEAR(date);
2348 int month = GET_MONTH(date);
2349 int deltadays = GET_TD_DAYS(delta);
2350 /* C-level overflow is impossible because |deltadays| < 1e9. */
2351 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2352
2353 if (normalize_date(&year, &month, &day) >= 0)
2354 result = new_date(year, month, day);
2355 return result;
2356}
2357
2358static PyObject *
2359date_add(PyObject *left, PyObject *right)
2360{
2361 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2362 Py_INCREF(Py_NotImplemented);
2363 return Py_NotImplemented;
2364 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002365 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002366 /* date + ??? */
2367 if (PyDelta_Check(right))
2368 /* date + delta */
2369 return add_date_timedelta((PyDateTime_Date *) left,
2370 (PyDateTime_Delta *) right,
2371 0);
2372 }
2373 else {
2374 /* ??? + date
2375 * 'right' must be one of us, or we wouldn't have been called
2376 */
2377 if (PyDelta_Check(left))
2378 /* delta + date */
2379 return add_date_timedelta((PyDateTime_Date *) right,
2380 (PyDateTime_Delta *) left,
2381 0);
2382 }
2383 Py_INCREF(Py_NotImplemented);
2384 return Py_NotImplemented;
2385}
2386
2387static PyObject *
2388date_subtract(PyObject *left, PyObject *right)
2389{
2390 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2391 Py_INCREF(Py_NotImplemented);
2392 return Py_NotImplemented;
2393 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002394 if (PyDate_Check(left)) {
2395 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002396 /* date - date */
2397 int left_ord = ymd_to_ord(GET_YEAR(left),
2398 GET_MONTH(left),
2399 GET_DAY(left));
2400 int right_ord = ymd_to_ord(GET_YEAR(right),
2401 GET_MONTH(right),
2402 GET_DAY(right));
2403 return new_delta(left_ord - right_ord, 0, 0, 0);
2404 }
2405 if (PyDelta_Check(right)) {
2406 /* date - delta */
2407 return add_date_timedelta((PyDateTime_Date *) left,
2408 (PyDateTime_Delta *) right,
2409 1);
2410 }
2411 }
2412 Py_INCREF(Py_NotImplemented);
2413 return Py_NotImplemented;
2414}
2415
2416
2417/* Various ways to turn a date into a string. */
2418
2419static PyObject *
2420date_repr(PyDateTime_Date *self)
2421{
2422 char buffer[1028];
Skip Montanaro14f88992006-04-18 19:35:04 +00002423 const char *type_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002424
Skip Montanaro14f88992006-04-18 19:35:04 +00002425 type_name = self->ob_type->tp_name;
Tim Peters2a799bf2002-12-16 20:18:38 +00002426 PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00002427 type_name,
Tim Peters2a799bf2002-12-16 20:18:38 +00002428 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2429
2430 return PyString_FromString(buffer);
2431}
2432
2433static PyObject *
2434date_isoformat(PyDateTime_Date *self)
2435{
2436 char buffer[128];
2437
2438 isoformat_date(self, buffer, sizeof(buffer));
2439 return PyString_FromString(buffer);
2440}
2441
Tim Peterse2df5ff2003-05-02 18:39:55 +00002442/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002443static PyObject *
2444date_str(PyDateTime_Date *self)
2445{
2446 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2447}
2448
2449
2450static PyObject *
2451date_ctime(PyDateTime_Date *self)
2452{
2453 return format_ctime(self, 0, 0, 0);
2454}
2455
2456static PyObject *
2457date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2458{
2459 /* This method can be inherited, and needs to call the
2460 * timetuple() method appropriate to self's class.
2461 */
2462 PyObject *result;
2463 PyObject *format;
2464 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002465 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002466
2467 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
2468 &PyString_Type, &format))
2469 return NULL;
2470
2471 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2472 if (tuple == NULL)
2473 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002474 result = wrap_strftime((PyObject *)self, format, tuple,
2475 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002476 Py_DECREF(tuple);
2477 return result;
2478}
2479
2480/* ISO methods. */
2481
2482static PyObject *
2483date_isoweekday(PyDateTime_Date *self)
2484{
2485 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2486
2487 return PyInt_FromLong(dow + 1);
2488}
2489
2490static PyObject *
2491date_isocalendar(PyDateTime_Date *self)
2492{
2493 int year = GET_YEAR(self);
2494 int week1_monday = iso_week1_monday(year);
2495 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2496 int week;
2497 int day;
2498
2499 week = divmod(today - week1_monday, 7, &day);
2500 if (week < 0) {
2501 --year;
2502 week1_monday = iso_week1_monday(year);
2503 week = divmod(today - week1_monday, 7, &day);
2504 }
2505 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2506 ++year;
2507 week = 0;
2508 }
2509 return Py_BuildValue("iii", year, week + 1, day + 1);
2510}
2511
2512/* Miscellaneous methods. */
2513
2514/* This is more natural as a tp_compare, but doesn't work then: for whatever
2515 * reason, Python's try_3way_compare ignores tp_compare unless
2516 * PyInstance_Check returns true, but these aren't old-style classes.
2517 */
2518static PyObject *
2519date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2520{
Tim Peters07534a62003-02-07 22:50:28 +00002521 int diff = 42; /* nonsense */
Tim Peters2a799bf2002-12-16 20:18:38 +00002522
Tim Peters07534a62003-02-07 22:50:28 +00002523 if (PyDate_Check(other))
2524 diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2525 _PyDateTime_DATE_DATASIZE);
2526
2527 else if (PyObject_HasAttrString(other, "timetuple")) {
2528 /* A hook for other kinds of date objects. */
2529 Py_INCREF(Py_NotImplemented);
2530 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002531 }
Tim Peters07534a62003-02-07 22:50:28 +00002532 else if (op == Py_EQ || op == Py_NE)
2533 diff = 1; /* any non-zero value will do */
2534
2535 else /* stop this from falling back to address comparison */
2536 return cmperror((PyObject *)self, other);
2537
Tim Peters2a799bf2002-12-16 20:18:38 +00002538 return diff_to_bool(diff, op);
2539}
2540
2541static PyObject *
2542date_timetuple(PyDateTime_Date *self)
2543{
2544 return build_struct_time(GET_YEAR(self),
2545 GET_MONTH(self),
2546 GET_DAY(self),
2547 0, 0, 0, -1);
2548}
2549
Tim Peters12bf3392002-12-24 05:41:27 +00002550static PyObject *
2551date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2552{
2553 PyObject *clone;
2554 PyObject *tuple;
2555 int year = GET_YEAR(self);
2556 int month = GET_MONTH(self);
2557 int day = GET_DAY(self);
2558
2559 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2560 &year, &month, &day))
2561 return NULL;
2562 tuple = Py_BuildValue("iii", year, month, day);
2563 if (tuple == NULL)
2564 return NULL;
2565 clone = date_new(self->ob_type, tuple, NULL);
2566 Py_DECREF(tuple);
2567 return clone;
2568}
2569
Tim Peters2a799bf2002-12-16 20:18:38 +00002570static PyObject *date_getstate(PyDateTime_Date *self);
2571
2572static long
2573date_hash(PyDateTime_Date *self)
2574{
2575 if (self->hashcode == -1) {
2576 PyObject *temp = date_getstate(self);
2577 if (temp != NULL) {
2578 self->hashcode = PyObject_Hash(temp);
2579 Py_DECREF(temp);
2580 }
2581 }
2582 return self->hashcode;
2583}
2584
2585static PyObject *
2586date_toordinal(PyDateTime_Date *self)
2587{
2588 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2589 GET_DAY(self)));
2590}
2591
2592static PyObject *
2593date_weekday(PyDateTime_Date *self)
2594{
2595 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2596
2597 return PyInt_FromLong(dow);
2598}
2599
Tim Peters371935f2003-02-01 01:52:50 +00002600/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002601
Tim Petersb57f8f02003-02-01 02:54:15 +00002602/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002603static PyObject *
2604date_getstate(PyDateTime_Date *self)
2605{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002606 return Py_BuildValue(
2607 "(N)",
2608 PyString_FromStringAndSize((char *)self->data,
2609 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002610}
2611
2612static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002613date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002614{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002615 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002616}
2617
2618static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002619
Tim Peters2a799bf2002-12-16 20:18:38 +00002620 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002621
Tim Peters2a799bf2002-12-16 20:18:38 +00002622 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2623 METH_CLASS,
2624 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2625 "time.time()).")},
2626
2627 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2628 METH_CLASS,
2629 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2630 "ordinal.")},
2631
2632 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2633 PyDoc_STR("Current date or datetime: same as "
2634 "self.__class__.fromtimestamp(time.time()).")},
2635
2636 /* Instance methods: */
2637
2638 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2639 PyDoc_STR("Return ctime() style string.")},
2640
2641 {"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
2642 PyDoc_STR("format -> strftime() style string.")},
2643
2644 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2645 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2646
2647 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2648 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2649 "weekday.")},
2650
2651 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2652 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2653
2654 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2655 PyDoc_STR("Return the day of the week represented by the date.\n"
2656 "Monday == 1 ... Sunday == 7")},
2657
2658 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2659 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2660 "1 is day 1.")},
2661
2662 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2663 PyDoc_STR("Return the day of the week represented by the date.\n"
2664 "Monday == 0 ... Sunday == 6")},
2665
Tim Peters12bf3392002-12-24 05:41:27 +00002666 {"replace", (PyCFunction)date_replace, METH_KEYWORDS,
2667 PyDoc_STR("Return date with new specified fields.")},
2668
Guido van Rossum177e41a2003-01-30 22:06:23 +00002669 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2670 PyDoc_STR("__reduce__() -> (cls, state)")},
2671
Tim Peters2a799bf2002-12-16 20:18:38 +00002672 {NULL, NULL}
2673};
2674
2675static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002676PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002677
2678static PyNumberMethods date_as_number = {
2679 date_add, /* nb_add */
2680 date_subtract, /* nb_subtract */
2681 0, /* nb_multiply */
2682 0, /* nb_divide */
2683 0, /* nb_remainder */
2684 0, /* nb_divmod */
2685 0, /* nb_power */
2686 0, /* nb_negative */
2687 0, /* nb_positive */
2688 0, /* nb_absolute */
2689 0, /* nb_nonzero */
2690};
2691
2692static PyTypeObject PyDateTime_DateType = {
2693 PyObject_HEAD_INIT(NULL)
2694 0, /* ob_size */
2695 "datetime.date", /* tp_name */
2696 sizeof(PyDateTime_Date), /* tp_basicsize */
2697 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002698 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002699 0, /* tp_print */
2700 0, /* tp_getattr */
2701 0, /* tp_setattr */
2702 0, /* tp_compare */
2703 (reprfunc)date_repr, /* tp_repr */
2704 &date_as_number, /* tp_as_number */
2705 0, /* tp_as_sequence */
2706 0, /* tp_as_mapping */
2707 (hashfunc)date_hash, /* tp_hash */
2708 0, /* tp_call */
2709 (reprfunc)date_str, /* tp_str */
2710 PyObject_GenericGetAttr, /* tp_getattro */
2711 0, /* tp_setattro */
2712 0, /* tp_as_buffer */
2713 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2714 Py_TPFLAGS_BASETYPE, /* tp_flags */
2715 date_doc, /* tp_doc */
2716 0, /* tp_traverse */
2717 0, /* tp_clear */
2718 (richcmpfunc)date_richcompare, /* tp_richcompare */
2719 0, /* tp_weaklistoffset */
2720 0, /* tp_iter */
2721 0, /* tp_iternext */
2722 date_methods, /* tp_methods */
2723 0, /* tp_members */
2724 date_getset, /* tp_getset */
2725 0, /* tp_base */
2726 0, /* tp_dict */
2727 0, /* tp_descr_get */
2728 0, /* tp_descr_set */
2729 0, /* tp_dictoffset */
2730 0, /* tp_init */
2731 0, /* tp_alloc */
2732 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002733 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002734};
2735
2736/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002737 * PyDateTime_TZInfo implementation.
2738 */
2739
2740/* This is a pure abstract base class, so doesn't do anything beyond
2741 * raising NotImplemented exceptions. Real tzinfo classes need
2742 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002743 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002744 * be subclasses of this tzinfo class, which is easy and quick to check).
2745 *
2746 * Note: For reasons having to do with pickling of subclasses, we have
2747 * to allow tzinfo objects to be instantiated. This wasn't an issue
2748 * in the Python implementation (__init__() could raise NotImplementedError
2749 * there without ill effect), but doing so in the C implementation hit a
2750 * brick wall.
2751 */
2752
2753static PyObject *
2754tzinfo_nogo(const char* methodname)
2755{
2756 PyErr_Format(PyExc_NotImplementedError,
2757 "a tzinfo subclass must implement %s()",
2758 methodname);
2759 return NULL;
2760}
2761
2762/* Methods. A subclass must implement these. */
2763
Tim Peters52dcce22003-01-23 16:36:11 +00002764static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002765tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2766{
2767 return tzinfo_nogo("tzname");
2768}
2769
Tim Peters52dcce22003-01-23 16:36:11 +00002770static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002771tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2772{
2773 return tzinfo_nogo("utcoffset");
2774}
2775
Tim Peters52dcce22003-01-23 16:36:11 +00002776static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002777tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2778{
2779 return tzinfo_nogo("dst");
2780}
2781
Tim Peters52dcce22003-01-23 16:36:11 +00002782static PyObject *
2783tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2784{
2785 int y, m, d, hh, mm, ss, us;
2786
2787 PyObject *result;
2788 int off, dst;
2789 int none;
2790 int delta;
2791
2792 if (! PyDateTime_Check(dt)) {
2793 PyErr_SetString(PyExc_TypeError,
2794 "fromutc: argument must be a datetime");
2795 return NULL;
2796 }
2797 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2798 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2799 "is not self");
2800 return NULL;
2801 }
2802
2803 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2804 if (off == -1 && PyErr_Occurred())
2805 return NULL;
2806 if (none) {
2807 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2808 "utcoffset() result required");
2809 return NULL;
2810 }
2811
2812 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2813 if (dst == -1 && PyErr_Occurred())
2814 return NULL;
2815 if (none) {
2816 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2817 "dst() result required");
2818 return NULL;
2819 }
2820
2821 y = GET_YEAR(dt);
2822 m = GET_MONTH(dt);
2823 d = GET_DAY(dt);
2824 hh = DATE_GET_HOUR(dt);
2825 mm = DATE_GET_MINUTE(dt);
2826 ss = DATE_GET_SECOND(dt);
2827 us = DATE_GET_MICROSECOND(dt);
2828
2829 delta = off - dst;
2830 mm += delta;
2831 if ((mm < 0 || mm >= 60) &&
2832 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002833 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002834 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2835 if (result == NULL)
2836 return result;
2837
2838 dst = call_dst(dt->tzinfo, result, &none);
2839 if (dst == -1 && PyErr_Occurred())
2840 goto Fail;
2841 if (none)
2842 goto Inconsistent;
2843 if (dst == 0)
2844 return result;
2845
2846 mm += dst;
2847 if ((mm < 0 || mm >= 60) &&
2848 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2849 goto Fail;
2850 Py_DECREF(result);
2851 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2852 return result;
2853
2854Inconsistent:
2855 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2856 "inconsistent results; cannot convert");
2857
2858 /* fall thru to failure */
2859Fail:
2860 Py_DECREF(result);
2861 return NULL;
2862}
2863
Tim Peters2a799bf2002-12-16 20:18:38 +00002864/*
2865 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002866 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002867 */
2868
Guido van Rossum177e41a2003-01-30 22:06:23 +00002869static PyObject *
2870tzinfo_reduce(PyObject *self)
2871{
2872 PyObject *args, *state, *tmp;
2873 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002874
Guido van Rossum177e41a2003-01-30 22:06:23 +00002875 tmp = PyTuple_New(0);
2876 if (tmp == NULL)
2877 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002878
Guido van Rossum177e41a2003-01-30 22:06:23 +00002879 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2880 if (getinitargs != NULL) {
2881 args = PyObject_CallObject(getinitargs, tmp);
2882 Py_DECREF(getinitargs);
2883 if (args == NULL) {
2884 Py_DECREF(tmp);
2885 return NULL;
2886 }
2887 }
2888 else {
2889 PyErr_Clear();
2890 args = tmp;
2891 Py_INCREF(args);
2892 }
2893
2894 getstate = PyObject_GetAttrString(self, "__getstate__");
2895 if (getstate != NULL) {
2896 state = PyObject_CallObject(getstate, tmp);
2897 Py_DECREF(getstate);
2898 if (state == NULL) {
2899 Py_DECREF(args);
2900 Py_DECREF(tmp);
2901 return NULL;
2902 }
2903 }
2904 else {
2905 PyObject **dictptr;
2906 PyErr_Clear();
2907 state = Py_None;
2908 dictptr = _PyObject_GetDictPtr(self);
2909 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2910 state = *dictptr;
2911 Py_INCREF(state);
2912 }
2913
2914 Py_DECREF(tmp);
2915
2916 if (state == Py_None) {
2917 Py_DECREF(state);
2918 return Py_BuildValue("(ON)", self->ob_type, args);
2919 }
2920 else
2921 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2922}
Tim Peters2a799bf2002-12-16 20:18:38 +00002923
2924static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002925
Tim Peters2a799bf2002-12-16 20:18:38 +00002926 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2927 PyDoc_STR("datetime -> string name of time zone.")},
2928
2929 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2930 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2931 "west of UTC).")},
2932
2933 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2934 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2935
Tim Peters52dcce22003-01-23 16:36:11 +00002936 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2937 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2938
Guido van Rossum177e41a2003-01-30 22:06:23 +00002939 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2940 PyDoc_STR("-> (cls, state)")},
2941
Tim Peters2a799bf2002-12-16 20:18:38 +00002942 {NULL, NULL}
2943};
2944
2945static char tzinfo_doc[] =
2946PyDoc_STR("Abstract base class for time zone info objects.");
2947
Neal Norwitzce3d34d2003-02-04 20:45:17 +00002948statichere PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002949 PyObject_HEAD_INIT(NULL)
2950 0, /* ob_size */
2951 "datetime.tzinfo", /* tp_name */
2952 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2953 0, /* tp_itemsize */
2954 0, /* tp_dealloc */
2955 0, /* tp_print */
2956 0, /* tp_getattr */
2957 0, /* tp_setattr */
2958 0, /* tp_compare */
2959 0, /* tp_repr */
2960 0, /* tp_as_number */
2961 0, /* tp_as_sequence */
2962 0, /* tp_as_mapping */
2963 0, /* tp_hash */
2964 0, /* tp_call */
2965 0, /* tp_str */
2966 PyObject_GenericGetAttr, /* tp_getattro */
2967 0, /* tp_setattro */
2968 0, /* tp_as_buffer */
2969 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2970 Py_TPFLAGS_BASETYPE, /* tp_flags */
2971 tzinfo_doc, /* tp_doc */
2972 0, /* tp_traverse */
2973 0, /* tp_clear */
2974 0, /* tp_richcompare */
2975 0, /* tp_weaklistoffset */
2976 0, /* tp_iter */
2977 0, /* tp_iternext */
2978 tzinfo_methods, /* tp_methods */
2979 0, /* tp_members */
2980 0, /* tp_getset */
2981 0, /* tp_base */
2982 0, /* tp_dict */
2983 0, /* tp_descr_get */
2984 0, /* tp_descr_set */
2985 0, /* tp_dictoffset */
2986 0, /* tp_init */
2987 0, /* tp_alloc */
2988 PyType_GenericNew, /* tp_new */
2989 0, /* tp_free */
2990};
2991
2992/*
Tim Peters37f39822003-01-10 03:49:02 +00002993 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002994 */
2995
Tim Peters37f39822003-01-10 03:49:02 +00002996/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002997 */
2998
2999static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003000time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003001{
Tim Peters37f39822003-01-10 03:49:02 +00003002 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003003}
3004
Tim Peters37f39822003-01-10 03:49:02 +00003005static PyObject *
3006time_minute(PyDateTime_Time *self, void *unused)
3007{
3008 return PyInt_FromLong(TIME_GET_MINUTE(self));
3009}
3010
3011/* The name time_second conflicted with some platform header file. */
3012static PyObject *
3013py_time_second(PyDateTime_Time *self, void *unused)
3014{
3015 return PyInt_FromLong(TIME_GET_SECOND(self));
3016}
3017
3018static PyObject *
3019time_microsecond(PyDateTime_Time *self, void *unused)
3020{
3021 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3022}
3023
3024static PyObject *
3025time_tzinfo(PyDateTime_Time *self, void *unused)
3026{
Tim Petersa032d2e2003-01-11 00:15:54 +00003027 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00003028 Py_INCREF(result);
3029 return result;
3030}
3031
3032static PyGetSetDef time_getset[] = {
3033 {"hour", (getter)time_hour},
3034 {"minute", (getter)time_minute},
3035 {"second", (getter)py_time_second},
3036 {"microsecond", (getter)time_microsecond},
3037 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003038 {NULL}
3039};
3040
3041/*
3042 * Constructors.
3043 */
3044
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003045static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003046 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003047
Tim Peters2a799bf2002-12-16 20:18:38 +00003048static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003049time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003050{
3051 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003052 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003053 int hour = 0;
3054 int minute = 0;
3055 int second = 0;
3056 int usecond = 0;
3057 PyObject *tzinfo = Py_None;
3058
Guido van Rossum177e41a2003-01-30 22:06:23 +00003059 /* Check for invocation from pickle with __getstate__ state */
3060 if (PyTuple_GET_SIZE(args) >= 1 &&
3061 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003062 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003063 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3064 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003065 {
Tim Peters70533e22003-02-01 04:40:04 +00003066 PyDateTime_Time *me;
3067 char aware;
3068
3069 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003070 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003071 if (check_tzinfo_subclass(tzinfo) < 0) {
3072 PyErr_SetString(PyExc_TypeError, "bad "
3073 "tzinfo state arg");
3074 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003075 }
3076 }
Tim Peters70533e22003-02-01 04:40:04 +00003077 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003078 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003079 if (me != NULL) {
3080 char *pdata = PyString_AS_STRING(state);
3081
3082 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3083 me->hashcode = -1;
3084 me->hastzinfo = aware;
3085 if (aware) {
3086 Py_INCREF(tzinfo);
3087 me->tzinfo = tzinfo;
3088 }
3089 }
3090 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003091 }
3092
Tim Peters37f39822003-01-10 03:49:02 +00003093 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003094 &hour, &minute, &second, &usecond,
3095 &tzinfo)) {
3096 if (check_time_args(hour, minute, second, usecond) < 0)
3097 return NULL;
3098 if (check_tzinfo_subclass(tzinfo) < 0)
3099 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003100 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3101 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003102 }
3103 return self;
3104}
3105
3106/*
3107 * Destructor.
3108 */
3109
3110static void
Tim Peters37f39822003-01-10 03:49:02 +00003111time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003112{
Tim Petersa032d2e2003-01-11 00:15:54 +00003113 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003114 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003115 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003116 self->ob_type->tp_free((PyObject *)self);
3117}
3118
3119/*
Tim Peters855fe882002-12-22 03:43:39 +00003120 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003121 */
3122
Tim Peters2a799bf2002-12-16 20:18:38 +00003123/* These are all METH_NOARGS, so don't need to check the arglist. */
3124static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003125time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003126 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003127 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003128}
3129
3130static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003131time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003132 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003133 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003134}
3135
3136static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003137time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003138 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003139 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003140}
3141
3142/*
Tim Peters37f39822003-01-10 03:49:02 +00003143 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003144 */
3145
3146static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003147time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003148{
Tim Peters37f39822003-01-10 03:49:02 +00003149 char buffer[100];
Skip Montanaro14f88992006-04-18 19:35:04 +00003150 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003151 int h = TIME_GET_HOUR(self);
3152 int m = TIME_GET_MINUTE(self);
3153 int s = TIME_GET_SECOND(self);
3154 int us = TIME_GET_MICROSECOND(self);
3155 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003156
Tim Peters37f39822003-01-10 03:49:02 +00003157 if (us)
3158 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003159 "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003160 else if (s)
3161 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003162 "%s(%d, %d, %d)", type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003163 else
3164 PyOS_snprintf(buffer, sizeof(buffer),
Skip Montanaro14f88992006-04-18 19:35:04 +00003165 "%s(%d, %d)", type_name, h, m);
Tim Peters37f39822003-01-10 03:49:02 +00003166 result = PyString_FromString(buffer);
Tim Petersa032d2e2003-01-11 00:15:54 +00003167 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003168 result = append_keyword_tzinfo(result, self->tzinfo);
3169 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003170}
3171
Tim Peters37f39822003-01-10 03:49:02 +00003172static PyObject *
3173time_str(PyDateTime_Time *self)
3174{
3175 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3176}
Tim Peters2a799bf2002-12-16 20:18:38 +00003177
Martin v. Löwisb8d661b2007-02-18 08:50:38 +00003178/* Even though this silently ignores all arguments, it cannot
3179 be fixed to reject them in release25-maint */
Tim Peters2a799bf2002-12-16 20:18:38 +00003180static PyObject *
Martin v. Löwisb8d661b2007-02-18 08:50:38 +00003181time_isoformat(PyDateTime_Time *self, PyObject *unused_args,
3182 PyObject *unused_keywords)
Tim Peters2a799bf2002-12-16 20:18:38 +00003183{
3184 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003185 PyObject *result;
3186 /* Reuse the time format code from the datetime type. */
3187 PyDateTime_DateTime datetime;
3188 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003189
Tim Peters37f39822003-01-10 03:49:02 +00003190 /* Copy over just the time bytes. */
3191 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3192 self->data,
3193 _PyDateTime_TIME_DATASIZE);
3194
3195 isoformat_time(pdatetime, buf, sizeof(buf));
3196 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003197 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003198 return result;
3199
3200 /* We need to append the UTC offset. */
3201 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003202 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003203 Py_DECREF(result);
3204 return NULL;
3205 }
3206 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3207 return result;
3208}
3209
Tim Peters37f39822003-01-10 03:49:02 +00003210static PyObject *
3211time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3212{
3213 PyObject *result;
3214 PyObject *format;
3215 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003216 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003217
3218 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:strftime", keywords,
3219 &PyString_Type, &format))
3220 return NULL;
3221
3222 /* Python's strftime does insane things with the year part of the
3223 * timetuple. The year is forced to (the otherwise nonsensical)
3224 * 1900 to worm around that.
3225 */
3226 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003227 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003228 TIME_GET_HOUR(self),
3229 TIME_GET_MINUTE(self),
3230 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003231 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003232 if (tuple == NULL)
3233 return NULL;
3234 assert(PyTuple_Size(tuple) == 9);
3235 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3236 Py_DECREF(tuple);
3237 return result;
3238}
Tim Peters2a799bf2002-12-16 20:18:38 +00003239
3240/*
3241 * Miscellaneous methods.
3242 */
3243
Tim Peters37f39822003-01-10 03:49:02 +00003244/* This is more natural as a tp_compare, but doesn't work then: for whatever
3245 * reason, Python's try_3way_compare ignores tp_compare unless
3246 * PyInstance_Check returns true, but these aren't old-style classes.
3247 */
3248static PyObject *
3249time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3250{
3251 int diff;
3252 naivety n1, n2;
3253 int offset1, offset2;
3254
3255 if (! PyTime_Check(other)) {
Tim Peters07534a62003-02-07 22:50:28 +00003256 if (op == Py_EQ || op == Py_NE) {
3257 PyObject *result = op == Py_EQ ? Py_False : Py_True;
3258 Py_INCREF(result);
3259 return result;
3260 }
Tim Peters37f39822003-01-10 03:49:02 +00003261 /* Stop this from falling back to address comparison. */
Tim Peters07534a62003-02-07 22:50:28 +00003262 return cmperror((PyObject *)self, other);
Tim Peters37f39822003-01-10 03:49:02 +00003263 }
3264 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
3265 other, &offset2, &n2, Py_None) < 0)
3266 return NULL;
3267 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3268 /* If they're both naive, or both aware and have the same offsets,
3269 * we get off cheap. Note that if they're both naive, offset1 ==
3270 * offset2 == 0 at this point.
3271 */
3272 if (n1 == n2 && offset1 == offset2) {
3273 diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3274 _PyDateTime_TIME_DATASIZE);
3275 return diff_to_bool(diff, op);
3276 }
3277
3278 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3279 assert(offset1 != offset2); /* else last "if" handled it */
3280 /* Convert everything except microseconds to seconds. These
3281 * can't overflow (no more than the # of seconds in 2 days).
3282 */
3283 offset1 = TIME_GET_HOUR(self) * 3600 +
3284 (TIME_GET_MINUTE(self) - offset1) * 60 +
3285 TIME_GET_SECOND(self);
3286 offset2 = TIME_GET_HOUR(other) * 3600 +
3287 (TIME_GET_MINUTE(other) - offset2) * 60 +
3288 TIME_GET_SECOND(other);
3289 diff = offset1 - offset2;
3290 if (diff == 0)
3291 diff = TIME_GET_MICROSECOND(self) -
3292 TIME_GET_MICROSECOND(other);
3293 return diff_to_bool(diff, op);
3294 }
3295
3296 assert(n1 != n2);
3297 PyErr_SetString(PyExc_TypeError,
3298 "can't compare offset-naive and "
3299 "offset-aware times");
3300 return NULL;
3301}
3302
3303static long
3304time_hash(PyDateTime_Time *self)
3305{
3306 if (self->hashcode == -1) {
3307 naivety n;
3308 int offset;
3309 PyObject *temp;
3310
3311 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3312 assert(n != OFFSET_UNKNOWN);
3313 if (n == OFFSET_ERROR)
3314 return -1;
3315
3316 /* Reduce this to a hash of another object. */
3317 if (offset == 0)
3318 temp = PyString_FromStringAndSize((char *)self->data,
3319 _PyDateTime_TIME_DATASIZE);
3320 else {
3321 int hour;
3322 int minute;
3323
3324 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003325 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003326 hour = divmod(TIME_GET_HOUR(self) * 60 +
3327 TIME_GET_MINUTE(self) - offset,
3328 60,
3329 &minute);
3330 if (0 <= hour && hour < 24)
3331 temp = new_time(hour, minute,
3332 TIME_GET_SECOND(self),
3333 TIME_GET_MICROSECOND(self),
3334 Py_None);
3335 else
3336 temp = Py_BuildValue("iiii",
3337 hour, minute,
3338 TIME_GET_SECOND(self),
3339 TIME_GET_MICROSECOND(self));
3340 }
3341 if (temp != NULL) {
3342 self->hashcode = PyObject_Hash(temp);
3343 Py_DECREF(temp);
3344 }
3345 }
3346 return self->hashcode;
3347}
Tim Peters2a799bf2002-12-16 20:18:38 +00003348
Tim Peters12bf3392002-12-24 05:41:27 +00003349static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003350time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003351{
3352 PyObject *clone;
3353 PyObject *tuple;
3354 int hh = TIME_GET_HOUR(self);
3355 int mm = TIME_GET_MINUTE(self);
3356 int ss = TIME_GET_SECOND(self);
3357 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003358 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003359
3360 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003361 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003362 &hh, &mm, &ss, &us, &tzinfo))
3363 return NULL;
3364 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3365 if (tuple == NULL)
3366 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003367 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003368 Py_DECREF(tuple);
3369 return clone;
3370}
3371
Tim Peters2a799bf2002-12-16 20:18:38 +00003372static int
Tim Peters37f39822003-01-10 03:49:02 +00003373time_nonzero(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003374{
3375 int offset;
3376 int none;
3377
3378 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3379 /* Since utcoffset is in whole minutes, nothing can
3380 * alter the conclusion that this is nonzero.
3381 */
3382 return 1;
3383 }
3384 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003385 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003386 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003387 if (offset == -1 && PyErr_Occurred())
3388 return -1;
3389 }
3390 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3391}
3392
Tim Peters371935f2003-02-01 01:52:50 +00003393/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003394
Tim Peters33e0f382003-01-10 02:05:14 +00003395/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003396 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3397 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003398 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003399 */
3400static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003401time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003402{
3403 PyObject *basestate;
3404 PyObject *result = NULL;
3405
Tim Peters33e0f382003-01-10 02:05:14 +00003406 basestate = PyString_FromStringAndSize((char *)self->data,
3407 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003408 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003409 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003410 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003411 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003412 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003413 Py_DECREF(basestate);
3414 }
3415 return result;
3416}
3417
3418static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003419time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003420{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003421 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003422}
3423
Tim Peters37f39822003-01-10 03:49:02 +00003424static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003425
Martin v. Löwisb8d661b2007-02-18 08:50:38 +00003426 {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003427 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3428 "[+HH:MM].")},
3429
Tim Peters37f39822003-01-10 03:49:02 +00003430 {"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
3431 PyDoc_STR("format -> strftime() style string.")},
3432
3433 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003434 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3435
Tim Peters37f39822003-01-10 03:49:02 +00003436 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003437 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3438
Tim Peters37f39822003-01-10 03:49:02 +00003439 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003440 PyDoc_STR("Return self.tzinfo.dst(self).")},
3441
Tim Peters37f39822003-01-10 03:49:02 +00003442 {"replace", (PyCFunction)time_replace, METH_KEYWORDS,
3443 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003444
Guido van Rossum177e41a2003-01-30 22:06:23 +00003445 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3446 PyDoc_STR("__reduce__() -> (cls, state)")},
3447
Tim Peters2a799bf2002-12-16 20:18:38 +00003448 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003449};
3450
Tim Peters37f39822003-01-10 03:49:02 +00003451static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003452PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3453\n\
3454All arguments are optional. tzinfo may be None, or an instance of\n\
3455a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003456
Tim Peters37f39822003-01-10 03:49:02 +00003457static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003458 0, /* nb_add */
3459 0, /* nb_subtract */
3460 0, /* nb_multiply */
3461 0, /* nb_divide */
3462 0, /* nb_remainder */
3463 0, /* nb_divmod */
3464 0, /* nb_power */
3465 0, /* nb_negative */
3466 0, /* nb_positive */
3467 0, /* nb_absolute */
Tim Peters37f39822003-01-10 03:49:02 +00003468 (inquiry)time_nonzero, /* nb_nonzero */
Tim Peters2a799bf2002-12-16 20:18:38 +00003469};
3470
Tim Peters37f39822003-01-10 03:49:02 +00003471statichere PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003472 PyObject_HEAD_INIT(NULL)
3473 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003474 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003475 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003476 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003477 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003478 0, /* tp_print */
3479 0, /* tp_getattr */
3480 0, /* tp_setattr */
3481 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003482 (reprfunc)time_repr, /* tp_repr */
3483 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003484 0, /* tp_as_sequence */
3485 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003486 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003487 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003488 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003489 PyObject_GenericGetAttr, /* tp_getattro */
3490 0, /* tp_setattro */
3491 0, /* tp_as_buffer */
3492 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3493 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003494 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003495 0, /* tp_traverse */
3496 0, /* tp_clear */
Tim Peters37f39822003-01-10 03:49:02 +00003497 (richcmpfunc)time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003498 0, /* tp_weaklistoffset */
3499 0, /* tp_iter */
3500 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003501 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003502 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003503 time_getset, /* tp_getset */
3504 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003505 0, /* tp_dict */
3506 0, /* tp_descr_get */
3507 0, /* tp_descr_set */
3508 0, /* tp_dictoffset */
3509 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003510 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003511 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003512 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003513};
3514
3515/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003516 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003517 */
3518
Tim Petersa9bc1682003-01-11 03:39:11 +00003519/* Accessor properties. Properties for day, month, and year are inherited
3520 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003521 */
3522
3523static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003524datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003525{
Tim Petersa9bc1682003-01-11 03:39:11 +00003526 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003527}
3528
Tim Petersa9bc1682003-01-11 03:39:11 +00003529static PyObject *
3530datetime_minute(PyDateTime_DateTime *self, void *unused)
3531{
3532 return PyInt_FromLong(DATE_GET_MINUTE(self));
3533}
3534
3535static PyObject *
3536datetime_second(PyDateTime_DateTime *self, void *unused)
3537{
3538 return PyInt_FromLong(DATE_GET_SECOND(self));
3539}
3540
3541static PyObject *
3542datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3543{
3544 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3545}
3546
3547static PyObject *
3548datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3549{
3550 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3551 Py_INCREF(result);
3552 return result;
3553}
3554
3555static PyGetSetDef datetime_getset[] = {
3556 {"hour", (getter)datetime_hour},
3557 {"minute", (getter)datetime_minute},
3558 {"second", (getter)datetime_second},
3559 {"microsecond", (getter)datetime_microsecond},
3560 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003561 {NULL}
3562};
3563
3564/*
3565 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003566 */
3567
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003568static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003569 "year", "month", "day", "hour", "minute", "second",
3570 "microsecond", "tzinfo", NULL
3571};
3572
Tim Peters2a799bf2002-12-16 20:18:38 +00003573static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003574datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003575{
3576 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003577 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003578 int year;
3579 int month;
3580 int day;
3581 int hour = 0;
3582 int minute = 0;
3583 int second = 0;
3584 int usecond = 0;
3585 PyObject *tzinfo = Py_None;
3586
Guido van Rossum177e41a2003-01-30 22:06:23 +00003587 /* Check for invocation from pickle with __getstate__ state */
3588 if (PyTuple_GET_SIZE(args) >= 1 &&
3589 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003590 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003591 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3592 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003593 {
Tim Peters70533e22003-02-01 04:40:04 +00003594 PyDateTime_DateTime *me;
3595 char aware;
3596
3597 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003598 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003599 if (check_tzinfo_subclass(tzinfo) < 0) {
3600 PyErr_SetString(PyExc_TypeError, "bad "
3601 "tzinfo state arg");
3602 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003603 }
3604 }
Tim Peters70533e22003-02-01 04:40:04 +00003605 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003606 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003607 if (me != NULL) {
3608 char *pdata = PyString_AS_STRING(state);
3609
3610 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3611 me->hashcode = -1;
3612 me->hastzinfo = aware;
3613 if (aware) {
3614 Py_INCREF(tzinfo);
3615 me->tzinfo = tzinfo;
3616 }
3617 }
3618 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003619 }
3620
Tim Petersa9bc1682003-01-11 03:39:11 +00003621 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003622 &year, &month, &day, &hour, &minute,
3623 &second, &usecond, &tzinfo)) {
3624 if (check_date_args(year, month, day) < 0)
3625 return NULL;
3626 if (check_time_args(hour, minute, second, usecond) < 0)
3627 return NULL;
3628 if (check_tzinfo_subclass(tzinfo) < 0)
3629 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003630 self = new_datetime_ex(year, month, day,
3631 hour, minute, second, usecond,
3632 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003633 }
3634 return self;
3635}
3636
Tim Petersa9bc1682003-01-11 03:39:11 +00003637/* TM_FUNC is the shared type of localtime() and gmtime(). */
3638typedef struct tm *(*TM_FUNC)(const time_t *timer);
3639
3640/* Internal helper.
3641 * Build datetime from a time_t and a distinct count of microseconds.
3642 * Pass localtime or gmtime for f, to control the interpretation of timet.
3643 */
3644static PyObject *
3645datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3646 PyObject *tzinfo)
3647{
3648 struct tm *tm;
3649 PyObject *result = NULL;
3650
3651 tm = f(&timet);
3652 if (tm) {
3653 /* The platform localtime/gmtime may insert leap seconds,
3654 * indicated by tm->tm_sec > 59. We don't care about them,
3655 * except to the extent that passing them on to the datetime
3656 * constructor would raise ValueError for a reason that
3657 * made no sense to the user.
3658 */
3659 if (tm->tm_sec > 59)
3660 tm->tm_sec = 59;
3661 result = PyObject_CallFunction(cls, "iiiiiiiO",
3662 tm->tm_year + 1900,
3663 tm->tm_mon + 1,
3664 tm->tm_mday,
3665 tm->tm_hour,
3666 tm->tm_min,
3667 tm->tm_sec,
3668 us,
3669 tzinfo);
3670 }
3671 else
3672 PyErr_SetString(PyExc_ValueError,
3673 "timestamp out of range for "
3674 "platform localtime()/gmtime() function");
3675 return result;
3676}
3677
3678/* Internal helper.
3679 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3680 * to control the interpretation of the timestamp. Since a double doesn't
3681 * have enough bits to cover a datetime's full range of precision, it's
3682 * better to call datetime_from_timet_and_us provided you have a way
3683 * to get that much precision (e.g., C time() isn't good enough).
3684 */
3685static PyObject *
3686datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3687 PyObject *tzinfo)
3688{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003689 time_t timet;
3690 double fraction;
3691 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003692
Tim Peters1b6f7a92004-06-20 02:50:16 +00003693 timet = _PyTime_DoubleToTimet(timestamp);
3694 if (timet == (time_t)-1 && PyErr_Occurred())
3695 return NULL;
3696 fraction = timestamp - (double)timet;
3697 us = (int)round_to_long(fraction * 1e6);
Georg Brandl02d7cff2007-03-06 17:46:17 +00003698 if (us < 0) {
3699 /* Truncation towards zero is not what we wanted
3700 for negative numbers (Python's mod semantics) */
3701 timet -= 1;
3702 us += 1000000;
3703 }
Georg Brandl6d78a582006-04-28 19:09:24 +00003704 /* If timestamp is less than one microsecond smaller than a
3705 * full second, round up. Otherwise, ValueErrors are raised
3706 * for some floats. */
3707 if (us == 1000000) {
3708 timet += 1;
3709 us = 0;
3710 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003711 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3712}
3713
3714/* Internal helper.
3715 * Build most accurate possible datetime for current time. Pass localtime or
3716 * gmtime for f as appropriate.
3717 */
3718static PyObject *
3719datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3720{
3721#ifdef HAVE_GETTIMEOFDAY
3722 struct timeval t;
3723
3724#ifdef GETTIMEOFDAY_NO_TZ
3725 gettimeofday(&t);
3726#else
3727 gettimeofday(&t, (struct timezone *)NULL);
3728#endif
3729 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3730 tzinfo);
3731
3732#else /* ! HAVE_GETTIMEOFDAY */
3733 /* No flavor of gettimeofday exists on this platform. Python's
3734 * time.time() does a lot of other platform tricks to get the
3735 * best time it can on the platform, and we're not going to do
3736 * better than that (if we could, the better code would belong
3737 * in time.time()!) We're limited by the precision of a double,
3738 * though.
3739 */
3740 PyObject *time;
3741 double dtime;
3742
3743 time = time_time();
3744 if (time == NULL)
3745 return NULL;
3746 dtime = PyFloat_AsDouble(time);
3747 Py_DECREF(time);
3748 if (dtime == -1.0 && PyErr_Occurred())
3749 return NULL;
3750 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3751#endif /* ! HAVE_GETTIMEOFDAY */
3752}
3753
Tim Peters2a799bf2002-12-16 20:18:38 +00003754/* Return best possible local time -- this isn't constrained by the
3755 * precision of a timestamp.
3756 */
3757static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003758datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003759{
Tim Peters10cadce2003-01-23 19:58:02 +00003760 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003761 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003762 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003763
Tim Peters10cadce2003-01-23 19:58:02 +00003764 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3765 &tzinfo))
3766 return NULL;
3767 if (check_tzinfo_subclass(tzinfo) < 0)
3768 return NULL;
3769
3770 self = datetime_best_possible(cls,
3771 tzinfo == Py_None ? localtime : gmtime,
3772 tzinfo);
3773 if (self != NULL && tzinfo != Py_None) {
3774 /* Convert UTC to tzinfo's zone. */
3775 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003776 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003777 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003778 }
3779 return self;
3780}
3781
Tim Petersa9bc1682003-01-11 03:39:11 +00003782/* Return best possible UTC time -- this isn't constrained by the
3783 * precision of a timestamp.
3784 */
3785static PyObject *
3786datetime_utcnow(PyObject *cls, PyObject *dummy)
3787{
3788 return datetime_best_possible(cls, gmtime, Py_None);
3789}
3790
Tim Peters2a799bf2002-12-16 20:18:38 +00003791/* Return new local datetime from timestamp (Python timestamp -- a double). */
3792static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003793datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003794{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003795 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003796 double timestamp;
3797 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003798 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003799
Tim Peters2a44a8d2003-01-23 20:53:10 +00003800 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3801 keywords, &timestamp, &tzinfo))
3802 return NULL;
3803 if (check_tzinfo_subclass(tzinfo) < 0)
3804 return NULL;
3805
3806 self = datetime_from_timestamp(cls,
3807 tzinfo == Py_None ? localtime : gmtime,
3808 timestamp,
3809 tzinfo);
3810 if (self != NULL && tzinfo != Py_None) {
3811 /* Convert UTC to tzinfo's zone. */
3812 PyObject *temp = self;
3813 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3814 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003815 }
3816 return self;
3817}
3818
Tim Petersa9bc1682003-01-11 03:39:11 +00003819/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3820static PyObject *
3821datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3822{
3823 double timestamp;
3824 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003825
Tim Petersa9bc1682003-01-11 03:39:11 +00003826 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3827 result = datetime_from_timestamp(cls, gmtime, timestamp,
3828 Py_None);
3829 return result;
3830}
3831
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003832/* Return new datetime from time.strptime(). */
3833static PyObject *
3834datetime_strptime(PyObject *cls, PyObject *args)
3835{
3836 PyObject *result = NULL, *obj, *module;
3837 const char *string, *format;
3838
3839 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3840 return NULL;
3841
3842 if ((module = PyImport_ImportModule("time")) == NULL)
3843 return NULL;
3844 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3845 Py_DECREF(module);
3846
3847 if (obj != NULL) {
3848 int i, good_timetuple = 1;
3849 long int ia[6];
3850 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3851 for (i=0; i < 6; i++) {
3852 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters3cfea2d2006-04-14 21:23:42 +00003853 if (p == NULL) {
3854 Py_DECREF(obj);
3855 return NULL;
3856 }
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003857 if (PyInt_Check(p))
3858 ia[i] = PyInt_AsLong(p);
3859 else
3860 good_timetuple = 0;
3861 Py_DECREF(p);
3862 }
3863 else
3864 good_timetuple = 0;
3865 if (good_timetuple)
3866 result = PyObject_CallFunction(cls, "iiiiii",
3867 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3868 else
3869 PyErr_SetString(PyExc_ValueError,
3870 "unexpected value from time.strptime");
3871 Py_DECREF(obj);
3872 }
3873 return result;
3874}
3875
Tim Petersa9bc1682003-01-11 03:39:11 +00003876/* Return new datetime from date/datetime and time arguments. */
3877static PyObject *
3878datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3879{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003880 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003881 PyObject *date;
3882 PyObject *time;
3883 PyObject *result = NULL;
3884
3885 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3886 &PyDateTime_DateType, &date,
3887 &PyDateTime_TimeType, &time)) {
3888 PyObject *tzinfo = Py_None;
3889
3890 if (HASTZINFO(time))
3891 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3892 result = PyObject_CallFunction(cls, "iiiiiiiO",
3893 GET_YEAR(date),
3894 GET_MONTH(date),
3895 GET_DAY(date),
3896 TIME_GET_HOUR(time),
3897 TIME_GET_MINUTE(time),
3898 TIME_GET_SECOND(time),
3899 TIME_GET_MICROSECOND(time),
3900 tzinfo);
3901 }
3902 return result;
3903}
Tim Peters2a799bf2002-12-16 20:18:38 +00003904
3905/*
3906 * Destructor.
3907 */
3908
3909static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003910datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003911{
Tim Petersa9bc1682003-01-11 03:39:11 +00003912 if (HASTZINFO(self)) {
3913 Py_XDECREF(self->tzinfo);
3914 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003915 self->ob_type->tp_free((PyObject *)self);
3916}
3917
3918/*
3919 * Indirect access to tzinfo methods.
3920 */
3921
Tim Peters2a799bf2002-12-16 20:18:38 +00003922/* These are all METH_NOARGS, so don't need to check the arglist. */
3923static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003924datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3925 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3926 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003927}
3928
3929static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003930datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3931 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3932 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003933}
3934
3935static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003936datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3937 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3938 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003939}
3940
3941/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003942 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003943 */
3944
Tim Petersa9bc1682003-01-11 03:39:11 +00003945/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3946 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003947 */
3948static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003949add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3950 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003951{
Tim Petersa9bc1682003-01-11 03:39:11 +00003952 /* Note that the C-level additions can't overflow, because of
3953 * invariant bounds on the member values.
3954 */
3955 int year = GET_YEAR(date);
3956 int month = GET_MONTH(date);
3957 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3958 int hour = DATE_GET_HOUR(date);
3959 int minute = DATE_GET_MINUTE(date);
3960 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3961 int microsecond = DATE_GET_MICROSECOND(date) +
3962 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003963
Tim Petersa9bc1682003-01-11 03:39:11 +00003964 assert(factor == 1 || factor == -1);
3965 if (normalize_datetime(&year, &month, &day,
3966 &hour, &minute, &second, &microsecond) < 0)
3967 return NULL;
3968 else
3969 return new_datetime(year, month, day,
3970 hour, minute, second, microsecond,
3971 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003972}
3973
3974static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003975datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003976{
Tim Petersa9bc1682003-01-11 03:39:11 +00003977 if (PyDateTime_Check(left)) {
3978 /* datetime + ??? */
3979 if (PyDelta_Check(right))
3980 /* datetime + delta */
3981 return add_datetime_timedelta(
3982 (PyDateTime_DateTime *)left,
3983 (PyDateTime_Delta *)right,
3984 1);
3985 }
3986 else if (PyDelta_Check(left)) {
3987 /* delta + datetime */
3988 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3989 (PyDateTime_Delta *) left,
3990 1);
3991 }
3992 Py_INCREF(Py_NotImplemented);
3993 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003994}
3995
3996static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003997datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003998{
3999 PyObject *result = Py_NotImplemented;
4000
4001 if (PyDateTime_Check(left)) {
4002 /* datetime - ??? */
4003 if (PyDateTime_Check(right)) {
4004 /* datetime - datetime */
4005 naivety n1, n2;
4006 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00004007 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00004008
Tim Peterse39a80c2002-12-30 21:28:52 +00004009 if (classify_two_utcoffsets(left, &offset1, &n1, left,
4010 right, &offset2, &n2,
4011 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00004012 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00004013 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00004014 if (n1 != n2) {
4015 PyErr_SetString(PyExc_TypeError,
4016 "can't subtract offset-naive and "
4017 "offset-aware datetimes");
4018 return NULL;
4019 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004020 delta_d = ymd_to_ord(GET_YEAR(left),
4021 GET_MONTH(left),
4022 GET_DAY(left)) -
4023 ymd_to_ord(GET_YEAR(right),
4024 GET_MONTH(right),
4025 GET_DAY(right));
4026 /* These can't overflow, since the values are
4027 * normalized. At most this gives the number of
4028 * seconds in one day.
4029 */
4030 delta_s = (DATE_GET_HOUR(left) -
4031 DATE_GET_HOUR(right)) * 3600 +
4032 (DATE_GET_MINUTE(left) -
4033 DATE_GET_MINUTE(right)) * 60 +
4034 (DATE_GET_SECOND(left) -
4035 DATE_GET_SECOND(right));
4036 delta_us = DATE_GET_MICROSECOND(left) -
4037 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00004038 /* (left - offset1) - (right - offset2) =
4039 * (left - right) + (offset2 - offset1)
4040 */
Tim Petersa9bc1682003-01-11 03:39:11 +00004041 delta_s += (offset2 - offset1) * 60;
4042 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004043 }
4044 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004045 /* datetime - delta */
4046 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00004047 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00004048 (PyDateTime_Delta *)right,
4049 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004050 }
4051 }
4052
4053 if (result == Py_NotImplemented)
4054 Py_INCREF(result);
4055 return result;
4056}
4057
4058/* Various ways to turn a datetime into a string. */
4059
4060static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004061datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004062{
Tim Petersa9bc1682003-01-11 03:39:11 +00004063 char buffer[1000];
Skip Montanaro14f88992006-04-18 19:35:04 +00004064 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004065 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004066
Tim Petersa9bc1682003-01-11 03:39:11 +00004067 if (DATE_GET_MICROSECOND(self)) {
4068 PyOS_snprintf(buffer, sizeof(buffer),
4069 "%s(%d, %d, %d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004070 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004071 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4072 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4073 DATE_GET_SECOND(self),
4074 DATE_GET_MICROSECOND(self));
4075 }
4076 else if (DATE_GET_SECOND(self)) {
4077 PyOS_snprintf(buffer, sizeof(buffer),
4078 "%s(%d, %d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004079 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004080 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4081 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4082 DATE_GET_SECOND(self));
4083 }
4084 else {
4085 PyOS_snprintf(buffer, sizeof(buffer),
4086 "%s(%d, %d, %d, %d, %d)",
Skip Montanaro14f88992006-04-18 19:35:04 +00004087 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004088 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4089 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4090 }
4091 baserepr = PyString_FromString(buffer);
4092 if (baserepr == NULL || ! HASTZINFO(self))
4093 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004094 return append_keyword_tzinfo(baserepr, self->tzinfo);
4095}
4096
Tim Petersa9bc1682003-01-11 03:39:11 +00004097static PyObject *
4098datetime_str(PyDateTime_DateTime *self)
4099{
4100 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4101}
Tim Peters2a799bf2002-12-16 20:18:38 +00004102
4103static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004104datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004105{
Tim Petersa9bc1682003-01-11 03:39:11 +00004106 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004107 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004108 char buffer[100];
4109 char *cp;
4110 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004111
Tim Petersa9bc1682003-01-11 03:39:11 +00004112 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4113 &sep))
4114 return NULL;
4115 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4116 assert(cp != NULL);
4117 *cp++ = sep;
4118 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4119 result = PyString_FromString(buffer);
4120 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004121 return result;
4122
4123 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004124 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004125 (PyObject *)self) < 0) {
4126 Py_DECREF(result);
4127 return NULL;
4128 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004129 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004130 return result;
4131}
4132
Tim Petersa9bc1682003-01-11 03:39:11 +00004133static PyObject *
4134datetime_ctime(PyDateTime_DateTime *self)
4135{
4136 return format_ctime((PyDateTime_Date *)self,
4137 DATE_GET_HOUR(self),
4138 DATE_GET_MINUTE(self),
4139 DATE_GET_SECOND(self));
4140}
4141
Tim Peters2a799bf2002-12-16 20:18:38 +00004142/* Miscellaneous methods. */
4143
Tim Petersa9bc1682003-01-11 03:39:11 +00004144/* This is more natural as a tp_compare, but doesn't work then: for whatever
4145 * reason, Python's try_3way_compare ignores tp_compare unless
4146 * PyInstance_Check returns true, but these aren't old-style classes.
4147 */
4148static PyObject *
4149datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
4150{
4151 int diff;
4152 naivety n1, n2;
4153 int offset1, offset2;
4154
4155 if (! PyDateTime_Check(other)) {
Tim Peters528ca532004-09-16 01:30:50 +00004156 /* If other has a "timetuple" attr, that's an advertised
4157 * hook for other classes to ask to get comparison control.
4158 * However, date instances have a timetuple attr, and we
4159 * don't want to allow that comparison. Because datetime
4160 * is a subclass of date, when mixing date and datetime
4161 * in a comparison, Python gives datetime the first shot
4162 * (it's the more specific subtype). So we can stop that
4163 * combination here reliably.
4164 */
4165 if (PyObject_HasAttrString(other, "timetuple") &&
4166 ! PyDate_Check(other)) {
Tim Peters8d81a012003-01-24 22:36:34 +00004167 /* A hook for other kinds of datetime objects. */
4168 Py_INCREF(Py_NotImplemented);
4169 return Py_NotImplemented;
4170 }
Tim Peters07534a62003-02-07 22:50:28 +00004171 if (op == Py_EQ || op == Py_NE) {
4172 PyObject *result = op == Py_EQ ? Py_False : Py_True;
4173 Py_INCREF(result);
4174 return result;
4175 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004176 /* Stop this from falling back to address comparison. */
Tim Peters07534a62003-02-07 22:50:28 +00004177 return cmperror((PyObject *)self, other);
Tim Petersa9bc1682003-01-11 03:39:11 +00004178 }
4179
4180 if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
4181 (PyObject *)self,
4182 other, &offset2, &n2,
4183 other) < 0)
4184 return NULL;
4185 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4186 /* If they're both naive, or both aware and have the same offsets,
4187 * we get off cheap. Note that if they're both naive, offset1 ==
4188 * offset2 == 0 at this point.
4189 */
4190 if (n1 == n2 && offset1 == offset2) {
4191 diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
4192 _PyDateTime_DATETIME_DATASIZE);
4193 return diff_to_bool(diff, op);
4194 }
4195
4196 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4197 PyDateTime_Delta *delta;
4198
4199 assert(offset1 != offset2); /* else last "if" handled it */
4200 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4201 other);
4202 if (delta == NULL)
4203 return NULL;
4204 diff = GET_TD_DAYS(delta);
4205 if (diff == 0)
4206 diff = GET_TD_SECONDS(delta) |
4207 GET_TD_MICROSECONDS(delta);
4208 Py_DECREF(delta);
4209 return diff_to_bool(diff, op);
4210 }
4211
4212 assert(n1 != n2);
4213 PyErr_SetString(PyExc_TypeError,
4214 "can't compare offset-naive and "
4215 "offset-aware datetimes");
4216 return NULL;
4217}
4218
4219static long
4220datetime_hash(PyDateTime_DateTime *self)
4221{
4222 if (self->hashcode == -1) {
4223 naivety n;
4224 int offset;
4225 PyObject *temp;
4226
4227 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4228 &offset);
4229 assert(n != OFFSET_UNKNOWN);
4230 if (n == OFFSET_ERROR)
4231 return -1;
4232
4233 /* Reduce this to a hash of another object. */
4234 if (n == OFFSET_NAIVE)
4235 temp = PyString_FromStringAndSize(
4236 (char *)self->data,
4237 _PyDateTime_DATETIME_DATASIZE);
4238 else {
4239 int days;
4240 int seconds;
4241
4242 assert(n == OFFSET_AWARE);
4243 assert(HASTZINFO(self));
4244 days = ymd_to_ord(GET_YEAR(self),
4245 GET_MONTH(self),
4246 GET_DAY(self));
4247 seconds = DATE_GET_HOUR(self) * 3600 +
4248 (DATE_GET_MINUTE(self) - offset) * 60 +
4249 DATE_GET_SECOND(self);
4250 temp = new_delta(days,
4251 seconds,
4252 DATE_GET_MICROSECOND(self),
4253 1);
4254 }
4255 if (temp != NULL) {
4256 self->hashcode = PyObject_Hash(temp);
4257 Py_DECREF(temp);
4258 }
4259 }
4260 return self->hashcode;
4261}
Tim Peters2a799bf2002-12-16 20:18:38 +00004262
4263static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004264datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004265{
4266 PyObject *clone;
4267 PyObject *tuple;
4268 int y = GET_YEAR(self);
4269 int m = GET_MONTH(self);
4270 int d = GET_DAY(self);
4271 int hh = DATE_GET_HOUR(self);
4272 int mm = DATE_GET_MINUTE(self);
4273 int ss = DATE_GET_SECOND(self);
4274 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004275 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004276
4277 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004278 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004279 &y, &m, &d, &hh, &mm, &ss, &us,
4280 &tzinfo))
4281 return NULL;
4282 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4283 if (tuple == NULL)
4284 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004285 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004286 Py_DECREF(tuple);
4287 return clone;
4288}
4289
4290static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004291datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004292{
Tim Peters52dcce22003-01-23 16:36:11 +00004293 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004294 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004295 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004296
Tim Peters80475bb2002-12-25 07:40:55 +00004297 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004298 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004299
Tim Peters52dcce22003-01-23 16:36:11 +00004300 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4301 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004302 return NULL;
4303
Tim Peters52dcce22003-01-23 16:36:11 +00004304 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4305 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004306
Tim Peters52dcce22003-01-23 16:36:11 +00004307 /* Conversion to self's own time zone is a NOP. */
4308 if (self->tzinfo == tzinfo) {
4309 Py_INCREF(self);
4310 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004311 }
Tim Peters521fc152002-12-31 17:36:56 +00004312
Tim Peters52dcce22003-01-23 16:36:11 +00004313 /* Convert self to UTC. */
4314 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4315 if (offset == -1 && PyErr_Occurred())
4316 return NULL;
4317 if (none)
4318 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004319
Tim Peters52dcce22003-01-23 16:36:11 +00004320 y = GET_YEAR(self);
4321 m = GET_MONTH(self);
4322 d = GET_DAY(self);
4323 hh = DATE_GET_HOUR(self);
4324 mm = DATE_GET_MINUTE(self);
4325 ss = DATE_GET_SECOND(self);
4326 us = DATE_GET_MICROSECOND(self);
4327
4328 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004329 if ((mm < 0 || mm >= 60) &&
4330 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004331 return NULL;
4332
4333 /* Attach new tzinfo and let fromutc() do the rest. */
4334 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4335 if (result != NULL) {
4336 PyObject *temp = result;
4337
4338 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4339 Py_DECREF(temp);
4340 }
Tim Petersadf64202003-01-04 06:03:15 +00004341 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004342
Tim Peters52dcce22003-01-23 16:36:11 +00004343NeedAware:
4344 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4345 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004346 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004347}
4348
4349static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004350datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004351{
4352 int dstflag = -1;
4353
Tim Petersa9bc1682003-01-11 03:39:11 +00004354 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004355 int none;
4356
4357 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4358 if (dstflag == -1 && PyErr_Occurred())
4359 return NULL;
4360
4361 if (none)
4362 dstflag = -1;
4363 else if (dstflag != 0)
4364 dstflag = 1;
4365
4366 }
4367 return build_struct_time(GET_YEAR(self),
4368 GET_MONTH(self),
4369 GET_DAY(self),
4370 DATE_GET_HOUR(self),
4371 DATE_GET_MINUTE(self),
4372 DATE_GET_SECOND(self),
4373 dstflag);
4374}
4375
4376static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004377datetime_getdate(PyDateTime_DateTime *self)
4378{
4379 return new_date(GET_YEAR(self),
4380 GET_MONTH(self),
4381 GET_DAY(self));
4382}
4383
4384static PyObject *
4385datetime_gettime(PyDateTime_DateTime *self)
4386{
4387 return new_time(DATE_GET_HOUR(self),
4388 DATE_GET_MINUTE(self),
4389 DATE_GET_SECOND(self),
4390 DATE_GET_MICROSECOND(self),
4391 Py_None);
4392}
4393
4394static PyObject *
4395datetime_gettimetz(PyDateTime_DateTime *self)
4396{
4397 return new_time(DATE_GET_HOUR(self),
4398 DATE_GET_MINUTE(self),
4399 DATE_GET_SECOND(self),
4400 DATE_GET_MICROSECOND(self),
4401 HASTZINFO(self) ? self->tzinfo : Py_None);
4402}
4403
4404static PyObject *
4405datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004406{
4407 int y = GET_YEAR(self);
4408 int m = GET_MONTH(self);
4409 int d = GET_DAY(self);
4410 int hh = DATE_GET_HOUR(self);
4411 int mm = DATE_GET_MINUTE(self);
4412 int ss = DATE_GET_SECOND(self);
4413 int us = 0; /* microseconds are ignored in a timetuple */
4414 int offset = 0;
4415
Tim Petersa9bc1682003-01-11 03:39:11 +00004416 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004417 int none;
4418
4419 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4420 if (offset == -1 && PyErr_Occurred())
4421 return NULL;
4422 }
4423 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4424 * 0 in a UTC timetuple regardless of what dst() says.
4425 */
4426 if (offset) {
4427 /* Subtract offset minutes & normalize. */
4428 int stat;
4429
4430 mm -= offset;
4431 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4432 if (stat < 0) {
4433 /* At the edges, it's possible we overflowed
4434 * beyond MINYEAR or MAXYEAR.
4435 */
4436 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4437 PyErr_Clear();
4438 else
4439 return NULL;
4440 }
4441 }
4442 return build_struct_time(y, m, d, hh, mm, ss, 0);
4443}
4444
Tim Peters371935f2003-02-01 01:52:50 +00004445/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004446
Tim Petersa9bc1682003-01-11 03:39:11 +00004447/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004448 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4449 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004450 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004451 */
4452static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004453datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004454{
4455 PyObject *basestate;
4456 PyObject *result = NULL;
4457
Tim Peters33e0f382003-01-10 02:05:14 +00004458 basestate = PyString_FromStringAndSize((char *)self->data,
4459 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004460 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004461 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004462 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004463 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004464 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004465 Py_DECREF(basestate);
4466 }
4467 return result;
4468}
4469
4470static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004471datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004472{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004473 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004474}
4475
Tim Petersa9bc1682003-01-11 03:39:11 +00004476static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004477
Tim Peters2a799bf2002-12-16 20:18:38 +00004478 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004479
Tim Petersa9bc1682003-01-11 03:39:11 +00004480 {"now", (PyCFunction)datetime_now,
Tim Peters2a799bf2002-12-16 20:18:38 +00004481 METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004482 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004483
Tim Petersa9bc1682003-01-11 03:39:11 +00004484 {"utcnow", (PyCFunction)datetime_utcnow,
4485 METH_NOARGS | METH_CLASS,
4486 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4487
4488 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Tim Peters2a799bf2002-12-16 20:18:38 +00004489 METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004490 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004491
Tim Petersa9bc1682003-01-11 03:39:11 +00004492 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4493 METH_VARARGS | METH_CLASS,
4494 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4495 "(like time.time()).")},
4496
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004497 {"strptime", (PyCFunction)datetime_strptime,
4498 METH_VARARGS | METH_CLASS,
4499 PyDoc_STR("string, format -> new datetime parsed from a string "
4500 "(like time.strptime()).")},
4501
Tim Petersa9bc1682003-01-11 03:39:11 +00004502 {"combine", (PyCFunction)datetime_combine,
4503 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4504 PyDoc_STR("date, time -> datetime with same date and time fields")},
4505
Tim Peters2a799bf2002-12-16 20:18:38 +00004506 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004507
Tim Petersa9bc1682003-01-11 03:39:11 +00004508 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4509 PyDoc_STR("Return date object with same year, month and day.")},
4510
4511 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4512 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4513
4514 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4515 PyDoc_STR("Return time object with same time and tzinfo.")},
4516
4517 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4518 PyDoc_STR("Return ctime() style string.")},
4519
4520 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004521 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4522
Tim Petersa9bc1682003-01-11 03:39:11 +00004523 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004524 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4525
Tim Petersa9bc1682003-01-11 03:39:11 +00004526 {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4528 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4529 "sep is used to separate the year from the time, and "
4530 "defaults to 'T'.")},
4531
Tim Petersa9bc1682003-01-11 03:39:11 +00004532 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004533 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4534
Tim Petersa9bc1682003-01-11 03:39:11 +00004535 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004536 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4537
Tim Petersa9bc1682003-01-11 03:39:11 +00004538 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004539 PyDoc_STR("Return self.tzinfo.dst(self).")},
4540
Tim Petersa9bc1682003-01-11 03:39:11 +00004541 {"replace", (PyCFunction)datetime_replace, METH_KEYWORDS,
4542 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004543
Tim Petersa9bc1682003-01-11 03:39:11 +00004544 {"astimezone", (PyCFunction)datetime_astimezone, METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004545 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4546
Guido van Rossum177e41a2003-01-30 22:06:23 +00004547 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4548 PyDoc_STR("__reduce__() -> (cls, state)")},
4549
Tim Peters2a799bf2002-12-16 20:18:38 +00004550 {NULL, NULL}
4551};
4552
Tim Petersa9bc1682003-01-11 03:39:11 +00004553static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004554PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4555\n\
4556The year, month and day arguments are required. tzinfo may be None, or an\n\
4557instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004558
Tim Petersa9bc1682003-01-11 03:39:11 +00004559static PyNumberMethods datetime_as_number = {
4560 datetime_add, /* nb_add */
4561 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004562 0, /* nb_multiply */
4563 0, /* nb_divide */
4564 0, /* nb_remainder */
4565 0, /* nb_divmod */
4566 0, /* nb_power */
4567 0, /* nb_negative */
4568 0, /* nb_positive */
4569 0, /* nb_absolute */
4570 0, /* nb_nonzero */
4571};
4572
Tim Petersa9bc1682003-01-11 03:39:11 +00004573statichere PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004574 PyObject_HEAD_INIT(NULL)
4575 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004576 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004577 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004578 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004579 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004580 0, /* tp_print */
4581 0, /* tp_getattr */
4582 0, /* tp_setattr */
4583 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004584 (reprfunc)datetime_repr, /* tp_repr */
4585 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004586 0, /* tp_as_sequence */
4587 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004588 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004589 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004590 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004591 PyObject_GenericGetAttr, /* tp_getattro */
4592 0, /* tp_setattro */
4593 0, /* tp_as_buffer */
4594 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4595 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004596 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004597 0, /* tp_traverse */
4598 0, /* tp_clear */
Tim Petersa9bc1682003-01-11 03:39:11 +00004599 (richcmpfunc)datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004600 0, /* tp_weaklistoffset */
4601 0, /* tp_iter */
4602 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004603 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004604 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004605 datetime_getset, /* tp_getset */
4606 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004607 0, /* tp_dict */
4608 0, /* tp_descr_get */
4609 0, /* tp_descr_set */
4610 0, /* tp_dictoffset */
4611 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004612 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004613 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004614 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004615};
4616
4617/* ---------------------------------------------------------------------------
4618 * Module methods and initialization.
4619 */
4620
4621static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004622 {NULL, NULL}
4623};
4624
Tim Peters9ddf40b2004-06-20 22:41:32 +00004625/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4626 * datetime.h.
4627 */
4628static PyDateTime_CAPI CAPI = {
4629 &PyDateTime_DateType,
4630 &PyDateTime_DateTimeType,
4631 &PyDateTime_TimeType,
4632 &PyDateTime_DeltaType,
4633 &PyDateTime_TZInfoType,
4634 new_date_ex,
4635 new_datetime_ex,
4636 new_time_ex,
4637 new_delta_ex,
4638 datetime_fromtimestamp,
4639 date_fromtimestamp
4640};
4641
4642
Tim Peters2a799bf2002-12-16 20:18:38 +00004643PyMODINIT_FUNC
4644initdatetime(void)
4645{
4646 PyObject *m; /* a module object */
4647 PyObject *d; /* its dict */
4648 PyObject *x;
4649
Tim Peters2a799bf2002-12-16 20:18:38 +00004650 m = Py_InitModule3("datetime", module_methods,
4651 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004652 if (m == NULL)
4653 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004654
4655 if (PyType_Ready(&PyDateTime_DateType) < 0)
4656 return;
4657 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4658 return;
4659 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4660 return;
4661 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4662 return;
4663 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4664 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004665
Tim Peters2a799bf2002-12-16 20:18:38 +00004666 /* timedelta values */
4667 d = PyDateTime_DeltaType.tp_dict;
4668
Tim Peters2a799bf2002-12-16 20:18:38 +00004669 x = new_delta(0, 0, 1, 0);
4670 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4671 return;
4672 Py_DECREF(x);
4673
4674 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4675 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4676 return;
4677 Py_DECREF(x);
4678
4679 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4680 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4681 return;
4682 Py_DECREF(x);
4683
4684 /* date values */
4685 d = PyDateTime_DateType.tp_dict;
4686
4687 x = new_date(1, 1, 1);
4688 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4689 return;
4690 Py_DECREF(x);
4691
4692 x = new_date(MAXYEAR, 12, 31);
4693 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4694 return;
4695 Py_DECREF(x);
4696
4697 x = new_delta(1, 0, 0, 0);
4698 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4699 return;
4700 Py_DECREF(x);
4701
Tim Peters37f39822003-01-10 03:49:02 +00004702 /* time values */
4703 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004704
Tim Peters37f39822003-01-10 03:49:02 +00004705 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004706 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4707 return;
4708 Py_DECREF(x);
4709
Tim Peters37f39822003-01-10 03:49:02 +00004710 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004711 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4712 return;
4713 Py_DECREF(x);
4714
4715 x = new_delta(0, 0, 1, 0);
4716 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4717 return;
4718 Py_DECREF(x);
4719
Tim Petersa9bc1682003-01-11 03:39:11 +00004720 /* datetime values */
4721 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004722
Tim Petersa9bc1682003-01-11 03:39:11 +00004723 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004724 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4725 return;
4726 Py_DECREF(x);
4727
Tim Petersa9bc1682003-01-11 03:39:11 +00004728 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004729 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4730 return;
4731 Py_DECREF(x);
4732
4733 x = new_delta(0, 0, 1, 0);
4734 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4735 return;
4736 Py_DECREF(x);
4737
Tim Peters2a799bf2002-12-16 20:18:38 +00004738 /* module initialization */
4739 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4740 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4741
4742 Py_INCREF(&PyDateTime_DateType);
4743 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4744
Tim Petersa9bc1682003-01-11 03:39:11 +00004745 Py_INCREF(&PyDateTime_DateTimeType);
4746 PyModule_AddObject(m, "datetime",
4747 (PyObject *)&PyDateTime_DateTimeType);
4748
4749 Py_INCREF(&PyDateTime_TimeType);
4750 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4751
Tim Peters2a799bf2002-12-16 20:18:38 +00004752 Py_INCREF(&PyDateTime_DeltaType);
4753 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4754
Tim Peters2a799bf2002-12-16 20:18:38 +00004755 Py_INCREF(&PyDateTime_TZInfoType);
4756 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4757
Tim Peters9ddf40b2004-06-20 22:41:32 +00004758 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4759 NULL);
4760 if (x == NULL)
4761 return;
4762 PyModule_AddObject(m, "datetime_CAPI", x);
4763
Tim Peters2a799bf2002-12-16 20:18:38 +00004764 /* A 4-year cycle has an extra leap day over what we'd get from
4765 * pasting together 4 single years.
4766 */
4767 assert(DI4Y == 4 * 365 + 1);
4768 assert(DI4Y == days_before_year(4+1));
4769
4770 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4771 * get from pasting together 4 100-year cycles.
4772 */
4773 assert(DI400Y == 4 * DI100Y + 1);
4774 assert(DI400Y == days_before_year(400+1));
4775
4776 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4777 * pasting together 25 4-year cycles.
4778 */
4779 assert(DI100Y == 25 * DI4Y - 1);
4780 assert(DI100Y == days_before_year(100+1));
4781
4782 us_per_us = PyInt_FromLong(1);
4783 us_per_ms = PyInt_FromLong(1000);
4784 us_per_second = PyInt_FromLong(1000000);
4785 us_per_minute = PyInt_FromLong(60000000);
4786 seconds_per_day = PyInt_FromLong(24 * 3600);
4787 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4788 us_per_minute == NULL || seconds_per_day == NULL)
4789 return;
4790
4791 /* The rest are too big for 32-bit ints, but even
4792 * us_per_week fits in 40 bits, so doubles should be exact.
4793 */
4794 us_per_hour = PyLong_FromDouble(3600000000.0);
4795 us_per_day = PyLong_FromDouble(86400000000.0);
4796 us_per_week = PyLong_FromDouble(604800000000.0);
4797 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4798 return;
4799}
Tim Petersf3615152003-01-01 21:51:37 +00004800
4801/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004802Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004803 x.n = x stripped of its timezone -- its naive time.
4804 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4805 return None
4806 x.d = x.dst(), and assuming that doesn't raise an exception or
4807 return None
4808 x.s = x's standard offset, x.o - x.d
4809
4810Now some derived rules, where k is a duration (timedelta).
4811
48121. x.o = x.s + x.d
4813 This follows from the definition of x.s.
4814
Tim Petersc5dc4da2003-01-02 17:55:03 +000048152. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004816 This is actually a requirement, an assumption we need to make about
4817 sane tzinfo classes.
4818
48193. The naive UTC time corresponding to x is x.n - x.o.
4820 This is again a requirement for a sane tzinfo class.
4821
48224. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004823 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004824
Tim Petersc5dc4da2003-01-02 17:55:03 +000048255. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004826 Again follows from how arithmetic is defined.
4827
Tim Peters8bb5ad22003-01-24 02:44:45 +00004828Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004829(meaning that the various tzinfo methods exist, and don't blow up or return
4830None when called).
4831
Tim Petersa9bc1682003-01-11 03:39:11 +00004832The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004833x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004834
4835By #3, we want
4836
Tim Peters8bb5ad22003-01-24 02:44:45 +00004837 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004838
4839The algorithm starts by attaching tz to x.n, and calling that y. So
4840x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4841becomes true; in effect, we want to solve [2] for k:
4842
Tim Peters8bb5ad22003-01-24 02:44:45 +00004843 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004844
4845By #1, this is the same as
4846
Tim Peters8bb5ad22003-01-24 02:44:45 +00004847 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004848
4849By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4850Substituting that into [3],
4851
Tim Peters8bb5ad22003-01-24 02:44:45 +00004852 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4853 k - (y+k).s - (y+k).d = 0; rearranging,
4854 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4855 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004856
Tim Peters8bb5ad22003-01-24 02:44:45 +00004857On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4858approximate k by ignoring the (y+k).d term at first. Note that k can't be
4859very large, since all offset-returning methods return a duration of magnitude
4860less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4861be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004862
4863In any case, the new value is
4864
Tim Peters8bb5ad22003-01-24 02:44:45 +00004865 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004866
Tim Peters8bb5ad22003-01-24 02:44:45 +00004867It's helpful to step back at look at [4] from a higher level: it's simply
4868mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004869
4870At this point, if
4871
Tim Peters8bb5ad22003-01-24 02:44:45 +00004872 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004873
4874we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004875at the start of daylight time. Picture US Eastern for concreteness. The wall
4876time 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 +00004877sense then. The docs ask that an Eastern tzinfo class consider such a time to
4878be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4879on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004880the only spelling that makes sense on the local wall clock.
4881
Tim Petersc5dc4da2003-01-02 17:55:03 +00004882In fact, if [5] holds at this point, we do have the standard-time spelling,
4883but that takes a bit of proof. We first prove a stronger result. What's the
4884difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004885
Tim Peters8bb5ad22003-01-24 02:44:45 +00004886 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004887
Tim Petersc5dc4da2003-01-02 17:55:03 +00004888Now
4889 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004890 (y + y.s).n = by #5
4891 y.n + y.s = since y.n = x.n
4892 x.n + y.s = since z and y are have the same tzinfo member,
4893 y.s = z.s by #2
4894 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004895
Tim Petersc5dc4da2003-01-02 17:55:03 +00004896Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004897
Tim Petersc5dc4da2003-01-02 17:55:03 +00004898 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004899 x.n - ((x.n + z.s) - z.o) = expanding
4900 x.n - x.n - z.s + z.o = cancelling
4901 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004902 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004903
Tim Petersc5dc4da2003-01-02 17:55:03 +00004904So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004905
Tim Petersc5dc4da2003-01-02 17:55:03 +00004906If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004907spelling we wanted in the endcase described above. We're done. Contrarily,
4908if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004909
Tim Petersc5dc4da2003-01-02 17:55:03 +00004910If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4911add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004912local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004913
Tim Petersc5dc4da2003-01-02 17:55:03 +00004914Let
Tim Petersf3615152003-01-01 21:51:37 +00004915
Tim Peters4fede1a2003-01-04 00:26:59 +00004916 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004917
Tim Peters4fede1a2003-01-04 00:26:59 +00004918and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004919
Tim Peters8bb5ad22003-01-24 02:44:45 +00004920 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004921
Tim Peters8bb5ad22003-01-24 02:44:45 +00004922If so, we're done. If not, the tzinfo class is insane, according to the
4923assumptions we've made. This also requires a bit of proof. As before, let's
4924compute the difference between the LHS and RHS of [8] (and skipping some of
4925the justifications for the kinds of substitutions we've done several times
4926already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004927
Tim Peters8bb5ad22003-01-24 02:44:45 +00004928 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4929 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4930 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4931 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4932 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004933 - z.o + z'.o = #1 twice
4934 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4935 z'.d - z.d
4936
4937So 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 +00004938we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4939return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004940
Tim Peters8bb5ad22003-01-24 02:44:45 +00004941How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4942a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4943would have to change the result dst() returns: we start in DST, and moving
4944a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004945
Tim Peters8bb5ad22003-01-24 02:44:45 +00004946There isn't a sane case where this can happen. The closest it gets is at
4947the end of DST, where there's an hour in UTC with no spelling in a hybrid
4948tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4949that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4950UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4951time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4952clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4953standard time. Since that's what the local clock *does*, we want to map both
4954UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004955in local time, but so it goes -- it's the way the local clock works.
4956
Tim Peters8bb5ad22003-01-24 02:44:45 +00004957When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4958so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4959z' = 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 +00004960(correctly) concludes that z' is not UTC-equivalent to x.
4961
4962Because we know z.d said z was in daylight time (else [5] would have held and
4963we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004964and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004965return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4966but the reasoning doesn't depend on the example -- it depends on there being
4967two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004968z' must be in standard time, and is the spelling we want in this case.
4969
4970Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4971concerned (because it takes z' as being in standard time rather than the
4972daylight time we intend here), but returning it gives the real-life "local
4973clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4974tz.
4975
4976When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4977the 1:MM standard time spelling we want.
4978
4979So how can this break? One of the assumptions must be violated. Two
4980possibilities:
4981
49821) [2] effectively says that y.s is invariant across all y belong to a given
4983 time zone. This isn't true if, for political reasons or continental drift,
4984 a region decides to change its base offset from UTC.
4985
49862) There may be versions of "double daylight" time where the tail end of
4987 the analysis gives up a step too early. I haven't thought about that
4988 enough to say.
4989
4990In any case, it's clear that the default fromutc() is strong enough to handle
4991"almost all" time zones: so long as the standard offset is invariant, it
4992doesn't matter if daylight time transition points change from year to year, or
4993if daylight time is skipped in some years; it doesn't matter how large or
4994small dst() may get within its bounds; and it doesn't even matter if some
4995perverse time zone returns a negative dst()). So a breaking case must be
4996pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004997--------------------------------------------------------------------------- */