blob: c355bb9424d2bbdf4f07ee7bb0edad300f420131 [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
Tim Peters2a799bf2002-12-16 20:18:38 +00001086 int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1087
Walter Dörwald4af32b32007-05-31 16:19:50 +00001088 return PyUnicode_FromFormat("%s %s %2d %02d:%02d:%02d %04d",
1089 DayNames[wday], MonthNames[GET_MONTH(date)-1],
1090 GET_DAY(date), hours, minutes, seconds,
1091 GET_YEAR(date));
Tim Peters2a799bf2002-12-16 20:18:38 +00001092}
1093
1094/* Add an hours & minutes UTC offset string to buf. buf has no more than
1095 * buflen bytes remaining. The UTC offset is gotten by calling
1096 * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
1097 * *buf, and that's all. Else the returned value is checked for sanity (an
1098 * integer in range), and if that's OK it's converted to an hours & minutes
1099 * string of the form
1100 * sign HH sep MM
1101 * Returns 0 if everything is OK. If the return value from utcoffset() is
1102 * bogus, an appropriate exception is set and -1 is returned.
1103 */
1104static int
Tim Peters328fff72002-12-20 01:31:27 +00001105format_utcoffset(char *buf, size_t buflen, const char *sep,
Tim Peters2a799bf2002-12-16 20:18:38 +00001106 PyObject *tzinfo, PyObject *tzinfoarg)
1107{
1108 int offset;
1109 int hours;
1110 int minutes;
1111 char sign;
1112 int none;
1113
1114 offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1115 if (offset == -1 && PyErr_Occurred())
1116 return -1;
1117 if (none) {
1118 *buf = '\0';
1119 return 0;
1120 }
1121 sign = '+';
1122 if (offset < 0) {
1123 sign = '-';
1124 offset = - offset;
1125 }
1126 hours = divmod(offset, 60, &minutes);
1127 PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1128 return 0;
1129}
1130
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001131static PyObject *
1132make_Zreplacement(PyObject *object, PyObject *tzinfoarg)
1133{
1134 PyObject *tzinfo = get_tzinfo_member(object);
1135 PyObject *Zreplacement = PyString_FromString("");
1136 if (Zreplacement == NULL)
1137 return NULL;
1138 if (tzinfo != Py_None && tzinfo != NULL) {
1139 PyObject *temp;
1140 assert(tzinfoarg != NULL);
1141 temp = call_tzname(tzinfo, tzinfoarg);
1142 if (temp == NULL)
1143 goto Error;
1144 if (temp != Py_None) {
1145 assert(PyUnicode_Check(temp));
1146 /* Since the tzname is getting stuffed into the
1147 * format, we have to double any % signs so that
1148 * strftime doesn't treat them as format codes.
1149 */
1150 Py_DECREF(Zreplacement);
1151 Zreplacement = PyObject_CallMethod(temp, "replace",
1152 "ss", "%", "%%");
1153 Py_DECREF(temp);
1154 if (Zreplacement == NULL)
1155 return NULL;
1156 if (PyUnicode_Check(Zreplacement)) {
1157 Zreplacement =
1158 _PyUnicode_AsDefaultEncodedString(
1159 Zreplacement, NULL);
1160 if (Zreplacement == NULL)
1161 return NULL;
1162 }
1163 if (!PyString_Check(Zreplacement)) {
1164 PyErr_SetString(PyExc_TypeError,
1165 "tzname.replace() did not return a string");
1166 goto Error;
1167 }
1168 }
1169 else
1170 Py_DECREF(temp);
1171 }
1172 return Zreplacement;
1173
1174 Error:
1175 Py_DECREF(Zreplacement);
1176 return NULL;
1177}
1178
Tim Peters2a799bf2002-12-16 20:18:38 +00001179/* I sure don't want to reproduce the strftime code from the time module,
1180 * so this imports the module and calls it. All the hair is due to
1181 * giving special meanings to the %z and %Z format codes via a preprocessing
1182 * step on the format string.
Tim Petersbad8ff02002-12-30 20:52:32 +00001183 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1184 * needed.
Tim Peters2a799bf2002-12-16 20:18:38 +00001185 */
1186static PyObject *
Tim Petersbad8ff02002-12-30 20:52:32 +00001187wrap_strftime(PyObject *object, PyObject *format, PyObject *timetuple,
1188 PyObject *tzinfoarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001189{
1190 PyObject *result = NULL; /* guilty until proved innocent */
1191
1192 PyObject *zreplacement = NULL; /* py string, replacement for %z */
1193 PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
1194
Guido van Rossumbce56a62007-05-10 18:04:33 +00001195 const char *pin;/* pointer to next char in input format */
1196 Py_ssize_t flen;/* length of input format */
Tim Peters2a799bf2002-12-16 20:18:38 +00001197 char ch; /* next char in input format */
1198
1199 PyObject *newfmt = NULL; /* py string, the output format */
1200 char *pnew; /* pointer to available byte in output format */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001201 int totalnew; /* number bytes total in output format buffer,
Tim Peters2a799bf2002-12-16 20:18:38 +00001202 exclusive of trailing \0 */
Thomas Wouters89f507f2006-12-13 04:49:30 +00001203 int usednew; /* number bytes used so far in output format buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001204
Guido van Rossumbce56a62007-05-10 18:04:33 +00001205 const char *ptoappend;/* pointer to string to append to output buffer */
Tim Peters2a799bf2002-12-16 20:18:38 +00001206 int ntoappend; /* # of bytes to append to output buffer */
1207
Tim Peters2a799bf2002-12-16 20:18:38 +00001208 assert(object && format && timetuple);
Guido van Rossumbce56a62007-05-10 18:04:33 +00001209 assert(PyString_Check(format) || PyUnicode_Check(format));
1210
1211 /* Convert the input format to a C string and size */
1212 if (PyObject_AsCharBuffer(format, &pin, &flen) < 0)
1213 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00001214
Tim Petersd6844152002-12-22 20:58:42 +00001215 /* Give up if the year is before 1900.
1216 * Python strftime() plays games with the year, and different
1217 * games depending on whether envar PYTHON2K is set. This makes
1218 * years before 1900 a nightmare, even if the platform strftime
1219 * supports them (and not all do).
1220 * We could get a lot farther here by avoiding Python's strftime
1221 * wrapper and calling the C strftime() directly, but that isn't
1222 * an option in the Python implementation of this module.
1223 */
1224 {
1225 long year;
1226 PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1227 if (pyyear == NULL) return NULL;
1228 assert(PyInt_Check(pyyear));
1229 year = PyInt_AsLong(pyyear);
1230 Py_DECREF(pyyear);
1231 if (year < 1900) {
1232 PyErr_Format(PyExc_ValueError, "year=%ld is before "
1233 "1900; the datetime strftime() "
1234 "methods require year >= 1900",
1235 year);
1236 return NULL;
1237 }
1238 }
1239
Tim Peters2a799bf2002-12-16 20:18:38 +00001240 /* Scan the input format, looking for %z and %Z escapes, building
Tim Peters328fff72002-12-20 01:31:27 +00001241 * a new format. Since computing the replacements for those codes
1242 * is expensive, don't unless they're actually used.
Tim Peters2a799bf2002-12-16 20:18:38 +00001243 */
Guido van Rossumbce56a62007-05-10 18:04:33 +00001244 totalnew = flen + 1; /* realistic if no %z/%Z */
Tim Peters2a799bf2002-12-16 20:18:38 +00001245 newfmt = PyString_FromStringAndSize(NULL, totalnew);
1246 if (newfmt == NULL) goto Done;
1247 pnew = PyString_AsString(newfmt);
1248 usednew = 0;
1249
Tim Peters2a799bf2002-12-16 20:18:38 +00001250 while ((ch = *pin++) != '\0') {
1251 if (ch != '%') {
Tim Peters328fff72002-12-20 01:31:27 +00001252 ptoappend = pin - 1;
Tim Peters2a799bf2002-12-16 20:18:38 +00001253 ntoappend = 1;
1254 }
1255 else if ((ch = *pin++) == '\0') {
1256 /* There's a lone trailing %; doesn't make sense. */
1257 PyErr_SetString(PyExc_ValueError, "strftime format "
1258 "ends with raw %");
1259 goto Done;
1260 }
1261 /* A % has been seen and ch is the character after it. */
1262 else if (ch == 'z') {
1263 if (zreplacement == NULL) {
1264 /* format utcoffset */
Tim Peters328fff72002-12-20 01:31:27 +00001265 char buf[100];
Tim Peters2a799bf2002-12-16 20:18:38 +00001266 PyObject *tzinfo = get_tzinfo_member(object);
1267 zreplacement = PyString_FromString("");
1268 if (zreplacement == NULL) goto Done;
1269 if (tzinfo != Py_None && tzinfo != NULL) {
Tim Petersbad8ff02002-12-30 20:52:32 +00001270 assert(tzinfoarg != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001271 if (format_utcoffset(buf,
Tim Peters328fff72002-12-20 01:31:27 +00001272 sizeof(buf),
Tim Peters2a799bf2002-12-16 20:18:38 +00001273 "",
1274 tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00001275 tzinfoarg) < 0)
Tim Peters2a799bf2002-12-16 20:18:38 +00001276 goto Done;
1277 Py_DECREF(zreplacement);
1278 zreplacement = PyString_FromString(buf);
1279 if (zreplacement == NULL) goto Done;
1280 }
1281 }
1282 assert(zreplacement != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001283 ptoappend = PyString_AS_STRING(zreplacement);
1284 ntoappend = PyString_GET_SIZE(zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001285 }
1286 else if (ch == 'Z') {
1287 /* format tzname */
1288 if (Zreplacement == NULL) {
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001289 Zreplacement = make_Zreplacement(object,
1290 tzinfoarg);
1291 if (Zreplacement == NULL)
1292 goto Done;
Tim Peters2a799bf2002-12-16 20:18:38 +00001293 }
1294 assert(Zreplacement != NULL);
Guido van Rossumd8595fe2007-05-23 21:36:49 +00001295 assert(PyString_Check(Zreplacement));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001296 ptoappend = PyString_AS_STRING(Zreplacement);
1297 ntoappend = PyString_GET_SIZE(Zreplacement);
Tim Peters2a799bf2002-12-16 20:18:38 +00001298 }
1299 else {
Tim Peters328fff72002-12-20 01:31:27 +00001300 /* percent followed by neither z nor Z */
1301 ptoappend = pin - 2;
Tim Peters2a799bf2002-12-16 20:18:38 +00001302 ntoappend = 2;
1303 }
1304
1305 /* Append the ntoappend chars starting at ptoappend to
1306 * the new format.
1307 */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001308 assert(ptoappend != NULL);
Tim Peters2a799bf2002-12-16 20:18:38 +00001309 assert(ntoappend >= 0);
1310 if (ntoappend == 0)
1311 continue;
1312 while (usednew + ntoappend > totalnew) {
1313 int bigger = totalnew << 1;
1314 if ((bigger >> 1) != totalnew) { /* overflow */
1315 PyErr_NoMemory();
1316 goto Done;
1317 }
1318 if (_PyString_Resize(&newfmt, bigger) < 0)
1319 goto Done;
1320 totalnew = bigger;
1321 pnew = PyString_AsString(newfmt) + usednew;
1322 }
1323 memcpy(pnew, ptoappend, ntoappend);
1324 pnew += ntoappend;
1325 usednew += ntoappend;
1326 assert(usednew <= totalnew);
1327 } /* end while() */
1328
1329 if (_PyString_Resize(&newfmt, usednew) < 0)
1330 goto Done;
1331 {
1332 PyObject *time = PyImport_ImportModule("time");
1333 if (time == NULL)
1334 goto Done;
1335 result = PyObject_CallMethod(time, "strftime", "OO",
1336 newfmt, timetuple);
1337 Py_DECREF(time);
1338 }
1339 Done:
1340 Py_XDECREF(zreplacement);
1341 Py_XDECREF(Zreplacement);
1342 Py_XDECREF(newfmt);
1343 return result;
1344}
1345
Tim Peters2a799bf2002-12-16 20:18:38 +00001346/* ---------------------------------------------------------------------------
1347 * Wrap functions from the time module. These aren't directly available
1348 * from C. Perhaps they should be.
1349 */
1350
1351/* Call time.time() and return its result (a Python float). */
1352static PyObject *
Guido van Rossumbd43e912002-12-16 20:34:55 +00001353time_time(void)
Tim Peters2a799bf2002-12-16 20:18:38 +00001354{
1355 PyObject *result = NULL;
1356 PyObject *time = PyImport_ImportModule("time");
1357
1358 if (time != NULL) {
1359 result = PyObject_CallMethod(time, "time", "()");
1360 Py_DECREF(time);
1361 }
1362 return result;
1363}
1364
1365/* Build a time.struct_time. The weekday and day number are automatically
1366 * computed from the y,m,d args.
1367 */
1368static PyObject *
1369build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1370{
1371 PyObject *time;
1372 PyObject *result = NULL;
1373
1374 time = PyImport_ImportModule("time");
1375 if (time != NULL) {
1376 result = PyObject_CallMethod(time, "struct_time",
1377 "((iiiiiiiii))",
1378 y, m, d,
1379 hh, mm, ss,
1380 weekday(y, m, d),
1381 days_before_month(y, m) + d,
1382 dstflag);
1383 Py_DECREF(time);
1384 }
1385 return result;
1386}
1387
1388/* ---------------------------------------------------------------------------
1389 * Miscellaneous helpers.
1390 */
1391
Guido van Rossum19960592006-08-24 17:29:38 +00001392/* For various reasons, we need to use tp_richcompare instead of tp_compare.
Tim Peters2a799bf2002-12-16 20:18:38 +00001393 * The comparisons here all most naturally compute a cmp()-like result.
1394 * This little helper turns that into a bool result for rich comparisons.
1395 */
1396static PyObject *
1397diff_to_bool(int diff, int op)
1398{
1399 PyObject *result;
1400 int istrue;
1401
1402 switch (op) {
1403 case Py_EQ: istrue = diff == 0; break;
1404 case Py_NE: istrue = diff != 0; break;
1405 case Py_LE: istrue = diff <= 0; break;
1406 case Py_GE: istrue = diff >= 0; break;
1407 case Py_LT: istrue = diff < 0; break;
1408 case Py_GT: istrue = diff > 0; break;
1409 default:
1410 assert(! "op unknown");
1411 istrue = 0; /* To shut up compiler */
1412 }
1413 result = istrue ? Py_True : Py_False;
1414 Py_INCREF(result);
1415 return result;
1416}
1417
Tim Peters07534a62003-02-07 22:50:28 +00001418/* Raises a "can't compare" TypeError and returns NULL. */
1419static PyObject *
1420cmperror(PyObject *a, PyObject *b)
1421{
1422 PyErr_Format(PyExc_TypeError,
1423 "can't compare %s to %s",
1424 a->ob_type->tp_name, b->ob_type->tp_name);
1425 return NULL;
1426}
1427
Tim Peters2a799bf2002-12-16 20:18:38 +00001428/* ---------------------------------------------------------------------------
Tim Peters2a799bf2002-12-16 20:18:38 +00001429 * Cached Python objects; these are set by the module init function.
1430 */
1431
1432/* Conversion factors. */
1433static PyObject *us_per_us = NULL; /* 1 */
1434static PyObject *us_per_ms = NULL; /* 1000 */
1435static PyObject *us_per_second = NULL; /* 1000000 */
1436static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
1437static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
1438static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
1439static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
1440static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1441
Tim Peters2a799bf2002-12-16 20:18:38 +00001442/* ---------------------------------------------------------------------------
1443 * Class implementations.
1444 */
1445
1446/*
1447 * PyDateTime_Delta implementation.
1448 */
1449
1450/* Convert a timedelta to a number of us,
1451 * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1452 * as a Python int or long.
1453 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1454 * due to ubiquitous overflow possibilities.
1455 */
1456static PyObject *
1457delta_to_microseconds(PyDateTime_Delta *self)
1458{
1459 PyObject *x1 = NULL;
1460 PyObject *x2 = NULL;
1461 PyObject *x3 = NULL;
1462 PyObject *result = NULL;
1463
1464 x1 = PyInt_FromLong(GET_TD_DAYS(self));
1465 if (x1 == NULL)
1466 goto Done;
1467 x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
1468 if (x2 == NULL)
1469 goto Done;
1470 Py_DECREF(x1);
1471 x1 = NULL;
1472
1473 /* x2 has days in seconds */
1474 x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
1475 if (x1 == NULL)
1476 goto Done;
1477 x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
1478 if (x3 == NULL)
1479 goto Done;
1480 Py_DECREF(x1);
1481 Py_DECREF(x2);
1482 x1 = x2 = NULL;
1483
1484 /* x3 has days+seconds in seconds */
1485 x1 = PyNumber_Multiply(x3, us_per_second); /* us */
1486 if (x1 == NULL)
1487 goto Done;
1488 Py_DECREF(x3);
1489 x3 = NULL;
1490
1491 /* x1 has days+seconds in us */
1492 x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1493 if (x2 == NULL)
1494 goto Done;
1495 result = PyNumber_Add(x1, x2);
1496
1497Done:
1498 Py_XDECREF(x1);
1499 Py_XDECREF(x2);
1500 Py_XDECREF(x3);
1501 return result;
1502}
1503
1504/* Convert a number of us (as a Python int or long) to a timedelta.
1505 */
1506static PyObject *
Tim Petersb0c854d2003-05-17 15:57:00 +00001507microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
Tim Peters2a799bf2002-12-16 20:18:38 +00001508{
1509 int us;
1510 int s;
1511 int d;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001512 long temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001513
1514 PyObject *tuple = NULL;
1515 PyObject *num = NULL;
1516 PyObject *result = NULL;
1517
1518 tuple = PyNumber_Divmod(pyus, us_per_second);
1519 if (tuple == NULL)
1520 goto Done;
1521
1522 num = PyTuple_GetItem(tuple, 1); /* us */
1523 if (num == NULL)
1524 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001525 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001526 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001527 if (temp == -1 && PyErr_Occurred())
1528 goto Done;
1529 assert(0 <= temp && temp < 1000000);
1530 us = (int)temp;
Tim Peters2a799bf2002-12-16 20:18:38 +00001531 if (us < 0) {
1532 /* The divisor was positive, so this must be an error. */
1533 assert(PyErr_Occurred());
1534 goto Done;
1535 }
1536
1537 num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
1538 if (num == NULL)
1539 goto Done;
1540 Py_INCREF(num);
1541 Py_DECREF(tuple);
1542
1543 tuple = PyNumber_Divmod(num, seconds_per_day);
1544 if (tuple == NULL)
1545 goto Done;
1546 Py_DECREF(num);
1547
1548 num = PyTuple_GetItem(tuple, 1); /* seconds */
1549 if (num == NULL)
1550 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001551 temp = PyLong_AsLong(num);
Tim Peters2a799bf2002-12-16 20:18:38 +00001552 num = NULL;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001553 if (temp == -1 && PyErr_Occurred())
1554 goto Done;
1555 assert(0 <= temp && temp < 24*3600);
1556 s = (int)temp;
1557
Tim Peters2a799bf2002-12-16 20:18:38 +00001558 if (s < 0) {
1559 /* The divisor was positive, so this must be an error. */
1560 assert(PyErr_Occurred());
1561 goto Done;
1562 }
1563
1564 num = PyTuple_GetItem(tuple, 0); /* leftover days */
1565 if (num == NULL)
1566 goto Done;
1567 Py_INCREF(num);
Tim Peters0b0f41c2002-12-19 01:44:38 +00001568 temp = PyLong_AsLong(num);
1569 if (temp == -1 && PyErr_Occurred())
Tim Peters2a799bf2002-12-16 20:18:38 +00001570 goto Done;
Tim Peters0b0f41c2002-12-19 01:44:38 +00001571 d = (int)temp;
1572 if ((long)d != temp) {
1573 PyErr_SetString(PyExc_OverflowError, "normalized days too "
1574 "large to fit in a C int");
1575 goto Done;
1576 }
Tim Petersb0c854d2003-05-17 15:57:00 +00001577 result = new_delta_ex(d, s, us, 0, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001578
1579Done:
1580 Py_XDECREF(tuple);
1581 Py_XDECREF(num);
1582 return result;
1583}
1584
Tim Petersb0c854d2003-05-17 15:57:00 +00001585#define microseconds_to_delta(pymicros) \
1586 microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1587
Tim Peters2a799bf2002-12-16 20:18:38 +00001588static PyObject *
1589multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1590{
1591 PyObject *pyus_in;
1592 PyObject *pyus_out;
1593 PyObject *result;
1594
1595 pyus_in = delta_to_microseconds(delta);
1596 if (pyus_in == NULL)
1597 return NULL;
1598
1599 pyus_out = PyNumber_Multiply(pyus_in, intobj);
1600 Py_DECREF(pyus_in);
1601 if (pyus_out == NULL)
1602 return NULL;
1603
1604 result = microseconds_to_delta(pyus_out);
1605 Py_DECREF(pyus_out);
1606 return result;
1607}
1608
1609static PyObject *
1610divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1611{
1612 PyObject *pyus_in;
1613 PyObject *pyus_out;
1614 PyObject *result;
1615
1616 pyus_in = delta_to_microseconds(delta);
1617 if (pyus_in == NULL)
1618 return NULL;
1619
1620 pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1621 Py_DECREF(pyus_in);
1622 if (pyus_out == NULL)
1623 return NULL;
1624
1625 result = microseconds_to_delta(pyus_out);
1626 Py_DECREF(pyus_out);
1627 return result;
1628}
1629
1630static PyObject *
1631delta_add(PyObject *left, PyObject *right)
1632{
1633 PyObject *result = Py_NotImplemented;
1634
1635 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1636 /* delta + delta */
1637 /* The C-level additions can't overflow because of the
1638 * invariant bounds.
1639 */
1640 int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1641 int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1642 int microseconds = GET_TD_MICROSECONDS(left) +
1643 GET_TD_MICROSECONDS(right);
1644 result = new_delta(days, seconds, microseconds, 1);
1645 }
1646
1647 if (result == Py_NotImplemented)
1648 Py_INCREF(result);
1649 return result;
1650}
1651
1652static PyObject *
1653delta_negative(PyDateTime_Delta *self)
1654{
1655 return new_delta(-GET_TD_DAYS(self),
1656 -GET_TD_SECONDS(self),
1657 -GET_TD_MICROSECONDS(self),
1658 1);
1659}
1660
1661static PyObject *
1662delta_positive(PyDateTime_Delta *self)
1663{
1664 /* Could optimize this (by returning self) if this isn't a
1665 * subclass -- but who uses unary + ? Approximately nobody.
1666 */
1667 return new_delta(GET_TD_DAYS(self),
1668 GET_TD_SECONDS(self),
1669 GET_TD_MICROSECONDS(self),
1670 0);
1671}
1672
1673static PyObject *
1674delta_abs(PyDateTime_Delta *self)
1675{
1676 PyObject *result;
1677
1678 assert(GET_TD_MICROSECONDS(self) >= 0);
1679 assert(GET_TD_SECONDS(self) >= 0);
1680
1681 if (GET_TD_DAYS(self) < 0)
1682 result = delta_negative(self);
1683 else
1684 result = delta_positive(self);
1685
1686 return result;
1687}
1688
1689static PyObject *
1690delta_subtract(PyObject *left, PyObject *right)
1691{
1692 PyObject *result = Py_NotImplemented;
1693
1694 if (PyDelta_Check(left) && PyDelta_Check(right)) {
1695 /* delta - delta */
1696 PyObject *minus_right = PyNumber_Negative(right);
1697 if (minus_right) {
1698 result = delta_add(left, minus_right);
1699 Py_DECREF(minus_right);
1700 }
1701 else
1702 result = NULL;
1703 }
1704
1705 if (result == Py_NotImplemented)
1706 Py_INCREF(result);
1707 return result;
1708}
1709
Tim Peters2a799bf2002-12-16 20:18:38 +00001710static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00001711delta_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00001712{
Tim Petersaa7d8492003-02-08 03:28:59 +00001713 if (PyDelta_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00001714 int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
Tim Peters07534a62003-02-07 22:50:28 +00001715 if (diff == 0) {
1716 diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1717 if (diff == 0)
1718 diff = GET_TD_MICROSECONDS(self) -
1719 GET_TD_MICROSECONDS(other);
1720 }
Guido van Rossum19960592006-08-24 17:29:38 +00001721 return diff_to_bool(diff, op);
Tim Peters2a799bf2002-12-16 20:18:38 +00001722 }
Guido van Rossum19960592006-08-24 17:29:38 +00001723 else {
1724 Py_INCREF(Py_NotImplemented);
1725 return Py_NotImplemented;
1726 }
Tim Peters2a799bf2002-12-16 20:18:38 +00001727}
1728
1729static PyObject *delta_getstate(PyDateTime_Delta *self);
1730
1731static long
1732delta_hash(PyDateTime_Delta *self)
1733{
1734 if (self->hashcode == -1) {
1735 PyObject *temp = delta_getstate(self);
1736 if (temp != NULL) {
1737 self->hashcode = PyObject_Hash(temp);
1738 Py_DECREF(temp);
1739 }
1740 }
1741 return self->hashcode;
1742}
1743
1744static PyObject *
1745delta_multiply(PyObject *left, PyObject *right)
1746{
1747 PyObject *result = Py_NotImplemented;
1748
1749 if (PyDelta_Check(left)) {
1750 /* delta * ??? */
1751 if (PyInt_Check(right) || PyLong_Check(right))
1752 result = multiply_int_timedelta(right,
1753 (PyDateTime_Delta *) left);
1754 }
1755 else if (PyInt_Check(left) || PyLong_Check(left))
1756 result = multiply_int_timedelta(left,
1757 (PyDateTime_Delta *) right);
1758
1759 if (result == Py_NotImplemented)
1760 Py_INCREF(result);
1761 return result;
1762}
1763
1764static PyObject *
1765delta_divide(PyObject *left, PyObject *right)
1766{
1767 PyObject *result = Py_NotImplemented;
1768
1769 if (PyDelta_Check(left)) {
1770 /* delta * ??? */
1771 if (PyInt_Check(right) || PyLong_Check(right))
1772 result = divide_timedelta_int(
1773 (PyDateTime_Delta *)left,
1774 right);
1775 }
1776
1777 if (result == Py_NotImplemented)
1778 Py_INCREF(result);
1779 return result;
1780}
1781
1782/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1783 * timedelta constructor. sofar is the # of microseconds accounted for
1784 * so far, and there are factor microseconds per current unit, the number
1785 * of which is given by num. num * factor is added to sofar in a
1786 * numerically careful way, and that's the result. Any fractional
1787 * microseconds left over (this can happen if num is a float type) are
1788 * added into *leftover.
1789 * Note that there are many ways this can give an error (NULL) return.
1790 */
1791static PyObject *
1792accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1793 double *leftover)
1794{
1795 PyObject *prod;
1796 PyObject *sum;
1797
1798 assert(num != NULL);
1799
1800 if (PyInt_Check(num) || PyLong_Check(num)) {
1801 prod = PyNumber_Multiply(num, factor);
1802 if (prod == NULL)
1803 return NULL;
1804 sum = PyNumber_Add(sofar, prod);
1805 Py_DECREF(prod);
1806 return sum;
1807 }
1808
1809 if (PyFloat_Check(num)) {
1810 double dnum;
1811 double fracpart;
1812 double intpart;
1813 PyObject *x;
1814 PyObject *y;
1815
1816 /* The Plan: decompose num into an integer part and a
1817 * fractional part, num = intpart + fracpart.
1818 * Then num * factor ==
1819 * intpart * factor + fracpart * factor
1820 * and the LHS can be computed exactly in long arithmetic.
1821 * The RHS is again broken into an int part and frac part.
1822 * and the frac part is added into *leftover.
1823 */
1824 dnum = PyFloat_AsDouble(num);
1825 if (dnum == -1.0 && PyErr_Occurred())
1826 return NULL;
1827 fracpart = modf(dnum, &intpart);
1828 x = PyLong_FromDouble(intpart);
1829 if (x == NULL)
1830 return NULL;
1831
1832 prod = PyNumber_Multiply(x, factor);
1833 Py_DECREF(x);
1834 if (prod == NULL)
1835 return NULL;
1836
1837 sum = PyNumber_Add(sofar, prod);
1838 Py_DECREF(prod);
1839 if (sum == NULL)
1840 return NULL;
1841
1842 if (fracpart == 0.0)
1843 return sum;
1844 /* So far we've lost no information. Dealing with the
1845 * fractional part requires float arithmetic, and may
1846 * lose a little info.
1847 */
1848 assert(PyInt_Check(factor) || PyLong_Check(factor));
Guido van Rossumddefaf32007-01-14 03:31:43 +00001849 dnum = PyLong_AsDouble(factor);
Tim Peters2a799bf2002-12-16 20:18:38 +00001850
1851 dnum *= fracpart;
1852 fracpart = modf(dnum, &intpart);
1853 x = PyLong_FromDouble(intpart);
1854 if (x == NULL) {
1855 Py_DECREF(sum);
1856 return NULL;
1857 }
1858
1859 y = PyNumber_Add(sum, x);
1860 Py_DECREF(sum);
1861 Py_DECREF(x);
1862 *leftover += fracpart;
1863 return y;
1864 }
1865
1866 PyErr_Format(PyExc_TypeError,
1867 "unsupported type for timedelta %s component: %s",
1868 tag, num->ob_type->tp_name);
1869 return NULL;
1870}
1871
1872static PyObject *
1873delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1874{
1875 PyObject *self = NULL;
1876
1877 /* Argument objects. */
1878 PyObject *day = NULL;
1879 PyObject *second = NULL;
1880 PyObject *us = NULL;
1881 PyObject *ms = NULL;
1882 PyObject *minute = NULL;
1883 PyObject *hour = NULL;
1884 PyObject *week = NULL;
1885
1886 PyObject *x = NULL; /* running sum of microseconds */
1887 PyObject *y = NULL; /* temp sum of microseconds */
1888 double leftover_us = 0.0;
1889
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00001890 static char *keywords[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00001891 "days", "seconds", "microseconds", "milliseconds",
1892 "minutes", "hours", "weeks", NULL
1893 };
1894
1895 if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1896 keywords,
1897 &day, &second, &us,
1898 &ms, &minute, &hour, &week) == 0)
1899 goto Done;
1900
1901 x = PyInt_FromLong(0);
1902 if (x == NULL)
1903 goto Done;
1904
1905#define CLEANUP \
1906 Py_DECREF(x); \
1907 x = y; \
1908 if (x == NULL) \
1909 goto Done
1910
1911 if (us) {
1912 y = accum("microseconds", x, us, us_per_us, &leftover_us);
1913 CLEANUP;
1914 }
1915 if (ms) {
1916 y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1917 CLEANUP;
1918 }
1919 if (second) {
1920 y = accum("seconds", x, second, us_per_second, &leftover_us);
1921 CLEANUP;
1922 }
1923 if (minute) {
1924 y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1925 CLEANUP;
1926 }
1927 if (hour) {
1928 y = accum("hours", x, hour, us_per_hour, &leftover_us);
1929 CLEANUP;
1930 }
1931 if (day) {
1932 y = accum("days", x, day, us_per_day, &leftover_us);
1933 CLEANUP;
1934 }
1935 if (week) {
1936 y = accum("weeks", x, week, us_per_week, &leftover_us);
1937 CLEANUP;
1938 }
1939 if (leftover_us) {
1940 /* Round to nearest whole # of us, and add into x. */
Tim Peters5d644dd2003-01-02 16:32:54 +00001941 PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
Tim Peters2a799bf2002-12-16 20:18:38 +00001942 if (temp == NULL) {
1943 Py_DECREF(x);
1944 goto Done;
1945 }
1946 y = PyNumber_Add(x, temp);
1947 Py_DECREF(temp);
1948 CLEANUP;
1949 }
1950
Tim Petersb0c854d2003-05-17 15:57:00 +00001951 self = microseconds_to_delta_ex(x, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00001952 Py_DECREF(x);
1953Done:
1954 return self;
1955
1956#undef CLEANUP
1957}
1958
1959static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00001960delta_bool(PyDateTime_Delta *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00001961{
1962 return (GET_TD_DAYS(self) != 0
1963 || GET_TD_SECONDS(self) != 0
1964 || GET_TD_MICROSECONDS(self) != 0);
1965}
1966
1967static PyObject *
1968delta_repr(PyDateTime_Delta *self)
1969{
1970 if (GET_TD_MICROSECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001971 return PyUnicode_FromFormat("%s(%d, %d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001972 self->ob_type->tp_name,
1973 GET_TD_DAYS(self),
1974 GET_TD_SECONDS(self),
1975 GET_TD_MICROSECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001976 if (GET_TD_SECONDS(self) != 0)
Walter Dörwald1ab83302007-05-18 17:15:44 +00001977 return PyUnicode_FromFormat("%s(%d, %d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001978 self->ob_type->tp_name,
1979 GET_TD_DAYS(self),
1980 GET_TD_SECONDS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001981
Walter Dörwald1ab83302007-05-18 17:15:44 +00001982 return PyUnicode_FromFormat("%s(%d)",
Walter Dörwald7569dfe2007-05-19 21:49:49 +00001983 self->ob_type->tp_name,
1984 GET_TD_DAYS(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00001985}
1986
1987static PyObject *
1988delta_str(PyDateTime_Delta *self)
1989{
1990 int days = GET_TD_DAYS(self);
1991 int seconds = GET_TD_SECONDS(self);
1992 int us = GET_TD_MICROSECONDS(self);
1993 int hours;
1994 int minutes;
Tim Petersba873472002-12-18 20:19:21 +00001995 char buf[100];
1996 char *pbuf = buf;
1997 size_t buflen = sizeof(buf);
1998 int n;
Tim Peters2a799bf2002-12-16 20:18:38 +00001999
2000 minutes = divmod(seconds, 60, &seconds);
2001 hours = divmod(minutes, 60, &minutes);
2002
2003 if (days) {
Tim Petersba873472002-12-18 20:19:21 +00002004 n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2005 (days == 1 || days == -1) ? "" : "s");
2006 if (n < 0 || (size_t)n >= buflen)
2007 goto Fail;
2008 pbuf += n;
2009 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002010 }
2011
Tim Petersba873472002-12-18 20:19:21 +00002012 n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2013 hours, minutes, seconds);
2014 if (n < 0 || (size_t)n >= buflen)
2015 goto Fail;
2016 pbuf += n;
2017 buflen -= (size_t)n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002018
2019 if (us) {
Tim Petersba873472002-12-18 20:19:21 +00002020 n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2021 if (n < 0 || (size_t)n >= buflen)
2022 goto Fail;
2023 pbuf += n;
Tim Peters2a799bf2002-12-16 20:18:38 +00002024 }
2025
Tim Petersba873472002-12-18 20:19:21 +00002026 return PyString_FromStringAndSize(buf, pbuf - buf);
2027
2028 Fail:
2029 PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2030 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002031}
2032
Tim Peters371935f2003-02-01 01:52:50 +00002033/* Pickle support, a simple use of __reduce__. */
2034
Tim Petersb57f8f02003-02-01 02:54:15 +00002035/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002036static PyObject *
2037delta_getstate(PyDateTime_Delta *self)
2038{
2039 return Py_BuildValue("iii", GET_TD_DAYS(self),
2040 GET_TD_SECONDS(self),
2041 GET_TD_MICROSECONDS(self));
2042}
2043
Tim Peters2a799bf2002-12-16 20:18:38 +00002044static PyObject *
2045delta_reduce(PyDateTime_Delta* self)
2046{
Tim Peters8a60c222003-02-01 01:47:29 +00002047 return Py_BuildValue("ON", self->ob_type, delta_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002048}
2049
2050#define OFFSET(field) offsetof(PyDateTime_Delta, field)
2051
2052static PyMemberDef delta_members[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002053
Neal Norwitzdfb80862002-12-19 02:30:56 +00002054 {"days", T_INT, OFFSET(days), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002055 PyDoc_STR("Number of days.")},
2056
Neal Norwitzdfb80862002-12-19 02:30:56 +00002057 {"seconds", T_INT, OFFSET(seconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002058 PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2059
Neal Norwitzdfb80862002-12-19 02:30:56 +00002060 {"microseconds", T_INT, OFFSET(microseconds), READONLY,
Tim Peters2a799bf2002-12-16 20:18:38 +00002061 PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2062 {NULL}
2063};
2064
2065static PyMethodDef delta_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002066 {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2067 PyDoc_STR("__reduce__() -> (cls, state)")},
2068
Tim Peters2a799bf2002-12-16 20:18:38 +00002069 {NULL, NULL},
2070};
2071
2072static char delta_doc[] =
2073PyDoc_STR("Difference between two datetime values.");
2074
2075static PyNumberMethods delta_as_number = {
2076 delta_add, /* nb_add */
2077 delta_subtract, /* nb_subtract */
2078 delta_multiply, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002079 0, /* nb_remainder */
2080 0, /* nb_divmod */
2081 0, /* nb_power */
2082 (unaryfunc)delta_negative, /* nb_negative */
2083 (unaryfunc)delta_positive, /* nb_positive */
2084 (unaryfunc)delta_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002085 (inquiry)delta_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002086 0, /*nb_invert*/
2087 0, /*nb_lshift*/
2088 0, /*nb_rshift*/
2089 0, /*nb_and*/
2090 0, /*nb_xor*/
2091 0, /*nb_or*/
2092 0, /*nb_coerce*/
2093 0, /*nb_int*/
2094 0, /*nb_long*/
2095 0, /*nb_float*/
2096 0, /*nb_oct*/
2097 0, /*nb_hex*/
2098 0, /*nb_inplace_add*/
2099 0, /*nb_inplace_subtract*/
2100 0, /*nb_inplace_multiply*/
Tim Peters2a799bf2002-12-16 20:18:38 +00002101 0, /*nb_inplace_remainder*/
2102 0, /*nb_inplace_power*/
2103 0, /*nb_inplace_lshift*/
2104 0, /*nb_inplace_rshift*/
2105 0, /*nb_inplace_and*/
2106 0, /*nb_inplace_xor*/
2107 0, /*nb_inplace_or*/
2108 delta_divide, /* nb_floor_divide */
2109 0, /* nb_true_divide */
2110 0, /* nb_inplace_floor_divide */
2111 0, /* nb_inplace_true_divide */
2112};
2113
2114static PyTypeObject PyDateTime_DeltaType = {
2115 PyObject_HEAD_INIT(NULL)
2116 0, /* ob_size */
2117 "datetime.timedelta", /* tp_name */
2118 sizeof(PyDateTime_Delta), /* tp_basicsize */
2119 0, /* tp_itemsize */
2120 0, /* tp_dealloc */
2121 0, /* tp_print */
2122 0, /* tp_getattr */
2123 0, /* tp_setattr */
2124 0, /* tp_compare */
2125 (reprfunc)delta_repr, /* tp_repr */
2126 &delta_as_number, /* tp_as_number */
2127 0, /* tp_as_sequence */
2128 0, /* tp_as_mapping */
2129 (hashfunc)delta_hash, /* tp_hash */
2130 0, /* tp_call */
2131 (reprfunc)delta_str, /* tp_str */
2132 PyObject_GenericGetAttr, /* tp_getattro */
2133 0, /* tp_setattro */
2134 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002135 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002136 delta_doc, /* tp_doc */
2137 0, /* tp_traverse */
2138 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002139 delta_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002140 0, /* tp_weaklistoffset */
2141 0, /* tp_iter */
2142 0, /* tp_iternext */
2143 delta_methods, /* tp_methods */
2144 delta_members, /* tp_members */
2145 0, /* tp_getset */
2146 0, /* tp_base */
2147 0, /* tp_dict */
2148 0, /* tp_descr_get */
2149 0, /* tp_descr_set */
2150 0, /* tp_dictoffset */
2151 0, /* tp_init */
2152 0, /* tp_alloc */
2153 delta_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002154 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002155};
2156
2157/*
2158 * PyDateTime_Date implementation.
2159 */
2160
2161/* Accessor properties. */
2162
2163static PyObject *
2164date_year(PyDateTime_Date *self, void *unused)
2165{
2166 return PyInt_FromLong(GET_YEAR(self));
2167}
2168
2169static PyObject *
2170date_month(PyDateTime_Date *self, void *unused)
2171{
2172 return PyInt_FromLong(GET_MONTH(self));
2173}
2174
2175static PyObject *
2176date_day(PyDateTime_Date *self, void *unused)
2177{
2178 return PyInt_FromLong(GET_DAY(self));
2179}
2180
2181static PyGetSetDef date_getset[] = {
2182 {"year", (getter)date_year},
2183 {"month", (getter)date_month},
2184 {"day", (getter)date_day},
2185 {NULL}
2186};
2187
2188/* Constructors. */
2189
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002190static char *date_kws[] = {"year", "month", "day", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00002191
Tim Peters2a799bf2002-12-16 20:18:38 +00002192static PyObject *
2193date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2194{
2195 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00002196 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00002197 int year;
2198 int month;
2199 int day;
2200
Guido van Rossum177e41a2003-01-30 22:06:23 +00002201 /* Check for invocation from pickle with __getstate__ state */
2202 if (PyTuple_GET_SIZE(args) == 1 &&
Tim Peters70533e22003-02-01 04:40:04 +00002203 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00002204 PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2205 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002206 {
Tim Peters70533e22003-02-01 04:40:04 +00002207 PyDateTime_Date *me;
2208
Tim Peters604c0132004-06-07 23:04:33 +00002209 me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
Tim Peters70533e22003-02-01 04:40:04 +00002210 if (me != NULL) {
2211 char *pdata = PyString_AS_STRING(state);
2212 memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2213 me->hashcode = -1;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002214 }
Tim Peters70533e22003-02-01 04:40:04 +00002215 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00002216 }
2217
Tim Peters12bf3392002-12-24 05:41:27 +00002218 if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00002219 &year, &month, &day)) {
2220 if (check_date_args(year, month, day) < 0)
2221 return NULL;
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002222 self = new_date_ex(year, month, day, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00002223 }
2224 return self;
2225}
2226
2227/* Return new date from localtime(t). */
2228static PyObject *
Tim Peters1b6f7a92004-06-20 02:50:16 +00002229date_local_from_time_t(PyObject *cls, double ts)
Tim Peters2a799bf2002-12-16 20:18:38 +00002230{
2231 struct tm *tm;
Tim Peters1b6f7a92004-06-20 02:50:16 +00002232 time_t t;
Tim Peters2a799bf2002-12-16 20:18:38 +00002233 PyObject *result = NULL;
2234
Tim Peters1b6f7a92004-06-20 02:50:16 +00002235 t = _PyTime_DoubleToTimet(ts);
2236 if (t == (time_t)-1 && PyErr_Occurred())
2237 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002238 tm = localtime(&t);
2239 if (tm)
2240 result = PyObject_CallFunction(cls, "iii",
2241 tm->tm_year + 1900,
2242 tm->tm_mon + 1,
2243 tm->tm_mday);
2244 else
2245 PyErr_SetString(PyExc_ValueError,
2246 "timestamp out of range for "
2247 "platform localtime() function");
2248 return result;
2249}
2250
2251/* Return new date from current time.
2252 * We say this is equivalent to fromtimestamp(time.time()), and the
2253 * only way to be sure of that is to *call* time.time(). That's not
2254 * generally the same as calling C's time.
2255 */
2256static PyObject *
2257date_today(PyObject *cls, PyObject *dummy)
2258{
2259 PyObject *time;
2260 PyObject *result;
2261
2262 time = time_time();
2263 if (time == NULL)
2264 return NULL;
2265
2266 /* Note well: today() is a class method, so this may not call
2267 * date.fromtimestamp. For example, it may call
2268 * datetime.fromtimestamp. That's why we need all the accuracy
2269 * time.time() delivers; if someone were gonzo about optimization,
2270 * date.today() could get away with plain C time().
2271 */
2272 result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2273 Py_DECREF(time);
2274 return result;
2275}
2276
2277/* Return new date from given timestamp (Python timestamp -- a double). */
2278static PyObject *
2279date_fromtimestamp(PyObject *cls, PyObject *args)
2280{
2281 double timestamp;
2282 PyObject *result = NULL;
2283
2284 if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
Tim Peters1b6f7a92004-06-20 02:50:16 +00002285 result = date_local_from_time_t(cls, timestamp);
Tim Peters2a799bf2002-12-16 20:18:38 +00002286 return result;
2287}
2288
2289/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
2290 * the ordinal is out of range.
2291 */
2292static PyObject *
2293date_fromordinal(PyObject *cls, PyObject *args)
2294{
2295 PyObject *result = NULL;
2296 int ordinal;
2297
2298 if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2299 int year;
2300 int month;
2301 int day;
2302
2303 if (ordinal < 1)
2304 PyErr_SetString(PyExc_ValueError, "ordinal must be "
2305 ">= 1");
2306 else {
2307 ord_to_ymd(ordinal, &year, &month, &day);
2308 result = PyObject_CallFunction(cls, "iii",
2309 year, month, day);
2310 }
2311 }
2312 return result;
2313}
2314
2315/*
2316 * Date arithmetic.
2317 */
2318
2319/* date + timedelta -> date. If arg negate is true, subtract the timedelta
2320 * instead.
2321 */
2322static PyObject *
2323add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2324{
2325 PyObject *result = NULL;
2326 int year = GET_YEAR(date);
2327 int month = GET_MONTH(date);
2328 int deltadays = GET_TD_DAYS(delta);
2329 /* C-level overflow is impossible because |deltadays| < 1e9. */
2330 int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2331
2332 if (normalize_date(&year, &month, &day) >= 0)
2333 result = new_date(year, month, day);
2334 return result;
2335}
2336
2337static PyObject *
2338date_add(PyObject *left, PyObject *right)
2339{
2340 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2341 Py_INCREF(Py_NotImplemented);
2342 return Py_NotImplemented;
2343 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002344 if (PyDate_Check(left)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002345 /* date + ??? */
2346 if (PyDelta_Check(right))
2347 /* date + delta */
2348 return add_date_timedelta((PyDateTime_Date *) left,
2349 (PyDateTime_Delta *) right,
2350 0);
2351 }
2352 else {
2353 /* ??? + date
2354 * 'right' must be one of us, or we wouldn't have been called
2355 */
2356 if (PyDelta_Check(left))
2357 /* delta + date */
2358 return add_date_timedelta((PyDateTime_Date *) right,
2359 (PyDateTime_Delta *) left,
2360 0);
2361 }
2362 Py_INCREF(Py_NotImplemented);
2363 return Py_NotImplemented;
2364}
2365
2366static PyObject *
2367date_subtract(PyObject *left, PyObject *right)
2368{
2369 if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2370 Py_INCREF(Py_NotImplemented);
2371 return Py_NotImplemented;
2372 }
Tim Petersaa7d8492003-02-08 03:28:59 +00002373 if (PyDate_Check(left)) {
2374 if (PyDate_Check(right)) {
Tim Peters2a799bf2002-12-16 20:18:38 +00002375 /* date - date */
2376 int left_ord = ymd_to_ord(GET_YEAR(left),
2377 GET_MONTH(left),
2378 GET_DAY(left));
2379 int right_ord = ymd_to_ord(GET_YEAR(right),
2380 GET_MONTH(right),
2381 GET_DAY(right));
2382 return new_delta(left_ord - right_ord, 0, 0, 0);
2383 }
2384 if (PyDelta_Check(right)) {
2385 /* date - delta */
2386 return add_date_timedelta((PyDateTime_Date *) left,
2387 (PyDateTime_Delta *) right,
2388 1);
2389 }
2390 }
2391 Py_INCREF(Py_NotImplemented);
2392 return Py_NotImplemented;
2393}
2394
2395
2396/* Various ways to turn a date into a string. */
2397
2398static PyObject *
2399date_repr(PyDateTime_Date *self)
2400{
Walter Dörwald7569dfe2007-05-19 21:49:49 +00002401 return PyUnicode_FromFormat("%s(%d, %d, %d)",
2402 self->ob_type->tp_name,
2403 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002404}
2405
2406static PyObject *
2407date_isoformat(PyDateTime_Date *self)
2408{
Walter Dörwaldbafa1372007-05-31 17:50:48 +00002409 return PyUnicode_FromFormat("%04d-%02d-%02d",
2410 GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002411}
2412
Tim Peterse2df5ff2003-05-02 18:39:55 +00002413/* str() calls the appropriate isoformat() method. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002414static PyObject *
2415date_str(PyDateTime_Date *self)
2416{
2417 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2418}
2419
2420
2421static PyObject *
2422date_ctime(PyDateTime_Date *self)
2423{
2424 return format_ctime(self, 0, 0, 0);
2425}
2426
2427static PyObject *
2428date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2429{
2430 /* This method can be inherited, and needs to call the
2431 * timetuple() method appropriate to self's class.
2432 */
2433 PyObject *result;
2434 PyObject *format;
2435 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00002436 static char *keywords[] = {"format", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00002437
Guido van Rossumbce56a62007-05-10 18:04:33 +00002438 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
2439 &format))
Tim Peters2a799bf2002-12-16 20:18:38 +00002440 return NULL;
2441
2442 tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2443 if (tuple == NULL)
2444 return NULL;
Tim Petersbad8ff02002-12-30 20:52:32 +00002445 result = wrap_strftime((PyObject *)self, format, tuple,
2446 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00002447 Py_DECREF(tuple);
2448 return result;
2449}
2450
2451/* ISO methods. */
2452
2453static PyObject *
2454date_isoweekday(PyDateTime_Date *self)
2455{
2456 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2457
2458 return PyInt_FromLong(dow + 1);
2459}
2460
2461static PyObject *
2462date_isocalendar(PyDateTime_Date *self)
2463{
2464 int year = GET_YEAR(self);
2465 int week1_monday = iso_week1_monday(year);
2466 int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2467 int week;
2468 int day;
2469
2470 week = divmod(today - week1_monday, 7, &day);
2471 if (week < 0) {
2472 --year;
2473 week1_monday = iso_week1_monday(year);
2474 week = divmod(today - week1_monday, 7, &day);
2475 }
2476 else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2477 ++year;
2478 week = 0;
2479 }
2480 return Py_BuildValue("iii", year, week + 1, day + 1);
2481}
2482
2483/* Miscellaneous methods. */
2484
Tim Peters2a799bf2002-12-16 20:18:38 +00002485static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00002486date_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters2a799bf2002-12-16 20:18:38 +00002487{
Guido van Rossum19960592006-08-24 17:29:38 +00002488 if (PyDate_Check(other)) {
2489 int diff = memcmp(((PyDateTime_Date *)self)->data,
2490 ((PyDateTime_Date *)other)->data,
2491 _PyDateTime_DATE_DATASIZE);
2492 return diff_to_bool(diff, op);
2493 }
2494 else {
Tim Peters07534a62003-02-07 22:50:28 +00002495 Py_INCREF(Py_NotImplemented);
2496 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00002497 }
Tim Peters2a799bf2002-12-16 20:18:38 +00002498}
2499
2500static PyObject *
2501date_timetuple(PyDateTime_Date *self)
2502{
2503 return build_struct_time(GET_YEAR(self),
2504 GET_MONTH(self),
2505 GET_DAY(self),
2506 0, 0, 0, -1);
2507}
2508
Tim Peters12bf3392002-12-24 05:41:27 +00002509static PyObject *
2510date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2511{
2512 PyObject *clone;
2513 PyObject *tuple;
2514 int year = GET_YEAR(self);
2515 int month = GET_MONTH(self);
2516 int day = GET_DAY(self);
2517
2518 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2519 &year, &month, &day))
2520 return NULL;
2521 tuple = Py_BuildValue("iii", year, month, day);
2522 if (tuple == NULL)
2523 return NULL;
2524 clone = date_new(self->ob_type, tuple, NULL);
2525 Py_DECREF(tuple);
2526 return clone;
2527}
2528
Tim Peters2a799bf2002-12-16 20:18:38 +00002529static PyObject *date_getstate(PyDateTime_Date *self);
2530
2531static long
2532date_hash(PyDateTime_Date *self)
2533{
2534 if (self->hashcode == -1) {
2535 PyObject *temp = date_getstate(self);
2536 if (temp != NULL) {
2537 self->hashcode = PyObject_Hash(temp);
2538 Py_DECREF(temp);
2539 }
2540 }
2541 return self->hashcode;
2542}
2543
2544static PyObject *
2545date_toordinal(PyDateTime_Date *self)
2546{
2547 return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2548 GET_DAY(self)));
2549}
2550
2551static PyObject *
2552date_weekday(PyDateTime_Date *self)
2553{
2554 int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2555
2556 return PyInt_FromLong(dow);
2557}
2558
Tim Peters371935f2003-02-01 01:52:50 +00002559/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00002560
Tim Petersb57f8f02003-02-01 02:54:15 +00002561/* __getstate__ isn't exposed */
Tim Peters2a799bf2002-12-16 20:18:38 +00002562static PyObject *
2563date_getstate(PyDateTime_Date *self)
2564{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002565 return Py_BuildValue(
2566 "(N)",
2567 PyString_FromStringAndSize((char *)self->data,
2568 _PyDateTime_DATE_DATASIZE));
Tim Peters2a799bf2002-12-16 20:18:38 +00002569}
2570
2571static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00002572date_reduce(PyDateTime_Date *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00002573{
Guido van Rossum177e41a2003-01-30 22:06:23 +00002574 return Py_BuildValue("(ON)", self->ob_type, date_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002575}
2576
2577static PyMethodDef date_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002578
Tim Peters2a799bf2002-12-16 20:18:38 +00002579 /* Class methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00002580
Tim Peters2a799bf2002-12-16 20:18:38 +00002581 {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2582 METH_CLASS,
2583 PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2584 "time.time()).")},
2585
2586 {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
2587 METH_CLASS,
2588 PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2589 "ordinal.")},
2590
2591 {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
2592 PyDoc_STR("Current date or datetime: same as "
2593 "self.__class__.fromtimestamp(time.time()).")},
2594
2595 /* Instance methods: */
2596
2597 {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
2598 PyDoc_STR("Return ctime() style string.")},
2599
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002600 {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00002601 PyDoc_STR("format -> strftime() style string.")},
2602
2603 {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
2604 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2605
2606 {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
2607 PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2608 "weekday.")},
2609
2610 {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
2611 PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2612
2613 {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
2614 PyDoc_STR("Return the day of the week represented by the date.\n"
2615 "Monday == 1 ... Sunday == 7")},
2616
2617 {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
2618 PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
2619 "1 is day 1.")},
2620
2621 {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
2622 PyDoc_STR("Return the day of the week represented by the date.\n"
2623 "Monday == 0 ... Sunday == 6")},
2624
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002625 {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters12bf3392002-12-24 05:41:27 +00002626 PyDoc_STR("Return date with new specified fields.")},
2627
Guido van Rossum177e41a2003-01-30 22:06:23 +00002628 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
2629 PyDoc_STR("__reduce__() -> (cls, state)")},
2630
Tim Peters2a799bf2002-12-16 20:18:38 +00002631 {NULL, NULL}
2632};
2633
2634static char date_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00002635PyDoc_STR("date(year, month, day) --> date object");
Tim Peters2a799bf2002-12-16 20:18:38 +00002636
2637static PyNumberMethods date_as_number = {
2638 date_add, /* nb_add */
2639 date_subtract, /* nb_subtract */
2640 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00002641 0, /* nb_remainder */
2642 0, /* nb_divmod */
2643 0, /* nb_power */
2644 0, /* nb_negative */
2645 0, /* nb_positive */
2646 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00002647 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00002648};
2649
2650static PyTypeObject PyDateTime_DateType = {
2651 PyObject_HEAD_INIT(NULL)
2652 0, /* ob_size */
2653 "datetime.date", /* tp_name */
2654 sizeof(PyDateTime_Date), /* tp_basicsize */
2655 0, /* tp_itemsize */
Guido van Rossum8b7a9a32003-04-14 22:01:58 +00002656 0, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00002657 0, /* tp_print */
2658 0, /* tp_getattr */
2659 0, /* tp_setattr */
2660 0, /* tp_compare */
2661 (reprfunc)date_repr, /* tp_repr */
2662 &date_as_number, /* tp_as_number */
2663 0, /* tp_as_sequence */
2664 0, /* tp_as_mapping */
2665 (hashfunc)date_hash, /* tp_hash */
2666 0, /* tp_call */
2667 (reprfunc)date_str, /* tp_str */
2668 PyObject_GenericGetAttr, /* tp_getattro */
2669 0, /* tp_setattro */
2670 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002671 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002672 date_doc, /* tp_doc */
2673 0, /* tp_traverse */
2674 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00002675 date_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00002676 0, /* tp_weaklistoffset */
2677 0, /* tp_iter */
2678 0, /* tp_iternext */
2679 date_methods, /* tp_methods */
2680 0, /* tp_members */
2681 date_getset, /* tp_getset */
2682 0, /* tp_base */
2683 0, /* tp_dict */
2684 0, /* tp_descr_get */
2685 0, /* tp_descr_set */
2686 0, /* tp_dictoffset */
2687 0, /* tp_init */
2688 0, /* tp_alloc */
2689 date_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00002690 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00002691};
2692
2693/*
Tim Peters2a799bf2002-12-16 20:18:38 +00002694 * PyDateTime_TZInfo implementation.
2695 */
2696
2697/* This is a pure abstract base class, so doesn't do anything beyond
2698 * raising NotImplemented exceptions. Real tzinfo classes need
2699 * to derive from this. This is mostly for clarity, and for efficiency in
Tim Petersa9bc1682003-01-11 03:39:11 +00002700 * datetime and time constructors (their tzinfo arguments need to
Tim Peters2a799bf2002-12-16 20:18:38 +00002701 * be subclasses of this tzinfo class, which is easy and quick to check).
2702 *
2703 * Note: For reasons having to do with pickling of subclasses, we have
2704 * to allow tzinfo objects to be instantiated. This wasn't an issue
2705 * in the Python implementation (__init__() could raise NotImplementedError
2706 * there without ill effect), but doing so in the C implementation hit a
2707 * brick wall.
2708 */
2709
2710static PyObject *
2711tzinfo_nogo(const char* methodname)
2712{
2713 PyErr_Format(PyExc_NotImplementedError,
2714 "a tzinfo subclass must implement %s()",
2715 methodname);
2716 return NULL;
2717}
2718
2719/* Methods. A subclass must implement these. */
2720
Tim Peters52dcce22003-01-23 16:36:11 +00002721static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002722tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2723{
2724 return tzinfo_nogo("tzname");
2725}
2726
Tim Peters52dcce22003-01-23 16:36:11 +00002727static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002728tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2729{
2730 return tzinfo_nogo("utcoffset");
2731}
2732
Tim Peters52dcce22003-01-23 16:36:11 +00002733static PyObject *
Tim Peters2a799bf2002-12-16 20:18:38 +00002734tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2735{
2736 return tzinfo_nogo("dst");
2737}
2738
Tim Peters52dcce22003-01-23 16:36:11 +00002739static PyObject *
2740tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2741{
2742 int y, m, d, hh, mm, ss, us;
2743
2744 PyObject *result;
2745 int off, dst;
2746 int none;
2747 int delta;
2748
2749 if (! PyDateTime_Check(dt)) {
2750 PyErr_SetString(PyExc_TypeError,
2751 "fromutc: argument must be a datetime");
2752 return NULL;
2753 }
2754 if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2755 PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2756 "is not self");
2757 return NULL;
2758 }
2759
2760 off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2761 if (off == -1 && PyErr_Occurred())
2762 return NULL;
2763 if (none) {
2764 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2765 "utcoffset() result required");
2766 return NULL;
2767 }
2768
2769 dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2770 if (dst == -1 && PyErr_Occurred())
2771 return NULL;
2772 if (none) {
2773 PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2774 "dst() result required");
2775 return NULL;
2776 }
2777
2778 y = GET_YEAR(dt);
2779 m = GET_MONTH(dt);
2780 d = GET_DAY(dt);
2781 hh = DATE_GET_HOUR(dt);
2782 mm = DATE_GET_MINUTE(dt);
2783 ss = DATE_GET_SECOND(dt);
2784 us = DATE_GET_MICROSECOND(dt);
2785
2786 delta = off - dst;
2787 mm += delta;
2788 if ((mm < 0 || mm >= 60) &&
2789 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Petersb1049e82003-01-23 17:20:36 +00002790 return NULL;
Tim Peters52dcce22003-01-23 16:36:11 +00002791 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2792 if (result == NULL)
2793 return result;
2794
2795 dst = call_dst(dt->tzinfo, result, &none);
2796 if (dst == -1 && PyErr_Occurred())
2797 goto Fail;
2798 if (none)
2799 goto Inconsistent;
2800 if (dst == 0)
2801 return result;
2802
2803 mm += dst;
2804 if ((mm < 0 || mm >= 60) &&
2805 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2806 goto Fail;
2807 Py_DECREF(result);
2808 result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2809 return result;
2810
2811Inconsistent:
2812 PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2813 "inconsistent results; cannot convert");
2814
2815 /* fall thru to failure */
2816Fail:
2817 Py_DECREF(result);
2818 return NULL;
2819}
2820
Tim Peters2a799bf2002-12-16 20:18:38 +00002821/*
2822 * Pickle support. This is solely so that tzinfo subclasses can use
Guido van Rossum177e41a2003-01-30 22:06:23 +00002823 * pickling -- tzinfo itself is supposed to be uninstantiable.
Tim Peters2a799bf2002-12-16 20:18:38 +00002824 */
2825
Guido van Rossum177e41a2003-01-30 22:06:23 +00002826static PyObject *
2827tzinfo_reduce(PyObject *self)
2828{
2829 PyObject *args, *state, *tmp;
2830 PyObject *getinitargs, *getstate;
Tim Peters2a799bf2002-12-16 20:18:38 +00002831
Guido van Rossum177e41a2003-01-30 22:06:23 +00002832 tmp = PyTuple_New(0);
2833 if (tmp == NULL)
2834 return NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00002835
Guido van Rossum177e41a2003-01-30 22:06:23 +00002836 getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2837 if (getinitargs != NULL) {
2838 args = PyObject_CallObject(getinitargs, tmp);
2839 Py_DECREF(getinitargs);
2840 if (args == NULL) {
2841 Py_DECREF(tmp);
2842 return NULL;
2843 }
2844 }
2845 else {
2846 PyErr_Clear();
2847 args = tmp;
2848 Py_INCREF(args);
2849 }
2850
2851 getstate = PyObject_GetAttrString(self, "__getstate__");
2852 if (getstate != NULL) {
2853 state = PyObject_CallObject(getstate, tmp);
2854 Py_DECREF(getstate);
2855 if (state == NULL) {
2856 Py_DECREF(args);
2857 Py_DECREF(tmp);
2858 return NULL;
2859 }
2860 }
2861 else {
2862 PyObject **dictptr;
2863 PyErr_Clear();
2864 state = Py_None;
2865 dictptr = _PyObject_GetDictPtr(self);
2866 if (dictptr && *dictptr && PyDict_Size(*dictptr))
2867 state = *dictptr;
2868 Py_INCREF(state);
2869 }
2870
2871 Py_DECREF(tmp);
2872
2873 if (state == Py_None) {
2874 Py_DECREF(state);
2875 return Py_BuildValue("(ON)", self->ob_type, args);
2876 }
2877 else
2878 return Py_BuildValue("(ONN)", self->ob_type, args, state);
2879}
Tim Peters2a799bf2002-12-16 20:18:38 +00002880
2881static PyMethodDef tzinfo_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00002882
Tim Peters2a799bf2002-12-16 20:18:38 +00002883 {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
2884 PyDoc_STR("datetime -> string name of time zone.")},
2885
2886 {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
2887 PyDoc_STR("datetime -> minutes east of UTC (negative for "
2888 "west of UTC).")},
2889
2890 {"dst", (PyCFunction)tzinfo_dst, METH_O,
2891 PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
2892
Tim Peters52dcce22003-01-23 16:36:11 +00002893 {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
2894 PyDoc_STR("datetime in UTC -> datetime in local time.")},
2895
Guido van Rossum177e41a2003-01-30 22:06:23 +00002896 {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
2897 PyDoc_STR("-> (cls, state)")},
2898
Tim Peters2a799bf2002-12-16 20:18:38 +00002899 {NULL, NULL}
2900};
2901
2902static char tzinfo_doc[] =
2903PyDoc_STR("Abstract base class for time zone info objects.");
2904
Neal Norwitz227b5332006-03-22 09:28:35 +00002905static PyTypeObject PyDateTime_TZInfoType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00002906 PyObject_HEAD_INIT(NULL)
2907 0, /* ob_size */
2908 "datetime.tzinfo", /* tp_name */
2909 sizeof(PyDateTime_TZInfo), /* tp_basicsize */
2910 0, /* tp_itemsize */
2911 0, /* tp_dealloc */
2912 0, /* tp_print */
2913 0, /* tp_getattr */
2914 0, /* tp_setattr */
2915 0, /* tp_compare */
2916 0, /* tp_repr */
2917 0, /* tp_as_number */
2918 0, /* tp_as_sequence */
2919 0, /* tp_as_mapping */
2920 0, /* tp_hash */
2921 0, /* tp_call */
2922 0, /* tp_str */
2923 PyObject_GenericGetAttr, /* tp_getattro */
2924 0, /* tp_setattro */
2925 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00002926 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters2a799bf2002-12-16 20:18:38 +00002927 tzinfo_doc, /* tp_doc */
2928 0, /* tp_traverse */
2929 0, /* tp_clear */
2930 0, /* tp_richcompare */
2931 0, /* tp_weaklistoffset */
2932 0, /* tp_iter */
2933 0, /* tp_iternext */
2934 tzinfo_methods, /* tp_methods */
2935 0, /* tp_members */
2936 0, /* tp_getset */
2937 0, /* tp_base */
2938 0, /* tp_dict */
2939 0, /* tp_descr_get */
2940 0, /* tp_descr_set */
2941 0, /* tp_dictoffset */
2942 0, /* tp_init */
2943 0, /* tp_alloc */
2944 PyType_GenericNew, /* tp_new */
2945 0, /* tp_free */
2946};
2947
2948/*
Tim Peters37f39822003-01-10 03:49:02 +00002949 * PyDateTime_Time implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00002950 */
2951
Tim Peters37f39822003-01-10 03:49:02 +00002952/* Accessor properties.
Tim Peters2a799bf2002-12-16 20:18:38 +00002953 */
2954
2955static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00002956time_hour(PyDateTime_Time *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00002957{
Tim Peters37f39822003-01-10 03:49:02 +00002958 return PyInt_FromLong(TIME_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00002959}
2960
Tim Peters37f39822003-01-10 03:49:02 +00002961static PyObject *
2962time_minute(PyDateTime_Time *self, void *unused)
2963{
2964 return PyInt_FromLong(TIME_GET_MINUTE(self));
2965}
2966
2967/* The name time_second conflicted with some platform header file. */
2968static PyObject *
2969py_time_second(PyDateTime_Time *self, void *unused)
2970{
2971 return PyInt_FromLong(TIME_GET_SECOND(self));
2972}
2973
2974static PyObject *
2975time_microsecond(PyDateTime_Time *self, void *unused)
2976{
2977 return PyInt_FromLong(TIME_GET_MICROSECOND(self));
2978}
2979
2980static PyObject *
2981time_tzinfo(PyDateTime_Time *self, void *unused)
2982{
Tim Petersa032d2e2003-01-11 00:15:54 +00002983 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters37f39822003-01-10 03:49:02 +00002984 Py_INCREF(result);
2985 return result;
2986}
2987
2988static PyGetSetDef time_getset[] = {
2989 {"hour", (getter)time_hour},
2990 {"minute", (getter)time_minute},
2991 {"second", (getter)py_time_second},
2992 {"microsecond", (getter)time_microsecond},
2993 {"tzinfo", (getter)time_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00002994 {NULL}
2995};
2996
2997/*
2998 * Constructors.
2999 */
3000
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003001static char *time_kws[] = {"hour", "minute", "second", "microsecond",
Tim Peters37f39822003-01-10 03:49:02 +00003002 "tzinfo", NULL};
Tim Peters12bf3392002-12-24 05:41:27 +00003003
Tim Peters2a799bf2002-12-16 20:18:38 +00003004static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003005time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003006{
3007 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003008 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003009 int hour = 0;
3010 int minute = 0;
3011 int second = 0;
3012 int usecond = 0;
3013 PyObject *tzinfo = Py_None;
3014
Guido van Rossum177e41a2003-01-30 22:06:23 +00003015 /* Check for invocation from pickle with __getstate__ state */
3016 if (PyTuple_GET_SIZE(args) >= 1 &&
3017 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003018 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Armin Rigof4afb212005-11-07 07:15:48 +00003019 PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3020 ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
Guido van Rossum177e41a2003-01-30 22:06:23 +00003021 {
Tim Peters70533e22003-02-01 04:40:04 +00003022 PyDateTime_Time *me;
3023 char aware;
3024
3025 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003026 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003027 if (check_tzinfo_subclass(tzinfo) < 0) {
3028 PyErr_SetString(PyExc_TypeError, "bad "
3029 "tzinfo state arg");
3030 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003031 }
3032 }
Tim Peters70533e22003-02-01 04:40:04 +00003033 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003034 me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
Tim Peters70533e22003-02-01 04:40:04 +00003035 if (me != NULL) {
3036 char *pdata = PyString_AS_STRING(state);
3037
3038 memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3039 me->hashcode = -1;
3040 me->hastzinfo = aware;
3041 if (aware) {
3042 Py_INCREF(tzinfo);
3043 me->tzinfo = tzinfo;
3044 }
3045 }
3046 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003047 }
3048
Tim Peters37f39822003-01-10 03:49:02 +00003049 if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003050 &hour, &minute, &second, &usecond,
3051 &tzinfo)) {
3052 if (check_time_args(hour, minute, second, usecond) < 0)
3053 return NULL;
3054 if (check_tzinfo_subclass(tzinfo) < 0)
3055 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003056 self = new_time_ex(hour, minute, second, usecond, tzinfo,
3057 type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003058 }
3059 return self;
3060}
3061
3062/*
3063 * Destructor.
3064 */
3065
3066static void
Tim Peters37f39822003-01-10 03:49:02 +00003067time_dealloc(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003068{
Tim Petersa032d2e2003-01-11 00:15:54 +00003069 if (HASTZINFO(self)) {
Tim Peters37f39822003-01-10 03:49:02 +00003070 Py_XDECREF(self->tzinfo);
Neal Norwitz8e914d92003-01-10 15:29:16 +00003071 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003072 self->ob_type->tp_free((PyObject *)self);
3073}
3074
3075/*
Tim Peters855fe882002-12-22 03:43:39 +00003076 * Indirect access to tzinfo methods.
Tim Peters2a799bf2002-12-16 20:18:38 +00003077 */
3078
Tim Peters2a799bf2002-12-16 20:18:38 +00003079/* These are all METH_NOARGS, so don't need to check the arglist. */
3080static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003081time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003082 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003083 "utcoffset", Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003084}
3085
3086static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003087time_dst(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003088 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003089 "dst", Py_None);
Tim Peters855fe882002-12-22 03:43:39 +00003090}
3091
3092static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003093time_tzname(PyDateTime_Time *self, PyObject *unused) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003094 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
Tim Peters37f39822003-01-10 03:49:02 +00003095 Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003096}
3097
3098/*
Tim Peters37f39822003-01-10 03:49:02 +00003099 * Various ways to turn a time into a string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003100 */
3101
3102static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003103time_repr(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003104{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003105 const char *type_name = self->ob_type->tp_name;
Tim Peters37f39822003-01-10 03:49:02 +00003106 int h = TIME_GET_HOUR(self);
3107 int m = TIME_GET_MINUTE(self);
3108 int s = TIME_GET_SECOND(self);
3109 int us = TIME_GET_MICROSECOND(self);
3110 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003111
Tim Peters37f39822003-01-10 03:49:02 +00003112 if (us)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003113 result = PyUnicode_FromFormat("%s(%d, %d, %d, %d)",
3114 type_name, h, m, s, us);
Tim Peters37f39822003-01-10 03:49:02 +00003115 else if (s)
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003116 result = PyUnicode_FromFormat("%s(%d, %d, %d)",
3117 type_name, h, m, s);
Tim Peters37f39822003-01-10 03:49:02 +00003118 else
Walter Dörwald7569dfe2007-05-19 21:49:49 +00003119 result = PyUnicode_FromFormat("%s(%d, %d)", type_name, h, m);
Tim Petersa032d2e2003-01-11 00:15:54 +00003120 if (result != NULL && HASTZINFO(self))
Tim Peters37f39822003-01-10 03:49:02 +00003121 result = append_keyword_tzinfo(result, self->tzinfo);
3122 return result;
Tim Peters2a799bf2002-12-16 20:18:38 +00003123}
3124
Tim Peters37f39822003-01-10 03:49:02 +00003125static PyObject *
3126time_str(PyDateTime_Time *self)
3127{
3128 return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3129}
Tim Peters2a799bf2002-12-16 20:18:38 +00003130
3131static PyObject *
Thomas Wouterscf297e42007-02-23 15:07:44 +00003132time_isoformat(PyDateTime_Time *self, PyObject *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003133{
3134 char buf[100];
Tim Peters37f39822003-01-10 03:49:02 +00003135 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003136 int us = TIME_GET_MICROSECOND(self);;
Tim Peters2a799bf2002-12-16 20:18:38 +00003137
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003138 if (us)
3139 result = PyUnicode_FromFormat("%02d:%02d:%02d.%06d",
3140 TIME_GET_HOUR(self),
3141 TIME_GET_MINUTE(self),
3142 TIME_GET_SECOND(self),
3143 us);
3144 else
3145 result = PyUnicode_FromFormat("%02d:%02d:%02d",
3146 TIME_GET_HOUR(self),
3147 TIME_GET_MINUTE(self),
3148 TIME_GET_SECOND(self));
Tim Peters37f39822003-01-10 03:49:02 +00003149
Tim Petersa032d2e2003-01-11 00:15:54 +00003150 if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
Tim Peters2a799bf2002-12-16 20:18:38 +00003151 return result;
3152
3153 /* We need to append the UTC offset. */
3154 if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
Tim Petersbad8ff02002-12-30 20:52:32 +00003155 Py_None) < 0) {
Tim Peters2a799bf2002-12-16 20:18:38 +00003156 Py_DECREF(result);
3157 return NULL;
3158 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00003159 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buf));
Tim Peters2a799bf2002-12-16 20:18:38 +00003160 return result;
3161}
3162
Tim Peters37f39822003-01-10 03:49:02 +00003163static PyObject *
3164time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3165{
3166 PyObject *result;
3167 PyObject *format;
3168 PyObject *tuple;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003169 static char *keywords[] = {"format", NULL};
Tim Peters37f39822003-01-10 03:49:02 +00003170
Guido van Rossumbce56a62007-05-10 18:04:33 +00003171 if (! PyArg_ParseTupleAndKeywords(args, kw, "S:strftime", keywords,
3172 &format))
Tim Peters37f39822003-01-10 03:49:02 +00003173 return NULL;
3174
3175 /* Python's strftime does insane things with the year part of the
3176 * timetuple. The year is forced to (the otherwise nonsensical)
3177 * 1900 to worm around that.
3178 */
3179 tuple = Py_BuildValue("iiiiiiiii",
Brett Cannond1080a32004-03-02 04:38:10 +00003180 1900, 1, 1, /* year, month, day */
Tim Peters37f39822003-01-10 03:49:02 +00003181 TIME_GET_HOUR(self),
3182 TIME_GET_MINUTE(self),
3183 TIME_GET_SECOND(self),
Brett Cannond1080a32004-03-02 04:38:10 +00003184 0, 1, -1); /* weekday, daynum, dst */
Tim Peters37f39822003-01-10 03:49:02 +00003185 if (tuple == NULL)
3186 return NULL;
3187 assert(PyTuple_Size(tuple) == 9);
3188 result = wrap_strftime((PyObject *)self, format, tuple, Py_None);
3189 Py_DECREF(tuple);
3190 return result;
3191}
Tim Peters2a799bf2002-12-16 20:18:38 +00003192
3193/*
3194 * Miscellaneous methods.
3195 */
3196
Tim Peters37f39822003-01-10 03:49:02 +00003197static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00003198time_richcompare(PyObject *self, PyObject *other, int op)
Tim Peters37f39822003-01-10 03:49:02 +00003199{
3200 int diff;
3201 naivety n1, n2;
3202 int offset1, offset2;
3203
3204 if (! PyTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00003205 Py_INCREF(Py_NotImplemented);
3206 return Py_NotImplemented;
Tim Peters37f39822003-01-10 03:49:02 +00003207 }
Guido van Rossum19960592006-08-24 17:29:38 +00003208 if (classify_two_utcoffsets(self, &offset1, &n1, Py_None,
3209 other, &offset2, &n2, Py_None) < 0)
Tim Peters37f39822003-01-10 03:49:02 +00003210 return NULL;
3211 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3212 /* If they're both naive, or both aware and have the same offsets,
3213 * we get off cheap. Note that if they're both naive, offset1 ==
3214 * offset2 == 0 at this point.
3215 */
3216 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00003217 diff = memcmp(((PyDateTime_Time *)self)->data,
3218 ((PyDateTime_Time *)other)->data,
Tim Peters37f39822003-01-10 03:49:02 +00003219 _PyDateTime_TIME_DATASIZE);
3220 return diff_to_bool(diff, op);
3221 }
3222
3223 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3224 assert(offset1 != offset2); /* else last "if" handled it */
3225 /* Convert everything except microseconds to seconds. These
3226 * can't overflow (no more than the # of seconds in 2 days).
3227 */
3228 offset1 = TIME_GET_HOUR(self) * 3600 +
3229 (TIME_GET_MINUTE(self) - offset1) * 60 +
3230 TIME_GET_SECOND(self);
3231 offset2 = TIME_GET_HOUR(other) * 3600 +
3232 (TIME_GET_MINUTE(other) - offset2) * 60 +
3233 TIME_GET_SECOND(other);
3234 diff = offset1 - offset2;
3235 if (diff == 0)
3236 diff = TIME_GET_MICROSECOND(self) -
3237 TIME_GET_MICROSECOND(other);
3238 return diff_to_bool(diff, op);
3239 }
3240
3241 assert(n1 != n2);
3242 PyErr_SetString(PyExc_TypeError,
3243 "can't compare offset-naive and "
3244 "offset-aware times");
3245 return NULL;
3246}
3247
3248static long
3249time_hash(PyDateTime_Time *self)
3250{
3251 if (self->hashcode == -1) {
3252 naivety n;
3253 int offset;
3254 PyObject *temp;
3255
3256 n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3257 assert(n != OFFSET_UNKNOWN);
3258 if (n == OFFSET_ERROR)
3259 return -1;
3260
3261 /* Reduce this to a hash of another object. */
3262 if (offset == 0)
3263 temp = PyString_FromStringAndSize((char *)self->data,
3264 _PyDateTime_TIME_DATASIZE);
3265 else {
3266 int hour;
3267 int minute;
3268
3269 assert(n == OFFSET_AWARE);
Tim Petersa032d2e2003-01-11 00:15:54 +00003270 assert(HASTZINFO(self));
Tim Peters37f39822003-01-10 03:49:02 +00003271 hour = divmod(TIME_GET_HOUR(self) * 60 +
3272 TIME_GET_MINUTE(self) - offset,
3273 60,
3274 &minute);
3275 if (0 <= hour && hour < 24)
3276 temp = new_time(hour, minute,
3277 TIME_GET_SECOND(self),
3278 TIME_GET_MICROSECOND(self),
3279 Py_None);
3280 else
3281 temp = Py_BuildValue("iiii",
3282 hour, minute,
3283 TIME_GET_SECOND(self),
3284 TIME_GET_MICROSECOND(self));
3285 }
3286 if (temp != NULL) {
3287 self->hashcode = PyObject_Hash(temp);
3288 Py_DECREF(temp);
3289 }
3290 }
3291 return self->hashcode;
3292}
Tim Peters2a799bf2002-12-16 20:18:38 +00003293
Tim Peters12bf3392002-12-24 05:41:27 +00003294static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003295time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00003296{
3297 PyObject *clone;
3298 PyObject *tuple;
3299 int hh = TIME_GET_HOUR(self);
3300 int mm = TIME_GET_MINUTE(self);
3301 int ss = TIME_GET_SECOND(self);
3302 int us = TIME_GET_MICROSECOND(self);
Tim Petersa032d2e2003-01-11 00:15:54 +00003303 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00003304
3305 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
Tim Peters37f39822003-01-10 03:49:02 +00003306 time_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00003307 &hh, &mm, &ss, &us, &tzinfo))
3308 return NULL;
3309 tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3310 if (tuple == NULL)
3311 return NULL;
Tim Peters37f39822003-01-10 03:49:02 +00003312 clone = time_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00003313 Py_DECREF(tuple);
3314 return clone;
3315}
3316
Tim Peters2a799bf2002-12-16 20:18:38 +00003317static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003318time_bool(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003319{
3320 int offset;
3321 int none;
3322
3323 if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3324 /* Since utcoffset is in whole minutes, nothing can
3325 * alter the conclusion that this is nonzero.
3326 */
3327 return 1;
3328 }
3329 offset = 0;
Tim Petersa032d2e2003-01-11 00:15:54 +00003330 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Petersbad8ff02002-12-30 20:52:32 +00003331 offset = call_utcoffset(self->tzinfo, Py_None, &none);
Tim Peters2a799bf2002-12-16 20:18:38 +00003332 if (offset == -1 && PyErr_Occurred())
3333 return -1;
3334 }
3335 return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3336}
3337
Tim Peters371935f2003-02-01 01:52:50 +00003338/* Pickle support, a simple use of __reduce__. */
Tim Peters2a799bf2002-12-16 20:18:38 +00003339
Tim Peters33e0f382003-01-10 02:05:14 +00003340/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00003341 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3342 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00003343 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00003344 */
3345static PyObject *
Tim Peters37f39822003-01-10 03:49:02 +00003346time_getstate(PyDateTime_Time *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003347{
3348 PyObject *basestate;
3349 PyObject *result = NULL;
3350
Tim Peters33e0f382003-01-10 02:05:14 +00003351 basestate = PyString_FromStringAndSize((char *)self->data,
3352 _PyDateTime_TIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00003353 if (basestate != NULL) {
Tim Petersa032d2e2003-01-11 00:15:54 +00003354 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003355 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00003356 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00003357 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00003358 Py_DECREF(basestate);
3359 }
3360 return result;
3361}
3362
3363static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00003364time_reduce(PyDateTime_Time *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00003365{
Guido van Rossum177e41a2003-01-30 22:06:23 +00003366 return Py_BuildValue("(ON)", self->ob_type, time_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003367}
3368
Tim Peters37f39822003-01-10 03:49:02 +00003369static PyMethodDef time_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003370
Thomas Wouterscf297e42007-02-23 15:07:44 +00003371 {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003372 PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3373 "[+HH:MM].")},
3374
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003375 {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003376 PyDoc_STR("format -> strftime() style string.")},
3377
3378 {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003379 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3380
Tim Peters37f39822003-01-10 03:49:02 +00003381 {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003382 PyDoc_STR("Return self.tzinfo.tzname(self).")},
3383
Tim Peters37f39822003-01-10 03:49:02 +00003384 {"dst", (PyCFunction)time_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00003385 PyDoc_STR("Return self.tzinfo.dst(self).")},
3386
Guido van Rossumd59da4b2007-05-22 18:11:13 +00003387 {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
Tim Peters37f39822003-01-10 03:49:02 +00003388 PyDoc_STR("Return time with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00003389
Guido van Rossum177e41a2003-01-30 22:06:23 +00003390 {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
3391 PyDoc_STR("__reduce__() -> (cls, state)")},
3392
Tim Peters2a799bf2002-12-16 20:18:38 +00003393 {NULL, NULL}
Tim Peters2a799bf2002-12-16 20:18:38 +00003394};
3395
Tim Peters37f39822003-01-10 03:49:02 +00003396static char time_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00003397PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3398\n\
3399All arguments are optional. tzinfo may be None, or an instance of\n\
3400a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00003401
Tim Peters37f39822003-01-10 03:49:02 +00003402static PyNumberMethods time_as_number = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003403 0, /* nb_add */
3404 0, /* nb_subtract */
3405 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00003406 0, /* nb_remainder */
3407 0, /* nb_divmod */
3408 0, /* nb_power */
3409 0, /* nb_negative */
3410 0, /* nb_positive */
3411 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00003412 (inquiry)time_bool, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00003413};
3414
Neal Norwitz227b5332006-03-22 09:28:35 +00003415static PyTypeObject PyDateTime_TimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00003416 PyObject_HEAD_INIT(NULL)
3417 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00003418 "datetime.time", /* tp_name */
Tim Peters37f39822003-01-10 03:49:02 +00003419 sizeof(PyDateTime_Time), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00003420 0, /* tp_itemsize */
Tim Peters37f39822003-01-10 03:49:02 +00003421 (destructor)time_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003422 0, /* tp_print */
3423 0, /* tp_getattr */
3424 0, /* tp_setattr */
3425 0, /* tp_compare */
Tim Peters37f39822003-01-10 03:49:02 +00003426 (reprfunc)time_repr, /* tp_repr */
3427 &time_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00003428 0, /* tp_as_sequence */
3429 0, /* tp_as_mapping */
Tim Peters37f39822003-01-10 03:49:02 +00003430 (hashfunc)time_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00003431 0, /* tp_call */
Tim Peters37f39822003-01-10 03:49:02 +00003432 (reprfunc)time_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00003433 PyObject_GenericGetAttr, /* tp_getattro */
3434 0, /* tp_setattro */
3435 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00003436 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters37f39822003-01-10 03:49:02 +00003437 time_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00003438 0, /* tp_traverse */
3439 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00003440 time_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00003441 0, /* tp_weaklistoffset */
3442 0, /* tp_iter */
3443 0, /* tp_iternext */
Tim Peters37f39822003-01-10 03:49:02 +00003444 time_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00003445 0, /* tp_members */
Tim Peters37f39822003-01-10 03:49:02 +00003446 time_getset, /* tp_getset */
3447 0, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00003448 0, /* tp_dict */
3449 0, /* tp_descr_get */
3450 0, /* tp_descr_set */
3451 0, /* tp_dictoffset */
3452 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00003453 time_alloc, /* tp_alloc */
Tim Peters37f39822003-01-10 03:49:02 +00003454 time_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00003455 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00003456};
3457
3458/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003459 * PyDateTime_DateTime implementation.
Tim Peters2a799bf2002-12-16 20:18:38 +00003460 */
3461
Tim Petersa9bc1682003-01-11 03:39:11 +00003462/* Accessor properties. Properties for day, month, and year are inherited
3463 * from date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003464 */
3465
3466static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003467datetime_hour(PyDateTime_DateTime *self, void *unused)
Tim Peters2a799bf2002-12-16 20:18:38 +00003468{
Tim Petersa9bc1682003-01-11 03:39:11 +00003469 return PyInt_FromLong(DATE_GET_HOUR(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00003470}
3471
Tim Petersa9bc1682003-01-11 03:39:11 +00003472static PyObject *
3473datetime_minute(PyDateTime_DateTime *self, void *unused)
3474{
3475 return PyInt_FromLong(DATE_GET_MINUTE(self));
3476}
3477
3478static PyObject *
3479datetime_second(PyDateTime_DateTime *self, void *unused)
3480{
3481 return PyInt_FromLong(DATE_GET_SECOND(self));
3482}
3483
3484static PyObject *
3485datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3486{
3487 return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3488}
3489
3490static PyObject *
3491datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3492{
3493 PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3494 Py_INCREF(result);
3495 return result;
3496}
3497
3498static PyGetSetDef datetime_getset[] = {
3499 {"hour", (getter)datetime_hour},
3500 {"minute", (getter)datetime_minute},
3501 {"second", (getter)datetime_second},
3502 {"microsecond", (getter)datetime_microsecond},
3503 {"tzinfo", (getter)datetime_tzinfo},
Tim Peters2a799bf2002-12-16 20:18:38 +00003504 {NULL}
3505};
3506
3507/*
3508 * Constructors.
Tim Peters2a799bf2002-12-16 20:18:38 +00003509 */
3510
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003511static char *datetime_kws[] = {
Tim Peters12bf3392002-12-24 05:41:27 +00003512 "year", "month", "day", "hour", "minute", "second",
3513 "microsecond", "tzinfo", NULL
3514};
3515
Tim Peters2a799bf2002-12-16 20:18:38 +00003516static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003517datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003518{
3519 PyObject *self = NULL;
Tim Peters70533e22003-02-01 04:40:04 +00003520 PyObject *state;
Tim Peters2a799bf2002-12-16 20:18:38 +00003521 int year;
3522 int month;
3523 int day;
3524 int hour = 0;
3525 int minute = 0;
3526 int second = 0;
3527 int usecond = 0;
3528 PyObject *tzinfo = Py_None;
3529
Guido van Rossum177e41a2003-01-30 22:06:23 +00003530 /* Check for invocation from pickle with __getstate__ state */
3531 if (PyTuple_GET_SIZE(args) >= 1 &&
3532 PyTuple_GET_SIZE(args) <= 2 &&
Tim Peters70533e22003-02-01 04:40:04 +00003533 PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
Tim Peters3f606292004-03-21 23:38:41 +00003534 PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3535 MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
Guido van Rossum177e41a2003-01-30 22:06:23 +00003536 {
Tim Peters70533e22003-02-01 04:40:04 +00003537 PyDateTime_DateTime *me;
3538 char aware;
3539
3540 if (PyTuple_GET_SIZE(args) == 2) {
Guido van Rossum177e41a2003-01-30 22:06:23 +00003541 tzinfo = PyTuple_GET_ITEM(args, 1);
Tim Peters70533e22003-02-01 04:40:04 +00003542 if (check_tzinfo_subclass(tzinfo) < 0) {
3543 PyErr_SetString(PyExc_TypeError, "bad "
3544 "tzinfo state arg");
3545 return NULL;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003546 }
3547 }
Tim Peters70533e22003-02-01 04:40:04 +00003548 aware = (char)(tzinfo != Py_None);
Tim Peters604c0132004-06-07 23:04:33 +00003549 me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
Tim Peters70533e22003-02-01 04:40:04 +00003550 if (me != NULL) {
3551 char *pdata = PyString_AS_STRING(state);
3552
3553 memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3554 me->hashcode = -1;
3555 me->hastzinfo = aware;
3556 if (aware) {
3557 Py_INCREF(tzinfo);
3558 me->tzinfo = tzinfo;
3559 }
3560 }
3561 return (PyObject *)me;
Guido van Rossum177e41a2003-01-30 22:06:23 +00003562 }
3563
Tim Petersa9bc1682003-01-11 03:39:11 +00003564 if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
Tim Peters2a799bf2002-12-16 20:18:38 +00003565 &year, &month, &day, &hour, &minute,
3566 &second, &usecond, &tzinfo)) {
3567 if (check_date_args(year, month, day) < 0)
3568 return NULL;
3569 if (check_time_args(hour, minute, second, usecond) < 0)
3570 return NULL;
3571 if (check_tzinfo_subclass(tzinfo) < 0)
3572 return NULL;
Tim Petersa98924a2003-05-17 05:55:19 +00003573 self = new_datetime_ex(year, month, day,
3574 hour, minute, second, usecond,
3575 tzinfo, type);
Tim Peters2a799bf2002-12-16 20:18:38 +00003576 }
3577 return self;
3578}
3579
Tim Petersa9bc1682003-01-11 03:39:11 +00003580/* TM_FUNC is the shared type of localtime() and gmtime(). */
3581typedef struct tm *(*TM_FUNC)(const time_t *timer);
3582
3583/* Internal helper.
3584 * Build datetime from a time_t and a distinct count of microseconds.
3585 * Pass localtime or gmtime for f, to control the interpretation of timet.
3586 */
3587static PyObject *
3588datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3589 PyObject *tzinfo)
3590{
3591 struct tm *tm;
3592 PyObject *result = NULL;
3593
3594 tm = f(&timet);
3595 if (tm) {
3596 /* The platform localtime/gmtime may insert leap seconds,
3597 * indicated by tm->tm_sec > 59. We don't care about them,
3598 * except to the extent that passing them on to the datetime
3599 * constructor would raise ValueError for a reason that
3600 * made no sense to the user.
3601 */
3602 if (tm->tm_sec > 59)
3603 tm->tm_sec = 59;
3604 result = PyObject_CallFunction(cls, "iiiiiiiO",
3605 tm->tm_year + 1900,
3606 tm->tm_mon + 1,
3607 tm->tm_mday,
3608 tm->tm_hour,
3609 tm->tm_min,
3610 tm->tm_sec,
3611 us,
3612 tzinfo);
3613 }
3614 else
3615 PyErr_SetString(PyExc_ValueError,
3616 "timestamp out of range for "
3617 "platform localtime()/gmtime() function");
3618 return result;
3619}
3620
3621/* Internal helper.
3622 * Build datetime from a Python timestamp. Pass localtime or gmtime for f,
3623 * to control the interpretation of the timestamp. Since a double doesn't
3624 * have enough bits to cover a datetime's full range of precision, it's
3625 * better to call datetime_from_timet_and_us provided you have a way
3626 * to get that much precision (e.g., C time() isn't good enough).
3627 */
3628static PyObject *
3629datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3630 PyObject *tzinfo)
3631{
Tim Peters1b6f7a92004-06-20 02:50:16 +00003632 time_t timet;
3633 double fraction;
3634 int us;
Tim Petersa9bc1682003-01-11 03:39:11 +00003635
Tim Peters1b6f7a92004-06-20 02:50:16 +00003636 timet = _PyTime_DoubleToTimet(timestamp);
3637 if (timet == (time_t)-1 && PyErr_Occurred())
3638 return NULL;
3639 fraction = timestamp - (double)timet;
3640 us = (int)round_to_long(fraction * 1e6);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003641 if (us < 0) {
3642 /* Truncation towards zero is not what we wanted
3643 for negative numbers (Python's mod semantics) */
3644 timet -= 1;
3645 us += 1000000;
3646 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00003647 /* If timestamp is less than one microsecond smaller than a
3648 * full second, round up. Otherwise, ValueErrors are raised
3649 * for some floats. */
3650 if (us == 1000000) {
3651 timet += 1;
3652 us = 0;
3653 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003654 return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3655}
3656
3657/* Internal helper.
3658 * Build most accurate possible datetime for current time. Pass localtime or
3659 * gmtime for f as appropriate.
3660 */
3661static PyObject *
3662datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3663{
3664#ifdef HAVE_GETTIMEOFDAY
3665 struct timeval t;
3666
3667#ifdef GETTIMEOFDAY_NO_TZ
3668 gettimeofday(&t);
3669#else
3670 gettimeofday(&t, (struct timezone *)NULL);
3671#endif
3672 return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3673 tzinfo);
3674
3675#else /* ! HAVE_GETTIMEOFDAY */
3676 /* No flavor of gettimeofday exists on this platform. Python's
3677 * time.time() does a lot of other platform tricks to get the
3678 * best time it can on the platform, and we're not going to do
3679 * better than that (if we could, the better code would belong
3680 * in time.time()!) We're limited by the precision of a double,
3681 * though.
3682 */
3683 PyObject *time;
3684 double dtime;
3685
3686 time = time_time();
3687 if (time == NULL)
3688 return NULL;
3689 dtime = PyFloat_AsDouble(time);
3690 Py_DECREF(time);
3691 if (dtime == -1.0 && PyErr_Occurred())
3692 return NULL;
3693 return datetime_from_timestamp(cls, f, dtime, tzinfo);
3694#endif /* ! HAVE_GETTIMEOFDAY */
3695}
3696
Tim Peters2a799bf2002-12-16 20:18:38 +00003697/* Return best possible local time -- this isn't constrained by the
3698 * precision of a timestamp.
3699 */
3700static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003701datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003702{
Tim Peters10cadce2003-01-23 19:58:02 +00003703 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003704 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003705 static char *keywords[] = {"tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003706
Tim Peters10cadce2003-01-23 19:58:02 +00003707 if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3708 &tzinfo))
3709 return NULL;
3710 if (check_tzinfo_subclass(tzinfo) < 0)
3711 return NULL;
3712
3713 self = datetime_best_possible(cls,
3714 tzinfo == Py_None ? localtime : gmtime,
3715 tzinfo);
3716 if (self != NULL && tzinfo != Py_None) {
3717 /* Convert UTC to tzinfo's zone. */
3718 PyObject *temp = self;
Tim Peters2a44a8d2003-01-23 20:53:10 +00003719 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
Tim Peters10cadce2003-01-23 19:58:02 +00003720 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003721 }
3722 return self;
3723}
3724
Tim Petersa9bc1682003-01-11 03:39:11 +00003725/* Return best possible UTC time -- this isn't constrained by the
3726 * precision of a timestamp.
3727 */
3728static PyObject *
3729datetime_utcnow(PyObject *cls, PyObject *dummy)
3730{
3731 return datetime_best_possible(cls, gmtime, Py_None);
3732}
3733
Tim Peters2a799bf2002-12-16 20:18:38 +00003734/* Return new local datetime from timestamp (Python timestamp -- a double). */
3735static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003736datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00003737{
Tim Peters2a44a8d2003-01-23 20:53:10 +00003738 PyObject *self;
Tim Peters2a799bf2002-12-16 20:18:38 +00003739 double timestamp;
3740 PyObject *tzinfo = Py_None;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003741 static char *keywords[] = {"timestamp", "tz", NULL};
Tim Peters2a799bf2002-12-16 20:18:38 +00003742
Tim Peters2a44a8d2003-01-23 20:53:10 +00003743 if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3744 keywords, &timestamp, &tzinfo))
3745 return NULL;
3746 if (check_tzinfo_subclass(tzinfo) < 0)
3747 return NULL;
3748
3749 self = datetime_from_timestamp(cls,
3750 tzinfo == Py_None ? localtime : gmtime,
3751 timestamp,
3752 tzinfo);
3753 if (self != NULL && tzinfo != Py_None) {
3754 /* Convert UTC to tzinfo's zone. */
3755 PyObject *temp = self;
3756 self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3757 Py_DECREF(temp);
Tim Peters2a799bf2002-12-16 20:18:38 +00003758 }
3759 return self;
3760}
3761
Tim Petersa9bc1682003-01-11 03:39:11 +00003762/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3763static PyObject *
3764datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3765{
3766 double timestamp;
3767 PyObject *result = NULL;
Tim Peters2a799bf2002-12-16 20:18:38 +00003768
Tim Petersa9bc1682003-01-11 03:39:11 +00003769 if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3770 result = datetime_from_timestamp(cls, gmtime, timestamp,
3771 Py_None);
3772 return result;
3773}
3774
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003775/* Return new datetime from time.strptime(). */
3776static PyObject *
3777datetime_strptime(PyObject *cls, PyObject *args)
3778{
3779 PyObject *result = NULL, *obj, *module;
3780 const char *string, *format;
3781
3782 if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3783 return NULL;
3784
3785 if ((module = PyImport_ImportModule("time")) == NULL)
3786 return NULL;
3787 obj = PyObject_CallMethod(module, "strptime", "ss", string, format);
3788 Py_DECREF(module);
3789
3790 if (obj != NULL) {
3791 int i, good_timetuple = 1;
3792 long int ia[6];
3793 if (PySequence_Check(obj) && PySequence_Size(obj) >= 6)
3794 for (i=0; i < 6; i++) {
3795 PyObject *p = PySequence_GetItem(obj, i);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003796 if (p == NULL) {
3797 Py_DECREF(obj);
3798 return NULL;
3799 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003800 if (PyInt_CheckExact(p))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00003801 ia[i] = PyInt_AsLong(p);
3802 else
3803 good_timetuple = 0;
3804 Py_DECREF(p);
3805 }
3806 else
3807 good_timetuple = 0;
3808 if (good_timetuple)
3809 result = PyObject_CallFunction(cls, "iiiiii",
3810 ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
3811 else
3812 PyErr_SetString(PyExc_ValueError,
3813 "unexpected value from time.strptime");
3814 Py_DECREF(obj);
3815 }
3816 return result;
3817}
3818
Tim Petersa9bc1682003-01-11 03:39:11 +00003819/* Return new datetime from date/datetime and time arguments. */
3820static PyObject *
3821datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
3822{
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00003823 static char *keywords[] = {"date", "time", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00003824 PyObject *date;
3825 PyObject *time;
3826 PyObject *result = NULL;
3827
3828 if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
3829 &PyDateTime_DateType, &date,
3830 &PyDateTime_TimeType, &time)) {
3831 PyObject *tzinfo = Py_None;
3832
3833 if (HASTZINFO(time))
3834 tzinfo = ((PyDateTime_Time *)time)->tzinfo;
3835 result = PyObject_CallFunction(cls, "iiiiiiiO",
3836 GET_YEAR(date),
3837 GET_MONTH(date),
3838 GET_DAY(date),
3839 TIME_GET_HOUR(time),
3840 TIME_GET_MINUTE(time),
3841 TIME_GET_SECOND(time),
3842 TIME_GET_MICROSECOND(time),
3843 tzinfo);
3844 }
3845 return result;
3846}
Tim Peters2a799bf2002-12-16 20:18:38 +00003847
3848/*
3849 * Destructor.
3850 */
3851
3852static void
Tim Petersa9bc1682003-01-11 03:39:11 +00003853datetime_dealloc(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00003854{
Tim Petersa9bc1682003-01-11 03:39:11 +00003855 if (HASTZINFO(self)) {
3856 Py_XDECREF(self->tzinfo);
3857 }
Tim Peters2a799bf2002-12-16 20:18:38 +00003858 self->ob_type->tp_free((PyObject *)self);
3859}
3860
3861/*
3862 * Indirect access to tzinfo methods.
3863 */
3864
Tim Peters2a799bf2002-12-16 20:18:38 +00003865/* These are all METH_NOARGS, so don't need to check the arglist. */
3866static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003867datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
3868 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3869 "utcoffset", (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003870}
3871
3872static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003873datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
3874 return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3875 "dst", (PyObject *)self);
Tim Peters855fe882002-12-22 03:43:39 +00003876}
3877
3878static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003879datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
3880 return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3881 (PyObject *)self);
Tim Peters2a799bf2002-12-16 20:18:38 +00003882}
3883
3884/*
Tim Petersa9bc1682003-01-11 03:39:11 +00003885 * datetime arithmetic.
Tim Peters2a799bf2002-12-16 20:18:38 +00003886 */
3887
Tim Petersa9bc1682003-01-11 03:39:11 +00003888/* factor must be 1 (to add) or -1 (to subtract). The result inherits
3889 * the tzinfo state of date.
Tim Peters2a799bf2002-12-16 20:18:38 +00003890 */
3891static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003892add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
3893 int factor)
Tim Peters2a799bf2002-12-16 20:18:38 +00003894{
Tim Petersa9bc1682003-01-11 03:39:11 +00003895 /* Note that the C-level additions can't overflow, because of
3896 * invariant bounds on the member values.
3897 */
3898 int year = GET_YEAR(date);
3899 int month = GET_MONTH(date);
3900 int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
3901 int hour = DATE_GET_HOUR(date);
3902 int minute = DATE_GET_MINUTE(date);
3903 int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
3904 int microsecond = DATE_GET_MICROSECOND(date) +
3905 GET_TD_MICROSECONDS(delta) * factor;
Tim Peters2a799bf2002-12-16 20:18:38 +00003906
Tim Petersa9bc1682003-01-11 03:39:11 +00003907 assert(factor == 1 || factor == -1);
3908 if (normalize_datetime(&year, &month, &day,
3909 &hour, &minute, &second, &microsecond) < 0)
3910 return NULL;
3911 else
3912 return new_datetime(year, month, day,
3913 hour, minute, second, microsecond,
3914 HASTZINFO(date) ? date->tzinfo : Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00003915}
3916
3917static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003918datetime_add(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003919{
Tim Petersa9bc1682003-01-11 03:39:11 +00003920 if (PyDateTime_Check(left)) {
3921 /* datetime + ??? */
3922 if (PyDelta_Check(right))
3923 /* datetime + delta */
3924 return add_datetime_timedelta(
3925 (PyDateTime_DateTime *)left,
3926 (PyDateTime_Delta *)right,
3927 1);
3928 }
3929 else if (PyDelta_Check(left)) {
3930 /* delta + datetime */
3931 return add_datetime_timedelta((PyDateTime_DateTime *) right,
3932 (PyDateTime_Delta *) left,
3933 1);
3934 }
3935 Py_INCREF(Py_NotImplemented);
3936 return Py_NotImplemented;
Tim Peters2a799bf2002-12-16 20:18:38 +00003937}
3938
3939static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00003940datetime_subtract(PyObject *left, PyObject *right)
Tim Peters2a799bf2002-12-16 20:18:38 +00003941{
3942 PyObject *result = Py_NotImplemented;
3943
3944 if (PyDateTime_Check(left)) {
3945 /* datetime - ??? */
3946 if (PyDateTime_Check(right)) {
3947 /* datetime - datetime */
3948 naivety n1, n2;
3949 int offset1, offset2;
Tim Petersa9bc1682003-01-11 03:39:11 +00003950 int delta_d, delta_s, delta_us;
Tim Peters2a799bf2002-12-16 20:18:38 +00003951
Tim Peterse39a80c2002-12-30 21:28:52 +00003952 if (classify_two_utcoffsets(left, &offset1, &n1, left,
3953 right, &offset2, &n2,
3954 right) < 0)
Tim Peters00237032002-12-27 02:21:51 +00003955 return NULL;
Tim Peters8702d5f2002-12-27 02:26:16 +00003956 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
Tim Peters2a799bf2002-12-16 20:18:38 +00003957 if (n1 != n2) {
3958 PyErr_SetString(PyExc_TypeError,
3959 "can't subtract offset-naive and "
3960 "offset-aware datetimes");
3961 return NULL;
3962 }
Tim Petersa9bc1682003-01-11 03:39:11 +00003963 delta_d = ymd_to_ord(GET_YEAR(left),
3964 GET_MONTH(left),
3965 GET_DAY(left)) -
3966 ymd_to_ord(GET_YEAR(right),
3967 GET_MONTH(right),
3968 GET_DAY(right));
3969 /* These can't overflow, since the values are
3970 * normalized. At most this gives the number of
3971 * seconds in one day.
3972 */
3973 delta_s = (DATE_GET_HOUR(left) -
3974 DATE_GET_HOUR(right)) * 3600 +
3975 (DATE_GET_MINUTE(left) -
3976 DATE_GET_MINUTE(right)) * 60 +
3977 (DATE_GET_SECOND(left) -
3978 DATE_GET_SECOND(right));
3979 delta_us = DATE_GET_MICROSECOND(left) -
3980 DATE_GET_MICROSECOND(right);
Tim Peters2a799bf2002-12-16 20:18:38 +00003981 /* (left - offset1) - (right - offset2) =
3982 * (left - right) + (offset2 - offset1)
3983 */
Tim Petersa9bc1682003-01-11 03:39:11 +00003984 delta_s += (offset2 - offset1) * 60;
3985 result = new_delta(delta_d, delta_s, delta_us, 1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003986 }
3987 else if (PyDelta_Check(right)) {
Tim Petersa9bc1682003-01-11 03:39:11 +00003988 /* datetime - delta */
3989 result = add_datetime_timedelta(
Tim Peters2a799bf2002-12-16 20:18:38 +00003990 (PyDateTime_DateTime *)left,
Tim Petersa9bc1682003-01-11 03:39:11 +00003991 (PyDateTime_Delta *)right,
3992 -1);
Tim Peters2a799bf2002-12-16 20:18:38 +00003993 }
3994 }
3995
3996 if (result == Py_NotImplemented)
3997 Py_INCREF(result);
3998 return result;
3999}
4000
4001/* Various ways to turn a datetime into a string. */
4002
4003static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004004datetime_repr(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004005{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004006 const char *type_name = self->ob_type->tp_name;
Tim Petersa9bc1682003-01-11 03:39:11 +00004007 PyObject *baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004008
Tim Petersa9bc1682003-01-11 03:39:11 +00004009 if (DATE_GET_MICROSECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004010 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004011 "%s(%d, %d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004012 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004013 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4014 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4015 DATE_GET_SECOND(self),
4016 DATE_GET_MICROSECOND(self));
4017 }
4018 else if (DATE_GET_SECOND(self)) {
Walter Dörwald7569dfe2007-05-19 21:49:49 +00004019 baserepr = PyUnicode_FromFormat(
Tim Petersa9bc1682003-01-11 03:39:11 +00004020 "%s(%d, %d, %d, %d, %d, %d)",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004021 type_name,
Tim Petersa9bc1682003-01-11 03:39:11 +00004022 GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4023 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4024 DATE_GET_SECOND(self));
4025 }
4026 else {
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)",
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 }
Tim Petersa9bc1682003-01-11 03:39:11 +00004033 if (baserepr == NULL || ! HASTZINFO(self))
4034 return baserepr;
Tim Peters2a799bf2002-12-16 20:18:38 +00004035 return append_keyword_tzinfo(baserepr, self->tzinfo);
4036}
4037
Tim Petersa9bc1682003-01-11 03:39:11 +00004038static PyObject *
4039datetime_str(PyDateTime_DateTime *self)
4040{
4041 return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4042}
Tim Peters2a799bf2002-12-16 20:18:38 +00004043
4044static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004045datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters2a799bf2002-12-16 20:18:38 +00004046{
Tim Petersa9bc1682003-01-11 03:39:11 +00004047 char sep = 'T';
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004048 static char *keywords[] = {"sep", NULL};
Tim Petersa9bc1682003-01-11 03:39:11 +00004049 char buffer[100];
Tim Petersa9bc1682003-01-11 03:39:11 +00004050 PyObject *result;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004051 int us = DATE_GET_MICROSECOND(self);
Tim Peters2a799bf2002-12-16 20:18:38 +00004052
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004053 if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords, &sep))
Tim Petersa9bc1682003-01-11 03:39:11 +00004054 return NULL;
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004055 if (us)
4056 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d.%06d",
4057 GET_YEAR(self), GET_MONTH(self),
4058 GET_DAY(self), (int)sep,
4059 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4060 DATE_GET_SECOND(self), us);
4061 else
4062 result = PyUnicode_FromFormat("%04d-%02d-%02d%c%02d:%02d:%02d",
4063 GET_YEAR(self), GET_MONTH(self),
4064 GET_DAY(self), (int)sep,
4065 DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4066 DATE_GET_SECOND(self));
4067
4068 if (!result || !HASTZINFO(self))
Tim Peters2a799bf2002-12-16 20:18:38 +00004069 return result;
4070
4071 /* We need to append the UTC offset. */
Tim Petersa9bc1682003-01-11 03:39:11 +00004072 if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
Tim Peters2a799bf2002-12-16 20:18:38 +00004073 (PyObject *)self) < 0) {
4074 Py_DECREF(result);
4075 return NULL;
4076 }
Walter Dörwaldbafa1372007-05-31 17:50:48 +00004077 PyUnicode_AppendAndDel(&result, PyUnicode_FromString(buffer));
Tim Peters2a799bf2002-12-16 20:18:38 +00004078 return result;
4079}
4080
Tim Petersa9bc1682003-01-11 03:39:11 +00004081static PyObject *
4082datetime_ctime(PyDateTime_DateTime *self)
4083{
4084 return format_ctime((PyDateTime_Date *)self,
4085 DATE_GET_HOUR(self),
4086 DATE_GET_MINUTE(self),
4087 DATE_GET_SECOND(self));
4088}
4089
Tim Peters2a799bf2002-12-16 20:18:38 +00004090/* Miscellaneous methods. */
4091
Tim Petersa9bc1682003-01-11 03:39:11 +00004092static PyObject *
Guido van Rossum19960592006-08-24 17:29:38 +00004093datetime_richcompare(PyObject *self, PyObject *other, int op)
Tim Petersa9bc1682003-01-11 03:39:11 +00004094{
4095 int diff;
4096 naivety n1, n2;
4097 int offset1, offset2;
4098
4099 if (! PyDateTime_Check(other)) {
Guido van Rossum19960592006-08-24 17:29:38 +00004100 if (PyDate_Check(other)) {
4101 /* Prevent invocation of date_richcompare. We want to
4102 return NotImplemented here to give the other object
4103 a chance. But since DateTime is a subclass of
4104 Date, if the other object is a Date, it would
4105 compute an ordering based on the date part alone,
4106 and we don't want that. So force unequal or
4107 uncomparable here in that case. */
4108 if (op == Py_EQ)
4109 Py_RETURN_FALSE;
4110 if (op == Py_NE)
4111 Py_RETURN_TRUE;
4112 return cmperror(self, other);
Tim Peters8d81a012003-01-24 22:36:34 +00004113 }
Guido van Rossum19960592006-08-24 17:29:38 +00004114 Py_INCREF(Py_NotImplemented);
4115 return Py_NotImplemented;
Tim Petersa9bc1682003-01-11 03:39:11 +00004116 }
4117
Guido van Rossum19960592006-08-24 17:29:38 +00004118 if (classify_two_utcoffsets(self, &offset1, &n1, self,
4119 other, &offset2, &n2, other) < 0)
Tim Petersa9bc1682003-01-11 03:39:11 +00004120 return NULL;
4121 assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4122 /* If they're both naive, or both aware and have the same offsets,
4123 * we get off cheap. Note that if they're both naive, offset1 ==
4124 * offset2 == 0 at this point.
4125 */
4126 if (n1 == n2 && offset1 == offset2) {
Guido van Rossum19960592006-08-24 17:29:38 +00004127 diff = memcmp(((PyDateTime_DateTime *)self)->data,
4128 ((PyDateTime_DateTime *)other)->data,
Tim Petersa9bc1682003-01-11 03:39:11 +00004129 _PyDateTime_DATETIME_DATASIZE);
4130 return diff_to_bool(diff, op);
4131 }
4132
4133 if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4134 PyDateTime_Delta *delta;
4135
4136 assert(offset1 != offset2); /* else last "if" handled it */
4137 delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4138 other);
4139 if (delta == NULL)
4140 return NULL;
4141 diff = GET_TD_DAYS(delta);
4142 if (diff == 0)
4143 diff = GET_TD_SECONDS(delta) |
4144 GET_TD_MICROSECONDS(delta);
4145 Py_DECREF(delta);
4146 return diff_to_bool(diff, op);
4147 }
4148
4149 assert(n1 != n2);
4150 PyErr_SetString(PyExc_TypeError,
4151 "can't compare offset-naive and "
4152 "offset-aware datetimes");
4153 return NULL;
4154}
4155
4156static long
4157datetime_hash(PyDateTime_DateTime *self)
4158{
4159 if (self->hashcode == -1) {
4160 naivety n;
4161 int offset;
4162 PyObject *temp;
4163
4164 n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4165 &offset);
4166 assert(n != OFFSET_UNKNOWN);
4167 if (n == OFFSET_ERROR)
4168 return -1;
4169
4170 /* Reduce this to a hash of another object. */
4171 if (n == OFFSET_NAIVE)
4172 temp = PyString_FromStringAndSize(
4173 (char *)self->data,
4174 _PyDateTime_DATETIME_DATASIZE);
4175 else {
4176 int days;
4177 int seconds;
4178
4179 assert(n == OFFSET_AWARE);
4180 assert(HASTZINFO(self));
4181 days = ymd_to_ord(GET_YEAR(self),
4182 GET_MONTH(self),
4183 GET_DAY(self));
4184 seconds = DATE_GET_HOUR(self) * 3600 +
4185 (DATE_GET_MINUTE(self) - offset) * 60 +
4186 DATE_GET_SECOND(self);
4187 temp = new_delta(days,
4188 seconds,
4189 DATE_GET_MICROSECOND(self),
4190 1);
4191 }
4192 if (temp != NULL) {
4193 self->hashcode = PyObject_Hash(temp);
4194 Py_DECREF(temp);
4195 }
4196 }
4197 return self->hashcode;
4198}
Tim Peters2a799bf2002-12-16 20:18:38 +00004199
4200static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004201datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters12bf3392002-12-24 05:41:27 +00004202{
4203 PyObject *clone;
4204 PyObject *tuple;
4205 int y = GET_YEAR(self);
4206 int m = GET_MONTH(self);
4207 int d = GET_DAY(self);
4208 int hh = DATE_GET_HOUR(self);
4209 int mm = DATE_GET_MINUTE(self);
4210 int ss = DATE_GET_SECOND(self);
4211 int us = DATE_GET_MICROSECOND(self);
Tim Petersa9bc1682003-01-11 03:39:11 +00004212 PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
Tim Peters12bf3392002-12-24 05:41:27 +00004213
4214 if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
Tim Petersa9bc1682003-01-11 03:39:11 +00004215 datetime_kws,
Tim Peters12bf3392002-12-24 05:41:27 +00004216 &y, &m, &d, &hh, &mm, &ss, &us,
4217 &tzinfo))
4218 return NULL;
4219 tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4220 if (tuple == NULL)
4221 return NULL;
Tim Petersa9bc1682003-01-11 03:39:11 +00004222 clone = datetime_new(self->ob_type, tuple, NULL);
Tim Peters12bf3392002-12-24 05:41:27 +00004223 Py_DECREF(tuple);
4224 return clone;
4225}
4226
4227static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004228datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
Tim Peters80475bb2002-12-25 07:40:55 +00004229{
Tim Peters52dcce22003-01-23 16:36:11 +00004230 int y, m, d, hh, mm, ss, us;
Tim Peters521fc152002-12-31 17:36:56 +00004231 PyObject *result;
Tim Peters52dcce22003-01-23 16:36:11 +00004232 int offset, none;
Tim Peters521fc152002-12-31 17:36:56 +00004233
Tim Peters80475bb2002-12-25 07:40:55 +00004234 PyObject *tzinfo;
Martin v. Löwis02cbf4a2006-02-27 17:20:04 +00004235 static char *keywords[] = {"tz", NULL};
Tim Peters80475bb2002-12-25 07:40:55 +00004236
Tim Peters52dcce22003-01-23 16:36:11 +00004237 if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4238 &PyDateTime_TZInfoType, &tzinfo))
Tim Peters80475bb2002-12-25 07:40:55 +00004239 return NULL;
4240
Tim Peters52dcce22003-01-23 16:36:11 +00004241 if (!HASTZINFO(self) || self->tzinfo == Py_None)
4242 goto NeedAware;
Tim Peters521fc152002-12-31 17:36:56 +00004243
Tim Peters52dcce22003-01-23 16:36:11 +00004244 /* Conversion to self's own time zone is a NOP. */
4245 if (self->tzinfo == tzinfo) {
4246 Py_INCREF(self);
4247 return (PyObject *)self;
Tim Peters710fb152003-01-02 19:35:54 +00004248 }
Tim Peters521fc152002-12-31 17:36:56 +00004249
Tim Peters52dcce22003-01-23 16:36:11 +00004250 /* Convert self to UTC. */
4251 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4252 if (offset == -1 && PyErr_Occurred())
4253 return NULL;
4254 if (none)
4255 goto NeedAware;
Tim Petersf3615152003-01-01 21:51:37 +00004256
Tim Peters52dcce22003-01-23 16:36:11 +00004257 y = GET_YEAR(self);
4258 m = GET_MONTH(self);
4259 d = GET_DAY(self);
4260 hh = DATE_GET_HOUR(self);
4261 mm = DATE_GET_MINUTE(self);
4262 ss = DATE_GET_SECOND(self);
4263 us = DATE_GET_MICROSECOND(self);
4264
4265 mm -= offset;
Tim Petersf3615152003-01-01 21:51:37 +00004266 if ((mm < 0 || mm >= 60) &&
4267 normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
Tim Peters52dcce22003-01-23 16:36:11 +00004268 return NULL;
4269
4270 /* Attach new tzinfo and let fromutc() do the rest. */
4271 result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4272 if (result != NULL) {
4273 PyObject *temp = result;
4274
4275 result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4276 Py_DECREF(temp);
4277 }
Tim Petersadf64202003-01-04 06:03:15 +00004278 return result;
Tim Peters521fc152002-12-31 17:36:56 +00004279
Tim Peters52dcce22003-01-23 16:36:11 +00004280NeedAware:
4281 PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4282 "a naive datetime");
Tim Peters521fc152002-12-31 17:36:56 +00004283 return NULL;
Tim Peters80475bb2002-12-25 07:40:55 +00004284}
4285
4286static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004287datetime_timetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004288{
4289 int dstflag = -1;
4290
Tim Petersa9bc1682003-01-11 03:39:11 +00004291 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004292 int none;
4293
4294 dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4295 if (dstflag == -1 && PyErr_Occurred())
4296 return NULL;
4297
4298 if (none)
4299 dstflag = -1;
4300 else if (dstflag != 0)
4301 dstflag = 1;
4302
4303 }
4304 return build_struct_time(GET_YEAR(self),
4305 GET_MONTH(self),
4306 GET_DAY(self),
4307 DATE_GET_HOUR(self),
4308 DATE_GET_MINUTE(self),
4309 DATE_GET_SECOND(self),
4310 dstflag);
4311}
4312
4313static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004314datetime_getdate(PyDateTime_DateTime *self)
4315{
4316 return new_date(GET_YEAR(self),
4317 GET_MONTH(self),
4318 GET_DAY(self));
4319}
4320
4321static PyObject *
4322datetime_gettime(PyDateTime_DateTime *self)
4323{
4324 return new_time(DATE_GET_HOUR(self),
4325 DATE_GET_MINUTE(self),
4326 DATE_GET_SECOND(self),
4327 DATE_GET_MICROSECOND(self),
4328 Py_None);
4329}
4330
4331static PyObject *
4332datetime_gettimetz(PyDateTime_DateTime *self)
4333{
4334 return new_time(DATE_GET_HOUR(self),
4335 DATE_GET_MINUTE(self),
4336 DATE_GET_SECOND(self),
4337 DATE_GET_MICROSECOND(self),
4338 HASTZINFO(self) ? self->tzinfo : Py_None);
4339}
4340
4341static PyObject *
4342datetime_utctimetuple(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004343{
4344 int y = GET_YEAR(self);
4345 int m = GET_MONTH(self);
4346 int d = GET_DAY(self);
4347 int hh = DATE_GET_HOUR(self);
4348 int mm = DATE_GET_MINUTE(self);
4349 int ss = DATE_GET_SECOND(self);
4350 int us = 0; /* microseconds are ignored in a timetuple */
4351 int offset = 0;
4352
Tim Petersa9bc1682003-01-11 03:39:11 +00004353 if (HASTZINFO(self) && self->tzinfo != Py_None) {
Tim Peters2a799bf2002-12-16 20:18:38 +00004354 int none;
4355
4356 offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4357 if (offset == -1 && PyErr_Occurred())
4358 return NULL;
4359 }
4360 /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4361 * 0 in a UTC timetuple regardless of what dst() says.
4362 */
4363 if (offset) {
4364 /* Subtract offset minutes & normalize. */
4365 int stat;
4366
4367 mm -= offset;
4368 stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4369 if (stat < 0) {
4370 /* At the edges, it's possible we overflowed
4371 * beyond MINYEAR or MAXYEAR.
4372 */
4373 if (PyErr_ExceptionMatches(PyExc_OverflowError))
4374 PyErr_Clear();
4375 else
4376 return NULL;
4377 }
4378 }
4379 return build_struct_time(y, m, d, hh, mm, ss, 0);
4380}
4381
Tim Peters371935f2003-02-01 01:52:50 +00004382/* Pickle support, a simple use of __reduce__. */
Tim Peters33e0f382003-01-10 02:05:14 +00004383
Tim Petersa9bc1682003-01-11 03:39:11 +00004384/* Let basestate be the non-tzinfo data string.
Tim Peters2a799bf2002-12-16 20:18:38 +00004385 * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4386 * So it's a tuple in any (non-error) case.
Tim Petersb57f8f02003-02-01 02:54:15 +00004387 * __getstate__ isn't exposed.
Tim Peters2a799bf2002-12-16 20:18:38 +00004388 */
4389static PyObject *
Tim Petersa9bc1682003-01-11 03:39:11 +00004390datetime_getstate(PyDateTime_DateTime *self)
Tim Peters2a799bf2002-12-16 20:18:38 +00004391{
4392 PyObject *basestate;
4393 PyObject *result = NULL;
4394
Tim Peters33e0f382003-01-10 02:05:14 +00004395 basestate = PyString_FromStringAndSize((char *)self->data,
4396 _PyDateTime_DATETIME_DATASIZE);
Tim Peters2a799bf2002-12-16 20:18:38 +00004397 if (basestate != NULL) {
Tim Petersa9bc1682003-01-11 03:39:11 +00004398 if (! HASTZINFO(self) || self->tzinfo == Py_None)
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004399 result = PyTuple_Pack(1, basestate);
Tim Peters2a799bf2002-12-16 20:18:38 +00004400 else
Raymond Hettinger8ae46892003-10-12 19:09:37 +00004401 result = PyTuple_Pack(2, basestate, self->tzinfo);
Tim Peters2a799bf2002-12-16 20:18:38 +00004402 Py_DECREF(basestate);
4403 }
4404 return result;
4405}
4406
4407static PyObject *
Guido van Rossum177e41a2003-01-30 22:06:23 +00004408datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
Tim Peters2a799bf2002-12-16 20:18:38 +00004409{
Guido van Rossum177e41a2003-01-30 22:06:23 +00004410 return Py_BuildValue("(ON)", self->ob_type, datetime_getstate(self));
Tim Peters2a799bf2002-12-16 20:18:38 +00004411}
4412
Tim Petersa9bc1682003-01-11 03:39:11 +00004413static PyMethodDef datetime_methods[] = {
Guido van Rossum177e41a2003-01-30 22:06:23 +00004414
Tim Peters2a799bf2002-12-16 20:18:38 +00004415 /* Class methods: */
Tim Peters2a799bf2002-12-16 20:18:38 +00004416
Tim Petersa9bc1682003-01-11 03:39:11 +00004417 {"now", (PyCFunction)datetime_now,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004418 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Neal Norwitz2fbe5372003-01-23 21:09:05 +00004419 PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004420
Tim Petersa9bc1682003-01-11 03:39:11 +00004421 {"utcnow", (PyCFunction)datetime_utcnow,
4422 METH_NOARGS | METH_CLASS,
4423 PyDoc_STR("Return a new datetime representing UTC day and time.")},
4424
4425 {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004426 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
Tim Peters2a44a8d2003-01-23 20:53:10 +00004427 PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
Tim Peters2a799bf2002-12-16 20:18:38 +00004428
Tim Petersa9bc1682003-01-11 03:39:11 +00004429 {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4430 METH_VARARGS | METH_CLASS,
4431 PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4432 "(like time.time()).")},
4433
Skip Montanaro0af3ade2005-01-13 04:12:31 +00004434 {"strptime", (PyCFunction)datetime_strptime,
4435 METH_VARARGS | METH_CLASS,
4436 PyDoc_STR("string, format -> new datetime parsed from a string "
4437 "(like time.strptime()).")},
4438
Tim Petersa9bc1682003-01-11 03:39:11 +00004439 {"combine", (PyCFunction)datetime_combine,
4440 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4441 PyDoc_STR("date, time -> datetime with same date and time fields")},
4442
Tim Peters2a799bf2002-12-16 20:18:38 +00004443 /* Instance methods: */
Guido van Rossum177e41a2003-01-30 22:06:23 +00004444
Tim Petersa9bc1682003-01-11 03:39:11 +00004445 {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
4446 PyDoc_STR("Return date object with same year, month and day.")},
4447
4448 {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
4449 PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4450
4451 {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
4452 PyDoc_STR("Return time object with same time and tzinfo.")},
4453
4454 {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
4455 PyDoc_STR("Return ctime() style string.")},
4456
4457 {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004458 PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4459
Tim Petersa9bc1682003-01-11 03:39:11 +00004460 {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004461 PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4462
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004463 {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004464 PyDoc_STR("[sep] -> string in ISO 8601 format, "
4465 "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4466 "sep is used to separate the year from the time, and "
4467 "defaults to 'T'.")},
4468
Tim Petersa9bc1682003-01-11 03:39:11 +00004469 {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004470 PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4471
Tim Petersa9bc1682003-01-11 03:39:11 +00004472 {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004473 PyDoc_STR("Return self.tzinfo.tzname(self).")},
4474
Tim Petersa9bc1682003-01-11 03:39:11 +00004475 {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
Tim Peters2a799bf2002-12-16 20:18:38 +00004476 PyDoc_STR("Return self.tzinfo.dst(self).")},
4477
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004478 {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
Tim Petersa9bc1682003-01-11 03:39:11 +00004479 PyDoc_STR("Return datetime with new specified fields.")},
Tim Peters12bf3392002-12-24 05:41:27 +00004480
Guido van Rossumd59da4b2007-05-22 18:11:13 +00004481 {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
Tim Peters80475bb2002-12-25 07:40:55 +00004482 PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4483
Guido van Rossum177e41a2003-01-30 22:06:23 +00004484 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
4485 PyDoc_STR("__reduce__() -> (cls, state)")},
4486
Tim Peters2a799bf2002-12-16 20:18:38 +00004487 {NULL, NULL}
4488};
4489
Tim Petersa9bc1682003-01-11 03:39:11 +00004490static char datetime_doc[] =
Raymond Hettinger3a4231d2004-12-19 20:13:24 +00004491PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4492\n\
4493The year, month and day arguments are required. tzinfo may be None, or an\n\
4494instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
Tim Peters2a799bf2002-12-16 20:18:38 +00004495
Tim Petersa9bc1682003-01-11 03:39:11 +00004496static PyNumberMethods datetime_as_number = {
4497 datetime_add, /* nb_add */
4498 datetime_subtract, /* nb_subtract */
Tim Peters2a799bf2002-12-16 20:18:38 +00004499 0, /* nb_multiply */
Tim Peters2a799bf2002-12-16 20:18:38 +00004500 0, /* nb_remainder */
4501 0, /* nb_divmod */
4502 0, /* nb_power */
4503 0, /* nb_negative */
4504 0, /* nb_positive */
4505 0, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00004506 0, /* nb_bool */
Tim Peters2a799bf2002-12-16 20:18:38 +00004507};
4508
Neal Norwitz227b5332006-03-22 09:28:35 +00004509static PyTypeObject PyDateTime_DateTimeType = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004510 PyObject_HEAD_INIT(NULL)
4511 0, /* ob_size */
Tim Peters0bf60bd2003-01-08 20:40:01 +00004512 "datetime.datetime", /* tp_name */
Tim Petersa9bc1682003-01-11 03:39:11 +00004513 sizeof(PyDateTime_DateTime), /* tp_basicsize */
Tim Peters2a799bf2002-12-16 20:18:38 +00004514 0, /* tp_itemsize */
Tim Petersa9bc1682003-01-11 03:39:11 +00004515 (destructor)datetime_dealloc, /* tp_dealloc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004516 0, /* tp_print */
4517 0, /* tp_getattr */
4518 0, /* tp_setattr */
4519 0, /* tp_compare */
Tim Petersa9bc1682003-01-11 03:39:11 +00004520 (reprfunc)datetime_repr, /* tp_repr */
4521 &datetime_as_number, /* tp_as_number */
Tim Peters2a799bf2002-12-16 20:18:38 +00004522 0, /* tp_as_sequence */
4523 0, /* tp_as_mapping */
Tim Petersa9bc1682003-01-11 03:39:11 +00004524 (hashfunc)datetime_hash, /* tp_hash */
Tim Peters2a799bf2002-12-16 20:18:38 +00004525 0, /* tp_call */
Tim Petersa9bc1682003-01-11 03:39:11 +00004526 (reprfunc)datetime_str, /* tp_str */
Tim Peters2a799bf2002-12-16 20:18:38 +00004527 PyObject_GenericGetAttr, /* tp_getattro */
4528 0, /* tp_setattro */
4529 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00004530 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Petersa9bc1682003-01-11 03:39:11 +00004531 datetime_doc, /* tp_doc */
Tim Peters2a799bf2002-12-16 20:18:38 +00004532 0, /* tp_traverse */
4533 0, /* tp_clear */
Guido van Rossum19960592006-08-24 17:29:38 +00004534 datetime_richcompare, /* tp_richcompare */
Tim Peters2a799bf2002-12-16 20:18:38 +00004535 0, /* tp_weaklistoffset */
4536 0, /* tp_iter */
4537 0, /* tp_iternext */
Tim Petersa9bc1682003-01-11 03:39:11 +00004538 datetime_methods, /* tp_methods */
Tim Peters2a799bf2002-12-16 20:18:38 +00004539 0, /* tp_members */
Tim Petersa9bc1682003-01-11 03:39:11 +00004540 datetime_getset, /* tp_getset */
4541 &PyDateTime_DateType, /* tp_base */
Tim Peters2a799bf2002-12-16 20:18:38 +00004542 0, /* tp_dict */
4543 0, /* tp_descr_get */
4544 0, /* tp_descr_set */
4545 0, /* tp_dictoffset */
4546 0, /* tp_init */
Tim Petersa98924a2003-05-17 05:55:19 +00004547 datetime_alloc, /* tp_alloc */
Tim Petersa9bc1682003-01-11 03:39:11 +00004548 datetime_new, /* tp_new */
Tim Peters4c530132003-05-16 22:44:06 +00004549 0, /* tp_free */
Tim Peters2a799bf2002-12-16 20:18:38 +00004550};
4551
4552/* ---------------------------------------------------------------------------
4553 * Module methods and initialization.
4554 */
4555
4556static PyMethodDef module_methods[] = {
Tim Peters2a799bf2002-12-16 20:18:38 +00004557 {NULL, NULL}
4558};
4559
Tim Peters9ddf40b2004-06-20 22:41:32 +00004560/* C API. Clients get at this via PyDateTime_IMPORT, defined in
4561 * datetime.h.
4562 */
4563static PyDateTime_CAPI CAPI = {
4564 &PyDateTime_DateType,
4565 &PyDateTime_DateTimeType,
4566 &PyDateTime_TimeType,
4567 &PyDateTime_DeltaType,
4568 &PyDateTime_TZInfoType,
4569 new_date_ex,
4570 new_datetime_ex,
4571 new_time_ex,
4572 new_delta_ex,
4573 datetime_fromtimestamp,
4574 date_fromtimestamp
4575};
4576
4577
Tim Peters2a799bf2002-12-16 20:18:38 +00004578PyMODINIT_FUNC
4579initdatetime(void)
4580{
4581 PyObject *m; /* a module object */
4582 PyObject *d; /* its dict */
4583 PyObject *x;
4584
Tim Peters2a799bf2002-12-16 20:18:38 +00004585 m = Py_InitModule3("datetime", module_methods,
4586 "Fast implementation of the datetime type.");
Neal Norwitz1ac754f2006-01-19 06:09:39 +00004587 if (m == NULL)
4588 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004589
4590 if (PyType_Ready(&PyDateTime_DateType) < 0)
4591 return;
4592 if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4593 return;
4594 if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4595 return;
4596 if (PyType_Ready(&PyDateTime_TimeType) < 0)
4597 return;
4598 if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4599 return;
Tim Peters2a799bf2002-12-16 20:18:38 +00004600
Tim Peters2a799bf2002-12-16 20:18:38 +00004601 /* timedelta values */
4602 d = PyDateTime_DeltaType.tp_dict;
4603
Tim Peters2a799bf2002-12-16 20:18:38 +00004604 x = new_delta(0, 0, 1, 0);
4605 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4606 return;
4607 Py_DECREF(x);
4608
4609 x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4610 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4611 return;
4612 Py_DECREF(x);
4613
4614 x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4615 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4616 return;
4617 Py_DECREF(x);
4618
4619 /* date values */
4620 d = PyDateTime_DateType.tp_dict;
4621
4622 x = new_date(1, 1, 1);
4623 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4624 return;
4625 Py_DECREF(x);
4626
4627 x = new_date(MAXYEAR, 12, 31);
4628 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4629 return;
4630 Py_DECREF(x);
4631
4632 x = new_delta(1, 0, 0, 0);
4633 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4634 return;
4635 Py_DECREF(x);
4636
Tim Peters37f39822003-01-10 03:49:02 +00004637 /* time values */
4638 d = PyDateTime_TimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004639
Tim Peters37f39822003-01-10 03:49:02 +00004640 x = new_time(0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004641 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4642 return;
4643 Py_DECREF(x);
4644
Tim Peters37f39822003-01-10 03:49:02 +00004645 x = new_time(23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004646 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4647 return;
4648 Py_DECREF(x);
4649
4650 x = new_delta(0, 0, 1, 0);
4651 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4652 return;
4653 Py_DECREF(x);
4654
Tim Petersa9bc1682003-01-11 03:39:11 +00004655 /* datetime values */
4656 d = PyDateTime_DateTimeType.tp_dict;
Tim Peters2a799bf2002-12-16 20:18:38 +00004657
Tim Petersa9bc1682003-01-11 03:39:11 +00004658 x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004659 if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4660 return;
4661 Py_DECREF(x);
4662
Tim Petersa9bc1682003-01-11 03:39:11 +00004663 x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
Tim Peters2a799bf2002-12-16 20:18:38 +00004664 if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4665 return;
4666 Py_DECREF(x);
4667
4668 x = new_delta(0, 0, 1, 0);
4669 if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4670 return;
4671 Py_DECREF(x);
4672
Tim Peters2a799bf2002-12-16 20:18:38 +00004673 /* module initialization */
4674 PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4675 PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4676
4677 Py_INCREF(&PyDateTime_DateType);
4678 PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4679
Tim Petersa9bc1682003-01-11 03:39:11 +00004680 Py_INCREF(&PyDateTime_DateTimeType);
4681 PyModule_AddObject(m, "datetime",
4682 (PyObject *)&PyDateTime_DateTimeType);
4683
4684 Py_INCREF(&PyDateTime_TimeType);
4685 PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4686
Tim Peters2a799bf2002-12-16 20:18:38 +00004687 Py_INCREF(&PyDateTime_DeltaType);
4688 PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4689
Tim Peters2a799bf2002-12-16 20:18:38 +00004690 Py_INCREF(&PyDateTime_TZInfoType);
4691 PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4692
Tim Peters9ddf40b2004-06-20 22:41:32 +00004693 x = PyCObject_FromVoidPtrAndDesc(&CAPI, (void*) DATETIME_API_MAGIC,
4694 NULL);
4695 if (x == NULL)
4696 return;
4697 PyModule_AddObject(m, "datetime_CAPI", x);
4698
Tim Peters2a799bf2002-12-16 20:18:38 +00004699 /* A 4-year cycle has an extra leap day over what we'd get from
4700 * pasting together 4 single years.
4701 */
4702 assert(DI4Y == 4 * 365 + 1);
4703 assert(DI4Y == days_before_year(4+1));
4704
4705 /* Similarly, a 400-year cycle has an extra leap day over what we'd
4706 * get from pasting together 4 100-year cycles.
4707 */
4708 assert(DI400Y == 4 * DI100Y + 1);
4709 assert(DI400Y == days_before_year(400+1));
4710
4711 /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4712 * pasting together 25 4-year cycles.
4713 */
4714 assert(DI100Y == 25 * DI4Y - 1);
4715 assert(DI100Y == days_before_year(100+1));
4716
4717 us_per_us = PyInt_FromLong(1);
4718 us_per_ms = PyInt_FromLong(1000);
4719 us_per_second = PyInt_FromLong(1000000);
4720 us_per_minute = PyInt_FromLong(60000000);
4721 seconds_per_day = PyInt_FromLong(24 * 3600);
4722 if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4723 us_per_minute == NULL || seconds_per_day == NULL)
4724 return;
4725
4726 /* The rest are too big for 32-bit ints, but even
4727 * us_per_week fits in 40 bits, so doubles should be exact.
4728 */
4729 us_per_hour = PyLong_FromDouble(3600000000.0);
4730 us_per_day = PyLong_FromDouble(86400000000.0);
4731 us_per_week = PyLong_FromDouble(604800000000.0);
4732 if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4733 return;
4734}
Tim Petersf3615152003-01-01 21:51:37 +00004735
4736/* ---------------------------------------------------------------------------
Tim Petersa9bc1682003-01-11 03:39:11 +00004737Some time zone algebra. For a datetime x, let
Tim Petersf3615152003-01-01 21:51:37 +00004738 x.n = x stripped of its timezone -- its naive time.
4739 x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4740 return None
4741 x.d = x.dst(), and assuming that doesn't raise an exception or
4742 return None
4743 x.s = x's standard offset, x.o - x.d
4744
4745Now some derived rules, where k is a duration (timedelta).
4746
47471. x.o = x.s + x.d
4748 This follows from the definition of x.s.
4749
Tim Petersc5dc4da2003-01-02 17:55:03 +000047502. If x and y have the same tzinfo member, x.s = y.s.
Tim Petersf3615152003-01-01 21:51:37 +00004751 This is actually a requirement, an assumption we need to make about
4752 sane tzinfo classes.
4753
47543. The naive UTC time corresponding to x is x.n - x.o.
4755 This is again a requirement for a sane tzinfo class.
4756
47574. (x+k).s = x.s
Tim Peters8bb5ad22003-01-24 02:44:45 +00004758 This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
Tim Petersf3615152003-01-01 21:51:37 +00004759
Tim Petersc5dc4da2003-01-02 17:55:03 +000047605. (x+k).n = x.n + k
Tim Petersf3615152003-01-01 21:51:37 +00004761 Again follows from how arithmetic is defined.
4762
Tim Peters8bb5ad22003-01-24 02:44:45 +00004763Now we can explain tz.fromutc(x). Let's assume it's an interesting case
Tim Petersf3615152003-01-01 21:51:37 +00004764(meaning that the various tzinfo methods exist, and don't blow up or return
4765None when called).
4766
Tim Petersa9bc1682003-01-11 03:39:11 +00004767The function wants to return a datetime y with timezone tz, equivalent to x.
Tim Peters8bb5ad22003-01-24 02:44:45 +00004768x is already in UTC.
Tim Petersf3615152003-01-01 21:51:37 +00004769
4770By #3, we want
4771
Tim Peters8bb5ad22003-01-24 02:44:45 +00004772 y.n - y.o = x.n [1]
Tim Petersf3615152003-01-01 21:51:37 +00004773
4774The algorithm starts by attaching tz to x.n, and calling that y. So
4775x.n = y.n at the start. Then it wants to add a duration k to y, so that [1]
4776becomes true; in effect, we want to solve [2] for k:
4777
Tim Peters8bb5ad22003-01-24 02:44:45 +00004778 (y+k).n - (y+k).o = x.n [2]
Tim Petersf3615152003-01-01 21:51:37 +00004779
4780By #1, this is the same as
4781
Tim Peters8bb5ad22003-01-24 02:44:45 +00004782 (y+k).n - ((y+k).s + (y+k).d) = x.n [3]
Tim Petersf3615152003-01-01 21:51:37 +00004783
4784By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4785Substituting that into [3],
4786
Tim Peters8bb5ad22003-01-24 02:44:45 +00004787 x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4788 k - (y+k).s - (y+k).d = 0; rearranging,
4789 k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4790 k = y.s - (y+k).d
Tim Petersf3615152003-01-01 21:51:37 +00004791
Tim Peters8bb5ad22003-01-24 02:44:45 +00004792On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4793approximate k by ignoring the (y+k).d term at first. Note that k can't be
4794very large, since all offset-returning methods return a duration of magnitude
4795less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must
4796be 0, so ignoring it has no consequence then.
Tim Petersf3615152003-01-01 21:51:37 +00004797
4798In any case, the new value is
4799
Tim Peters8bb5ad22003-01-24 02:44:45 +00004800 z = y + y.s [4]
Tim Petersf3615152003-01-01 21:51:37 +00004801
Tim Peters8bb5ad22003-01-24 02:44:45 +00004802It's helpful to step back at look at [4] from a higher level: it's simply
4803mapping from UTC to tz's standard time.
Tim Petersc5dc4da2003-01-02 17:55:03 +00004804
4805At this point, if
4806
Tim Peters8bb5ad22003-01-24 02:44:45 +00004807 z.n - z.o = x.n [5]
Tim Petersc5dc4da2003-01-02 17:55:03 +00004808
4809we have an equivalent time, and are almost done. The insecurity here is
Tim Petersf3615152003-01-01 21:51:37 +00004810at the start of daylight time. Picture US Eastern for concreteness. The wall
4811time 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 +00004812sense then. The docs ask that an Eastern tzinfo class consider such a time to
4813be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
4814on the day DST starts. We want to return the 1:MM EST spelling because that's
Tim Petersf3615152003-01-01 21:51:37 +00004815the only spelling that makes sense on the local wall clock.
4816
Tim Petersc5dc4da2003-01-02 17:55:03 +00004817In fact, if [5] holds at this point, we do have the standard-time spelling,
4818but that takes a bit of proof. We first prove a stronger result. What's the
4819difference between the LHS and RHS of [5]? Let
Tim Petersf3615152003-01-01 21:51:37 +00004820
Tim Peters8bb5ad22003-01-24 02:44:45 +00004821 diff = x.n - (z.n - z.o) [6]
Tim Petersf3615152003-01-01 21:51:37 +00004822
Tim Petersc5dc4da2003-01-02 17:55:03 +00004823Now
4824 z.n = by [4]
Tim Peters8bb5ad22003-01-24 02:44:45 +00004825 (y + y.s).n = by #5
4826 y.n + y.s = since y.n = x.n
4827 x.n + y.s = since z and y are have the same tzinfo member,
4828 y.s = z.s by #2
4829 x.n + z.s
Tim Petersf3615152003-01-01 21:51:37 +00004830
Tim Petersc5dc4da2003-01-02 17:55:03 +00004831Plugging that back into [6] gives
Tim Petersf3615152003-01-01 21:51:37 +00004832
Tim Petersc5dc4da2003-01-02 17:55:03 +00004833 diff =
Tim Peters8bb5ad22003-01-24 02:44:45 +00004834 x.n - ((x.n + z.s) - z.o) = expanding
4835 x.n - x.n - z.s + z.o = cancelling
4836 - z.s + z.o = by #2
Tim Petersc5dc4da2003-01-02 17:55:03 +00004837 z.d
Tim Petersf3615152003-01-01 21:51:37 +00004838
Tim Petersc5dc4da2003-01-02 17:55:03 +00004839So diff = z.d.
Tim Petersf3615152003-01-01 21:51:37 +00004840
Tim Petersc5dc4da2003-01-02 17:55:03 +00004841If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
Tim Peters8bb5ad22003-01-24 02:44:45 +00004842spelling we wanted in the endcase described above. We're done. Contrarily,
4843if z.d = 0, then we have a UTC equivalent, and are also done.
Tim Petersf3615152003-01-01 21:51:37 +00004844
Tim Petersc5dc4da2003-01-02 17:55:03 +00004845If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
4846add to z (in effect, z is in tz's standard time, and we need to shift the
Tim Peters8bb5ad22003-01-24 02:44:45 +00004847local clock into tz's daylight time).
Tim Petersf3615152003-01-01 21:51:37 +00004848
Tim Petersc5dc4da2003-01-02 17:55:03 +00004849Let
Tim Petersf3615152003-01-01 21:51:37 +00004850
Tim Peters4fede1a2003-01-04 00:26:59 +00004851 z' = z + z.d = z + diff [7]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004852
Tim Peters4fede1a2003-01-04 00:26:59 +00004853and we can again ask whether
Tim Petersc3bb26a2003-01-02 03:14:59 +00004854
Tim Peters8bb5ad22003-01-24 02:44:45 +00004855 z'.n - z'.o = x.n [8]
Tim Petersc3bb26a2003-01-02 03:14:59 +00004856
Tim Peters8bb5ad22003-01-24 02:44:45 +00004857If so, we're done. If not, the tzinfo class is insane, according to the
4858assumptions we've made. This also requires a bit of proof. As before, let's
4859compute the difference between the LHS and RHS of [8] (and skipping some of
4860the justifications for the kinds of substitutions we've done several times
4861already):
Tim Peters4fede1a2003-01-04 00:26:59 +00004862
Tim Peters8bb5ad22003-01-24 02:44:45 +00004863 diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
4864 x.n - (z.n + diff - z'.o) = replacing diff via [6]
4865 x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
4866 x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
4867 - z.n + z.n - z.o + z'.o = cancel z.n
Tim Peters4fede1a2003-01-04 00:26:59 +00004868 - z.o + z'.o = #1 twice
4869 -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
4870 z'.d - z.d
4871
4872So 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 +00004873we've found the UTC-equivalent so are done. In fact, we stop with [7] and
4874return z', not bothering to compute z'.d.
Tim Peters4fede1a2003-01-04 00:26:59 +00004875
Tim Peters8bb5ad22003-01-24 02:44:45 +00004876How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by
4877a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
4878would have to change the result dst() returns: we start in DST, and moving
4879a little further into it takes us out of DST.
Tim Peters4fede1a2003-01-04 00:26:59 +00004880
Tim Peters8bb5ad22003-01-24 02:44:45 +00004881There isn't a sane case where this can happen. The closest it gets is at
4882the end of DST, where there's an hour in UTC with no spelling in a hybrid
4883tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During
4884that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
4885UTC) because the docs insist on that, but 0:MM is taken as being in daylight
4886time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local
4887clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
4888standard time. Since that's what the local clock *does*, we want to map both
4889UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous
Tim Peters4fede1a2003-01-04 00:26:59 +00004890in local time, but so it goes -- it's the way the local clock works.
4891
Tim Peters8bb5ad22003-01-24 02:44:45 +00004892When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
4893so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
4894z' = 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 +00004895(correctly) concludes that z' is not UTC-equivalent to x.
4896
4897Because we know z.d said z was in daylight time (else [5] would have held and
4898we would have stopped then), and we know z.d != z'.d (else [8] would have held
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00004899and we would have stopped then), and there are only 2 possible values dst() can
Tim Peters4fede1a2003-01-04 00:26:59 +00004900return in Eastern, it follows that z'.d must be 0 (which it is in the example,
4901but the reasoning doesn't depend on the example -- it depends on there being
4902two possible dst() outcomes, one zero and the other non-zero). Therefore
Tim Peters8bb5ad22003-01-24 02:44:45 +00004903z' must be in standard time, and is the spelling we want in this case.
4904
4905Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
4906concerned (because it takes z' as being in standard time rather than the
4907daylight time we intend here), but returning it gives the real-life "local
4908clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
4909tz.
4910
4911When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
4912the 1:MM standard time spelling we want.
4913
4914So how can this break? One of the assumptions must be violated. Two
4915possibilities:
4916
49171) [2] effectively says that y.s is invariant across all y belong to a given
4918 time zone. This isn't true if, for political reasons or continental drift,
4919 a region decides to change its base offset from UTC.
4920
49212) There may be versions of "double daylight" time where the tail end of
4922 the analysis gives up a step too early. I haven't thought about that
4923 enough to say.
4924
4925In any case, it's clear that the default fromutc() is strong enough to handle
4926"almost all" time zones: so long as the standard offset is invariant, it
4927doesn't matter if daylight time transition points change from year to year, or
4928if daylight time is skipped in some years; it doesn't matter how large or
4929small dst() may get within its bounds; and it doesn't even matter if some
4930perverse time zone returns a negative dst()). So a breaking case must be
4931pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
Tim Petersf3615152003-01-01 21:51:37 +00004932--------------------------------------------------------------------------- */