blob: 5190175dfbfd16eb37d9db553e22c98c1b003a76 [file] [log] [blame]
Tim Peters2a799bf2002-12-16 20:18:38 +00001/* C implementation for the date/time type documented at
2 * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3 */
4
5#include "Python.h"
6#include "modsupport.h"
7#include "structmember.h"
8
9#include <time.h>
10
Tim Peters1b6f7a92004-06-20 02:50:16 +000011#include "timefuncs.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000012
13/* Differentiate between building the core module and building extension
14 * modules.
15 */
Guido van Rossum360e4b82007-05-14 22:51:27 +000016#ifndef Py_BUILD_CORE
Tim Peters9ddf40b2004-06-20 22:41:32 +000017#define Py_BUILD_CORE
Guido van Rossum360e4b82007-05-14 22:51:27 +000018#endif
Tim Peters2a799bf2002-12-16 20:18:38 +000019#include "datetime.h"
Tim Peters9ddf40b2004-06-20 22:41:32 +000020#undef Py_BUILD_CORE
Tim Peters2a799bf2002-12-16 20:18:38 +000021
22/* We require that C int be at least 32 bits, and use int virtually
23 * everywhere. In just a few cases we use a temp long, where a Python
24 * API returns a C long. In such cases, we have to ensure that the
25 * final result fits in a C int (this can be an issue on 64-bit boxes).
26 */
27#if SIZEOF_INT < 4
28# error "datetime.c requires that C int have at least 32 bits"
29#endif
30
31#define MINYEAR 1
32#define MAXYEAR 9999
33
34/* Nine decimal digits is easy to communicate, and leaves enough room
35 * so that two delta days can be added w/o fear of overflowing a signed
36 * 32-bit int, and with plenty of room left over to absorb any possible
37 * carries from adding seconds.
38 */
39#define MAX_DELTA_DAYS 999999999
40
41/* Rename the long macros in datetime.h to more reasonable short names. */
42#define GET_YEAR PyDateTime_GET_YEAR
43#define GET_MONTH PyDateTime_GET_MONTH
44#define GET_DAY PyDateTime_GET_DAY
45#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
46#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
47#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
48#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
49
50/* Date accessors for date and datetime. */
51#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
52 ((o)->data[1] = ((v) & 0x00ff)))
53#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
54#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
55
56/* Date/Time accessors for datetime. */
57#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
58#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
59#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
60#define DATE_SET_MICROSECOND(o, v) \
61 (((o)->data[7] = ((v) & 0xff0000) >> 16), \
62 ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
63 ((o)->data[9] = ((v) & 0x0000ff)))
64
65/* Time accessors for time. */
66#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
67#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
68#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
69#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
70#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
71#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
72#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
73#define TIME_SET_MICROSECOND(o, v) \
74 (((o)->data[3] = ((v) & 0xff0000) >> 16), \
75 ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
76 ((o)->data[5] = ((v) & 0x0000ff)))
77
78/* Delta accessors for timedelta. */
79#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
80#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
81#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
82
83#define SET_TD_DAYS(o, v) ((o)->days = (v))
84#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
85#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
86
Tim Petersa032d2e2003-01-11 00:15:54 +000087/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
88 * p->hastzinfo.
89 */
90#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
91
Tim Peters3f606292004-03-21 23:38:41 +000092/* M is a char or int claiming to be a valid month. The macro is equivalent
93 * to the two-sided Python test
94 * 1 <= M <= 12
95 */
96#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
97
Tim Peters2a799bf2002-12-16 20:18:38 +000098/* Forward declarations. */
99static PyTypeObject PyDateTime_DateType;
100static PyTypeObject PyDateTime_DateTimeType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000101static PyTypeObject PyDateTime_DeltaType;
102static PyTypeObject PyDateTime_TimeType;
103static PyTypeObject PyDateTime_TZInfoType;
Tim Peters2a799bf2002-12-16 20:18:38 +0000104
105/* ---------------------------------------------------------------------------
106 * Math utilities.
107 */
108
109/* k = i+j overflows iff k differs in sign from both inputs,
110 * iff k^i has sign bit set and k^j has sign bit set,
111 * iff (k^i)&(k^j) has sign bit set.
112 */
113#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
114 ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
115
116/* Compute Python divmod(x, y), returning the quotient and storing the
117 * remainder into *r. The quotient is the floor of x/y, and that's
118 * the real point of this. C will probably truncate instead (C99
119 * requires truncation; C89 left it implementation-defined).
120 * Simplification: we *require* that y > 0 here. That's appropriate
121 * for all the uses made of it. This simplifies the code and makes
122 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
123 * overflow case).
124 */
125static int
126divmod(int x, int y, int *r)
127{
128 int quo;
129
130 assert(y > 0);
131 quo = x / y;
132 *r = x - quo * y;
133 if (*r < 0) {
134 --quo;
135 *r += y;
136 }
137 assert(0 <= *r && *r < y);
138 return quo;
139}
140
Tim Peters5d644dd2003-01-02 16:32:54 +0000141/* Round a double to the nearest long. |x| must be small enough to fit
142 * in a C long; this is not checked.
143 */
144static long
145round_to_long(double x)
146{
147 if (x >= 0.0)
148 x = floor(x + 0.5);
149 else
150 x = ceil(x - 0.5);
151 return (long)x;
152}
153
Tim Peters2a799bf2002-12-16 20:18:38 +0000154/* ---------------------------------------------------------------------------
155 * General calendrical helper functions
156 */
157
158/* For each month ordinal in 1..12, the number of days in that month,
159 * and the number of days before that month in the same year. These
160 * are correct for non-leap years only.
161 */
162static int _days_in_month[] = {
163 0, /* unused; this vector uses 1-based indexing */
164 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
165};
166
167static int _days_before_month[] = {
168 0, /* unused; this vector uses 1-based indexing */
169 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
170};
171
172/* year -> 1 if leap year, else 0. */
173static int
174is_leap(int year)
175{
176 /* Cast year to unsigned. The result is the same either way, but
177 * C can generate faster code for unsigned mod than for signed
178 * mod (especially for % 4 -- a good compiler should just grab
179 * the last 2 bits when the LHS is unsigned).
180 */
181 const unsigned int ayear = (unsigned int)year;
182 return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
183}
184
185/* year, month -> number of days in that month in that year */
186static int
187days_in_month(int year, int month)
188{
189 assert(month >= 1);
190 assert(month <= 12);
191 if (month == 2 && is_leap(year))
192 return 29;
193 else
194 return _days_in_month[month];
195}
196
197/* year, month -> number of days in year preceeding first day of month */
198static int
199days_before_month(int year, int month)
200{
201 int days;
202
203 assert(month >= 1);
204 assert(month <= 12);
205 days = _days_before_month[month];
206 if (month > 2 && is_leap(year))
207 ++days;
208 return days;
209}
210
211/* year -> number of days before January 1st of year. Remember that we
212 * start with year 1, so days_before_year(1) == 0.
213 */
214static int
215days_before_year(int year)
216{
217 int y = year - 1;
218 /* This is incorrect if year <= 0; we really want the floor
219 * here. But so long as MINYEAR is 1, the smallest year this
220 * can see is 0 (this can happen in some normalization endcases),
221 * so we'll just special-case that.
222 */
223 assert (year >= 0);
224 if (y >= 0)
225 return y*365 + y/4 - y/100 + y/400;
226 else {
227 assert(y == -1);
228 return -366;
229 }
230}
231
232/* Number of days in 4, 100, and 400 year cycles. That these have
233 * the correct values is asserted in the module init function.
234 */
235#define DI4Y 1461 /* days_before_year(5); days in 4 years */
236#define DI100Y 36524 /* days_before_year(101); days in 100 years */
237#define DI400Y 146097 /* days_before_year(401); days in 400 years */
238
239/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
240static void
241ord_to_ymd(int ordinal, int *year, int *month, int *day)
242{
243 int n, n1, n4, n100, n400, leapyear, preceding;
244
245 /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
246 * leap years repeats exactly every 400 years. The basic strategy is
247 * to find the closest 400-year boundary at or before ordinal, then
248 * work with the offset from that boundary to ordinal. Life is much
249 * clearer if we subtract 1 from ordinal first -- then the values
250 * of ordinal at 400-year boundaries are exactly those divisible
251 * by DI400Y:
252 *
253 * D M Y n n-1
254 * -- --- ---- ---------- ----------------
255 * 31 Dec -400 -DI400Y -DI400Y -1
256 * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
257 * ...
258 * 30 Dec 000 -1 -2
259 * 31 Dec 000 0 -1
260 * 1 Jan 001 1 0 400-year boundary
261 * 2 Jan 001 2 1
262 * 3 Jan 001 3 2
263 * ...
264 * 31 Dec 400 DI400Y DI400Y -1
265 * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
266 */
267 assert(ordinal >= 1);
268 --ordinal;
269 n400 = ordinal / DI400Y;
270 n = ordinal % DI400Y;
271 *year = n400 * 400 + 1;
272
273 /* Now n is the (non-negative) offset, in days, from January 1 of
274 * year, to the desired date. Now compute how many 100-year cycles
275 * precede n.
276 * Note that it's possible for n100 to equal 4! In that case 4 full
277 * 100-year cycles precede the desired day, which implies the
278 * desired day is December 31 at the end of a 400-year cycle.
279 */
280 n100 = n / DI100Y;
281 n = n % DI100Y;
282
283 /* Now compute how many 4-year cycles precede it. */
284 n4 = n / DI4Y;
285 n = n % DI4Y;
286
287 /* And now how many single years. Again n1 can be 4, and again
288 * meaning that the desired day is December 31 at the end of the
289 * 4-year cycle.
290 */
291 n1 = n / 365;
292 n = n % 365;
293
294 *year += n100 * 100 + n4 * 4 + n1;
295 if (n1 == 4 || n100 == 4) {
296 assert(n == 0);
297 *year -= 1;
298 *month = 12;
299 *day = 31;
300 return;
301 }
302
303 /* Now the year is correct, and n is the offset from January 1. We
304 * find the month via an estimate that's either exact or one too
305 * large.
306 */
307 leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
308 assert(leapyear == is_leap(*year));
309 *month = (n + 50) >> 5;
310 preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
311 if (preceding > n) {
312 /* estimate is too large */
313 *month -= 1;
314 preceding -= days_in_month(*year, *month);
315 }
316 n -= preceding;
317 assert(0 <= n);
318 assert(n < days_in_month(*year, *month));
319
320 *day = n + 1;
321}
322
323/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
324static int
325ymd_to_ord(int year, int month, int day)
326{
327 return days_before_year(year) + days_before_month(year, month) + day;
328}
329
330/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
331static int
332weekday(int year, int month, int day)
333{
334 return (ymd_to_ord(year, month, day) + 6) % 7;
335}
336
337/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
338 * first calendar week containing a Thursday.
339 */
340static int
341iso_week1_monday(int year)
342{
343 int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
344 /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
345 int first_weekday = (first_day + 6) % 7;
346 /* ordinal of closest Monday at or before 1/1 */
347 int week1_monday = first_day - first_weekday;
348
349 if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
350 week1_monday += 7;
351 return week1_monday;
352}
353
354/* ---------------------------------------------------------------------------
355 * Range checkers.
356 */
357
358/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
359 * If not, raise OverflowError and return -1.
360 */
361static int
362check_delta_day_range(int days)
363{
364 if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
365 return 0;
366 PyErr_Format(PyExc_OverflowError,
367 "days=%d; must have magnitude <= %d",
Guido van Rossumbd43e912002-12-16 20:34:55 +0000368 days, MAX_DELTA_DAYS);
Tim Peters2a799bf2002-12-16 20:18:38 +0000369 return -1;
370}
371
372/* Check that date arguments are in range. Return 0 if they are. If they
373 * aren't, raise ValueError and return -1.
374 */
375static int
376check_date_args(int year, int month, int day)
377{
378
379 if (year < MINYEAR || year > MAXYEAR) {
380 PyErr_SetString(PyExc_ValueError,
381 "year is out of range");
382 return -1;
383 }
384 if (month < 1 || month > 12) {
385 PyErr_SetString(PyExc_ValueError,
386 "month must be in 1..12");
387 return -1;
388 }
389 if (day < 1 || day > days_in_month(year, month)) {
390 PyErr_SetString(PyExc_ValueError,
391 "day is out of range for month");
392 return -1;
393 }
394 return 0;
395}
396
397/* Check that time arguments are in range. Return 0 if they are. If they
398 * aren't, raise ValueError and return -1.
399 */
400static int
401check_time_args(int h, int m, int s, int us)
402{
403 if (h < 0 || h > 23) {
404 PyErr_SetString(PyExc_ValueError,
405 "hour must be in 0..23");
406 return -1;
407 }
408 if (m < 0 || m > 59) {
409 PyErr_SetString(PyExc_ValueError,
410 "minute must be in 0..59");
411 return -1;
412 }
413 if (s < 0 || s > 59) {
414 PyErr_SetString(PyExc_ValueError,
415 "second must be in 0..59");
416 return -1;
417 }
418 if (us < 0 || us > 999999) {
419 PyErr_SetString(PyExc_ValueError,
420 "microsecond must be in 0..999999");
421 return -1;
422 }
423 return 0;
424}
425
426/* ---------------------------------------------------------------------------
427 * Normalization utilities.
428 */
429
430/* One step of a mixed-radix conversion. A "hi" unit is equivalent to
431 * factor "lo" units. factor must be > 0. If *lo is less than 0, or
432 * at least factor, enough of *lo is converted into "hi" units so that
433 * 0 <= *lo < factor. The input values must be such that int overflow
434 * is impossible.
435 */
436static void
437normalize_pair(int *hi, int *lo, int factor)
438{
439 assert(factor > 0);
440 assert(lo != hi);
441 if (*lo < 0 || *lo >= factor) {
442 const int num_hi = divmod(*lo, factor, lo);
443 const int new_hi = *hi + num_hi;
444 assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
445 *hi = new_hi;
446 }
447 assert(0 <= *lo && *lo < factor);
448}
449
450/* Fiddle days (d), seconds (s), and microseconds (us) so that
451 * 0 <= *s < 24*3600
452 * 0 <= *us < 1000000
453 * The input values must be such that the internals don't overflow.
454 * The way this routine is used, we don't get close.
455 */
456static void
457normalize_d_s_us(int *d, int *s, int *us)
458{
459 if (*us < 0 || *us >= 1000000) {
460 normalize_pair(s, us, 1000000);
461 /* |s| can't be bigger than about
462 * |original s| + |original us|/1000000 now.
463 */
464
465 }
466 if (*s < 0 || *s >= 24*3600) {
467 normalize_pair(d, s, 24*3600);
468 /* |d| can't be bigger than about
469 * |original d| +
470 * (|original s| + |original us|/1000000) / (24*3600) now.
471 */
472 }
473 assert(0 <= *s && *s < 24*3600);
474 assert(0 <= *us && *us < 1000000);
475}
476
477/* Fiddle years (y), months (m), and days (d) so that
478 * 1 <= *m <= 12
479 * 1 <= *d <= days_in_month(*y, *m)
480 * The input values must be such that the internals don't overflow.
481 * The way this routine is used, we don't get close.
482 */
483static void
484normalize_y_m_d(int *y, int *m, int *d)
485{
486 int dim; /* # of days in month */
487
488 /* This gets muddy: the proper range for day can't be determined
489 * without knowing the correct month and year, but if day is, e.g.,
490 * plus or minus a million, the current month and year values make
491 * no sense (and may also be out of bounds themselves).
492 * Saying 12 months == 1 year should be non-controversial.
493 */
494 if (*m < 1 || *m > 12) {
495 --*m;
496 normalize_pair(y, m, 12);
497 ++*m;
498 /* |y| can't be bigger than about
499 * |original y| + |original m|/12 now.
500 */
501 }
502 assert(1 <= *m && *m <= 12);
503
504 /* Now only day can be out of bounds (year may also be out of bounds
505 * for a datetime object, but we don't care about that here).
506 * If day is out of bounds, what to do is arguable, but at least the
507 * method here is principled and explainable.
508 */
509 dim = days_in_month(*y, *m);
510 if (*d < 1 || *d > dim) {
511 /* Move day-1 days from the first of the month. First try to
512 * get off cheap if we're only one day out of range
513 * (adjustments for timezone alone can't be worse than that).
514 */
515 if (*d == 0) {
516 --*m;
517 if (*m > 0)
518 *d = days_in_month(*y, *m);
519 else {
520 --*y;
521 *m = 12;
522 *d = 31;
523 }
524 }
525 else if (*d == dim + 1) {
526 /* move forward a day */
527 ++*m;
528 *d = 1;
529 if (*m > 12) {
530 *m = 1;
531 ++*y;
532 }
533 }
534 else {
535 int ordinal = ymd_to_ord(*y, *m, 1) +
536 *d - 1;
537 ord_to_ymd(ordinal, y, m, d);
538 }
539 }
540 assert(*m > 0);
541 assert(*d > 0);
542}
543
544/* Fiddle out-of-bounds months and days so that the result makes some kind
545 * of sense. The parameters are both inputs and outputs. Returns < 0 on
546 * failure, where failure means the adjusted year is out of bounds.
547 */
548static int
549normalize_date(int *year, int *month, int *day)
550{
551 int result;
552
553 normalize_y_m_d(year, month, day);
554 if (MINYEAR <= *year && *year <= MAXYEAR)
555 result = 0;
556 else {
557 PyErr_SetString(PyExc_OverflowError,
558 "date value out of range");
559 result = -1;
560 }
561 return result;
562}
563
564/* Force all the datetime fields into range. The parameters are both
565 * inputs and outputs. Returns < 0 on error.
566 */
567static int
568normalize_datetime(int *year, int *month, int *day,
569 int *hour, int *minute, int *second,
570 int *microsecond)
571{
572 normalize_pair(second, microsecond, 1000000);
573 normalize_pair(minute, second, 60);
574 normalize_pair(hour, minute, 60);
575 normalize_pair(day, hour, 24);
576 return normalize_date(year, month, day);
577}
578
579/* ---------------------------------------------------------------------------
Tim Petersb0c854d2003-05-17 15:57:00 +0000580 * Basic object allocation: tp_alloc implementations. These allocate
581 * Python objects of the right size and type, and do the Python object-
582 * initialization bit. If there's not enough memory, they return NULL after
583 * setting MemoryError. All data members remain uninitialized trash.
584 *
585 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
Tim Peters03eaf8b2003-05-18 02:24:46 +0000586 * member is needed. This is ugly, imprecise, and possibly insecure.
587 * tp_basicsize for the time and datetime types is set to the size of the
588 * struct that has room for the tzinfo member, so subclasses in Python will
589 * allocate enough space for a tzinfo member whether or not one is actually
590 * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
591 * part is that PyType_GenericAlloc() (which subclasses in Python end up
592 * using) just happens today to effectively ignore the nitems argument
593 * when tp_itemsize is 0, which it is for these type objects. If that
594 * changes, perhaps the callers of tp_alloc slots in this file should
595 * be changed to force a 0 nitems argument unless the type being allocated
596 * is a base type implemented in this file (so that tp_alloc is time_alloc
597 * or datetime_alloc below, which know about the nitems abuse).
Tim Petersb0c854d2003-05-17 15:57:00 +0000598 */
599
600static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000601time_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000602{
603 PyObject *self;
604
605 self = (PyObject *)
606 PyObject_MALLOC(aware ?
607 sizeof(PyDateTime_Time) :
608 sizeof(_PyDateTime_BaseTime));
609 if (self == NULL)
610 return (PyObject *)PyErr_NoMemory();
611 PyObject_INIT(self, type);
612 return self;
613}
614
615static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000616datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
Tim Petersb0c854d2003-05-17 15:57:00 +0000617{
618 PyObject *self;
619
620 self = (PyObject *)
621 PyObject_MALLOC(aware ?
622 sizeof(PyDateTime_DateTime) :
623 sizeof(_PyDateTime_BaseDateTime));
624 if (self == NULL)
625 return (PyObject *)PyErr_NoMemory();
626 PyObject_INIT(self, type);
627 return self;
628}
629
630/* ---------------------------------------------------------------------------
631 * Helpers for setting object fields. These work on pointers to the
632 * appropriate base class.
633 */
634
635/* For date and datetime. */
636static void
637set_date_fields(PyDateTime_Date *self, int y, int m, int d)
638{
639 self->hashcode = -1;
640 SET_YEAR(self, y);
641 SET_MONTH(self, m);
642 SET_DAY(self, d);
643}
644
645/* ---------------------------------------------------------------------------
646 * Create various objects, mostly without range checking.
647 */
648
649/* Create a date instance with no range checking. */
650static PyObject *
651new_date_ex(int year, int month, int day, PyTypeObject *type)
652{
653 PyDateTime_Date *self;
654
655 self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
656 if (self != NULL)
657 set_date_fields(self, year, month, day);
658 return (PyObject *) self;
659}
660
661#define new_date(year, month, day) \
662 new_date_ex(year, month, day, &PyDateTime_DateType)
663
664/* Create a datetime instance with no range checking. */
665static PyObject *
666new_datetime_ex(int year, int month, int day, int hour, int minute,
667 int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
668{
669 PyDateTime_DateTime *self;
670 char aware = tzinfo != Py_None;
671
672 self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
673 if (self != NULL) {
674 self->hastzinfo = aware;
675 set_date_fields((PyDateTime_Date *)self, year, month, day);
676 DATE_SET_HOUR(self, hour);
677 DATE_SET_MINUTE(self, minute);
678 DATE_SET_SECOND(self, second);
679 DATE_SET_MICROSECOND(self, usecond);
680 if (aware) {
681 Py_INCREF(tzinfo);
682 self->tzinfo = tzinfo;
683 }
684 }
685 return (PyObject *)self;
686}
687
688#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
689 new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
690 &PyDateTime_DateTimeType)
691
692/* Create a time instance with no range checking. */
693static PyObject *
694new_time_ex(int hour, int minute, int second, int usecond,
695 PyObject *tzinfo, PyTypeObject *type)
696{
697 PyDateTime_Time *self;
698 char aware = tzinfo != Py_None;
699
700 self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
701 if (self != NULL) {
702 self->hastzinfo = aware;
703 self->hashcode = -1;
704 TIME_SET_HOUR(self, hour);
705 TIME_SET_MINUTE(self, minute);
706 TIME_SET_SECOND(self, second);
707 TIME_SET_MICROSECOND(self, usecond);
708 if (aware) {
709 Py_INCREF(tzinfo);
710 self->tzinfo = tzinfo;
711 }
712 }
713 return (PyObject *)self;
714}
715
716#define new_time(hh, mm, ss, us, tzinfo) \
717 new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
718
719/* Create a timedelta instance. Normalize the members iff normalize is
720 * true. Passing false is a speed optimization, if you know for sure
721 * that seconds and microseconds are already in their proper ranges. In any
722 * case, raises OverflowError and returns NULL if the normalized days is out
723 * of range).
724 */
725static PyObject *
726new_delta_ex(int days, int seconds, int microseconds, int normalize,
727 PyTypeObject *type)
728{
729 PyDateTime_Delta *self;
730
731 if (normalize)
732 normalize_d_s_us(&days, &seconds, &microseconds);
733 assert(0 <= seconds && seconds < 24*3600);
734 assert(0 <= microseconds && microseconds < 1000000);
735
736 if (check_delta_day_range(days) < 0)
737 return NULL;
738
739 self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
740 if (self != NULL) {
741 self->hashcode = -1;
742 SET_TD_DAYS(self, days);
743 SET_TD_SECONDS(self, seconds);
744 SET_TD_MICROSECONDS(self, microseconds);
745 }
746 return (PyObject *) self;
747}
748
749#define new_delta(d, s, us, normalize) \
750 new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
751
752/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +0000753 * tzinfo helpers.
754 */
755
Tim Peters855fe882002-12-22 03:43:39 +0000756/* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
757 * raise TypeError and return -1.
758 */
759static int
760check_tzinfo_subclass(PyObject *p)
761{
762 if (p == Py_None || PyTZInfo_Check(p))
763 return 0;
764 PyErr_Format(PyExc_TypeError,
765 "tzinfo argument must be None or of a tzinfo subclass, "
766 "not type '%s'",
767 p->ob_type->tp_name);
768 return -1;
769}
770
Tim Petersbad8ff02002-12-30 20:52:32 +0000771/* Return tzinfo.methname(tzinfoarg), without any checking of results.
Tim Peters855fe882002-12-22 03:43:39 +0000772 * If tzinfo is None, returns None.
773 */
774static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000775call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
Tim Peters855fe882002-12-22 03:43:39 +0000776{
777 PyObject *result;
778
Tim Petersbad8ff02002-12-30 20:52:32 +0000779 assert(tzinfo && methname && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000780 assert(check_tzinfo_subclass(tzinfo) >= 0);
781 if (tzinfo == Py_None) {
782 result = Py_None;
783 Py_INCREF(result);
784 }
785 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000786 result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000787 return result;
788}
789
Tim Peters2a799bf2002-12-16 20:18:38 +0000790/* If self has a tzinfo member, return a BORROWED reference to it. Else
791 * return NULL, which is NOT AN ERROR. There are no error returns here,
792 * and the caller must not decref the result.
793 */
794static PyObject *
795get_tzinfo_member(PyObject *self)
796{
797 PyObject *tzinfo = NULL;
798
Tim Petersa9bc1682003-01-11 03:39:11 +0000799 if (PyDateTime_Check(self) && HASTZINFO(self))
800 tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
Tim Petersa032d2e2003-01-11 00:15:54 +0000801 else if (PyTime_Check(self) && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +0000802 tzinfo = ((PyDateTime_Time *)self)->tzinfo;
Tim Peters2a799bf2002-12-16 20:18:38 +0000803
804 return tzinfo;
805}
806
Tim Petersbad8ff02002-12-30 20:52:32 +0000807/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
Tim Peters2a799bf2002-12-16 20:18:38 +0000808 * result. tzinfo must be an instance of the tzinfo class. If the method
809 * returns None, this returns 0 and sets *none to 1. If the method doesn't
Tim Peters397301e2003-01-02 21:28:08 +0000810 * return None or timedelta, TypeError is raised and this returns -1. If it
811 * returnsa timedelta and the value is out of range or isn't a whole number
812 * of minutes, ValueError is raised and this returns -1.
Tim Peters2a799bf2002-12-16 20:18:38 +0000813 * Else *none is set to 0 and the integer method result is returned.
814 */
815static int
816call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
817 int *none)
818{
819 PyObject *u;
Tim Peters397301e2003-01-02 21:28:08 +0000820 int result = -1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000821
822 assert(tzinfo != NULL);
823 assert(PyTZInfo_Check(tzinfo));
824 assert(tzinfoarg != NULL);
825
826 *none = 0;
Tim Petersbad8ff02002-12-30 20:52:32 +0000827 u = call_tzinfo_method(tzinfo, name, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +0000828 if (u == NULL)
829 return -1;
830
Tim Peters27362852002-12-23 16:17:39 +0000831 else if (u == Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +0000832 result = 0;
833 *none = 1;
Tim Peters2a799bf2002-12-16 20:18:38 +0000834 }
Tim Peters855fe882002-12-22 03:43:39 +0000835 else if (PyDelta_Check(u)) {
836 const int days = GET_TD_DAYS(u);
837 if (days < -1 || days > 0)
838 result = 24*60; /* trigger ValueError below */
839 else {
840 /* next line can't overflow because we know days
841 * is -1 or 0 now
842 */
843 int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
844 result = divmod(ss, 60, &ss);
845 if (ss || GET_TD_MICROSECONDS(u)) {
846 PyErr_Format(PyExc_ValueError,
847 "tzinfo.%s() must return a "
848 "whole number of minutes",
849 name);
850 result = -1;
Tim Peters855fe882002-12-22 03:43:39 +0000851 }
852 }
853 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000854 else {
855 PyErr_Format(PyExc_TypeError,
Tim Peters397301e2003-01-02 21:28:08 +0000856 "tzinfo.%s() must return None or "
Tim Peters855fe882002-12-22 03:43:39 +0000857 "timedelta, not '%s'",
858 name, u->ob_type->tp_name);
Tim Peters2a799bf2002-12-16 20:18:38 +0000859 }
860
Tim Peters2a799bf2002-12-16 20:18:38 +0000861 Py_DECREF(u);
862 if (result < -1439 || result > 1439) {
863 PyErr_Format(PyExc_ValueError,
Neal Norwitz506a2242003-01-04 01:02:25 +0000864 "tzinfo.%s() returned %d; must be in "
Tim Peters2a799bf2002-12-16 20:18:38 +0000865 "-1439 .. 1439",
866 name, result);
867 result = -1;
868 }
Tim Peters397301e2003-01-02 21:28:08 +0000869 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +0000870}
871
872/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
873 * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
874 * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
Tim Peters397301e2003-01-02 21:28:08 +0000875 * doesn't return None or timedelta, TypeError is raised and this returns -1.
876 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
877 * # of minutes), ValueError is raised and this returns -1. Else *none is
878 * set to 0 and the offset is returned (as int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000879 */
880static int
881call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
882{
883 return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
884}
885
Tim Petersbad8ff02002-12-30 20:52:32 +0000886/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
887 */
Tim Peters855fe882002-12-22 03:43:39 +0000888static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000889offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
Tim Peters855fe882002-12-22 03:43:39 +0000890 PyObject *result;
891
Tim Petersbad8ff02002-12-30 20:52:32 +0000892 assert(tzinfo && name && tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000893 if (tzinfo == Py_None) {
894 result = Py_None;
895 Py_INCREF(result);
896 }
897 else {
898 int none;
Tim Petersbad8ff02002-12-30 20:52:32 +0000899 int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
900 &none);
Tim Peters855fe882002-12-22 03:43:39 +0000901 if (offset < 0 && PyErr_Occurred())
902 return NULL;
903 if (none) {
904 result = Py_None;
905 Py_INCREF(result);
906 }
907 else
908 result = new_delta(0, offset * 60, 0, 1);
909 }
910 return result;
911}
912
Tim Peters2a799bf2002-12-16 20:18:38 +0000913/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
914 * result. tzinfo must be an instance of the tzinfo class. If dst()
915 * returns None, call_dst returns 0 and sets *none to 1. If dst()
Tim Peters397301e2003-01-02 21:28:08 +0000916 & doesn't return None or timedelta, TypeError is raised and this
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000917 * returns -1. If dst() returns an invalid timedelta for a UTC offset,
Tim Peters397301e2003-01-02 21:28:08 +0000918 * ValueError is raised and this returns -1. Else *none is set to 0 and
919 * the offset is returned (as an int # of minutes east of UTC).
Tim Peters2a799bf2002-12-16 20:18:38 +0000920 */
921static int
922call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
923{
924 return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
925}
926
Tim Petersbad8ff02002-12-30 20:52:32 +0000927/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
Tim Peters855fe882002-12-22 03:43:39 +0000928 * an instance of the tzinfo class or None. If tzinfo isn't None, and
Tim Petersbad8ff02002-12-30 20:52:32 +0000929 * tzname() doesn't return None or a string, TypeError is raised and this
Guido van Rossume3d1d412007-05-23 21:24:35 +0000930 * returns NULL. If the result is a string, we ensure it is a Unicode
931 * string.
Tim Peters2a799bf2002-12-16 20:18:38 +0000932 */
933static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +0000934call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000935{
936 PyObject *result;
937
938 assert(tzinfo != NULL);
Tim Peters855fe882002-12-22 03:43:39 +0000939 assert(check_tzinfo_subclass(tzinfo) >= 0);
Tim Petersbad8ff02002-12-30 20:52:32 +0000940 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +0000941
Tim Peters855fe882002-12-22 03:43:39 +0000942 if (tzinfo == Py_None) {
943 result = Py_None;
944 Py_INCREF(result);
945 }
946 else
Tim Petersbad8ff02002-12-30 20:52:32 +0000947 result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
Tim Peters855fe882002-12-22 03:43:39 +0000948
Guido van Rossume3d1d412007-05-23 21:24:35 +0000949 if (result != NULL && result != Py_None) {
950 if (!PyString_Check(result) && !PyUnicode_Check(result)) {
951 PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
952 "return None or a string, not '%s'",
953 result->ob_type->tp_name);
954 Py_DECREF(result);
955 result = NULL;
956 }
957 else if (!PyUnicode_Check(result)) {
958 PyObject *temp = PyUnicode_FromObject(result);
959 Py_DECREF(result);
960 result = temp;
961 }
Tim Peters2a799bf2002-12-16 20:18:38 +0000962 }
963 return result;
964}
965
966typedef enum {
967 /* an exception has been set; the caller should pass it on */
968 OFFSET_ERROR,
969
Tim Petersa9bc1682003-01-11 03:39:11 +0000970 /* type isn't date, datetime, or time subclass */
Tim Peters2a799bf2002-12-16 20:18:38 +0000971 OFFSET_UNKNOWN,
972
973 /* date,
Tim Petersa9bc1682003-01-11 03:39:11 +0000974 * datetime with !hastzinfo
975 * datetime with None tzinfo,
976 * datetime where utcoffset() returns None
Tim Peters37f39822003-01-10 03:49:02 +0000977 * time with !hastzinfo
978 * time with None tzinfo,
979 * time where utcoffset() returns None
Tim Peters2a799bf2002-12-16 20:18:38 +0000980 */
981 OFFSET_NAIVE,
982
Tim Petersa9bc1682003-01-11 03:39:11 +0000983 /* time or datetime where utcoffset() doesn't return None */
Georg Brandle810fe22006-02-19 15:28:47 +0000984 OFFSET_AWARE
Tim Peters2a799bf2002-12-16 20:18:38 +0000985} naivety;
986
Tim Peters14b69412002-12-22 18:10:22 +0000987/* Classify an object as to whether it's naive or offset-aware. See
Tim Peters2a799bf2002-12-16 20:18:38 +0000988 * the "naivety" typedef for details. If the type is aware, *offset is set
989 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
Tim Peters14b69412002-12-22 18:10:22 +0000990 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
Tim Peterse39a80c2002-12-30 21:28:52 +0000991 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
Tim Peters2a799bf2002-12-16 20:18:38 +0000992 */
993static naivety
Tim Peterse39a80c2002-12-30 21:28:52 +0000994classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000995{
996 int none;
997 PyObject *tzinfo;
998
Tim Peterse39a80c2002-12-30 21:28:52 +0000999 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001000 *offset = 0;
Tim Peters14b69412002-12-22 18:10:22 +00001001 tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
Tim Peters2a799bf2002-12-16 20:18:38 +00001002 if (tzinfo == Py_None)
1003 return OFFSET_NAIVE;
Tim Peters14b69412002-12-22 18:10:22 +00001004 if (tzinfo == NULL) {
1005 /* note that a datetime passes the PyDate_Check test */
1006 return (PyTime_Check(op) || PyDate_Check(op)) ?
1007 OFFSET_NAIVE : OFFSET_UNKNOWN;
1008 }
Tim Peterse39a80c2002-12-30 21:28:52 +00001009 *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00001010 if (*offset == -1 && PyErr_Occurred())
1011 return OFFSET_ERROR;
1012 return none ? OFFSET_NAIVE : OFFSET_AWARE;
1013}
1014
Tim Peters00237032002-12-27 02:21:51 +00001015/* Classify two objects as to whether they're naive or offset-aware.
1016 * This isn't quite the same as calling classify_utcoffset() twice: for
1017 * binary operations (comparison and subtraction), we generally want to
1018 * ignore the tzinfo members if they're identical. This is by design,
1019 * so that results match "naive" expectations when mixing objects from a
1020 * single timezone. So in that case, this sets both offsets to 0 and
1021 * both naiveties to OFFSET_NAIVE.
1022 * The function returns 0 if everything's OK, and -1 on error.
1023 */
1024static int
1025classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
Tim Peterse39a80c2002-12-30 21:28:52 +00001026 PyObject *tzinfoarg1,
1027 PyObject *o2, int *offset2, naivety *n2,
1028 PyObject *tzinfoarg2)
Tim Peters00237032002-12-27 02:21:51 +00001029{
1030 if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1031 *offset1 = *offset2 = 0;
1032 *n1 = *n2 = OFFSET_NAIVE;
1033 }
1034 else {
Tim Peterse39a80c2002-12-30 21:28:52 +00001035 *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
Tim Peters00237032002-12-27 02:21:51 +00001036 if (*n1 == OFFSET_ERROR)
1037 return -1;
Tim Peterse39a80c2002-12-30 21:28:52 +00001038 *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
Tim Peters00237032002-12-27 02:21:51 +00001039 if (*n2 == OFFSET_ERROR)
1040 return -1;
1041 }
1042 return 0;
1043}
1044
Tim Peters2a799bf2002-12-16 20:18:38 +00001045/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
1046 * stuff
1047 * ", tzinfo=" + repr(tzinfo)
1048 * before the closing ")".
1049 */
1050static PyObject *
1051append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1052{
1053 PyObject *temp;
1054
Walter Dörwald1ab83302007-05-18 17:15:44 +00001055 assert(PyUnicode_Check(repr));
Tim Peters2a799bf2002-12-16 20:18:38 +00001056 assert(tzinfo);
1057 if (tzinfo == Py_None)
1058 return repr;
1059 /* Get rid of the trailing ')'. */
Walter Dörwald1ab83302007-05-18 17:15:44 +00001060 assert(PyUnicode_AS_UNICODE(repr)[PyUnicode_GET_SIZE(repr)-1] == ')');
1061 temp = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(repr),
1062 PyUnicode_GET_SIZE(repr) - 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00001063 Py_DECREF(repr);
1064 if (temp == NULL)
1065 return NULL;
Walter Dörwald517bcfe2007-05-23 20:45:05 +00001066 repr = PyUnicode_FromFormat("%U, tzinfo=%R)", temp, tzinfo);
1067 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00001068 return repr;
1069}
1070
1071/* ---------------------------------------------------------------------------
1072 * String format helpers.
1073 */
1074
1075static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00001076format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
Tim Peters2a799bf2002-12-16 20:18:38 +00001077{
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001078 static const char *DayNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001079 "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1080 };
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001081 static const char *MonthNames[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001082 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1083 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1084 };
1085
1086 char buffer[128];
1087 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1088
1089 PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1090 DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1091 GET_DAY(date), hours, minutes, seconds,
1092 GET_YEAR(date));
1093 return PyString_FromString(buffer);
1094}
1095
1096/* Add an hours & minutes UTC offset string to buf. buf has no more than
1097 * buflen bytes remaining. The UTC offset is gotten by calling
1098 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1099 * *buf, and that's all. Else the returned value is checked for sanity (an
1100 * integer in range), and if that's OK it's converted to an hours & minutes
1101 * string of the form
1102 * sign HH sep MM
1103 * Returns 0 if everything is OK. If the return value from utcoffset() is
1104 * bogus, an appropriate exception is set and -1 is returned.
1105 */
1106static int
Tim Peters328fff72002-12-20 01:31:27 +00001107format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001108 PyObject *tzinfo, PyObject *tzinfoarg)
1109{
1110 int offset;
1111 int hours;
1112 int minutes;
1113 char sign;
1114 int none;
1115
1116 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1117 if (offset == -1 && PyErr_Occurred())
1118 return -1;
1119 if (none) {
1120 *buf = '\0';
1121 return 0;
1122 }
1123 sign = '+';
1124 if (offset < 0) {
1125 sign = '-';
1126 offset = - offset;
1127 }
1128 hours = divmod(offset, 60, &minutes);
1129 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1130 return 0;
1131}
1132
1133/* I sure don't want to reproduce the strftime code from the time module,
1134 * so this imports the module and calls it. All the hair is due to
1135 * giving special meanings to the %z and %Z format codes via a preprocessing
1136 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001137 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1138 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001139 */
1140static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001141wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1142 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001143{
1144 PyObject *result = NULL; /* guilty until proved innocent */
1145
1146 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1147 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1148
Guido van Rossumbce56a62007-05-10 18:04:33 +00001149 const char *pin;/* pointer to next char in input format */
1150 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001151 char ch; /* next char in input format */
1152
1153 PyObject *newfmt = NULL; /* py string, the output format */
1154 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001155 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001156 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001157 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001158
Guido van Rossumbce56a62007-05-10 18:04:33 +00001159 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001160 int ntoappend; /* # of bytes to append to output buffer */
1161
Tim Peters2a799bf2002-12-16 20:18:38 +00001162 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001163 assert(PyString_Check(format) || PyUnicode_Check(format));
1164
1165 /* Convert the input format to a C string and size */
1166 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1167 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001168
Tim Petersd6844152002-12-22 20:58:42 +00001169 /* Give up if the year is before 1900.
1170 * Python strftime() plays games with the year, and different
1171 * games depending on whether envar PYTHON2K is set. This makes
1172 * years before 1900 a nightmare, even if the platform strftime
1173 * supports them (and not all do).
1174 * We could get a lot farther here by avoiding Python's strftime
1175 * wrapper and calling the C strftime() directly, but that isn't
1176 * an option in the Python implementation of this module.
1177 */
1178 {
1179 long year;
1180 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1181 if (pyyear == NULL) return NULL;
1182 assert(PyInt_Check(pyyear));
1183 year = PyInt_AsLong(pyyear);
1184 Py_DECREF(pyyear);
1185 if (year < 1900) {
1186 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1187 "1900; the datetime strftime() "
1188 "methods require year >= 1900",
1189 year);
1190 return NULL;
1191 }
1192 }
1193
Tim Peters2a799bf2002-12-16 20:18:38 +00001194 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001195 * a new format. Since computing the replacements for those codes
1196 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001197 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001198 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001199 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1200 if (newfmt == NULL) goto Done;
1201 pnew = PyString_AsString(newfmt);
1202 usednew = 0;
1203
Tim Peters2a799bf2002-12-16 20:18:38 +00001204 while ((ch = *pin++) != '\0') {
1205 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001206 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001207 ntoappend = 1;
1208 }
1209 else if ((ch = *pin++) == '\0') {
1210 /* There's a lone trailing %; doesn't make sense. */
1211 PyErr_SetString(PyExc_ValueError, "strftime format "
1212 "ends with raw %");
1213 goto Done;
1214 }
1215 /* A % has been seen and ch is the character after it. */
1216 else if (ch == 'z') {
1217 if (zreplacement == NULL) {
1218 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001219 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001220 PyObject *tzinfo = get_tzinfo_member(object);
1221 zreplacement = PyString_FromString("");
1222 if (zreplacement == NULL) goto Done;
1223 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001224 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001225 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001226 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001227 "",
1228 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001229 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001230 goto Done;
1231 Py_DECREF(zreplacement);
1232 zreplacement = PyString_FromString(buf);
1233 if (zreplacement == NULL) goto Done;
1234 }
1235 }
1236 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001237 ptoappend = PyString_AS_STRING(zreplacement);
1238 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001239 }
1240 else if (ch == 'Z') {
1241 /* format tzname */
1242 if (Zreplacement == NULL) {
1243 PyObject *tzinfo = get_tzinfo_member(object);
1244 Zreplacement = PyString_FromString("");
1245 if (Zreplacement == NULL) goto Done;
1246 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001247 PyObject *temp;
1248 assert(tzinfoarg != NULL);
1249 temp = call_tzname(tzinfo, tzinfoarg);
Tim Peters2a799bf2002-12-16 20:18:38 +00001250 if (temp == NULL) goto Done;
1251 if (temp != Py_None) {
Guido van Rossume3d1d412007-05-23 21:24:35 +00001252 assert(PyUnicode_Check(temp));
Tim Peters2a799bf2002-12-16 20:18:38 +00001253 /* Since the tzname is getting
1254 * stuffed into the format, we
1255 * have to double any % signs
1256 * so that strftime doesn't
1257 * treat them as format codes.
1258 */
1259 Py_DECREF(Zreplacement);
1260 Zreplacement = PyObject_CallMethod(
1261 temp, "replace",
1262 "ss", "%", "%%");
1263 Py_DECREF(temp);
1264 if (Zreplacement == NULL)
1265 goto Done;
Guido van Rossume3d1d412007-05-23 21:24:35 +00001266 if (PyUnicode_Check(Zreplacement)) {
1267 Zreplacement = _PyUnicode_AsDefaultEncodedString(Zreplacement, NULL);
1268 if (Zreplacement == NULL)
1269 goto Done;
1270 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001271 if (!PyString_Check(Zreplacement)) {
1272 PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1273 goto Done;
1274 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001275 }
1276 else
1277 Py_DECREF(temp);
1278 }
1279 }
1280 assert(Zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001281 ptoappend = PyString_AS_STRING(Zreplacement);
1282 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001283 }
1284 else {
Tim Peters328fff72002-12-20 01:31:27 +00001285 /* percent followed by neither z nor Z */
1286 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001287 ntoappend = 2;
1288 }
1289
1290 /* Append the ntoappend chars starting at ptoappend to
1291 * the new format.
1292 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001293 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001294 assert(ntoappend >= 0);
1295 if (ntoappend == 0)
1296 continue;
1297 while (usednew + ntoappend > totalnew) {
1298 int bigger = totalnew << 1;
1299 if ((bigger >> 1) != totalnew) { /* overflow */
1300 PyErr_NoMemory();
1301 goto Done;
1302 }
1303 if (_PyString_Resize(&newfmt, bigger) < 0)
1304 goto Done;
1305 totalnew = bigger;
1306 pnew = PyString_AsString(newfmt) + usednew;
1307 }
1308 memcpy(pnew, ptoappend, ntoappend);
1309 pnew += ntoappend;
1310 usednew += ntoappend;
1311 assert(usednew <= totalnew);
1312 } /* end while() */
1313
1314 if (_PyString_Resize(&newfmt, usednew) < 0)
1315 goto Done;
1316 {
1317 PyObject *time = PyImport_ImportModule("time");
1318 if (time == NULL)
1319 goto Done;
1320 result = PyObject_CallMethod(time, "strftime", "OO",
1321 newfmt, timetuple);
1322 Py_DECREF(time);
1323 }
1324 Done:
1325 Py_XDECREF(zreplacement);
1326 Py_XDECREF(Zreplacement);
1327 Py_XDECREF(newfmt);
1328 return result;
1329}
1330
1331static char *
1332isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1333{
1334 int x;
1335 x = PyOS_snprintf(buffer, bufflen,
1336 "%04d-%02d-%02d",
1337 GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1338 return buffer + x;
1339}
1340
1341static void
1342isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1343{
1344 int us = DATE_GET_MICROSECOND(dt);
1345
1346 PyOS_snprintf(buffer, bufflen,
1347 "%02d:%02d:%02d", /* 8 characters */
1348 DATE_GET_HOUR(dt),
1349 DATE_GET_MINUTE(dt),
1350 DATE_GET_SECOND(dt));
1351 if (us)
1352 PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1353}
1354
1355/* ---------------------------------------------------------------------------
1356 * Wrap functions from the time module. These aren't directly available
1357 * from C. Perhaps they should be.
1358 */
1359
1360/* Call time.time() and return its result (a Python float). */
1361static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001362time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001363{
1364 PyObject *result = NULL;
1365 PyObject *time = PyImport_ImportModule("time");
1366
1367 if (time != NULL) {
1368 result = PyObject_CallMethod(time, "time", "()");
1369 Py_DECREF(time);
1370 }
1371 return result;
1372}
1373
1374/* Build a time.struct_time. The weekday and day number are automatically
1375 * computed from the y,m,d args.
1376 */
1377static PyObject *
1378build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1379{
1380 PyObject *time;
1381 PyObject *result = NULL;
1382
1383 time = PyImport_ImportModule("time");
1384 if (time != NULL) {
1385 result = PyObject_CallMethod(time, "struct_time",
1386 "((iiiiiiiii))",
1387 y, m, d,
1388 hh, mm, ss,
1389 weekday(y, m, d),
1390 days_before_month(y, m) + d,
1391 dstflag);
1392 Py_DECREF(time);
1393 }
1394 return result;
1395}
1396
1397/* ---------------------------------------------------------------------------
1398 * Miscellaneous helpers.
1399 */
1400
Guido van Rossum19960592006-08-24 17:29:38 +00001401/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001402 * The comparisons here all most naturally compute a cmp()-like result.
1403 * This little helper turns that into a bool result for rich comparisons.
1404 */
1405static PyObject *
1406diff_to_bool(int diff, int op)
1407{
1408 PyObject *result;
1409 int istrue;
1410
1411 switch (op) {
1412 case Py_EQ: istrue = diff == 0; break;
1413 case Py_NE: istrue = diff != 0; break;
1414 case Py_LE: istrue = diff <= 0; break;
1415 case Py_GE: istrue = diff >= 0; break;
1416 case Py_LT: istrue = diff < 0; break;
1417 case Py_GT: istrue = diff > 0; break;
1418 default:
1419 assert(! "op unknown");
1420 istrue = 0; /* To shut up compiler */
1421 }
1422 result = istrue ? Py_True : Py_False;
1423 Py_INCREF(result);
1424 return result;
1425}
1426
Tim Peters07534a62003-02-07 22:50:28 +00001427/* Raises a "can't compare" TypeError and returns NULL. */
1428static PyObject *
1429cmperror(PyObject *a, PyObject *b)
1430{
1431 PyErr_Format(PyExc_TypeError,
1432 "can't compare %s to %s",
1433 a->ob_type->tp_name, b->ob_type->tp_name);
1434 return NULL;
1435}
1436
Tim Peters2a799bf2002-12-16 20:18:38 +00001437/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001438 * Cached Python objects; these are set by the module init function.
1439 */
1440
1441/* Conversion factors. */
1442static PyObject *us_per_us = NULL; /* 1 */
1443static PyObject *us_per_ms = NULL; /* 1000 */
1444static PyObject *us_per_second = NULL; /* 1000000 */
1445static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1446static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1447static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1448static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1449static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1450
Tim Peters2a799bf2002-12-16 20:18:38 +00001451/* ---------------------------------------------------------------------------
1452 * Class implementations.
1453 */
1454
1455/*
1456 * PyDateTime_Delta implementation.
1457 */
1458
1459/* Convert a timedelta to a number of us,
1460 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1461 * as a Python int or long.
1462 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1463 * due to ubiquitous overflow possibilities.
1464 */
1465static PyObject *
1466delta_to_microseconds(PyDateTime_Delta *self)
1467{
1468 PyObject *x1 = NULL;
1469 PyObject *x2 = NULL;
1470 PyObject *x3 = NULL;
1471 PyObject *result = NULL;
1472
1473 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1474 if (x1 == NULL)
1475 goto Done;
1476 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1477 if (x2 == NULL)
1478 goto Done;
1479 Py_DECREF(x1);
1480 x1 = NULL;
1481
1482 /* x2 has days in seconds */
1483 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1484 if (x1 == NULL)
1485 goto Done;
1486 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1487 if (x3 == NULL)
1488 goto Done;
1489 Py_DECREF(x1);
1490 Py_DECREF(x2);
1491 x1 = x2 = NULL;
1492
1493 /* x3 has days+seconds in seconds */
1494 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1495 if (x1 == NULL)
1496 goto Done;
1497 Py_DECREF(x3);
1498 x3 = NULL;
1499
1500 /* x1 has days+seconds in us */
1501 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1502 if (x2 == NULL)
1503 goto Done;
1504 result = PyNumber_Add(x1, x2);
1505
1506Done:
1507 Py_XDECREF(x1);
1508 Py_XDECREF(x2);
1509 Py_XDECREF(x3);
1510 return result;
1511}
1512
1513/* Convert a number of us (as a Python int or long) to a timedelta.
1514 */
1515static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001516microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001517{
1518 int us;
1519 int s;
1520 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001521 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001522
1523 PyObject *tuple = NULL;
1524 PyObject *num = NULL;
1525 PyObject *result = NULL;
1526
1527 tuple = PyNumber_Divmod(pyus, us_per_second);
1528 if (tuple == NULL)
1529 goto Done;
1530
1531 num = PyTuple_GetItem(tuple, 1); /* us */
1532 if (num == NULL)
1533 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001534 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001535 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001536 if (temp == -1 && PyErr_Occurred())
1537 goto Done;
1538 assert(0 <= temp && temp < 1000000);
1539 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001540 if (us < 0) {
1541 /* The divisor was positive, so this must be an error. */
1542 assert(PyErr_Occurred());
1543 goto Done;
1544 }
1545
1546 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1547 if (num == NULL)
1548 goto Done;
1549 Py_INCREF(num);
1550 Py_DECREF(tuple);
1551
1552 tuple = PyNumber_Divmod(num, seconds_per_day);
1553 if (tuple == NULL)
1554 goto Done;
1555 Py_DECREF(num);
1556
1557 num = PyTuple_GetItem(tuple, 1); /* seconds */
1558 if (num == NULL)
1559 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001560 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001561 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001562 if (temp == -1 && PyErr_Occurred())
1563 goto Done;
1564 assert(0 <= temp && temp < 24*3600);
1565 s = (int)temp;
1566
Tim Peters2a799bf2002-12-16 20:18:38 +00001567 if (s < 0) {
1568 /* The divisor was positive, so this must be an error. */
1569 assert(PyErr_Occurred());
1570 goto Done;
1571 }
1572
1573 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1574 if (num == NULL)
1575 goto Done;
1576 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001577 temp = PyLong_AsLong(num);
1578 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001579 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001580 d = (int)temp;
1581 if ((long)d != temp) {
1582 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1583 "large to fit in a C int");
1584 goto Done;
1585 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001586 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001587
1588Done:
1589 Py_XDECREF(tuple);
1590 Py_XDECREF(num);
1591 return result;
1592}
1593
Tim Petersb0c854d2003-05-17 15:57:00 +00001594#define microseconds_to_delta(pymicros) \
1595 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1596
Tim Peters2a799bf2002-12-16 20:18:38 +00001597static PyObject *
1598multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1599{
1600 PyObject *pyus_in;
1601 PyObject *pyus_out;
1602 PyObject *result;
1603
1604 pyus_in = delta_to_microseconds(delta);
1605 if (pyus_in == NULL)
1606 return NULL;
1607
1608 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1609 Py_DECREF(pyus_in);
1610 if (pyus_out == NULL)
1611 return NULL;
1612
1613 result = microseconds_to_delta(pyus_out);
1614 Py_DECREF(pyus_out);
1615 return result;
1616}
1617
1618static PyObject *
1619divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1620{
1621 PyObject *pyus_in;
1622 PyObject *pyus_out;
1623 PyObject *result;
1624
1625 pyus_in = delta_to_microseconds(delta);
1626 if (pyus_in == NULL)
1627 return NULL;
1628
1629 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1630 Py_DECREF(pyus_in);
1631 if (pyus_out == NULL)
1632 return NULL;
1633
1634 result = microseconds_to_delta(pyus_out);
1635 Py_DECREF(pyus_out);
1636 return result;
1637}
1638
1639static PyObject *
1640delta_add(PyObject *left, PyObject *right)
1641{
1642 PyObject *result = Py_NotImplemented;
1643
1644 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1645 /* delta + delta */
1646 /* The C-level additions can't overflow because of the
1647 * invariant bounds.
1648 */
1649 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1650 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1651 int microseconds = GET_TD_MICROSECONDS(left) +
1652 GET_TD_MICROSECONDS(right);
1653 result = new_delta(days, seconds, microseconds, 1);
1654 }
1655
1656 if (result == Py_NotImplemented)
1657 Py_INCREF(result);
1658 return result;
1659}
1660
1661static PyObject *
1662delta_negative(PyDateTime_Delta *self)
1663{
1664 return new_delta(-GET_TD_DAYS(self),
1665 -GET_TD_SECONDS(self),
1666 -GET_TD_MICROSECONDS(self),
1667 1);
1668}
1669
1670static PyObject *
1671delta_positive(PyDateTime_Delta *self)
1672{
1673 /* Could optimize this (by returning self) if this isn't a
1674 * subclass -- but who uses unary + ? Approximately nobody.
1675 */
1676 return new_delta(GET_TD_DAYS(self),
1677 GET_TD_SECONDS(self),
1678 GET_TD_MICROSECONDS(self),
1679 0);
1680}
1681
1682static PyObject *
1683delta_abs(PyDateTime_Delta *self)
1684{
1685 PyObject *result;
1686
1687 assert(GET_TD_MICROSECONDS(self) >= 0);
1688 assert(GET_TD_SECONDS(self) >= 0);
1689
1690 if (GET_TD_DAYS(self) < 0)
1691 result = delta_negative(self);
1692 else
1693 result = delta_positive(self);
1694
1695 return result;
1696}
1697
1698static PyObject *
1699delta_subtract(PyObject *left, PyObject *right)
1700{
1701 PyObject *result = Py_NotImplemented;
1702
1703 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1704 /* delta - delta */
1705 PyObject *minus_right = PyNumber_Negative(right);
1706 if (minus_right) {
1707 result = delta_add(left, minus_right);
1708 Py_DECREF(minus_right);
1709 }
1710 else
1711 result = NULL;
1712 }
1713
1714 if (result == Py_NotImplemented)
1715 Py_INCREF(result);
1716 return result;
1717}
1718
Tim Peters2a799bf2002-12-16 20:18:38 +00001719static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001720delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001721{
Tim Petersaa7d8492003-02-08 03:28:59 +00001722 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001723 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001724 if (diff == 0) {
1725 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1726 if (diff == 0)
1727 diff = GET_TD_MICROSECONDS(self) -
1728 GET_TD_MICROSECONDS(other);
1729 }
Guido van Rossum19960592006-08-24 17:29:38 +00001730 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001731 }
Guido van Rossum19960592006-08-24 17:29:38 +00001732 else {
1733 Py_INCREF(Py_NotImplemented);
1734 return Py_NotImplemented;
1735 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001736}
1737
1738static PyObject *delta_getstate(PyDateTime_Delta *self);
1739
1740static long
1741delta_hash(PyDateTime_Delta *self)
1742{
1743 if (self->hashcode == -1) {
1744 PyObject *temp = delta_getstate(self);
1745 if (temp != NULL) {
1746 self->hashcode = PyObject_Hash(temp);
1747 Py_DECREF(temp);
1748 }
1749 }
1750 return self->hashcode;
1751}
1752
1753static PyObject *
1754delta_multiply(PyObject *left, PyObject *right)
1755{
1756 PyObject *result = Py_NotImplemented;
1757
1758 if (PyDelta_Check(left)) {
1759 /* delta * ??? */
1760 if (PyInt_Check(right) || PyLong_Check(right))
1761 result = multiply_int_timedelta(right,
1762 (PyDateTime_Delta *) left);
1763 }
1764 else if (PyInt_Check(left) || PyLong_Check(left))
1765 result = multiply_int_timedelta(left,
1766 (PyDateTime_Delta *) right);
1767
1768 if (result == Py_NotImplemented)
1769 Py_INCREF(result);
1770 return result;
1771}
1772
1773static PyObject *
1774delta_divide(PyObject *left, PyObject *right)
1775{
1776 PyObject *result = Py_NotImplemented;
1777
1778 if (PyDelta_Check(left)) {
1779 /* delta * ??? */
1780 if (PyInt_Check(right) || PyLong_Check(right))
1781 result = divide_timedelta_int(
1782 (PyDateTime_Delta *)left,
1783 right);
1784 }
1785
1786 if (result == Py_NotImplemented)
1787 Py_INCREF(result);
1788 return result;
1789}
1790
1791/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1792 * timedelta constructor. sofar is the # of microseconds accounted for
1793 * so far, and there are factor microseconds per current unit, the number
1794 * of which is given by num. num * factor is added to sofar in a
1795 * numerically careful way, and that's the result. Any fractional
1796 * microseconds left over (this can happen if num is a float type) are
1797 * added into *leftover.
1798 * Note that there are many ways this can give an error (NULL) return.
1799 */
1800static PyObject *
1801accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1802 double *leftover)
1803{
1804 PyObject *prod;
1805 PyObject *sum;
1806
1807 assert(num != NULL);
1808
1809 if (PyInt_Check(num) || PyLong_Check(num)) {
1810 prod = PyNumber_Multiply(num, factor);
1811 if (prod == NULL)
1812 return NULL;
1813 sum = PyNumber_Add(sofar, prod);
1814 Py_DECREF(prod);
1815 return sum;
1816 }
1817
1818 if (PyFloat_Check(num)) {
1819 double dnum;
1820 double fracpart;
1821 double intpart;
1822 PyObject *x;
1823 PyObject *y;
1824
1825 /* The Plan: decompose num into an integer part and a
1826 * fractional part, num = intpart + fracpart.
1827 * Then num * factor ==
1828 * intpart * factor + fracpart * factor
1829 * and the LHS can be computed exactly in long arithmetic.
1830 * The RHS is again broken into an int part and frac part.
1831 * and the frac part is added into *leftover.
1832 */
1833 dnum = PyFloat_AsDouble(num);
1834 if (dnum == -1.0 && PyErr_Occurred())
1835 return NULL;
1836 fracpart = modf(dnum, &intpart);
1837 x = PyLong_FromDouble(intpart);
1838 if (x == NULL)
1839 return NULL;
1840
1841 prod = PyNumber_Multiply(x, factor);
1842 Py_DECREF(x);
1843 if (prod == NULL)
1844 return NULL;
1845
1846 sum = PyNumber_Add(sofar, prod);
1847 Py_DECREF(prod);
1848 if (sum == NULL)
1849 return NULL;
1850
1851 if (fracpart == 0.0)
1852 return sum;
1853 /* So far we've lost no information. Dealing with the
1854 * fractional part requires float arithmetic, and may
1855 * lose a little info.
1856 */
1857 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001858 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001859
1860 dnum *= fracpart;
1861 fracpart = modf(dnum, &intpart);
1862 x = PyLong_FromDouble(intpart);
1863 if (x == NULL) {
1864 Py_DECREF(sum);
1865 return NULL;
1866 }
1867
1868 y = PyNumber_Add(sum, x);
1869 Py_DECREF(sum);
1870 Py_DECREF(x);
1871 *leftover += fracpart;
1872 return y;
1873 }
1874
1875 PyErr_Format(PyExc_TypeError,
1876 "unsupported type for timedelta %s component: %s",
1877 tag, num->ob_type->tp_name);
1878 return NULL;
1879}
1880
1881static PyObject *
1882delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1883{
1884 PyObject *self = NULL;
1885
1886 /* Argument objects. */
1887 PyObject *day = NULL;
1888 PyObject *second = NULL;
1889 PyObject *us = NULL;
1890 PyObject *ms = NULL;
1891 PyObject *minute = NULL;
1892 PyObject *hour = NULL;
1893 PyObject *week = NULL;
1894
1895 PyObject *x = NULL; /* running sum of microseconds */
1896 PyObject *y = NULL; /* temp sum of microseconds */
1897 double leftover_us = 0.0;
1898
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001899 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001900 "days", "seconds", "microseconds", "milliseconds",
1901 "minutes", "hours", "weeks", NULL
1902 };
1903
1904 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1905 keywords,
1906 &day, &second, &us,
1907 &ms, &minute, &hour, &week) == 0)
1908 goto Done;
1909
1910 x = PyInt_FromLong(0);
1911 if (x == NULL)
1912 goto Done;
1913
1914#define CLEANUP \
1915 Py_DECREF(x); \
1916 x = y; \
1917 if (x == NULL) \
1918 goto Done
1919
1920 if (us) {
1921 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1922 CLEANUP;
1923 }
1924 if (ms) {
1925 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1926 CLEANUP;
1927 }
1928 if (second) {
1929 y = accum("seconds", x, second, us_per_second, &leftover_us);
1930 CLEANUP;
1931 }
1932 if (minute) {
1933 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1934 CLEANUP;
1935 }
1936 if (hour) {
1937 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1938 CLEANUP;
1939 }
1940 if (day) {
1941 y = accum("days", x, day, us_per_day, &leftover_us);
1942 CLEANUP;
1943 }
1944 if (week) {
1945 y = accum("weeks", x, week, us_per_week, &leftover_us);
1946 CLEANUP;
1947 }
1948 if (leftover_us) {
1949 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001950 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001951 if (temp == NULL) {
1952 Py_DECREF(x);
1953 goto Done;
1954 }
1955 y = PyNumber_Add(x, temp);
1956 Py_DECREF(temp);
1957 CLEANUP;
1958 }
1959
Tim Petersb0c854d2003-05-17 15:57:00 +00001960 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001961 Py_DECREF(x);
1962Done:
1963 return self;
1964
1965#undef CLEANUP
1966}
1967
1968static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001969delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001970{
1971 return (GET_TD_DAYS(self) != 0
1972 || GET_TD_SECONDS(self) != 0
1973 || GET_TD_MICROSECONDS(self) != 0);
1974}
1975
1976static PyObject *
1977delta_repr(PyDateTime_Delta *self)
1978{
1979 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001980 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001981 self->ob_type->tp_name,
1982 GET_TD_DAYS(self),
1983 GET_TD_SECONDS(self),
1984 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001985 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001986 return PyUnicode_FromFormat("%s(%d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001987 self->ob_type->tp_name,
1988 GET_TD_DAYS(self),
1989 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001990
Walter Dörwald1ab83302007-05-18 17:15:44 +00001991 return PyUnicode_FromFormat("%s(%d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001992 self->ob_type->tp_name,
1993 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001994}
1995
1996static PyObject *
1997delta_str(PyDateTime_Delta *self)
1998{
1999 int days = GET_TD_DAYS(self);
2000 int seconds = GET_TD_SECONDS(self);
2001 int us = GET_TD_MICROSECONDS(self);
2002 int hours;
2003 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00002004 char buf[100];
2005 char *pbuf = buf;
2006 size_t buflen = sizeof(buf);
2007 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002008
2009 minutes = divmod(seconds, 60, &seconds);
2010 hours = divmod(minutes, 60, &minutes);
2011
2012 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002013 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2014 (days == 1 || days == -1) ? "" : "s");
2015 if (n < 0 || (size_t)n >= buflen)
2016 goto Fail;
2017 pbuf += n;
2018 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002019 }
2020
Tim Petersba873472002-12-18 20:19:21 +00002021 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2022 hours, minutes, seconds);
2023 if (n < 0 || (size_t)n >= buflen)
2024 goto Fail;
2025 pbuf += n;
2026 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002027
2028 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002029 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2030 if (n < 0 || (size_t)n >= buflen)
2031 goto Fail;
2032 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002033 }
2034
Tim Petersba873472002-12-18 20:19:21 +00002035 return PyString_FromStringAndSize(buf, pbuf - buf);
2036
2037 Fail:
2038 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2039 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002040}
2041
Tim Peters371935f2003-02-01 01:52:50 +00002042/* Pickle support, a simple use of __reduce__. */
2043
Tim Petersb57f8f02003-02-01 02:54:15 +00002044/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002045static PyObject *
2046delta_getstate(PyDateTime_Delta *self)
2047{
2048 return Py_BuildValue("iii", GET_TD_DAYS(self),
2049 GET_TD_SECONDS(self),
2050 GET_TD_MICROSECONDS(self));
2051}
2052
Tim Peters2a799bf2002-12-16 20:18:38 +00002053static PyObject *
2054delta_reduce(PyDateTime_Delta* self)
2055{
Tim Peters8a60c222003-02-01 01:47:29 +00002056 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002057}
2058
2059#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2060
2061static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002062
Neal Norwitzdfb80862002-12-19 02:30:56 +00002063 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002064 PyDoc_STR("Number of days.")},
2065
Neal Norwitzdfb80862002-12-19 02:30:56 +00002066 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002067 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2068
Neal Norwitzdfb80862002-12-19 02:30:56 +00002069 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002070 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2071 {NULL}
2072};
2073
2074static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002075 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2076 PyDoc_STR("__reduce__() -> (cls, state)")},
2077
Tim Peters2a799bf2002-12-16 20:18:38 +00002078 {NULL, NULL},
2079};
2080
2081static char delta_doc[] =
2082PyDoc_STR("Difference between two datetime values.");
2083
2084static PyNumberMethods delta_as_number = {
2085 delta_add, /* nb_add */
2086 delta_subtract, /* nb_subtract */
2087 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002088 0, /* nb_remainder */
2089 0, /* nb_divmod */
2090 0, /* nb_power */
2091 (unaryfunc)delta_negative, /* nb_negative */
2092 (unaryfunc)delta_positive, /* nb_positive */
2093 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002094 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002095 0, /*nb_invert*/
2096 0, /*nb_lshift*/
2097 0, /*nb_rshift*/
2098 0, /*nb_and*/
2099 0, /*nb_xor*/
2100 0, /*nb_or*/
2101 0, /*nb_coerce*/
2102 0, /*nb_int*/
2103 0, /*nb_long*/
2104 0, /*nb_float*/
2105 0, /*nb_oct*/
2106 0, /*nb_hex*/
2107 0, /*nb_inplace_add*/
2108 0, /*nb_inplace_subtract*/
2109 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002110 0, /*nb_inplace_remainder*/
2111 0, /*nb_inplace_power*/
2112 0, /*nb_inplace_lshift*/
2113 0, /*nb_inplace_rshift*/
2114 0, /*nb_inplace_and*/
2115 0, /*nb_inplace_xor*/
2116 0, /*nb_inplace_or*/
2117 delta_divide, /* nb_floor_divide */
2118 0, /* nb_true_divide */
2119 0, /* nb_inplace_floor_divide */
2120 0, /* nb_inplace_true_divide */
2121};
2122
2123static PyTypeObject PyDateTime_DeltaType = {
2124 PyObject_HEAD_INIT(NULL)
2125 0, /* ob_size */
2126 "datetime.timedelta", /* tp_name */
2127 sizeof(PyDateTime_Delta), /* tp_basicsize */
2128 0, /* tp_itemsize */
2129 0, /* tp_dealloc */
2130 0, /* tp_print */
2131 0, /* tp_getattr */
2132 0, /* tp_setattr */
2133 0, /* tp_compare */
2134 (reprfunc)delta_repr, /* tp_repr */
2135 &delta_as_number, /* tp_as_number */
2136 0, /* tp_as_sequence */
2137 0, /* tp_as_mapping */
2138 (hashfunc)delta_hash, /* tp_hash */
2139 0, /* tp_call */
2140 (reprfunc)delta_str, /* tp_str */
2141 PyObject_GenericGetAttr, /* tp_getattro */
2142 0, /* tp_setattro */
2143 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002144 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002145 delta_doc, /* tp_doc */
2146 0, /* tp_traverse */
2147 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002148 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002149 0, /* tp_weaklistoffset */
2150 0, /* tp_iter */
2151 0, /* tp_iternext */
2152 delta_methods, /* tp_methods */
2153 delta_members, /* tp_members */
2154 0, /* tp_getset */
2155 0, /* tp_base */
2156 0, /* tp_dict */
2157 0, /* tp_descr_get */
2158 0, /* tp_descr_set */
2159 0, /* tp_dictoffset */
2160 0, /* tp_init */
2161 0, /* tp_alloc */
2162 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002163 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002164};
2165
2166/*
2167 * PyDateTime_Date implementation.
2168 */
2169
2170/* Accessor properties. */
2171
2172static PyObject *
2173date_year(PyDateTime_Date *self, void *unused)
2174{
2175 return PyInt_FromLong(GET_YEAR(self));
2176}
2177
2178static PyObject *
2179date_month(PyDateTime_Date *self, void *unused)
2180{
2181 return PyInt_FromLong(GET_MONTH(self));
2182}
2183
2184static PyObject *
2185date_day(PyDateTime_Date *self, void *unused)
2186{
2187 return PyInt_FromLong(GET_DAY(self));
2188}
2189
2190static PyGetSetDef date_getset[] = {
2191 {"year", (getter)date_year},
2192 {"month", (getter)date_month},
2193 {"day", (getter)date_day},
2194 {NULL}
2195};
2196
2197/* Constructors. */
2198
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002199static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002200
Tim Peters2a799bf2002-12-16 20:18:38 +00002201static PyObject *
2202date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2203{
2204 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002205 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002206 int year;
2207 int month;
2208 int day;
2209
Guido van Rossum177e41a2003-01-30 22:06:23 +00002210 /* Check for invocation from pickle with __getstate__ state */
2211 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002212 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002213 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2214 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002215 {
Tim Peters70533e22003-02-01 04:40:04 +00002216 PyDateTime_Date *me;
2217
Tim Peters604c0132004-06-07 23:04:33 +00002218 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002219 if (me != NULL) {
2220 char *pdata = PyString_AS_STRING(state);
2221 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2222 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002223 }
Tim Peters70533e22003-02-01 04:40:04 +00002224 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002225 }
2226
Tim Peters12bf3392002-12-24 05:41:27 +00002227 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002228 &year, &month, &day)) {
2229 if (check_date_args(year, month, day) < 0)
2230 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002231 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002232 }
2233 return self;
2234}
2235
2236/* Return new date from localtime(t). */
2237static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002238date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002239{
2240 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002241 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002242 PyObject *result = NULL;
2243
Tim Peters1b6f7a92004-06-20 02:50:16 +00002244 t = _PyTime_DoubleToTimet(ts);
2245 if (t == (time_t)-1 && PyErr_Occurred())
2246 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002247 tm = localtime(&t);
2248 if (tm)
2249 result = PyObject_CallFunction(cls, "iii",
2250 tm->tm_year + 1900,
2251 tm->tm_mon + 1,
2252 tm->tm_mday);
2253 else
2254 PyErr_SetString(PyExc_ValueError,
2255 "timestamp out of range for "
2256 "platform localtime() function");
2257 return result;
2258}
2259
2260/* Return new date from current time.
2261 * We say this is equivalent to fromtimestamp(time.time()), and the
2262 * only way to be sure of that is to *call* time.time(). That's not
2263 * generally the same as calling C's time.
2264 */
2265static PyObject *
2266date_today(PyObject *cls, PyObject *dummy)
2267{
2268 PyObject *time;
2269 PyObject *result;
2270
2271 time = time_time();
2272 if (time == NULL)
2273 return NULL;
2274
2275 /* Note well: today() is a class method, so this may not call
2276 * date.fromtimestamp. For example, it may call
2277 * datetime.fromtimestamp. That's why we need all the accuracy
2278 * time.time() delivers; if someone were gonzo about optimization,
2279 * date.today() could get away with plain C time().
2280 */
2281 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2282 Py_DECREF(time);
2283 return result;
2284}
2285
2286/* Return new date from given timestamp (Python timestamp -- a double). */
2287static PyObject *
2288date_fromtimestamp(PyObject *cls, PyObject *args)
2289{
2290 double timestamp;
2291 PyObject *result = NULL;
2292
2293 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002294 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002295 return result;
2296}
2297
2298/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2299 * the ordinal is out of range.
2300 */
2301static PyObject *
2302date_fromordinal(PyObject *cls, PyObject *args)
2303{
2304 PyObject *result = NULL;
2305 int ordinal;
2306
2307 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2308 int year;
2309 int month;
2310 int day;
2311
2312 if (ordinal < 1)
2313 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2314 ">= 1");
2315 else {
2316 ord_to_ymd(ordinal, &year, &month, &day);
2317 result = PyObject_CallFunction(cls, "iii",
2318 year, month, day);
2319 }
2320 }
2321 return result;
2322}
2323
2324/*
2325 * Date arithmetic.
2326 */
2327
2328/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2329 * instead.
2330 */
2331static PyObject *
2332add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2333{
2334 PyObject *result = NULL;
2335 int year = GET_YEAR(date);
2336 int month = GET_MONTH(date);
2337 int deltadays = GET_TD_DAYS(delta);
2338 /* C-level overflow is impossible because |deltadays| < 1e9. */
2339 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2340
2341 if (normalize_date(&year, &month, &day) >= 0)
2342 result = new_date(year, month, day);
2343 return result;
2344}
2345
2346static PyObject *
2347date_add(PyObject *left, PyObject *right)
2348{
2349 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2350 Py_INCREF(Py_NotImplemented);
2351 return Py_NotImplemented;
2352 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002353 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002354 /* date + ??? */
2355 if (PyDelta_Check(right))
2356 /* date + delta */
2357 return add_date_timedelta((PyDateTime_Date *) left,
2358 (PyDateTime_Delta *) right,
2359 0);
2360 }
2361 else {
2362 /* ??? + date
2363 * 'right' must be one of us, or we wouldn't have been called
2364 */
2365 if (PyDelta_Check(left))
2366 /* delta + date */
2367 return add_date_timedelta((PyDateTime_Date *) right,
2368 (PyDateTime_Delta *) left,
2369 0);
2370 }
2371 Py_INCREF(Py_NotImplemented);
2372 return Py_NotImplemented;
2373}
2374
2375static PyObject *
2376date_subtract(PyObject *left, PyObject *right)
2377{
2378 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2379 Py_INCREF(Py_NotImplemented);
2380 return Py_NotImplemented;
2381 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002382 if (PyDate_Check(left)) {
2383 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002384 /* date - date */
2385 int left_ord = ymd_to_ord(GET_YEAR(left),
2386 GET_MONTH(left),
2387 GET_DAY(left));
2388 int right_ord = ymd_to_ord(GET_YEAR(right),
2389 GET_MONTH(right),
2390 GET_DAY(right));
2391 return new_delta(left_ord - right_ord, 0, 0, 0);
2392 }
2393 if (PyDelta_Check(right)) {
2394 /* date - delta */
2395 return add_date_timedelta((PyDateTime_Date *) left,
2396 (PyDateTime_Delta *) right,
2397 1);
2398 }
2399 }
2400 Py_INCREF(Py_NotImplemented);
2401 return Py_NotImplemented;
2402}
2403
2404
2405/* Various ways to turn a date into a string. */
2406
2407static PyObject *
2408date_repr(PyDateTime_Date *self)
2409{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002410 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2411 self->ob_type->tp_name,
2412 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002413}
2414
2415static PyObject *
2416date_isoformat(PyDateTime_Date *self)
2417{
2418 char buffer[128];
2419
2420 isoformat_date(self, buffer, sizeof(buffer));
2421 return PyString_FromString(buffer);
2422}
2423
Tim Peterse2df5ff2003-05-02 18:39:55 +00002424/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002425static PyObject *
2426date_str(PyDateTime_Date *self)
2427{
2428 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2429}
2430
2431
2432static PyObject *
2433date_ctime(PyDateTime_Date *self)
2434{
2435 return format_ctime(self, 0, 0, 0);
2436}
2437
2438static PyObject *
2439date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2440{
2441 /* This method can be inherited, and needs to call the
2442 * timetuple() method appropriate to self's class.
2443 */
2444 PyObject *result;
2445 PyObject *format;
2446 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002447 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002448
Guido van Rossumbce56a62007-05-10 18:04:33 +00002449 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2450 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002451 return NULL;
2452
2453 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2454 if (tuple == NULL)
2455 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002456 result = wrap_strftime((PyObject *)self, format, tuple,
2457 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002458 Py_DECREF(tuple);
2459 return result;
2460}
2461
2462/* ISO methods. */
2463
2464static PyObject *
2465date_isoweekday(PyDateTime_Date *self)
2466{
2467 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2468
2469 return PyInt_FromLong(dow + 1);
2470}
2471
2472static PyObject *
2473date_isocalendar(PyDateTime_Date *self)
2474{
2475 int year = GET_YEAR(self);
2476 int week1_monday = iso_week1_monday(year);
2477 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2478 int week;
2479 int day;
2480
2481 week = divmod(today - week1_monday, 7, &day);
2482 if (week < 0) {
2483 --year;
2484 week1_monday = iso_week1_monday(year);
2485 week = divmod(today - week1_monday, 7, &day);
2486 }
2487 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2488 ++year;
2489 week = 0;
2490 }
2491 return Py_BuildValue("iii", year, week + 1, day + 1);
2492}
2493
2494/* Miscellaneous methods. */
2495
Tim Peters2a799bf2002-12-16 20:18:38 +00002496static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002497date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002498{
Guido van Rossum19960592006-08-24 17:29:38 +00002499 if (PyDate_Check(other)) {
2500 int diff = memcmp(((PyDateTime_Date *)self)->data,
2501 ((PyDateTime_Date *)other)->data,
2502 _PyDateTime_DATE_DATASIZE);
2503 return diff_to_bool(diff, op);
2504 }
2505 else {
Tim Peters07534a62003-02-07 22:50:28 +00002506 Py_INCREF(Py_NotImplemented);
2507 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002508 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002509}
2510
2511static PyObject *
2512date_timetuple(PyDateTime_Date *self)
2513{
2514 return build_struct_time(GET_YEAR(self),
2515 GET_MONTH(self),
2516 GET_DAY(self),
2517 0, 0, 0, -1);
2518}
2519
Tim Peters12bf3392002-12-24 05:41:27 +00002520static PyObject *
2521date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2522{
2523 PyObject *clone;
2524 PyObject *tuple;
2525 int year = GET_YEAR(self);
2526 int month = GET_MONTH(self);
2527 int day = GET_DAY(self);
2528
2529 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2530 &year, &month, &day))
2531 return NULL;
2532 tuple = Py_BuildValue("iii", year, month, day);
2533 if (tuple == NULL)
2534 return NULL;
2535 clone = date_new(self->ob_type, tuple, NULL);
2536 Py_DECREF(tuple);
2537 return clone;
2538}
2539
Tim Peters2a799bf2002-12-16 20:18:38 +00002540static PyObject *date_getstate(PyDateTime_Date *self);
2541
2542static long
2543date_hash(PyDateTime_Date *self)
2544{
2545 if (self->hashcode == -1) {
2546 PyObject *temp = date_getstate(self);
2547 if (temp != NULL) {
2548 self->hashcode = PyObject_Hash(temp);
2549 Py_DECREF(temp);
2550 }
2551 }
2552 return self->hashcode;
2553}
2554
2555static PyObject *
2556date_toordinal(PyDateTime_Date *self)
2557{
2558 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2559 GET_DAY(self)));
2560}
2561
2562static PyObject *
2563date_weekday(PyDateTime_Date *self)
2564{
2565 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2566
2567 return PyInt_FromLong(dow);
2568}
2569
Tim Peters371935f2003-02-01 01:52:50 +00002570/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002571
Tim Petersb57f8f02003-02-01 02:54:15 +00002572/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002573static PyObject *
2574date_getstate(PyDateTime_Date *self)
2575{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002576 return Py_BuildValue(
2577 "(N)",
2578 PyString_FromStringAndSize((char *)self->data,
2579 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002580}
2581
2582static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002583date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002584{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002585 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002586}
2587
2588static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002589
Tim Peters2a799bf2002-12-16 20:18:38 +00002590 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002591
Tim Peters2a799bf2002-12-16 20:18:38 +00002592 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2593 METH_CLASS,
2594 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2595 "time.time()).")},
2596
2597 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2598 METH_CLASS,
2599 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2600 "ordinal.")},
2601
2602 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2603 PyDoc_STR("Current date or datetime: same as "
2604 "self.__class__.fromtimestamp(time.time()).")},
2605
2606 /* Instance methods: */
2607
2608 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2609 PyDoc_STR("Return ctime() style string.")},
2610
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002611 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002612 PyDoc_STR("format -> strftime() style string.")},
2613
2614 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2615 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2616
2617 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2618 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2619 "weekday.")},
2620
2621 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2622 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2623
2624 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2625 PyDoc_STR("Return the day of the week represented by the date.\n"
2626 "Monday == 1 ... Sunday == 7")},
2627
2628 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2629 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2630 "1 is day 1.")},
2631
2632 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2633 PyDoc_STR("Return the day of the week represented by the date.\n"
2634 "Monday == 0 ... Sunday == 6")},
2635
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002636 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002637 PyDoc_STR("Return date with new specified fields.")},
2638
Guido van Rossum177e41a2003-01-30 22:06:23 +00002639 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2640 PyDoc_STR("__reduce__() -> (cls, state)")},
2641
Tim Peters2a799bf2002-12-16 20:18:38 +00002642 {NULL, NULL}
2643};
2644
2645static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002646PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002647
2648static PyNumberMethods date_as_number = {
2649 date_add, /* nb_add */
2650 date_subtract, /* nb_subtract */
2651 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002652 0, /* nb_remainder */
2653 0, /* nb_divmod */
2654 0, /* nb_power */
2655 0, /* nb_negative */
2656 0, /* nb_positive */
2657 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002658 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002659};
2660
2661static PyTypeObject PyDateTime_DateType = {
2662 PyObject_HEAD_INIT(NULL)
2663 0, /* ob_size */
2664 "datetime.date", /* tp_name */
2665 sizeof(PyDateTime_Date), /* tp_basicsize */
2666 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002667 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002668 0, /* tp_print */
2669 0, /* tp_getattr */
2670 0, /* tp_setattr */
2671 0, /* tp_compare */
2672 (reprfunc)date_repr, /* tp_repr */
2673 &date_as_number, /* tp_as_number */
2674 0, /* tp_as_sequence */
2675 0, /* tp_as_mapping */
2676 (hashfunc)date_hash, /* tp_hash */
2677 0, /* tp_call */
2678 (reprfunc)date_str, /* tp_str */
2679 PyObject_GenericGetAttr, /* tp_getattro */
2680 0, /* tp_setattro */
2681 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002682 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002683 date_doc, /* tp_doc */
2684 0, /* tp_traverse */
2685 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002686 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002687 0, /* tp_weaklistoffset */
2688 0, /* tp_iter */
2689 0, /* tp_iternext */
2690 date_methods, /* tp_methods */
2691 0, /* tp_members */
2692 date_getset, /* tp_getset */
2693 0, /* tp_base */
2694 0, /* tp_dict */
2695 0, /* tp_descr_get */
2696 0, /* tp_descr_set */
2697 0, /* tp_dictoffset */
2698 0, /* tp_init */
2699 0, /* tp_alloc */
2700 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002701 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002702};
2703
2704/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002705 * PyDateTime_TZInfo implementation.
2706 */
2707
2708/* This is a pure abstract base class, so doesn't do anything beyond
2709 * raising NotImplemented exceptions. Real tzinfo classes need
2710 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002711 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002712 * be subclasses of this tzinfo class, which is easy and quick to check).
2713 *
2714 * Note: For reasons having to do with pickling of subclasses, we have
2715 * to allow tzinfo objects to be instantiated. This wasn't an issue
2716 * in the Python implementation (__init__() could raise NotImplementedError
2717 * there without ill effect), but doing so in the C implementation hit a
2718 * brick wall.
2719 */
2720
2721static PyObject *
2722tzinfo_nogo(const char* methodname)
2723{
2724 PyErr_Format(PyExc_NotImplementedError,
2725 "a tzinfo subclass must implement %s()",
2726 methodname);
2727 return NULL;
2728}
2729
2730/* Methods. A subclass must implement these. */
2731
Tim Peters52dcce22003-01-23 16:36:11 +00002732static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002733tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2734{
2735 return tzinfo_nogo("tzname");
2736}
2737
Tim Peters52dcce22003-01-23 16:36:11 +00002738static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002739tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2740{
2741 return tzinfo_nogo("utcoffset");
2742}
2743
Tim Peters52dcce22003-01-23 16:36:11 +00002744static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002745tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2746{
2747 return tzinfo_nogo("dst");
2748}
2749
Tim Peters52dcce22003-01-23 16:36:11 +00002750static PyObject *
2751tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2752{
2753 int y, m, d, hh, mm, ss, us;
2754
2755 PyObject *result;
2756 int off, dst;
2757 int none;
2758 int delta;
2759
2760 if (! PyDateTime_Check(dt)) {
2761 PyErr_SetString(PyExc_TypeError,
2762 "fromutc: argument must be a datetime");
2763 return NULL;
2764 }
2765 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2766 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2767 "is not self");
2768 return NULL;
2769 }
2770
2771 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2772 if (off == -1 && PyErr_Occurred())
2773 return NULL;
2774 if (none) {
2775 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2776 "utcoffset() result required");
2777 return NULL;
2778 }
2779
2780 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2781 if (dst == -1 && PyErr_Occurred())
2782 return NULL;
2783 if (none) {
2784 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2785 "dst() result required");
2786 return NULL;
2787 }
2788
2789 y = GET_YEAR(dt);
2790 m = GET_MONTH(dt);
2791 d = GET_DAY(dt);
2792 hh = DATE_GET_HOUR(dt);
2793 mm = DATE_GET_MINUTE(dt);
2794 ss = DATE_GET_SECOND(dt);
2795 us = DATE_GET_MICROSECOND(dt);
2796
2797 delta = off - dst;
2798 mm += delta;
2799 if ((mm < 0 || mm >= 60) &&
2800 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002801 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002802 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2803 if (result == NULL)
2804 return result;
2805
2806 dst = call_dst(dt->tzinfo, result, &none);
2807 if (dst == -1 && PyErr_Occurred())
2808 goto Fail;
2809 if (none)
2810 goto Inconsistent;
2811 if (dst == 0)
2812 return result;
2813
2814 mm += dst;
2815 if ((mm < 0 || mm >= 60) &&
2816 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2817 goto Fail;
2818 Py_DECREF(result);
2819 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2820 return result;
2821
2822Inconsistent:
2823 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2824 "inconsistent results; cannot convert");
2825
2826 /* fall thru to failure */
2827Fail:
2828 Py_DECREF(result);
2829 return NULL;
2830}
2831
Tim Peters2a799bf2002-12-16 20:18:38 +00002832/*
2833 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002834 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002835 */
2836
Guido van Rossum177e41a2003-01-30 22:06:23 +00002837static PyObject *
2838tzinfo_reduce(PyObject *self)
2839{
2840 PyObject *args, *state, *tmp;
2841 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002842
Guido van Rossum177e41a2003-01-30 22:06:23 +00002843 tmp = PyTuple_New(0);
2844 if (tmp == NULL)
2845 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002846
Guido van Rossum177e41a2003-01-30 22:06:23 +00002847 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2848 if (getinitargs != NULL) {
2849 args = PyObject_CallObject(getinitargs, tmp);
2850 Py_DECREF(getinitargs);
2851 if (args == NULL) {
2852 Py_DECREF(tmp);
2853 return NULL;
2854 }
2855 }
2856 else {
2857 PyErr_Clear();
2858 args = tmp;
2859 Py_INCREF(args);
2860 }
2861
2862 getstate = PyObject_GetAttrString(self, "__getstate__");
2863 if (getstate != NULL) {
2864 state = PyObject_CallObject(getstate, tmp);
2865 Py_DECREF(getstate);
2866 if (state == NULL) {
2867 Py_DECREF(args);
2868 Py_DECREF(tmp);
2869 return NULL;
2870 }
2871 }
2872 else {
2873 PyObject **dictptr;
2874 PyErr_Clear();
2875 state = Py_None;
2876 dictptr = _PyObject_GetDictPtr(self);
2877 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2878 state = *dictptr;
2879 Py_INCREF(state);
2880 }
2881
2882 Py_DECREF(tmp);
2883
2884 if (state == Py_None) {
2885 Py_DECREF(state);
2886 return Py_BuildValue("(ON)", self->ob_type, args);
2887 }
2888 else
2889 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2890}
Tim Peters2a799bf2002-12-16 20:18:38 +00002891
2892static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002893
Tim Peters2a799bf2002-12-16 20:18:38 +00002894 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2895 PyDoc_STR("datetime -> string name of time zone.")},
2896
2897 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2898 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2899 "west of UTC).")},
2900
2901 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2902 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2903
Tim Peters52dcce22003-01-23 16:36:11 +00002904 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2905 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2906
Guido van Rossum177e41a2003-01-30 22:06:23 +00002907 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2908 PyDoc_STR("-> (cls, state)")},
2909
Tim Peters2a799bf2002-12-16 20:18:38 +00002910 {NULL, NULL}
2911};
2912
2913static char tzinfo_doc[] =
2914PyDoc_STR("Abstract base class for time zone info objects.");
2915
Neal Norwitz227b5332006-03-22 09:28:35 +00002916static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002917 PyObject_HEAD_INIT(NULL)
2918 0, /* ob_size */
2919 "datetime.tzinfo", /* tp_name */
2920 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2921 0, /* tp_itemsize */
2922 0, /* tp_dealloc */
2923 0, /* tp_print */
2924 0, /* tp_getattr */
2925 0, /* tp_setattr */
2926 0, /* tp_compare */
2927 0, /* tp_repr */
2928 0, /* tp_as_number */
2929 0, /* tp_as_sequence */
2930 0, /* tp_as_mapping */
2931 0, /* tp_hash */
2932 0, /* tp_call */
2933 0, /* tp_str */
2934 PyObject_GenericGetAttr, /* tp_getattro */
2935 0, /* tp_setattro */
2936 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002937 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002938 tzinfo_doc, /* tp_doc */
2939 0, /* tp_traverse */
2940 0, /* tp_clear */
2941 0, /* tp_richcompare */
2942 0, /* tp_weaklistoffset */
2943 0, /* tp_iter */
2944 0, /* tp_iternext */
2945 tzinfo_methods, /* tp_methods */
2946 0, /* tp_members */
2947 0, /* tp_getset */
2948 0, /* tp_base */
2949 0, /* tp_dict */
2950 0, /* tp_descr_get */
2951 0, /* tp_descr_set */
2952 0, /* tp_dictoffset */
2953 0, /* tp_init */
2954 0, /* tp_alloc */
2955 PyType_GenericNew, /* tp_new */
2956 0, /* tp_free */
2957};
2958
2959/*
Tim Peters37f39822003-01-10 03:49:02 +00002960 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002961 */
2962
Tim Peters37f39822003-01-10 03:49:02 +00002963/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002964 */
2965
2966static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002967time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002968{
Tim Peters37f39822003-01-10 03:49:02 +00002969 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002970}
2971
Tim Peters37f39822003-01-10 03:49:02 +00002972static PyObject *
2973time_minute(PyDateTime_Time *self, void *unused)
2974{
2975 return PyInt_FromLong(TIME_GET_MINUTE(self));
2976}
2977
2978/* The name time_second conflicted with some platform header file. */
2979static PyObject *
2980py_time_second(PyDateTime_Time *self, void *unused)
2981{
2982 return PyInt_FromLong(TIME_GET_SECOND(self));
2983}
2984
2985static PyObject *
2986time_microsecond(PyDateTime_Time *self, void *unused)
2987{
2988 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2989}
2990
2991static PyObject *
2992time_tzinfo(PyDateTime_Time *self, void *unused)
2993{
Tim Petersa032d2e2003-01-11 00:15:54 +00002994 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002995 Py_INCREF(result);
2996 return result;
2997}
2998
2999static PyGetSetDef time_getset[] = {
3000 {"hour", (getter)time_hour},
3001 {"minute", (getter)time_minute},
3002 {"second", (getter)py_time_second},
3003 {"microsecond", (getter)time_microsecond},
3004 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003005 {NULL}
3006};
3007
3008/*
3009 * Constructors.
3010 */
3011
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003012static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003013 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003014
Tim Peters2a799bf2002-12-16 20:18:38 +00003015static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003016time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003017{
3018 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003019 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003020 int hour = 0;
3021 int minute = 0;
3022 int second = 0;
3023 int usecond = 0;
3024 PyObject *tzinfo = Py_None;
3025
Guido van Rossum177e41a2003-01-30 22:06:23 +00003026 /* Check for invocation from pickle with __getstate__ state */
3027 if (PyTuple_GET_SIZE(args) >= 1 &&
3028 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003029 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003030 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3031 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003032 {
Tim Peters70533e22003-02-01 04:40:04 +00003033 PyDateTime_Time *me;
3034 char aware;
3035
3036 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003037 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003038 if (check_tzinfo_subclass(tzinfo) < 0) {
3039 PyErr_SetString(PyExc_TypeError, "bad "
3040 "tzinfo state arg");
3041 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003042 }
3043 }
Tim Peters70533e22003-02-01 04:40:04 +00003044 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003045 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003046 if (me != NULL) {
3047 char *pdata = PyString_AS_STRING(state);
3048
3049 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3050 me->hashcode = -1;
3051 me->hastzinfo = aware;
3052 if (aware) {
3053 Py_INCREF(tzinfo);
3054 me->tzinfo = tzinfo;
3055 }
3056 }
3057 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003058 }
3059
Tim Peters37f39822003-01-10 03:49:02 +00003060 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003061 &hour, &minute, &second, &usecond,
3062 &tzinfo)) {
3063 if (check_time_args(hour, minute, second, usecond) < 0)
3064 return NULL;
3065 if (check_tzinfo_subclass(tzinfo) < 0)
3066 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003067 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3068 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003069 }
3070 return self;
3071}
3072
3073/*
3074 * Destructor.
3075 */
3076
3077static void
Tim Peters37f39822003-01-10 03:49:02 +00003078time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003079{
Tim Petersa032d2e2003-01-11 00:15:54 +00003080 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003081 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003082 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003083 self->ob_type->tp_free((PyObject *)self);
3084}
3085
3086/*
Tim Peters855fe882002-12-22 03:43:39 +00003087 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003088 */
3089
Tim Peters2a799bf2002-12-16 20:18:38 +00003090/* These are all METH_NOARGS, so don't need to check the arglist. */
3091static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003092time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003093 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003094 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003095}
3096
3097static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003098time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003099 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003100 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003101}
3102
3103static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003104time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003105 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003106 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003107}
3108
3109/*
Tim Peters37f39822003-01-10 03:49:02 +00003110 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003111 */
3112
3113static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003114time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003115{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003116 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003117 int h = TIME_GET_HOUR(self);
3118 int m = TIME_GET_MINUTE(self);
3119 int s = TIME_GET_SECOND(self);
3120 int us = TIME_GET_MICROSECOND(self);
3121 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003122
Tim Peters37f39822003-01-10 03:49:02 +00003123 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003124 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3125 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003126 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003127 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3128 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003129 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003130 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003131 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003132 result = append_keyword_tzinfo(result, self->tzinfo);
3133 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003134}
3135
Tim Peters37f39822003-01-10 03:49:02 +00003136static PyObject *
3137time_str(PyDateTime_Time *self)
3138{
3139 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3140}
Tim Peters2a799bf2002-12-16 20:18:38 +00003141
3142static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003143time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003144{
3145 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003146 PyObject *result;
3147 /* Reuse the time format code from the datetime type. */
3148 PyDateTime_DateTime datetime;
3149 PyDateTime_DateTime *pdatetime = &datetime;
Tim Peters2a799bf2002-12-16 20:18:38 +00003150
Tim Peters37f39822003-01-10 03:49:02 +00003151 /* Copy over just the time bytes. */
3152 memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3153 self->data,
3154 _PyDateTime_TIME_DATASIZE);
3155
3156 isoformat_time(pdatetime, buf, sizeof(buf));
3157 result = PyString_FromString(buf);
Tim Petersa032d2e2003-01-11 00:15:54 +00003158 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003159 return result;
3160
3161 /* We need to append the UTC offset. */
3162 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003163 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003164 Py_DECREF(result);
3165 return NULL;
3166 }
3167 PyString_ConcatAndDel(&result, PyString_FromString(buf));
3168 return result;
3169}
3170
Tim Peters37f39822003-01-10 03:49:02 +00003171static PyObject *
3172time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3173{
3174 PyObject *result;
3175 PyObject *format;
3176 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003177 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003178
Guido van Rossumbce56a62007-05-10 18:04:33 +00003179 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3180 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003181 return NULL;
3182
3183 /* Python's strftime does insane things with the year part of the
3184 * timetuple. The year is forced to (the otherwise nonsensical)
3185 * 1900 to worm around that.
3186 */
3187 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003188 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003189 TIME_GET_HOUR(self),
3190 TIME_GET_MINUTE(self),
3191 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003192 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003193 if (tuple == NULL)
3194 return NULL;
3195 assert(PyTuple_Size(tuple) == 9);
3196 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3197 Py_DECREF(tuple);
3198 return result;
3199}
Tim Peters2a799bf2002-12-16 20:18:38 +00003200
3201/*
3202 * Miscellaneous methods.
3203 */
3204
Tim Peters37f39822003-01-10 03:49:02 +00003205static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003206time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003207{
3208 int diff;
3209 naivety n1, n2;
3210 int offset1, offset2;
3211
3212 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003213 Py_INCREF(Py_NotImplemented);
3214 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003215 }
Guido van Rossum19960592006-08-24 17:29:38 +00003216 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3217 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003218 return NULL;
3219 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3220 /* If they're both naive, or both aware and have the same offsets,
3221 * we get off cheap. Note that if they're both naive, offset1 ==
3222 * offset2 == 0 at this point.
3223 */
3224 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003225 diff = memcmp(((PyDateTime_Time *)self)->data,
3226 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003227 _PyDateTime_TIME_DATASIZE);
3228 return diff_to_bool(diff, op);
3229 }
3230
3231 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3232 assert(offset1 != offset2); /* else last "if" handled it */
3233 /* Convert everything except microseconds to seconds. These
3234 * can't overflow (no more than the # of seconds in 2 days).
3235 */
3236 offset1 = TIME_GET_HOUR(self) * 3600 +
3237 (TIME_GET_MINUTE(self) - offset1) * 60 +
3238 TIME_GET_SECOND(self);
3239 offset2 = TIME_GET_HOUR(other) * 3600 +
3240 (TIME_GET_MINUTE(other) - offset2) * 60 +
3241 TIME_GET_SECOND(other);
3242 diff = offset1 - offset2;
3243 if (diff == 0)
3244 diff = TIME_GET_MICROSECOND(self) -
3245 TIME_GET_MICROSECOND(other);
3246 return diff_to_bool(diff, op);
3247 }
3248
3249 assert(n1 != n2);
3250 PyErr_SetString(PyExc_TypeError,
3251 "can't compare offset-naive and "
3252 "offset-aware times");
3253 return NULL;
3254}
3255
3256static long
3257time_hash(PyDateTime_Time *self)
3258{
3259 if (self->hashcode == -1) {
3260 naivety n;
3261 int offset;
3262 PyObject *temp;
3263
3264 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3265 assert(n != OFFSET_UNKNOWN);
3266 if (n == OFFSET_ERROR)
3267 return -1;
3268
3269 /* Reduce this to a hash of another object. */
3270 if (offset == 0)
3271 temp = PyString_FromStringAndSize((char *)self->data,
3272 _PyDateTime_TIME_DATASIZE);
3273 else {
3274 int hour;
3275 int minute;
3276
3277 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003278 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003279 hour = divmod(TIME_GET_HOUR(self) * 60 +
3280 TIME_GET_MINUTE(self) - offset,
3281 60,
3282 &minute);
3283 if (0 <= hour && hour < 24)
3284 temp = new_time(hour, minute,
3285 TIME_GET_SECOND(self),
3286 TIME_GET_MICROSECOND(self),
3287 Py_None);
3288 else
3289 temp = Py_BuildValue("iiii",
3290 hour, minute,
3291 TIME_GET_SECOND(self),
3292 TIME_GET_MICROSECOND(self));
3293 }
3294 if (temp != NULL) {
3295 self->hashcode = PyObject_Hash(temp);
3296 Py_DECREF(temp);
3297 }
3298 }
3299 return self->hashcode;
3300}
Tim Peters2a799bf2002-12-16 20:18:38 +00003301
Tim Peters12bf3392002-12-24 05:41:27 +00003302static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003303time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003304{
3305 PyObject *clone;
3306 PyObject *tuple;
3307 int hh = TIME_GET_HOUR(self);
3308 int mm = TIME_GET_MINUTE(self);
3309 int ss = TIME_GET_SECOND(self);
3310 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003311 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003312
3313 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003314 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003315 &hh, &mm, &ss, &us, &tzinfo))
3316 return NULL;
3317 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3318 if (tuple == NULL)
3319 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003320 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003321 Py_DECREF(tuple);
3322 return clone;
3323}
3324
Tim Peters2a799bf2002-12-16 20:18:38 +00003325static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003326time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003327{
3328 int offset;
3329 int none;
3330
3331 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3332 /* Since utcoffset is in whole minutes, nothing can
3333 * alter the conclusion that this is nonzero.
3334 */
3335 return 1;
3336 }
3337 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003338 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003339 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003340 if (offset == -1 && PyErr_Occurred())
3341 return -1;
3342 }
3343 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3344}
3345
Tim Peters371935f2003-02-01 01:52:50 +00003346/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003347
Tim Peters33e0f382003-01-10 02:05:14 +00003348/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003349 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3350 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003351 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003352 */
3353static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003354time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003355{
3356 PyObject *basestate;
3357 PyObject *result = NULL;
3358
Tim Peters33e0f382003-01-10 02:05:14 +00003359 basestate = PyString_FromStringAndSize((char *)self->data,
3360 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003361 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003362 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003363 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003364 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003365 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003366 Py_DECREF(basestate);
3367 }
3368 return result;
3369}
3370
3371static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003372time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003373{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003374 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003375}
3376
Tim Peters37f39822003-01-10 03:49:02 +00003377static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003378
Thomas Wouterscf297e42007-02-23 15:07:44 +00003379 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003380 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3381 "[+HH:MM].")},
3382
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003383 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003384 PyDoc_STR("format -> strftime() style string.")},
3385
3386 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003387 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3388
Tim Peters37f39822003-01-10 03:49:02 +00003389 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003390 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3391
Tim Peters37f39822003-01-10 03:49:02 +00003392 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003393 PyDoc_STR("Return self.tzinfo.dst(self).")},
3394
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003395 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003396 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003397
Guido van Rossum177e41a2003-01-30 22:06:23 +00003398 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3399 PyDoc_STR("__reduce__() -> (cls, state)")},
3400
Tim Peters2a799bf2002-12-16 20:18:38 +00003401 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003402};
3403
Tim Peters37f39822003-01-10 03:49:02 +00003404static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003405PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3406\n\
3407All arguments are optional. tzinfo may be None, or an instance of\n\
3408a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003409
Tim Peters37f39822003-01-10 03:49:02 +00003410static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003411 0, /* nb_add */
3412 0, /* nb_subtract */
3413 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003414 0, /* nb_remainder */
3415 0, /* nb_divmod */
3416 0, /* nb_power */
3417 0, /* nb_negative */
3418 0, /* nb_positive */
3419 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003420 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003421};
3422
Neal Norwitz227b5332006-03-22 09:28:35 +00003423static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003424 PyObject_HEAD_INIT(NULL)
3425 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003426 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003427 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003429 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003430 0, /* tp_print */
3431 0, /* tp_getattr */
3432 0, /* tp_setattr */
3433 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003434 (reprfunc)time_repr, /* tp_repr */
3435 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003436 0, /* tp_as_sequence */
3437 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003438 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003439 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003440 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003441 PyObject_GenericGetAttr, /* tp_getattro */
3442 0, /* tp_setattro */
3443 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003444 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003445 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003446 0, /* tp_traverse */
3447 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003448 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003449 0, /* tp_weaklistoffset */
3450 0, /* tp_iter */
3451 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003452 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003453 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003454 time_getset, /* tp_getset */
3455 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003456 0, /* tp_dict */
3457 0, /* tp_descr_get */
3458 0, /* tp_descr_set */
3459 0, /* tp_dictoffset */
3460 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003461 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003462 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003463 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003464};
3465
3466/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003467 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003468 */
3469
Tim Petersa9bc1682003-01-11 03:39:11 +00003470/* Accessor properties. Properties for day, month, and year are inherited
3471 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003472 */
3473
3474static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003475datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003476{
Tim Petersa9bc1682003-01-11 03:39:11 +00003477 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003478}
3479
Tim Petersa9bc1682003-01-11 03:39:11 +00003480static PyObject *
3481datetime_minute(PyDateTime_DateTime *self, void *unused)
3482{
3483 return PyInt_FromLong(DATE_GET_MINUTE(self));
3484}
3485
3486static PyObject *
3487datetime_second(PyDateTime_DateTime *self, void *unused)
3488{
3489 return PyInt_FromLong(DATE_GET_SECOND(self));
3490}
3491
3492static PyObject *
3493datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3494{
3495 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3496}
3497
3498static PyObject *
3499datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3500{
3501 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3502 Py_INCREF(result);
3503 return result;
3504}
3505
3506static PyGetSetDef datetime_getset[] = {
3507 {"hour", (getter)datetime_hour},
3508 {"minute", (getter)datetime_minute},
3509 {"second", (getter)datetime_second},
3510 {"microsecond", (getter)datetime_microsecond},
3511 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003512 {NULL}
3513};
3514
3515/*
3516 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003517 */
3518
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003519static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003520 "year", "month", "day", "hour", "minute", "second",
3521 "microsecond", "tzinfo", NULL
3522};
3523
Tim Peters2a799bf2002-12-16 20:18:38 +00003524static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003525datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003526{
3527 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003528 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003529 int year;
3530 int month;
3531 int day;
3532 int hour = 0;
3533 int minute = 0;
3534 int second = 0;
3535 int usecond = 0;
3536 PyObject *tzinfo = Py_None;
3537
Guido van Rossum177e41a2003-01-30 22:06:23 +00003538 /* Check for invocation from pickle with __getstate__ state */
3539 if (PyTuple_GET_SIZE(args) >= 1 &&
3540 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003541 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003542 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3543 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003544 {
Tim Peters70533e22003-02-01 04:40:04 +00003545 PyDateTime_DateTime *me;
3546 char aware;
3547
3548 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003549 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003550 if (check_tzinfo_subclass(tzinfo) < 0) {
3551 PyErr_SetString(PyExc_TypeError, "bad "
3552 "tzinfo state arg");
3553 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003554 }
3555 }
Tim Peters70533e22003-02-01 04:40:04 +00003556 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003557 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003558 if (me != NULL) {
3559 char *pdata = PyString_AS_STRING(state);
3560
3561 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3562 me->hashcode = -1;
3563 me->hastzinfo = aware;
3564 if (aware) {
3565 Py_INCREF(tzinfo);
3566 me->tzinfo = tzinfo;
3567 }
3568 }
3569 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003570 }
3571
Tim Petersa9bc1682003-01-11 03:39:11 +00003572 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003573 &year, &month, &day, &hour, &minute,
3574 &second, &usecond, &tzinfo)) {
3575 if (check_date_args(year, month, day) < 0)
3576 return NULL;
3577 if (check_time_args(hour, minute, second, usecond) < 0)
3578 return NULL;
3579 if (check_tzinfo_subclass(tzinfo) < 0)
3580 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003581 self = new_datetime_ex(year, month, day,
3582 hour, minute, second, usecond,
3583 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003584 }
3585 return self;
3586}
3587
Tim Petersa9bc1682003-01-11 03:39:11 +00003588/* TM_FUNC is the shared type of localtime() and gmtime(). */
3589typedef struct tm *(*TM_FUNC)(const time_t *timer);
3590
3591/* Internal helper.
3592 * Build datetime from a time_t and a distinct count of microseconds.
3593 * Pass localtime or gmtime for f, to control the interpretation of timet.
3594 */
3595static PyObject *
3596datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3597 PyObject *tzinfo)
3598{
3599 struct tm *tm;
3600 PyObject *result = NULL;
3601
3602 tm = f(&timet);
3603 if (tm) {
3604 /* The platform localtime/gmtime may insert leap seconds,
3605 * indicated by tm->tm_sec > 59. We don't care about them,
3606 * except to the extent that passing them on to the datetime
3607 * constructor would raise ValueError for a reason that
3608 * made no sense to the user.
3609 */
3610 if (tm->tm_sec > 59)
3611 tm->tm_sec = 59;
3612 result = PyObject_CallFunction(cls, "iiiiiiiO",
3613 tm->tm_year + 1900,
3614 tm->tm_mon + 1,
3615 tm->tm_mday,
3616 tm->tm_hour,
3617 tm->tm_min,
3618 tm->tm_sec,
3619 us,
3620 tzinfo);
3621 }
3622 else
3623 PyErr_SetString(PyExc_ValueError,
3624 "timestamp out of range for "
3625 "platform localtime()/gmtime() function");
3626 return result;
3627}
3628
3629/* Internal helper.
3630 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3631 * to control the interpretation of the timestamp. Since a double doesn't
3632 * have enough bits to cover a datetime's full range of precision, it's
3633 * better to call datetime_from_timet_and_us provided you have a way
3634 * to get that much precision (e.g., C time() isn't good enough).
3635 */
3636static PyObject *
3637datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3638 PyObject *tzinfo)
3639{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003640 time_t timet;
3641 double fraction;
3642 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003643
Tim Peters1b6f7a92004-06-20 02:50:16 +00003644 timet = _PyTime_DoubleToTimet(timestamp);
3645 if (timet == (time_t)-1 && PyErr_Occurred())
3646 return NULL;
3647 fraction = timestamp - (double)timet;
3648 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003649 if (us < 0) {
3650 /* Truncation towards zero is not what we wanted
3651 for negative numbers (Python's mod semantics) */
3652 timet -= 1;
3653 us += 1000000;
3654 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003655 /* If timestamp is less than one microsecond smaller than a
3656 * full second, round up. Otherwise, ValueErrors are raised
3657 * for some floats. */
3658 if (us == 1000000) {
3659 timet += 1;
3660 us = 0;
3661 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003662 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3663}
3664
3665/* Internal helper.
3666 * Build most accurate possible datetime for current time. Pass localtime or
3667 * gmtime for f as appropriate.
3668 */
3669static PyObject *
3670datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3671{
3672#ifdef HAVE_GETTIMEOFDAY
3673 struct timeval t;
3674
3675#ifdef GETTIMEOFDAY_NO_TZ
3676 gettimeofday(&t);
3677#else
3678 gettimeofday(&t, (struct timezone *)NULL);
3679#endif
3680 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3681 tzinfo);
3682
3683#else /* ! HAVE_GETTIMEOFDAY */
3684 /* No flavor of gettimeofday exists on this platform. Python's
3685 * time.time() does a lot of other platform tricks to get the
3686 * best time it can on the platform, and we're not going to do
3687 * better than that (if we could, the better code would belong
3688 * in time.time()!) We're limited by the precision of a double,
3689 * though.
3690 */
3691 PyObject *time;
3692 double dtime;
3693
3694 time = time_time();
3695 if (time == NULL)
3696 return NULL;
3697 dtime = PyFloat_AsDouble(time);
3698 Py_DECREF(time);
3699 if (dtime == -1.0 && PyErr_Occurred())
3700 return NULL;
3701 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3702#endif /* ! HAVE_GETTIMEOFDAY */
3703}
3704
Tim Peters2a799bf2002-12-16 20:18:38 +00003705/* Return best possible local time -- this isn't constrained by the
3706 * precision of a timestamp.
3707 */
3708static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003709datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003710{
Tim Peters10cadce2003-01-23 19:58:02 +00003711 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003712 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003713 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003714
Tim Peters10cadce2003-01-23 19:58:02 +00003715 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3716 &tzinfo))
3717 return NULL;
3718 if (check_tzinfo_subclass(tzinfo) < 0)
3719 return NULL;
3720
3721 self = datetime_best_possible(cls,
3722 tzinfo == Py_None ? localtime : gmtime,
3723 tzinfo);
3724 if (self != NULL && tzinfo != Py_None) {
3725 /* Convert UTC to tzinfo's zone. */
3726 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003727 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003728 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003729 }
3730 return self;
3731}
3732
Tim Petersa9bc1682003-01-11 03:39:11 +00003733/* Return best possible UTC time -- this isn't constrained by the
3734 * precision of a timestamp.
3735 */
3736static PyObject *
3737datetime_utcnow(PyObject *cls, PyObject *dummy)
3738{
3739 return datetime_best_possible(cls, gmtime, Py_None);
3740}
3741
Tim Peters2a799bf2002-12-16 20:18:38 +00003742/* Return new local datetime from timestamp (Python timestamp -- a double). */
3743static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003744datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003745{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003746 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003747 double timestamp;
3748 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003749 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003750
Tim Peters2a44a8d2003-01-23 20:53:10 +00003751 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3752 keywords, &timestamp, &tzinfo))
3753 return NULL;
3754 if (check_tzinfo_subclass(tzinfo) < 0)
3755 return NULL;
3756
3757 self = datetime_from_timestamp(cls,
3758 tzinfo == Py_None ? localtime : gmtime,
3759 timestamp,
3760 tzinfo);
3761 if (self != NULL && tzinfo != Py_None) {
3762 /* Convert UTC to tzinfo's zone. */
3763 PyObject *temp = self;
3764 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3765 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003766 }
3767 return self;
3768}
3769
Tim Petersa9bc1682003-01-11 03:39:11 +00003770/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3771static PyObject *
3772datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3773{
3774 double timestamp;
3775 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003776
Tim Petersa9bc1682003-01-11 03:39:11 +00003777 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3778 result = datetime_from_timestamp(cls, gmtime, timestamp,
3779 Py_None);
3780 return result;
3781}
3782
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003783/* Return new datetime from time.strptime(). */
3784static PyObject *
3785datetime_strptime(PyObject *cls, PyObject *args)
3786{
3787 PyObject *result = NULL, *obj, *module;
3788 const char *string, *format;
3789
3790 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3791 return NULL;
3792
3793 if ((module = PyImport_ImportModule("time")) == NULL)
3794 return NULL;
3795 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3796 Py_DECREF(module);
3797
3798 if (obj != NULL) {
3799 int i, good_timetuple = 1;
3800 long int ia[6];
3801 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3802 for (i=0; i < 6; i++) {
3803 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003804 if (p == NULL) {
3805 Py_DECREF(obj);
3806 return NULL;
3807 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003808 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003809 ia[i] = PyInt_AsLong(p);
3810 else
3811 good_timetuple = 0;
3812 Py_DECREF(p);
3813 }
3814 else
3815 good_timetuple = 0;
3816 if (good_timetuple)
3817 result = PyObject_CallFunction(cls, "iiiiii",
3818 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3819 else
3820 PyErr_SetString(PyExc_ValueError,
3821 "unexpected value from time.strptime");
3822 Py_DECREF(obj);
3823 }
3824 return result;
3825}
3826
Tim Petersa9bc1682003-01-11 03:39:11 +00003827/* Return new datetime from date/datetime and time arguments. */
3828static PyObject *
3829datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3830{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003831 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003832 PyObject *date;
3833 PyObject *time;
3834 PyObject *result = NULL;
3835
3836 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3837 &PyDateTime_DateType, &date,
3838 &PyDateTime_TimeType, &time)) {
3839 PyObject *tzinfo = Py_None;
3840
3841 if (HASTZINFO(time))
3842 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3843 result = PyObject_CallFunction(cls, "iiiiiiiO",
3844 GET_YEAR(date),
3845 GET_MONTH(date),
3846 GET_DAY(date),
3847 TIME_GET_HOUR(time),
3848 TIME_GET_MINUTE(time),
3849 TIME_GET_SECOND(time),
3850 TIME_GET_MICROSECOND(time),
3851 tzinfo);
3852 }
3853 return result;
3854}
Tim Peters2a799bf2002-12-16 20:18:38 +00003855
3856/*
3857 * Destructor.
3858 */
3859
3860static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003861datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003862{
Tim Petersa9bc1682003-01-11 03:39:11 +00003863 if (HASTZINFO(self)) {
3864 Py_XDECREF(self->tzinfo);
3865 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003866 self->ob_type->tp_free((PyObject *)self);
3867}
3868
3869/*
3870 * Indirect access to tzinfo methods.
3871 */
3872
Tim Peters2a799bf2002-12-16 20:18:38 +00003873/* These are all METH_NOARGS, so don't need to check the arglist. */
3874static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003875datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3876 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3877 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003878}
3879
3880static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003881datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3882 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3883 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003884}
3885
3886static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003887datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3888 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3889 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003890}
3891
3892/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003893 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003894 */
3895
Tim Petersa9bc1682003-01-11 03:39:11 +00003896/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3897 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003898 */
3899static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003900add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3901 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003902{
Tim Petersa9bc1682003-01-11 03:39:11 +00003903 /* Note that the C-level additions can't overflow, because of
3904 * invariant bounds on the member values.
3905 */
3906 int year = GET_YEAR(date);
3907 int month = GET_MONTH(date);
3908 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3909 int hour = DATE_GET_HOUR(date);
3910 int minute = DATE_GET_MINUTE(date);
3911 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3912 int microsecond = DATE_GET_MICROSECOND(date) +
3913 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003914
Tim Petersa9bc1682003-01-11 03:39:11 +00003915 assert(factor == 1 || factor == -1);
3916 if (normalize_datetime(&year, &month, &day,
3917 &hour, &minute, &second, &microsecond) < 0)
3918 return NULL;
3919 else
3920 return new_datetime(year, month, day,
3921 hour, minute, second, microsecond,
3922 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003923}
3924
3925static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003926datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003927{
Tim Petersa9bc1682003-01-11 03:39:11 +00003928 if (PyDateTime_Check(left)) {
3929 /* datetime + ??? */
3930 if (PyDelta_Check(right))
3931 /* datetime + delta */
3932 return add_datetime_timedelta(
3933 (PyDateTime_DateTime *)left,
3934 (PyDateTime_Delta *)right,
3935 1);
3936 }
3937 else if (PyDelta_Check(left)) {
3938 /* delta + datetime */
3939 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3940 (PyDateTime_Delta *) left,
3941 1);
3942 }
3943 Py_INCREF(Py_NotImplemented);
3944 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003945}
3946
3947static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003948datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003949{
3950 PyObject *result = Py_NotImplemented;
3951
3952 if (PyDateTime_Check(left)) {
3953 /* datetime - ??? */
3954 if (PyDateTime_Check(right)) {
3955 /* datetime - datetime */
3956 naivety n1, n2;
3957 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003958 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003959
Tim Peterse39a80c2002-12-30 21:28:52 +00003960 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3961 right, &offset2, &n2,
3962 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003963 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003964 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003965 if (n1 != n2) {
3966 PyErr_SetString(PyExc_TypeError,
3967 "can't subtract offset-naive and "
3968 "offset-aware datetimes");
3969 return NULL;
3970 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003971 delta_d = ymd_to_ord(GET_YEAR(left),
3972 GET_MONTH(left),
3973 GET_DAY(left)) -
3974 ymd_to_ord(GET_YEAR(right),
3975 GET_MONTH(right),
3976 GET_DAY(right));
3977 /* These can't overflow, since the values are
3978 * normalized. At most this gives the number of
3979 * seconds in one day.
3980 */
3981 delta_s = (DATE_GET_HOUR(left) -
3982 DATE_GET_HOUR(right)) * 3600 +
3983 (DATE_GET_MINUTE(left) -
3984 DATE_GET_MINUTE(right)) * 60 +
3985 (DATE_GET_SECOND(left) -
3986 DATE_GET_SECOND(right));
3987 delta_us = DATE_GET_MICROSECOND(left) -
3988 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003989 /* (left - offset1) - (right - offset2) =
3990 * (left - right) + (offset2 - offset1)
3991 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003992 delta_s += (offset2 - offset1) * 60;
3993 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003994 }
3995 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003996 /* datetime - delta */
3997 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003998 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00003999 (PyDateTime_Delta *)right,
4000 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00004001 }
4002 }
4003
4004 if (result == Py_NotImplemented)
4005 Py_INCREF(result);
4006 return result;
4007}
4008
4009/* Various ways to turn a datetime into a string. */
4010
4011static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004012datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004013{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004014 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004015 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004016
Tim Petersa9bc1682003-01-11 03:39:11 +00004017 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004018 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004019 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004020 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004021 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4022 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4023 DATE_GET_SECOND(self),
4024 DATE_GET_MICROSECOND(self));
4025 }
4026 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004027 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004028 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004029 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004030 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4031 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4032 DATE_GET_SECOND(self));
4033 }
4034 else {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004035 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004036 "%s(%d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004037 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004038 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4039 DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4040 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004041 if (baserepr == NULL || ! HASTZINFO(self))
4042 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004043 return append_keyword_tzinfo(baserepr, self->tzinfo);
4044}
4045
Tim Petersa9bc1682003-01-11 03:39:11 +00004046static PyObject *
4047datetime_str(PyDateTime_DateTime *self)
4048{
4049 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4050}
Tim Peters2a799bf2002-12-16 20:18:38 +00004051
4052static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004053datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004054{
Tim Petersa9bc1682003-01-11 03:39:11 +00004055 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004056 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004057 char buffer[100];
4058 char *cp;
4059 PyObject *result;
Tim Peters2a799bf2002-12-16 20:18:38 +00004060
Tim Petersa9bc1682003-01-11 03:39:11 +00004061 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4062 &sep))
4063 return NULL;
4064 cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4065 assert(cp != NULL);
4066 *cp++ = sep;
4067 isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4068 result = PyString_FromString(buffer);
4069 if (result == NULL || ! HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004070 return result;
4071
4072 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004073 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004074 (PyObject *)self) < 0) {
4075 Py_DECREF(result);
4076 return NULL;
4077 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004078 PyString_ConcatAndDel(&result, PyString_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004079 return result;
4080}
4081
Tim Petersa9bc1682003-01-11 03:39:11 +00004082static PyObject *
4083datetime_ctime(PyDateTime_DateTime *self)
4084{
4085 return format_ctime((PyDateTime_Date *)self,
4086 DATE_GET_HOUR(self),
4087 DATE_GET_MINUTE(self),
4088 DATE_GET_SECOND(self));
4089}
4090
Tim Peters2a799bf2002-12-16 20:18:38 +00004091/* Miscellaneous methods. */
4092
Tim Petersa9bc1682003-01-11 03:39:11 +00004093static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004094datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004095{
4096 int diff;
4097 naivety n1, n2;
4098 int offset1, offset2;
4099
4100 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004101 if (PyDate_Check(other)) {
4102 /* Prevent invocation of date_richcompare. We want to
4103 return NotImplemented here to give the other object
4104 a chance. But since DateTime is a subclass of
4105 Date, if the other object is a Date, it would
4106 compute an ordering based on the date part alone,
4107 and we don't want that. So force unequal or
4108 uncomparable here in that case. */
4109 if (op == Py_EQ)
4110 Py_RETURN_FALSE;
4111 if (op == Py_NE)
4112 Py_RETURN_TRUE;
4113 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004114 }
Guido van Rossum19960592006-08-24 17:29:38 +00004115 Py_INCREF(Py_NotImplemented);
4116 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004117 }
4118
Guido van Rossum19960592006-08-24 17:29:38 +00004119 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4120 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004121 return NULL;
4122 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4123 /* If they're both naive, or both aware and have the same offsets,
4124 * we get off cheap. Note that if they're both naive, offset1 ==
4125 * offset2 == 0 at this point.
4126 */
4127 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004128 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4129 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004130 _PyDateTime_DATETIME_DATASIZE);
4131 return diff_to_bool(diff, op);
4132 }
4133
4134 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4135 PyDateTime_Delta *delta;
4136
4137 assert(offset1 != offset2); /* else last "if" handled it */
4138 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4139 other);
4140 if (delta == NULL)
4141 return NULL;
4142 diff = GET_TD_DAYS(delta);
4143 if (diff == 0)
4144 diff = GET_TD_SECONDS(delta) |
4145 GET_TD_MICROSECONDS(delta);
4146 Py_DECREF(delta);
4147 return diff_to_bool(diff, op);
4148 }
4149
4150 assert(n1 != n2);
4151 PyErr_SetString(PyExc_TypeError,
4152 "can't compare offset-naive and "
4153 "offset-aware datetimes");
4154 return NULL;
4155}
4156
4157static long
4158datetime_hash(PyDateTime_DateTime *self)
4159{
4160 if (self->hashcode == -1) {
4161 naivety n;
4162 int offset;
4163 PyObject *temp;
4164
4165 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4166 &offset);
4167 assert(n != OFFSET_UNKNOWN);
4168 if (n == OFFSET_ERROR)
4169 return -1;
4170
4171 /* Reduce this to a hash of another object. */
4172 if (n == OFFSET_NAIVE)
4173 temp = PyString_FromStringAndSize(
4174 (char *)self->data,
4175 _PyDateTime_DATETIME_DATASIZE);
4176 else {
4177 int days;
4178 int seconds;
4179
4180 assert(n == OFFSET_AWARE);
4181 assert(HASTZINFO(self));
4182 days = ymd_to_ord(GET_YEAR(self),
4183 GET_MONTH(self),
4184 GET_DAY(self));
4185 seconds = DATE_GET_HOUR(self) * 3600 +
4186 (DATE_GET_MINUTE(self) - offset) * 60 +
4187 DATE_GET_SECOND(self);
4188 temp = new_delta(days,
4189 seconds,
4190 DATE_GET_MICROSECOND(self),
4191 1);
4192 }
4193 if (temp != NULL) {
4194 self->hashcode = PyObject_Hash(temp);
4195 Py_DECREF(temp);
4196 }
4197 }
4198 return self->hashcode;
4199}
Tim Peters2a799bf2002-12-16 20:18:38 +00004200
4201static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004202datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004203{
4204 PyObject *clone;
4205 PyObject *tuple;
4206 int y = GET_YEAR(self);
4207 int m = GET_MONTH(self);
4208 int d = GET_DAY(self);
4209 int hh = DATE_GET_HOUR(self);
4210 int mm = DATE_GET_MINUTE(self);
4211 int ss = DATE_GET_SECOND(self);
4212 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004213 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004214
4215 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004216 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004217 &y, &m, &d, &hh, &mm, &ss, &us,
4218 &tzinfo))
4219 return NULL;
4220 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4221 if (tuple == NULL)
4222 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004223 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004224 Py_DECREF(tuple);
4225 return clone;
4226}
4227
4228static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004229datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004230{
Tim Peters52dcce22003-01-23 16:36:11 +00004231 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004232 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004233 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004234
Tim Peters80475bb2002-12-25 07:40:55 +00004235 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004236 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004237
Tim Peters52dcce22003-01-23 16:36:11 +00004238 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4239 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004240 return NULL;
4241
Tim Peters52dcce22003-01-23 16:36:11 +00004242 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4243 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004244
Tim Peters52dcce22003-01-23 16:36:11 +00004245 /* Conversion to self's own time zone is a NOP. */
4246 if (self->tzinfo == tzinfo) {
4247 Py_INCREF(self);
4248 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004249 }
Tim Peters521fc152002-12-31 17:36:56 +00004250
Tim Peters52dcce22003-01-23 16:36:11 +00004251 /* Convert self to UTC. */
4252 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4253 if (offset == -1 && PyErr_Occurred())
4254 return NULL;
4255 if (none)
4256 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004257
Tim Peters52dcce22003-01-23 16:36:11 +00004258 y = GET_YEAR(self);
4259 m = GET_MONTH(self);
4260 d = GET_DAY(self);
4261 hh = DATE_GET_HOUR(self);
4262 mm = DATE_GET_MINUTE(self);
4263 ss = DATE_GET_SECOND(self);
4264 us = DATE_GET_MICROSECOND(self);
4265
4266 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004267 if ((mm < 0 || mm >= 60) &&
4268 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004269 return NULL;
4270
4271 /* Attach new tzinfo and let fromutc() do the rest. */
4272 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4273 if (result != NULL) {
4274 PyObject *temp = result;
4275
4276 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4277 Py_DECREF(temp);
4278 }
Tim Petersadf64202003-01-04 06:03:15 +00004279 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004280
Tim Peters52dcce22003-01-23 16:36:11 +00004281NeedAware:
4282 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4283 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004284 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004285}
4286
4287static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004288datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004289{
4290 int dstflag = -1;
4291
Tim Petersa9bc1682003-01-11 03:39:11 +00004292 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004293 int none;
4294
4295 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4296 if (dstflag == -1 && PyErr_Occurred())
4297 return NULL;
4298
4299 if (none)
4300 dstflag = -1;
4301 else if (dstflag != 0)
4302 dstflag = 1;
4303
4304 }
4305 return build_struct_time(GET_YEAR(self),
4306 GET_MONTH(self),
4307 GET_DAY(self),
4308 DATE_GET_HOUR(self),
4309 DATE_GET_MINUTE(self),
4310 DATE_GET_SECOND(self),
4311 dstflag);
4312}
4313
4314static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004315datetime_getdate(PyDateTime_DateTime *self)
4316{
4317 return new_date(GET_YEAR(self),
4318 GET_MONTH(self),
4319 GET_DAY(self));
4320}
4321
4322static PyObject *
4323datetime_gettime(PyDateTime_DateTime *self)
4324{
4325 return new_time(DATE_GET_HOUR(self),
4326 DATE_GET_MINUTE(self),
4327 DATE_GET_SECOND(self),
4328 DATE_GET_MICROSECOND(self),
4329 Py_None);
4330}
4331
4332static PyObject *
4333datetime_gettimetz(PyDateTime_DateTime *self)
4334{
4335 return new_time(DATE_GET_HOUR(self),
4336 DATE_GET_MINUTE(self),
4337 DATE_GET_SECOND(self),
4338 DATE_GET_MICROSECOND(self),
4339 HASTZINFO(self) ? self->tzinfo : Py_None);
4340}
4341
4342static PyObject *
4343datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004344{
4345 int y = GET_YEAR(self);
4346 int m = GET_MONTH(self);
4347 int d = GET_DAY(self);
4348 int hh = DATE_GET_HOUR(self);
4349 int mm = DATE_GET_MINUTE(self);
4350 int ss = DATE_GET_SECOND(self);
4351 int us = 0; /* microseconds are ignored in a timetuple */
4352 int offset = 0;
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 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4358 if (offset == -1 && PyErr_Occurred())
4359 return NULL;
4360 }
4361 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4362 * 0 in a UTC timetuple regardless of what dst() says.
4363 */
4364 if (offset) {
4365 /* Subtract offset minutes & normalize. */
4366 int stat;
4367
4368 mm -= offset;
4369 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4370 if (stat < 0) {
4371 /* At the edges, it's possible we overflowed
4372 * beyond MINYEAR or MAXYEAR.
4373 */
4374 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4375 PyErr_Clear();
4376 else
4377 return NULL;
4378 }
4379 }
4380 return build_struct_time(y, m, d, hh, mm, ss, 0);
4381}
4382
Tim Peters371935f2003-02-01 01:52:50 +00004383/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004384
Tim Petersa9bc1682003-01-11 03:39:11 +00004385/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004386 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4387 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004388 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004389 */
4390static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004391datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004392{
4393 PyObject *basestate;
4394 PyObject *result = NULL;
4395
Tim Peters33e0f382003-01-10 02:05:14 +00004396 basestate = PyString_FromStringAndSize((char *)self->data,
4397 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004398 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004399 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004400 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004401 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004402 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004403 Py_DECREF(basestate);
4404 }
4405 return result;
4406}
4407
4408static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004409datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004410{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004411 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004412}
4413
Tim Petersa9bc1682003-01-11 03:39:11 +00004414static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004415
Tim Peters2a799bf2002-12-16 20:18:38 +00004416 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004417
Tim Petersa9bc1682003-01-11 03:39:11 +00004418 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004419 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004420 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004421
Tim Petersa9bc1682003-01-11 03:39:11 +00004422 {"utcnow", (PyCFunction)datetime_utcnow,
4423 METH_NOARGS | METH_CLASS,
4424 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4425
4426 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004427 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004428 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004429
Tim Petersa9bc1682003-01-11 03:39:11 +00004430 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4431 METH_VARARGS | METH_CLASS,
4432 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4433 "(like time.time()).")},
4434
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004435 {"strptime", (PyCFunction)datetime_strptime,
4436 METH_VARARGS | METH_CLASS,
4437 PyDoc_STR("string, format -> new datetime parsed from a string "
4438 "(like time.strptime()).")},
4439
Tim Petersa9bc1682003-01-11 03:39:11 +00004440 {"combine", (PyCFunction)datetime_combine,
4441 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4442 PyDoc_STR("date, time -> datetime with same date and time fields")},
4443
Tim Peters2a799bf2002-12-16 20:18:38 +00004444 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004445
Tim Petersa9bc1682003-01-11 03:39:11 +00004446 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4447 PyDoc_STR("Return date object with same year, month and day.")},
4448
4449 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4450 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4451
4452 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4453 PyDoc_STR("Return time object with same time and tzinfo.")},
4454
4455 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4456 PyDoc_STR("Return ctime() style string.")},
4457
4458 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004459 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4460
Tim Petersa9bc1682003-01-11 03:39:11 +00004461 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004462 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4463
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004464 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004465 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4466 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4467 "sep is used to separate the year from the time, and "
4468 "defaults to 'T'.")},
4469
Tim Petersa9bc1682003-01-11 03:39:11 +00004470 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004471 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4472
Tim Petersa9bc1682003-01-11 03:39:11 +00004473 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004474 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4475
Tim Petersa9bc1682003-01-11 03:39:11 +00004476 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004477 PyDoc_STR("Return self.tzinfo.dst(self).")},
4478
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004479 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004480 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004481
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004482 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004483 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4484
Guido van Rossum177e41a2003-01-30 22:06:23 +00004485 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4486 PyDoc_STR("__reduce__() -> (cls, state)")},
4487
Tim Peters2a799bf2002-12-16 20:18:38 +00004488 {NULL, NULL}
4489};
4490
Tim Petersa9bc1682003-01-11 03:39:11 +00004491static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004492PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4493\n\
4494The year, month and day arguments are required. tzinfo may be None, or an\n\
4495instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004496
Tim Petersa9bc1682003-01-11 03:39:11 +00004497static PyNumberMethods datetime_as_number = {
4498 datetime_add, /* nb_add */
4499 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004500 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004501 0, /* nb_remainder */
4502 0, /* nb_divmod */
4503 0, /* nb_power */
4504 0, /* nb_negative */
4505 0, /* nb_positive */
4506 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004507 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004508};
4509
Neal Norwitz227b5332006-03-22 09:28:35 +00004510static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004511 PyObject_HEAD_INIT(NULL)
4512 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004513 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004514 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004515 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004516 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004517 0, /* tp_print */
4518 0, /* tp_getattr */
4519 0, /* tp_setattr */
4520 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004521 (reprfunc)datetime_repr, /* tp_repr */
4522 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004523 0, /* tp_as_sequence */
4524 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004525 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004526 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004527 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004528 PyObject_GenericGetAttr, /* tp_getattro */
4529 0, /* tp_setattro */
4530 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004531 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004532 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004533 0, /* tp_traverse */
4534 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004535 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004536 0, /* tp_weaklistoffset */
4537 0, /* tp_iter */
4538 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004539 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004540 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004541 datetime_getset, /* tp_getset */
4542 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004543 0, /* tp_dict */
4544 0, /* tp_descr_get */
4545 0, /* tp_descr_set */
4546 0, /* tp_dictoffset */
4547 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004548 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004549 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004550 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004551};
4552
4553/* ---------------------------------------------------------------------------
4554 * Module methods and initialization.
4555 */
4556
4557static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004558 {NULL, NULL}
4559};
4560
Tim Peters9ddf40b2004-06-20 22:41:32 +00004561/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4562 * datetime.h.
4563 */
4564static PyDateTime_CAPI CAPI = {
4565 &PyDateTime_DateType,
4566 &PyDateTime_DateTimeType,
4567 &PyDateTime_TimeType,
4568 &PyDateTime_DeltaType,
4569 &PyDateTime_TZInfoType,
4570 new_date_ex,
4571 new_datetime_ex,
4572 new_time_ex,
4573 new_delta_ex,
4574 datetime_fromtimestamp,
4575 date_fromtimestamp
4576};
4577
4578
Tim Peters2a799bf2002-12-16 20:18:38 +00004579PyMODINIT_FUNC
4580initdatetime(void)
4581{
4582 PyObject *m; /* a module object */
4583 PyObject *d; /* its dict */
4584 PyObject *x;
4585
Tim Peters2a799bf2002-12-16 20:18:38 +00004586 m = Py_InitModule3("datetime", module_methods,
4587 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004588 if (m == NULL)
4589 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004590
4591 if (PyType_Ready(&PyDateTime_DateType) < 0)
4592 return;
4593 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4594 return;
4595 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4596 return;
4597 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4598 return;
4599 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4600 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004601
Tim Peters2a799bf2002-12-16 20:18:38 +00004602 /* timedelta values */
4603 d = PyDateTime_DeltaType.tp_dict;
4604
Tim Peters2a799bf2002-12-16 20:18:38 +00004605 x = new_delta(0, 0, 1, 0);
4606 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4607 return;
4608 Py_DECREF(x);
4609
4610 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4611 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4612 return;
4613 Py_DECREF(x);
4614
4615 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4616 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4617 return;
4618 Py_DECREF(x);
4619
4620 /* date values */
4621 d = PyDateTime_DateType.tp_dict;
4622
4623 x = new_date(1, 1, 1);
4624 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4625 return;
4626 Py_DECREF(x);
4627
4628 x = new_date(MAXYEAR, 12, 31);
4629 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4630 return;
4631 Py_DECREF(x);
4632
4633 x = new_delta(1, 0, 0, 0);
4634 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4635 return;
4636 Py_DECREF(x);
4637
Tim Peters37f39822003-01-10 03:49:02 +00004638 /* time values */
4639 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004640
Tim Peters37f39822003-01-10 03:49:02 +00004641 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004642 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4643 return;
4644 Py_DECREF(x);
4645
Tim Peters37f39822003-01-10 03:49:02 +00004646 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004647 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4648 return;
4649 Py_DECREF(x);
4650
4651 x = new_delta(0, 0, 1, 0);
4652 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4653 return;
4654 Py_DECREF(x);
4655
Tim Petersa9bc1682003-01-11 03:39:11 +00004656 /* datetime values */
4657 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004658
Tim Petersa9bc1682003-01-11 03:39:11 +00004659 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004660 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4661 return;
4662 Py_DECREF(x);
4663
Tim Petersa9bc1682003-01-11 03:39:11 +00004664 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004665 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4666 return;
4667 Py_DECREF(x);
4668
4669 x = new_delta(0, 0, 1, 0);
4670 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4671 return;
4672 Py_DECREF(x);
4673
Tim Peters2a799bf2002-12-16 20:18:38 +00004674 /* module initialization */
4675 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4676 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4677
4678 Py_INCREF(&PyDateTime_DateType);
4679 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4680
Tim Petersa9bc1682003-01-11 03:39:11 +00004681 Py_INCREF(&PyDateTime_DateTimeType);
4682 PyModule_AddObject(m, "datetime",
4683 (PyObject *)&PyDateTime_DateTimeType);
4684
4685 Py_INCREF(&PyDateTime_TimeType);
4686 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4687
Tim Peters2a799bf2002-12-16 20:18:38 +00004688 Py_INCREF(&PyDateTime_DeltaType);
4689 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4690
Tim Peters2a799bf2002-12-16 20:18:38 +00004691 Py_INCREF(&PyDateTime_TZInfoType);
4692 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4693
Tim Peters9ddf40b2004-06-20 22:41:32 +00004694 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4695 NULL);
4696 if (x == NULL)
4697 return;
4698 PyModule_AddObject(m, "datetime_CAPI", x);
4699
Tim Peters2a799bf2002-12-16 20:18:38 +00004700 /* A 4-year cycle has an extra leap day over what we'd get from
4701 * pasting together 4 single years.
4702 */
4703 assert(DI4Y == 4 * 365 + 1);
4704 assert(DI4Y == days_before_year(4+1));
4705
4706 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4707 * get from pasting together 4 100-year cycles.
4708 */
4709 assert(DI400Y == 4 * DI100Y + 1);
4710 assert(DI400Y == days_before_year(400+1));
4711
4712 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4713 * pasting together 25 4-year cycles.
4714 */
4715 assert(DI100Y == 25 * DI4Y - 1);
4716 assert(DI100Y == days_before_year(100+1));
4717
4718 us_per_us = PyInt_FromLong(1);
4719 us_per_ms = PyInt_FromLong(1000);
4720 us_per_second = PyInt_FromLong(1000000);
4721 us_per_minute = PyInt_FromLong(60000000);
4722 seconds_per_day = PyInt_FromLong(24 * 3600);
4723 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4724 us_per_minute == NULL || seconds_per_day == NULL)
4725 return;
4726
4727 /* The rest are too big for 32-bit ints, but even
4728 * us_per_week fits in 40 bits, so doubles should be exact.
4729 */
4730 us_per_hour = PyLong_FromDouble(3600000000.0);
4731 us_per_day = PyLong_FromDouble(86400000000.0);
4732 us_per_week = PyLong_FromDouble(604800000000.0);
4733 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4734 return;
4735}
Tim Petersf3615152003-01-01 21:51:37 +00004736
4737/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004738Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004739 x.n = x stripped of its timezone -- its naive time.
4740 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4741 return None
4742 x.d = x.dst(), and assuming that doesn't raise an exception or
4743 return None
4744 x.s = x's standard offset, x.o - x.d
4745
4746Now some derived rules, where k is a duration (timedelta).
4747
47481. x.o = x.s + x.d
4749 This follows from the definition of x.s.
4750
Tim Petersc5dc4da2003-01-02 17:55:03 +000047512. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004752 This is actually a requirement, an assumption we need to make about
4753 sane tzinfo classes.
4754
47553. The naive UTC time corresponding to x is x.n - x.o.
4756 This is again a requirement for a sane tzinfo class.
4757
47584. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004759 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004760
Tim Petersc5dc4da2003-01-02 17:55:03 +000047615. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004762 Again follows from how arithmetic is defined.
4763
Tim Peters8bb5ad22003-01-24 02:44:45 +00004764Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004765(meaning that the various tzinfo methods exist, and don't blow up or return
4766None when called).
4767
Tim Petersa9bc1682003-01-11 03:39:11 +00004768The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004769x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004770
4771By #3, we want
4772
Tim Peters8bb5ad22003-01-24 02:44:45 +00004773 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004774
4775The algorithm starts by attaching tz to x.n, and calling that y. So
4776x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4777becomes true; in effect, we want to solve [2] for k:
4778
Tim Peters8bb5ad22003-01-24 02:44:45 +00004779 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004780
4781By #1, this is the same as
4782
Tim Peters8bb5ad22003-01-24 02:44:45 +00004783 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004784
4785By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4786Substituting that into [3],
4787
Tim Peters8bb5ad22003-01-24 02:44:45 +00004788 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4789 k - (y+k).s - (y+k).d = 0; rearranging,
4790 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4791 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004792
Tim Peters8bb5ad22003-01-24 02:44:45 +00004793On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4794approximate k by ignoring the (y+k).d term at first. Note that k can't be
4795very large, since all offset-returning methods return a duration of magnitude
4796less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4797be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004798
4799In any case, the new value is
4800
Tim Peters8bb5ad22003-01-24 02:44:45 +00004801 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004802
Tim Peters8bb5ad22003-01-24 02:44:45 +00004803It's helpful to step back at look at [4] from a higher level: it's simply
4804mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004805
4806At this point, if
4807
Tim Peters8bb5ad22003-01-24 02:44:45 +00004808 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004809
4810we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004811at the start of daylight time. Picture US Eastern for concreteness. The wall
4812time 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 +00004813sense then. The docs ask that an Eastern tzinfo class consider such a time to
4814be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4815on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004816the only spelling that makes sense on the local wall clock.
4817
Tim Petersc5dc4da2003-01-02 17:55:03 +00004818In fact, if [5] holds at this point, we do have the standard-time spelling,
4819but that takes a bit of proof. We first prove a stronger result. What's the
4820difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004821
Tim Peters8bb5ad22003-01-24 02:44:45 +00004822 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004823
Tim Petersc5dc4da2003-01-02 17:55:03 +00004824Now
4825 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004826 (y + y.s).n = by #5
4827 y.n + y.s = since y.n = x.n
4828 x.n + y.s = since z and y are have the same tzinfo member,
4829 y.s = z.s by #2
4830 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004831
Tim Petersc5dc4da2003-01-02 17:55:03 +00004832Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004833
Tim Petersc5dc4da2003-01-02 17:55:03 +00004834 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004835 x.n - ((x.n + z.s) - z.o) = expanding
4836 x.n - x.n - z.s + z.o = cancelling
4837 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004838 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004839
Tim Petersc5dc4da2003-01-02 17:55:03 +00004840So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004841
Tim Petersc5dc4da2003-01-02 17:55:03 +00004842If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004843spelling we wanted in the endcase described above. We're done. Contrarily,
4844if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004845
Tim Petersc5dc4da2003-01-02 17:55:03 +00004846If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4847add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004848local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004849
Tim Petersc5dc4da2003-01-02 17:55:03 +00004850Let
Tim Petersf3615152003-01-01 21:51:37 +00004851
Tim Peters4fede1a2003-01-04 00:26:59 +00004852 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004853
Tim Peters4fede1a2003-01-04 00:26:59 +00004854and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004855
Tim Peters8bb5ad22003-01-24 02:44:45 +00004856 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004857
Tim Peters8bb5ad22003-01-24 02:44:45 +00004858If so, we're done. If not, the tzinfo class is insane, according to the
4859assumptions we've made. This also requires a bit of proof. As before, let's
4860compute the difference between the LHS and RHS of [8] (and skipping some of
4861the justifications for the kinds of substitutions we've done several times
4862already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004863
Tim Peters8bb5ad22003-01-24 02:44:45 +00004864 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4865 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4866 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4867 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4868 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004869 - z.o + z'.o = #1 twice
4870 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4871 z'.d - z.d
4872
4873So 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 +00004874we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4875return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004876
Tim Peters8bb5ad22003-01-24 02:44:45 +00004877How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4878a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4879would have to change the result dst() returns: we start in DST, and moving
4880a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004881
Tim Peters8bb5ad22003-01-24 02:44:45 +00004882There isn't a sane case where this can happen. The closest it gets is at
4883the end of DST, where there's an hour in UTC with no spelling in a hybrid
4884tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4885that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4886UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4887time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4888clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4889standard time. Since that's what the local clock *does*, we want to map both
4890UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004891in local time, but so it goes -- it's the way the local clock works.
4892
Tim Peters8bb5ad22003-01-24 02:44:45 +00004893When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4894so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4895z' = 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 +00004896(correctly) concludes that z' is not UTC-equivalent to x.
4897
4898Because we know z.d said z was in daylight time (else [5] would have held and
4899we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004900and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004901return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4902but the reasoning doesn't depend on the example -- it depends on there being
4903two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004904z' must be in standard time, and is the spelling we want in this case.
4905
4906Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4907concerned (because it takes z' as being in standard time rather than the
4908daylight time we intend here), but returning it gives the real-life "local
4909clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4910tz.
4911
4912When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4913the 1:MM standard time spelling we want.
4914
4915So how can this break? One of the assumptions must be violated. Two
4916possibilities:
4917
49181) [2] effectively says that y.s is invariant across all y belong to a given
4919 time zone. This isn't true if, for political reasons or continental drift,
4920 a region decides to change its base offset from UTC.
4921
49222) There may be versions of "double daylight" time where the tail end of
4923 the analysis gives up a step too early. I haven't thought about that
4924 enough to say.
4925
4926In any case, it's clear that the default fromutc() is strong enough to handle
4927"almost all" time zones: so long as the standard offset is invariant, it
4928doesn't matter if daylight time transition points change from year to year, or
4929if daylight time is skipped in some years; it doesn't matter how large or
4930small dst() may get within its bounds; and it doesn't even matter if some
4931perverse time zone returns a negative dst()). So a breaking case must be
4932pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004933--------------------------------------------------------------------------- */